예제 #1
0
 def gerar_widgets(self):
     '''
     Gera todos os widgets dos gráficos que serão colocados nas telas
     '''
     for indice in range(len(self.matrizes)):
         graph_widget = Grafics_widget()
         graph_widget.setup()
         
         widget_delaunay = FigureWidget(self.figuras_triang[indice])
         widget_delaunay.setObjectName(_fromUtf8("widget_delaunay"))
         widget_delaunay.setParent(graph_widget.groupBox_2)
         graph_widget.gridLayout_4.addWidget(widget_delaunay, 0, 0, 1, 1)
         
         widget_vector = FigureWidget(self.figuras_vet[indice])
         widget_vector.setObjectName(_fromUtf8("widget_vector"))
         widget_vector.setParent(graph_widget.groupBox)
         graph_widget.gridLayout_3.addWidget(widget_vector, 0, 0, 1, 1)
         
         graph_widget.label.setText("%1.6f" % self.GAs[indice])
         
         vect_widget = Detail_widget()
         vect_widget.setup()
         
         widget_vector_tab = FigureWidget(self.figuras_vet[indice])
         widget_vector_tab.setObjectName(_fromUtf8("widget_vector_tab"))
         widget_vector_tab.setParent(vect_widget.groupBox)
         vect_widget.gridLayout_1.addWidget(widget_vector_tab, 0, 0, 1, 1)
         
         navbar_vetor = Navbar(widget_vector_tab, self.ui.ui.centralwidget)
         vect_widget.gridLayout_2.addWidget(navbar_vetor, 0, 0, 1, 1)
         
         trian_widget = Detail_widget()
         trian_widget.setup()
         
         widget_delaunay_tab = FigureWidget(self.figuras_triang[indice])
         widget_delaunay_tab.setObjectName(_fromUtf8("widget_delaunay_tab"))
         widget_delaunay_tab.setParent(trian_widget.groupBox)
         trian_widget.gridLayout_1.addWidget(widget_delaunay_tab, 0, 0, 1, 1)
         
         navbar_delaunay = Navbar(widget_delaunay_tab, self.ui.ui.centralwidget)
         trian_widget.gridLayout_2.addWidget(navbar_delaunay, 0, 0, 1, 1)
     
         widget_gpa_ev = FigureWidget(self.figuras_GA[indice])
         widget_gpa_ev.setObjectName(_fromUtf8("widget_gpa_ev"))
         widget_gpa_ev.setParent(self.ui.ui.GPAGraphGroup)
         
         self.ui.ui.stackedGraphics.addWidget(graph_widget)
         self.ui.ui.stackedVet.addWidget(vect_widget)
         self.ui.ui.stackedTriang.addWidget(trian_widget)
         self.ui.ui.stackedGPA.addWidget(widget_gpa_ev)
         
     self.ui.ui.horizontalSlider.setMaximum(len(self.matrizes) - 1)
     self.ui.ui.horizontalSlider.setSingleStep(1)
     self.ui.ui.horizontalSlider.setPageStep(1)
예제 #2
0
    def init_Drawing_Figures(self):
        i = 0
        for (fig, ls) in self.figs:
            ls[0] = fig.add_subplot(111)
            ls[0].grid(true)
            canvas = FigureCanvas(fig)
            canvas.setObjectName("canvas" + str(i))
            ls[1].addWidget(canvas)
            toolbar = NavigationToolbar(canvas, ls[2], coordinates=True)
            ls[1].addWidget(toolbar)
            ls[0].autoscale(true, tight=false)
            i += 1

        self.rootPlot = self.figs[0][1][0]
예제 #3
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        MainWindow.setCentralWidget(self.centralwidget)

        self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setObjectName("verticalLayout")

        self.fig = plt.Figure()
        self.graph01 = FigureCanvas(self.fig)
        self.ax1 = self.fig.add_subplot(211)
        self.ax2 = self.fig.add_subplot(212)

        self.graph01.setObjectName("graph01")
        self.verticalLayout.addWidget(self.graph01)

        self.psbtn = QtGui.QPushButton(self.centralwidget)
        self.psbtn.setObjectName("psbtn")
        self.psbtn.setText("Plot")
        self.verticalLayout.addWidget(self.psbtn)
        QtCore.QObject.connect(self.psbtn, QtCore.SIGNAL("clicked()"),
                               self.plot)

    def plot(self):
        frq1 = 10.0
        frq2 = 30.0
        frq3 = 50.0
        duration = 1.0
        samples = 1001

        x1 = np.linspace(0, duration, samples)
        rad1 = np.linspace(0, 2 * np.pi * frq1, samples)
        rad2 = np.linspace(0, 2 * np.pi * frq2, samples)
        rad3 = np.linspace(0, 2 * np.pi * frq3, samples)
        y1 = np.sin(rad1) + np.sin(rad2) + np.sin(rad3)

        x2 = np.linspace(0, 1001, 1001)[0:np.floor(len(y1) / 2)]
        y2 = abs(np.fft.fft(y1))[0:np.floor(len(y1) / 2)]

        self.ax1.plot(x1, y1)
        self.ax2.plot(x2, y2)
        self.graph01.draw()  #zettai iru
예제 #4
0
class ValueWidget(QWidget, Ui_Widget):

    def __init__(self, iface):

        self.hasqwt=hasqwt
        self.hasmpl=hasmpl
        self.layerMap=dict()
        self.statsChecked=False
        self.ymin=0
        self.ymax=250

        self.iface=iface
        self.canvas=self.iface.mapCanvas()
        self.legend=self.iface.legendInterface()
        self.logger = logging.getLogger('.'.join((__name__, 
                                        self.__class__.__name__)))

        QWidget.__init__(self)
        self.setupUi(self)
        self.setupUi_extra()

        QObject.connect(self.cbxActive,SIGNAL("stateChanged(int)"),self.changeActive)
        QObject.connect(self.cbxGraph,SIGNAL("stateChanged(int)"),self.changePage)
        QObject.connect(self.canvas, SIGNAL( "keyPressed( QKeyEvent * )" ), self.pauseDisplay )
        QObject.connect(self.plotSelector, SIGNAL( "currentIndexChanged ( int )" ), self.changePlot )

    def setupUi_extra(self):

        # checkboxes
        #self.changeActive(Qt.Checked)
        #set inactive by default - should save last state in user config
        self.cbxActive.setCheckState(Qt.Unchecked)

        # plot
        self.plotSelector.setVisible( False )
        self.cbxStats.setVisible( False )
        self.graphControls.setVisible( False )
        if self.hasqwt:
            self.plotSelector.addItem( 'Qwt' )
        if self.hasmpl:
            self.plotSelector.addItem( 'mpl' )
        self.plotSelector.setCurrentIndex( 0 );
        if (not self.hasqwt or not self.hasmpl):
            #self.plotSelector.setVisible(False)
            self.plotSelector.setEnabled(False)

        # Page 2 - qwt
        if self.hasqwt:
            self.qwtPlot = QwtPlot(self.stackedWidget)
            self.qwtPlot.setAutoFillBackground(False)
            self.qwtPlot.setObjectName("qwtPlot")
            self.curve = QwtPlotCurve()
            self.curve.setSymbol(
                QwtSymbol(QwtSymbol.Ellipse,
                          QBrush(Qt.white),
                          QPen(Qt.red, 2),
                          QSize(9, 9)))
            self.curve.attach(self.qwtPlot)
            self.qwtPlot.setVisible(False)
        else:
            self.qwtPlot = QtGui.QLabel("Need Qwt >= 5.0 or matplotlib >= 1.0 !")

        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.qwtPlot.sizePolicy().hasHeightForWidth())
        self.qwtPlot.setSizePolicy(sizePolicy)
        self.qwtPlot.setObjectName("qwtPlot")
        self.qwtPlot.updateGeometry()
        self.stackedWidget.addWidget(self.qwtPlot)

        #Page 3 - matplotlib
        self.mplLine = None #make sure to invalidate when layers change
        if self.hasmpl:
            # mpl stuff
            # should make figure light gray
            self.mplBackground = None #http://www.scipy.org/Cookbook/Matplotlib/Animations
            self.mplFig = plt.Figure(facecolor='w', edgecolor='w')
            self.mplFig.subplots_adjust(left=0.1, right=0.975, bottom=0.13, top=0.95)
            self.mplPlt = self.mplFig.add_subplot(111)   
            self.mplPlt.tick_params(axis='both', which='major', labelsize=12)
            self.mplPlt.tick_params(axis='both', which='minor', labelsize=10)                           
            # qt stuff
            self.pltCanvas = FigureCanvasQTAgg(self.mplFig)
            self.pltCanvas.setParent(self.stackedWidget)
            self.pltCanvas.setAutoFillBackground(False)
            self.pltCanvas.setObjectName("mplPlot")
            self.mplPlot = self.pltCanvas
            self.mplPlot.setVisible(False)
        else:
            self.mplPlot = QtGui.QLabel("Need Qwt >= 5.0 or matplotlib >= 1.0 !")

        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.mplPlot.sizePolicy().hasHeightForWidth())
        self.mplPlot.setSizePolicy(sizePolicy)
        self.qwtPlot.setObjectName("qwtPlot")
        self.mplPlot.updateGeometry()
        self.stackedWidget.addWidget(self.mplPlot)

        self.stackedWidget.setCurrentIndex(0)


    def disconnect(self):
        self.changeActive(False)
        QObject.disconnect(self.canvas, SIGNAL( "keyPressed( QKeyEvent * )" ), self.pauseDisplay )
    
    def pauseDisplay(self,e):
      if ( e.modifiers() == Qt.ShiftModifier or e.modifiers() == Qt.MetaModifier ) and e.key() == Qt.Key_A:

        self.cbxActive.toggle()
        return True
      return False


    def keyPressEvent( self, e ):
      if ( e.modifiers() == Qt.ControlModifier or e.modifiers() == Qt.MetaModifier ) and e.key() == Qt.Key_C:
        items = QString()
        for rec in range( self.tableWidget.rowCount() ):
          items.append( '"' + self.tableWidget.item( rec, 0 ).text() + '",' + self.tableWidget.item( rec, 1 ).text() + "\n" )
        if not items.isEmpty():
          clipboard = QApplication.clipboard()
          clipboard.setText( items )
      elif (self.pauseDisplay(e)):
        pass
      else:
        QWidget.keyPressEvent( self, e )


    def changePage(self,state):
        if (state==Qt.Checked):
            self.plotSelector.setVisible( True )
            self.cbxStats.setVisible( True )
            self.graphControls.setVisible( True )
            if (self.plotSelector.currentText()=='mpl'):
                self.stackedWidget.setCurrentIndex(2)
            else:
                self.stackedWidget.setCurrentIndex(1)
        else:
            self.plotSelector.setVisible( False )
            self.cbxStats.setVisible( False )
            self.graphControls.setVisible( False )
            self.stackedWidget.setCurrentIndex(0)

    def changePlot(self):
        self.changePage(self.cbxActive.checkState())

    def changeActive(self,state):
        if (state==Qt.Checked):
            #QObject.connect(self.legend, SIGNAL( "itemAdded ( QModelIndex )" ), self.statsNeedChecked )
            #QObject.connect(self.legend, SIGNAL( "itemRemoved ()" ), self.invalidatePlot )
            QObject.connect(self.canvas, SIGNAL( "layersChanged ()" ), self.invalidatePlot )
            if int(QGis.QGIS_VERSION[2]) > 2: # for QGIS >= 1.3
                QObject.connect(self.canvas, SIGNAL("xyCoordinates(const QgsPoint &)"), self.printValue)
            else:
                QObject.connect(self.canvas, SIGNAL("xyCoordinates(QgsPoint &)"), self.printValue)
        else:
            QObject.disconnect(self.canvas, SIGNAL( "layersChanged ()" ), self.invalidatePlot )
            if int(QGis.QGIS_VERSION[2]) > 2: # for QGIS >= 1.3
                QObject.disconnect(self.canvas, SIGNAL("xyCoordinates(const QgsPoint &)"), self.printValue)
            else:
                QObject.disconnect(self.canvas, SIGNAL("xyCoordinates(QgsPoint &)"), self.printValue)


    def printValue(self,position):

        if self.canvas.layerCount() == 0:
            self.values=[]         
            self.showValues()
            return
        
        needextremum = self.cbxGraph.isChecked() # if plot is checked

        # count the number of requires rows and remember the raster layers
        nrow=0
        rasterlayers=[]
        layersWOStatistics=[]

        for i in range(self.canvas.layerCount()):
            layer = self.canvas.layer(i)
            if (layer!=None and layer.isValid() and layer.type()==QgsMapLayer.RasterLayer):
              if QGis.QGIS_VERSION_INT >= 10900: # for QGIS >= 1.9
                if not layer.dataProvider():
                  continue

                if not layer.dataProvider().capabilities() & QgsRasterDataProvider.IdentifyValue:
                  continue

                nrow+=layer.bandCount()
                rasterlayers.append(layer)

              else: # < 1.9
                if layer.providerKey()=="wms":
                  continue

                if layer.providerKey()=="grassraster":
                  nrow+=1
                  rasterlayers.append(layer)
                else: # normal raster layer
                  nrow+=layer.bandCount()
                  rasterlayers.append(layer)
                
              # check statistics for each band
              if needextremum:
                for i in range( 1,layer.bandCount()+1 ):
                  if int(QGis.QGIS_VERSION[2]) > 8: # for QGIS > 1.8
                    has_stats=layer.dataProvider().hasStatistics(i)
                  else:
                    has_stats=layer.hasStatistics(i)
                  if not layer.id() in self.layerMap and not has_stats\
                          and not layer in layersWOStatistics:
                    layersWOStatistics.append(layer)

        if layersWOStatistics and not self.statsChecked:
          self.calculateStatistics(layersWOStatistics)
                  
        # create the row if necessary
        self.tableWidget.setRowCount(nrow)

        irow=0
        self.values=[]
        self.ymin=1e38
        self.ymax=-1e38

        mapCanvasSrs = self.iface.mapCanvas().mapRenderer().destinationSrs()

        # TODO - calculate the min/max values only once, instead of every time!!!
        # keep them in a dict() with key=layer.id()
                
        for layer in rasterlayers:
            layername=unicode(layer.name())
            layerSrs = layer.srs()
            pos = position         

            # if given no position, get dummy values
            if position is None:
                pos = QgsPoint(0,0)
            # transform points if needed
            elif not mapCanvasSrs == layerSrs and self.iface.mapCanvas().hasCrsTransformEnabled():
              srsTransform = QgsCoordinateTransform(mapCanvasSrs, layerSrs)
              try:
                pos = srsTransform.transform(position)
              except QgsCsException, err:
                # ignore transformation errors
                continue

            if QGis.QGIS_VERSION_INT >= 10900: # for QGIS >= 1.9
              if not layer.dataProvider():
                continue

              ident = None
              if position is not None:
                canvas = self.iface.mapCanvas()

                # we can only use context if layer is not projected
                if canvas.hasCrsTransformEnabled() and layer.dataProvider().crs() != canvas.mapRenderer().destinationCrs():
                  ident = layer.dataProvider().identify(pos, QgsRasterDataProvider.IdentifyFormatValue )
                else:
                  extent = canvas.extent()
                  width = round(extent.width() / canvas.mapUnitsPerPixel());
                  height = round(extent.height() / canvas.mapUnitsPerPixel());

                  extent = canvas.mapRenderer().mapToLayerCoordinates( layer, extent );

                  ident = layer.dataProvider().identify(pos, QgsRasterDataProvider.IdentifyFormatValue, canvas.extent(), width, height )
                if not len( ident ) > 0:
                    continue

              # if given no position, set values to 0
              if position is None:
                  for key in ident.iterkeys():
                      ident[key] = layer.dataProvider().noDataValue(key)

              for iband in range(1,layer.bandCount()+1): # loop over the bands
                layernamewithband=layername
                if len(ident)>1:
                    layernamewithband+=' '+layer.bandName(iband)

                if not ident or not ident.has_key( iband ): # should not happen
                  bandvalue = "?"
                else: 
                  doubleValue =  ident[iband].toDouble()[0]
                  if layer.dataProvider().isNoDataValue ( iband, doubleValue ):  
                    bandvalue = "no data"
                  else:
                    bandvalue = QgsRasterBlock.printValue( doubleValue )

                self.values.append((layernamewithband,bandvalue))

                if needextremum:
                    has_stats=layer.hasStatistics(i)
                    if has_stats:
                        cstr=layer.bandStatistics(iband)
                    if has_stats:
                        self.ymin=min(self.ymin,cstr.minimumValue)
                        self.ymax=max(self.ymax,cstr.maximumValue)
                    else:
                        self.ymin=min(self.ymin,layer.minimumValue(i))
                        self.ymax=max(self.ymax,layer.maximumValue(i))

            else: # QGIS < 1.9
              isok,ident = layer.identify(pos)
              if not isok:
                  continue

              # if given no position, set values to 0
              if position is None:
                  for key in ident.iterkeys():
                      ident[key] = 0

              if layer.providerKey()=="grassraster":
                if not ident.has_key(QString("value")):
                  continue
                cstr = ident[QString("value")]
                if cstr.isNull():
                  continue
                value = cstr.toDouble()
                if not value[1]:
                  # if this is not a double, it is probably a (GRASS string like
                  # 'out of extent' or 'null (no data)'. Let's just show that:
                  self.values.append((layername, cstr))
                  continue
                self.values.append((layername,cstr))
                if needextremum:
                  self.ymin = min(self.ymin,value[0])
                  self.ymax = max(self.ymax,value[0])

              else:
                for iband in range(1,layer.bandCount()+1): # loop over the bands
                  bandvalue=ident[layer.bandName(iband)]
                  layernamewithband=layername
                  if len(ident)>1:
                      layernamewithband+=' '+layer.bandName(iband)

                  self.values.append((layernamewithband,bandvalue))

                  if needextremum:
                      if int(QGis.QGIS_VERSION[2]) > 8: # for QGIS > 1.8
                          has_stats=layer.dataProvider().hasStatistics(i)
                          if has_stats:
                              cstr=layer.dataProvider().bandStatistics(iband)
                      else:
                          has_stats=layer.hasStatistics(i)
                          if has_stats:
                              cstr=layer.bandStatistics(iband)
                      if has_stats:
                          self.ymin=min(self.ymin,cstr.minimumValue)
                          self.ymax=max(self.ymax,cstr.maximumValue)
                      else:
                          self.ymin=min(self.ymin,layer.minimumValue(i))
                          self.ymax=max(self.ymax,layer.maximumValue(i))

        self.showValues()
예제 #5
0
class MutantWidget(QWidget, Ui_Widget):
    def __init__(self, iface):
        self.hasqwt = has_qwt
        self.hasmpl = has_mpl
        self.haspqg = has_pyqtgraph
        self.layerMap = dict()
        self.statsChecked = False
        self.ymin = 0
        self.ymax = 365
        self.isActive = False
        self.mt_enabled = False

        # Statistics (>=1.9)
        self.statsSampleSize = 2500000
        self.stats = {}  # stats per layer

        self.layersSelected = []
        self.layerBands = dict()

        self.iface = iface
        self.canvas = self.iface.mapCanvas()

        self.legend = self.iface.legendInterface()
        self.logger = logging.getLogger('.'.join(
            (__name__, self.__class__.__name__)))

        QWidget.__init__(self)
        self.setupUi(self)
        self.tabWidget.setEnabled(False)
        self.plotOnMove.setChecked(QSettings().value(
            'plugins/mutant/mouseClick', False, type=bool))

        self.leYMin.setText(str(self.ymin))
        self.leYMax.setText(str(self.ymax))

        self.tracker = TimeTracker(self, self.canvas)
        self.filter = ApplyFilter(self, self.canvas)
        if has_mpl:
            self.mpl_cust = MplSettings(self, self.canvas)

        # self.setupUi_plot()
        # don't setup plot until Graph(1) tab is clicked - workaround for bug
        # #7450
        # qgis will still crash in some cases, but at least the tool can be
        # used in Table mode

        self.qwtPlot = None
        self.mplPlot = None
        self.mplLine = None

        QObject.connect(self.plotLibSelector,
                        SIGNAL("currentIndexChanged ( int )"),
                        self.change_plot)
        QObject.connect(self.tabWidget, SIGNAL("currentChanged ( int )"),
                        self.tabWidgetChanged)
        QObject.connect(self.layerSelection,
                        SIGNAL("currentIndexChanged ( int )"),
                        self.update_layers)
        QObject.connect(self.bandSelection,
                        SIGNAL("currentIndexChanged ( int )"),
                        self.update_layers)
        QObject.connect(self.selectionTable,
                        SIGNAL("cellChanged ( int , int )"),
                        self.layerSelected)
        QObject.connect(self.enableMTAnalysesCheckBox,
                        SIGNAL("toggled ( bool )"),
                        self.on_mt_analysis_toggled)
        QObject.connect(self.selectionStringLineEdit,
                        SIGNAL("textChanged ( QString )"), self.update_layers)
        QObject.connect(self.yAutoCheckBox, SIGNAL("toggled ( bool )"),
                        self.y_auto_toggle)

        QObject.connect(self.toggleMutant, SIGNAL("toggled ( bool )"),
                        self.catch_errors)

        self.exportPushButton.clicked.connect(self.export_values)
        # TODO Get Export from graph values
        # self.exportPushButton_2.clicked.connect(self.xxxx)

        self.registry = QgsMapLayerRegistry.instance()
        QObject.connect(self.registry,
                        SIGNAL("layersAdded(QList< QgsMapLayer * >)"),
                        self.catch_errors)
        QObject.connect(self.registry, SIGNAL("layersRemoved(QStringList)"),
                        self.catch_errors)
        self.setupUi_plot()

    def catch_errors(self):
        if self.toggleMutant.isChecked():
            layers = self.activeRasterLayers()
            if len(layers) == 0:
                if self.canvas.layerCount() > 0:
                    text = self.tr("Mutant: No valid layers to display - "
                                   "add Rasterlayers")
                    self.pop_messagebar(text)
                    self.changeActive(False)
                else:
                    text = self.tr("Mutant: No valid layers to display")
                    self.pop_messagebar(text)
                    self.changeActive(False)
                self.values = []
                return
            else:
                return
        else:
            return

    def y_auto_toggle(self, state):
        # User has toggled automatic (default) y min/max values
        if state == 1:
            self.leYMin.setEnabled(False)
            self.leYMax.setEnabled(False)
            self.leYMin.setText(str(self.ymin))
            self.leYMax.setText(str(self.ymax))
        else:
            self.leYMin.setEnabled(True)
            self.leYMax.setEnabled(True)

    def pop_messagebar(self, text, d_time=5):
        if d_time == 0:
            self.iface.messageBar().pushWidget(
                self.iface.messageBar().createMessage(text),
                QgsMessageBar.WARNING)
        else:
            self.iface.messageBar().pushWidget(
                self.iface.messageBar().createMessage(text),
                QgsMessageBar.WARNING, d_time)

    def setupUi_plot(self):
        # plot
        self.plotLibSelector.setVisible(False)
        self.enableStatistics.setVisible(False)
        # stats by default because estimated are fast
        self.enableStatistics.setChecked(True)

        plot_count = 0
        self.mplLine = None  # make sure to invalidate when layers change

        if self.hasqwt:  # Page 2 - qwt
            self.plotLibSelector.addItem('Qwt')
            plot_count += 1
            # Setup Qwt Plot Area in Widget
            self.qwtPlot = QwtPlot(self.stackedWidget)
            self.qwtPlot.setAutoFillBackground(False)
            self.qwtPlot.setObjectName("qwtPlot")
            self.curve = QwtPlotCurve()
            self.curve.setSymbol(
                QwtSymbol(QwtSymbol.Ellipse, QBrush(Qt.white), QPen(Qt.red, 2),
                          QSize(9, 9)))
            self.curve.attach(self.qwtPlot)

            # Size Policy ???
            sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
                                           QtGui.QSizePolicy.Expanding)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            sizePolicy.setHeightForWidth(
                self.qwtPlot.sizePolicy().hasHeightForWidth())
            self.qwtPlot.setSizePolicy(sizePolicy)
            # Size Policy ???

            self.qwtPlot.updateGeometry()
            self.stackedWidget.addWidget(self.qwtPlot)
            self.qwt_widgetnumber = self.stackedWidget.indexOf(self.qwtPlot)

        if self.hasmpl:  # Page 3 -  setup matplotlib
            self.plotLibSelector.addItem('matplotlib')
            # If matplotlib is the only one
            self.toggleInterpolation.setEnabled(True)
            self.toggleInterpolation.setVisible(True)
            plot_count += 1
            self.mplBackground = None
            # http://www.scipy.org/Cookbook/Matplotlib/Animations
            self.mplFig = plt.Figure(facecolor='w',
                                     edgecolor='g',
                                     linewidth=0.0)

            self.mpl_subplot = self.mplFig.add_subplot(111)
            self.pltCanvas = FigureCanvasQTAgg(self.mplFig)
            self.pltCanvas.setParent(self.stackedWidget)
            self.pltCanvas.setAutoFillBackground(False)
            self.pltCanvas.setObjectName("mplPlot")
            self.mplPlot = self.pltCanvas
            self.mplPlot.updateGeometry()
            self.stackedWidget.addWidget(self.mplPlot)
            self.mpl_widgetnumber = self.stackedWidget.indexOf(self.mplPlot)

        if self.haspqg:  # Page 3 - setup PyQtGraph
            self.plotLibSelector.addItem('PyQtGraph')
            plot_count += 1
            # Setup PyQtGraph stuff
            pg.setConfigOption('background', 'w')
            pg.setConfigOption('foreground', 'k')
            self.pqg_axis = DateTimeAxis(orientation='bottom')
            self.pqg_plot_widget = pg.PlotWidget(
                parent=self.stackedWidget, axisItems={'bottom': self.pqg_axis})
            self.pqg_plot_item = self.pqg_plot_widget.getPlotItem()
            self.pqg_plot_widget.updateGeometry()
            self.stackedWidget.addWidget(self.pqg_plot_widget)
            self.pqg_widgetnumber = self.stackedWidget.indexOf(
                self.pqg_plot_widget)
            # on zoom change do:
            self.pqg_plot_item.sigXRangeChanged.connect(self.refresh_ticks)

        if plot_count > 1:
            self.plotLibSelector.setEnabled(True)
            self.plotLibSelector.setVisible(True)
            self.plotLibSelector.setCurrentIndex(0)
            if self.hasqwt:
                self.plotLibSelector.setCurrentIndex(self.qwt_widgetnumber)
            elif self.hasmpl:
                self.plotLibSelector.setCurrentIndex(self.mpl_widgetnumber)
            else:
                self.plotLibSelector.setCurrentIndex(self.pqg_widgetnumber)
            self.change_plot()
        elif plot_count == 1:
            self.plotLibSelector.setCurrentIndex(0)
            self.change_plot()
        else:  # can only be 0 if nothing else matched
            message_text = "Mutant cannot find any graphiclibrary for " \
                           "creating plots. Please install either Qwt >= 5.0 " \
                           ",matplotlib >= 1.0 or PyQtGraph >= 0.9.8!"
            self.plot_message = QtGui.QLabel(message_text)
            self.plot_message.setWordWrap(True)
            self.stackedWidget.addWidget(self.plot_message)
            self.pop_messagebar(message_text)

    def change_plot(self):
        if self.stackedWidget.count() > 1:
            if self.plotLibSelector.currentText() == 'Qwt':
                self.stackedWidget.setCurrentIndex(self.qwt_widgetnumber)
                self.toggleInterpolation.setDisabled(True)
                self.toggleInterpolation.setVisible(False)
            elif self.plotLibSelector.currentText() == 'matplotlib':
                self.stackedWidget.setCurrentIndex(self.mpl_widgetnumber)
                self.toggleInterpolation.setEnabled(True)
                self.toggleInterpolation.setVisible(True)
                self.mpl_subplot.clear()
            elif self.plotLibSelector.currentText() == 'PyQtGraph':
                self.stackedWidget.setCurrentIndex(self.pqg_widgetnumber)
                self.toggleInterpolation.setDisabled(True)
                self.toggleInterpolation.setVisible(False)
                self.pqg_plot_widget.clear()
        elif self.stackedWidget.count() == 1:
            self.stackedWidget.setCurrentIndex(0)
        else:
            self.stackedWidget.setCurrentIndex(-1)

    def keyPressEvent(self, e):
        if (e.modifiers() == Qt.ControlModifier
                or e.modifiers() == Qt.MetaModifier) and e.key() == Qt.Key_C:
            items = ''
            for rec in range(self.valueTable.rowCount()):
                items += '"' + self.valueTable.item(
                    rec, 0).text() + '",' + self.valueTable.item(
                        rec, 1).text() + "\n"
            if not items == '':
                clipboard = QApplication.clipboard()
                clipboard.setText(items)
        else:
            QWidget.keyPressEvent(self, e)

    def changeActive(self, active, gui=True):
        self.isActive = active

        if active:
            self.toggleMutant.setCheckState(Qt.Checked)
            QObject.connect(self.canvas, SIGNAL("layersChanged ()"),
                            self.invalidatePlot)
            #QObject.connect(self.canvas,
            #                SIGNAL("layersChanged ()"),
            #                self.catch_errors)
            if not self.plotOnMove.isChecked():
                QObject.connect(self.canvas,
                                SIGNAL("xyCoordinates(const QgsPoint &)"),
                                self.printValue)
        else:
            self.toggleMutant.setCheckState(Qt.Unchecked)
            QObject.disconnect(self.canvas, SIGNAL("layersChanged ()"),
                               self.invalidatePlot)
            QObject.disconnect(self.canvas,
                               SIGNAL("xyCoordinates(const QgsPoint &)"),
                               self.printValue)

        if gui:
            self.tabWidget.setEnabled(active)
            if active:
                self.labelStatus.setText(self.tr("Mutant is enabled!"))
                # FIXME: Only on Options Tab?
                if self.tabWidget.currentIndex() == 2:
                    self.update_layers()
            else:
                self.labelStatus.setText(self.tr(""))
                #use this to clear plot when deactivated
                #self.values=[]
                #self.showValues()

    def activeRasterLayers(self, index=None):
        layers = []
        allLayers = []

        if not index:
            index = self.layerSelection.currentIndex()
        if index == 0:
            allLayers = self.canvas.layers()
        elif index == 1 or index == 3:
            allLayers = self.legend.layers()
        elif index == 2:
            for layer in self.legend.layers():
                if layer.id() in self.layersSelected:
                    allLayers.append(layer)

        for layer in allLayers:

            if index == 3:
                # Check if the layer name matches our filter and skip it if it
                # doesn't
                if not self.name_matches_filter(layer.name()):
                    continue

            if layer is not None and layer.isValid() and \
                    layer.type() == QgsMapLayer.RasterLayer and \
                    layer.dataProvider() and \
                    (layer.dataProvider().capabilities() & QgsRasterDataProvider.IdentifyValue):
                layers.append(layer)

        return layers

    def activeBandsForRaster(self, layer):
        activeBands = []

        if self.bandSelection.currentIndex() == 1 and layer.renderer():
            activeBands = layer.renderer().usesBands()
        elif self.bandSelection.currentIndex() == 2:
            if layer.bandCount() == 1:
                activeBands = [1]
            else:
                activeBands = self.layerBands[layer.id()] if (
                    layer.id() in self.layerBands) else []
        else:
            activeBands = range(1, layer.bandCount() + 1)

        return activeBands

    def printValue(self, position):

        if debug > 0:
            print(position)

        if not position:
            return
        if self.tabWidget.currentIndex() == 2:
            return

        if debug > 0:
            print("%d active rasters, %d canvas layers" %
                  (len(self.activeRasterLayers()), self.canvas.layerCount()))

        layers = self.activeRasterLayers()

        self.labelStatus.setText(
            self.tr('Coordinate:') + ' (%f, %f)' %
            (position.x(), position.y()))

        need_extremum = (self.tabWidget.currentIndex() == 1
                         )  # if plot is shown
        # count the number of required rows and remember the raster layers
        nrow = 0
        rasterlayers = []
        layersWOStatistics = []

        for layer in layers:
            nrow += layer.bandCount()
            rasterlayers.append(layer)

            # check statistics for each band
            if need_extremum:
                for i in range(1, layer.bandCount() + 1):
                    has_stats = self.get_statistics(layer, i) is not None
                    if not layer.id() in self.layerMap and not has_stats \
                            and not layer in layersWOStatistics:
                        layersWOStatistics.append(layer)

        if layersWOStatistics and not self.statsChecked:
            self.calculateStatistics(layersWOStatistics)

        irow = 0
        self.values = []
        self.ymin = 1e38
        self.ymax = -1e38

        mapCanvasSrs = self.iface.mapCanvas().mapRenderer().destinationCrs()

        # TODO - calculate the min/max values only once,
        # instead of every time!!!
        # And keep them in a dict() with key=layer.id()

        counter = 0
        for layer in rasterlayers:
            layer_name = unicode(layer.name())
            layer_srs = layer.crs()

            pos = position

            # if given no position, get dummy values
            if position is None:
                pos = QgsPoint(0, 0)
            # transform points if needed
            elif not mapCanvasSrs == layer_srs and \
                    self.iface.mapCanvas().hasCrsTransformEnabled():
                srsTransform = QgsCoordinateTransform(mapCanvasSrs, layer_srs)
                try:
                    pos = srsTransform.transform(position)
                except QgsCsException, err:
                    # ignore transformation errors
                    continue

            if True:
                if not layer.dataProvider():
                    continue
                ident = None

                if position is not None:
                    canvas = self.iface.mapCanvas()

                    # first test if point is within map layer extent
                    # maintain same behaviour as in 1.8 and print out of extent
                    if not layer.dataProvider().extent().contains(pos):
                        ident = dict()
                        for iband in range(1, layer.bandCount() + 1):
                            ident[iband] = str(self.tr('out of extent'))
                    # we can only use context if layer is not projected
                    elif canvas.hasCrsTransformEnabled() and \
                                    layer.dataProvider().crs() != \
                                    canvas.mapRenderer().destinationCrs():
                        ident = layer.dataProvider().identify(
                            pos, QgsRaster.IdentifyFormatValue).results()
                    else:
                        extent = canvas.extent()
                        width = round(extent.width() /
                                      canvas.mapUnitsPerPixel())
                        height = round(extent.height() /
                                       canvas.mapUnitsPerPixel())
                        extent = canvas.mapRenderer().mapToLayerCoordinates(
                            layer, extent)
                        ident = layer.dataProvider().identify(
                            pos, QgsRaster.IdentifyFormatValue,
                            canvas.extent(), width, height).results()
                    if not len(ident) > 0:
                        continue

                # if given no position, set values to 0
                if position is None and ident is not None and ident.iterkeys(
                ) is not None:
                    for key in ident.iterkeys():
                        ident[key] = layer.dataProvider().noDataValue(key)

                # bands displayed depends on cbxBands (all / active / selected)
                activeBands = self.activeBandsForRaster(layer)

                for iband in activeBands:  # loop over the active bands
                    layer_name_with_band = layer_name
                    if ident is not None and len(ident) > 1:
                        layer_name_with_band += ' ' + layer.bandName(iband)

                    if not ident or not ident.has_key(iband):
                        bandvalue = "?"
                    else:
                        bandvalue = ident[iband]
                        if bandvalue is None:
                            bandvalue = "no data"

                    # different x-Axis depending on if we want to use time or
                    # not
                    if self.mt_enabled:
                        layer_time = self.tracker.get_time_for_layer(layer)

                        if layer_time is None:
                            continue
                        else:
                            # pyqtgraph enabled convert date to epoch
                            graphlib = self.plotLibSelector.currentText()

                            if graphlib == 'PyQtGraph':
                                layer_time = time.mktime(
                                    layer_time.timetuple())
                                # overwrite
                            tup = (layer_name_with_band, layer_time,
                                   str(bandvalue))
                    else:
                        tup = (layer_name_with_band, counter + 1,
                               str(bandvalue))

                    self.values.append(tup)

                    if need_extremum:
                        # estimated statistics
                        stats = self.get_statistics(layer, iband)
                        if stats:
                            self.ymin = min(self.ymin, stats.minimumValue)
                            self.ymax = max(self.ymax, stats.maximumValue)
                    counter += 1

        # Update the ymin, ymax line edits if required
        if self.yAutoCheckBox.isChecked():
            self.leYMin.setText(str(self.ymin))
            self.leYMax.setText(str(self.ymax))

        self.values.sort(key=operator.itemgetter(1))

        if len(self.values) == 0:
            self.labelStatus.setText(self.tr("No valid bands to display"))

        self.showValues(position)
예제 #6
0
class Ui_Monitor(object):
    def setupUi(self, Monitor):
        Monitor.setObjectName(_fromUtf8("Monitor"))
        Monitor.resize(1060, 680)
        self.setrunning(Monitor)
        self.setbutton(Monitor)
        self.setramprate(Monitor)

        # matplotlib canvas
        self._figVI = Figure(facecolor="whitesmoke")
        self.plotVI = FigureCanvas(self._figVI)
        self.plotVI.setGeometry(QtCore.QRect(380, 20, 640, 400))
        self.plotVI.setObjectName(_fromUtf8("VIshow"))
        self.plotVI.setParent(Monitor)

        self._fig_tI = Figure(facecolor="whitesmoke")
        self.plot_tI = FigureCanvas(self._fig_tI)
        self.plot_tI.setGeometry(QtCore.QRect(40, 450, 300, 200))
        self.plot_tI.setObjectName(_fromUtf8("tIshow"))
        self.plot_tI.setParent(Monitor)

        self._fig_tVp = Figure(facecolor="whitesmoke")
        self.plot_tVp = FigureCanvas(self._fig_tVp)
        self.plot_tVp.setGeometry(QtCore.QRect(380, 450, 300, 200))
        self.plot_tVp.setObjectName(_fromUtf8("tVpshow"))
        self.plot_tVp.setParent(Monitor)

        self._fig_tVh = Figure(facecolor="whitesmoke")
        self.plot_tVh = FigureCanvas(self._fig_tVh)
        self.plot_tVh.setGeometry(QtCore.QRect(720, 450, 300, 200))
        self.plot_tVh.setObjectName(_fromUtf8("tVhshow"))
        self.plot_tVh.setParent(Monitor)

        self.retranslateUi(Monitor)
        #QtCore.QObject.connect(self.exit_but, QtCore.SIGNAL(_fromUtf8("clicked()")), Monitor.close)
        QtCore.QMetaObject.connectSlotsByName(Monitor)

    def retranslateUi(self, Monitor):
        Monitor.setWindowTitle(_translate("Monitor", "Form", None))
        self.supply_dis.setText(
            _translate("Dialog", "Current Supply: OFF", None))
        self.I_on_but.setText(_translate("Dialog", "ON", None))
        self.I_up_but.setText(_translate("Dialog", "SET RAMP", None))
        self.I_off_but.setText(_translate("Dialog", "OFF", None))
        self.exit_but.setText(_translate("Dialog", "EXIT", None))
        self.meas_but.setText(_translate("Dialog", "MEASURE", None))
        self.ramp_lab.setText(_translate("Dialog", "Ramp Rate [A/sec]:", None))

    def setrunning(self, mainwin):
        self.supply_dis = QtGui.QLabel(mainwin)
        self.supply_dis.setGeometry(QtCore.QRect(30, 30, 310, 80))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Helvetica"))
        font.setPointSize(28)
        font.setBold(True)
        font.setWeight(75)
        self.supply_dis.setFont(font)
        self.supply_dis.setAlignment(QtCore.Qt.AlignCenter)
        self.supply_dis.setObjectName(_fromUtf8("supply_dis"))

    def setbutton(self, mainwin):
        self.I_on_but = QtGui.QPushButton(mainwin)
        self.I_on_but.setGeometry(QtCore.QRect(90, 200, 200, 40))
        font = QtGui.QFont()
        font.setPointSize(17)
        font.setUnderline(True)
        self.I_on_but.setFont(font)
        self.I_on_but.setAutoFillBackground(False)
        self.I_on_but.setObjectName(_fromUtf8("I_on_but"))
        self.I_up_but = QtGui.QPushButton(mainwin)
        self.I_up_but.setGeometry(QtCore.QRect(90, 250, 200, 40))
        self.I_up_but.setFont(font)
        self.I_up_but.setObjectName(_fromUtf8("I_up_but"))
        self.I_off_but = QtGui.QPushButton(mainwin)
        self.I_off_but.setGeometry(QtCore.QRect(90, 300, 200, 40))
        self.I_off_but.setFont(font)
        self.I_off_but.setObjectName(_fromUtf8("I_off_but"))
        self.meas_but = QtGui.QPushButton(mainwin)
        self.meas_but.setGeometry(QtCore.QRect(90, 360, 200, 40))
        self.meas_but.setFont(font)
        self.meas_but.setObjectName(_fromUtf8("I_off_but"))
        self.exit_but = QtGui.QPushButton(mainwin)
        self.exit_but.setGeometry(QtCore.QRect(90, 410, 200, 40))
        font = QtGui.QFont()
        font.setPointSize(15)
        font.setBold(False)
        font.setItalic(False)
        font.setUnderline(True)
        font.setWeight(50)
        font.setStrikeOut(False)
        font.setKerning(False)
        self.exit_but.setFont(font)
        self.exit_but.setToolTip(_fromUtf8(""))
        self.exit_but.setObjectName(_fromUtf8("exit_but"))

    def setramprate(self, win):
        self.ramp_box = QtGui.QDoubleSpinBox(win)
        self.ramp_box.setEnabled(True)
        self.ramp_box.setGeometry(QtCore.QRect(180, 130, 120, 30))
        self.ramp_box.setProperty("value", 0.1)
        font = QtGui.QFont()
        font.setPointSize(18)
        self.ramp_box.setFont(font)
        self.ramp_box.setAlignment(QtCore.Qt.AlignCenter)
        self.ramp_box.setDecimals(2)
        self.ramp_box.setMaximum(40.0)
        self.ramp_box.setObjectName(_fromUtf8("ramp_box"))
        self.ramp_lab = QtGui.QLabel(win)
        self.ramp_lab.setGeometry(QtCore.QRect(30, 130, 151, 31))
        font = QtGui.QFont()
        font.setPointSize(16)
        self.ramp_lab.setFont(font)
        self.ramp_lab.setObjectName(_fromUtf8("ramp_lab"))
class Ui_MainWindow(object):
    def __init__(self):

        self.ms = 5
        self.lw = 1.1
        self.e_capthick = 1
        self.e_capsize = 5

        # color mode
        self.cted = (0, 0, 1)
        self.ctmd = (1, 0, 0)
        self.ctrd = (0.5, 0.5, 0)
        self.ctid = (0, 0.5, 0.5)
        self.mted = "s"
        self.mtmd = "o"

        # color for occam2d model
        self.ctem = (0, 0.6, 0.3)
        self.ctmm = (0.9, 0, 0.8)
        self.ctrm = (0.9, 0.4, 0.2)
        self.ctim = (0.2, 0.4, 0.9)

        self.mtem = self.mted
        self.mtmm = self.mtmd

        self.res_xx_limits = None
        self.res_xy_limits = None
        self.res_yx_limits = None
        self.res_yy_limits = None

        self.phase_xx_limits = None
        self.phase_xy_limits = None
        self.phase_yx_limits = None
        self.phase_yy_limits = None

        self.subplot_wspace = 0.25
        self.subplot_hspace = 0.0
        self.subplot_right = 0.98
        self.subplot_left = 0.08
        self.subplot_top = 0.90
        self.subplot_bottom = 0.08

        self.legend_loc = "upper center"
        self.legend_pos = (0.5, 1.22)
        self.legend_marker_scale = 1
        self.legend_border_axes_pad = 0.01
        self.legend_label_spacing = 0.07
        self.legend_handle_text_pad = 0.2
        self.legend_border_pad = 0.15

        self.fs = 11

        self.plot_component = 4
        self.plot_tipper = True
        self.plot_z = True
        self.ylabel_pad = 1.25
        self.station = None

        self.modem_data = None
        self.modem_resp = None
        self.dirpath = os.getcwd()

    def setupUi(self, MainWindow):
        MainWindow.setWindowTitle("Plot ModEM MT Response")
        MainWindow.resize(1920, 1080)

        # make a central widget that everything is tied to.
        self.central_widget = QtGui.QWidget(MainWindow)
        self.central_widget.setWindowTitle("Plot MT Response")

        # make a widget that will be the station list
        self.list_widget = QtGui.QListWidget()
        self.list_widget.itemClicked.connect(self.get_station)
        self.list_widget.setMaximumWidth(150)

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.figure = Figure(dpi=150)
        self.mpl_widget = FigureCanvas(self.figure)

        # make sure the figure takes up the entire plottable space
        self.mpl_widget.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.mpl_toolbar = NavigationToolbar(self.mpl_widget, MainWindow)

        # set the layout for the plot
        mpl_vbox = QtGui.QVBoxLayout()
        mpl_vbox.addWidget(self.mpl_toolbar)
        mpl_vbox.addWidget(self.mpl_widget)

        # set the layout the main window
        layout = QtGui.QHBoxLayout()
        layout.addWidget(self.list_widget)
        layout.addLayout(mpl_vbox)
        self.central_widget.setLayout(layout)

        # set the geometry of each widget
        self.list_widget.setObjectName(_fromUtf8("listWidget"))
        self.mpl_widget.setObjectName(_fromUtf8("mpl_widget"))
        self.mpl_widget.updateGeometry()

        # set the central widget
        MainWindow.setCentralWidget(self.central_widget)

        # create a menu bar on the window
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1920, 38))
        self.menubar.setObjectName(_fromUtf8("menubar"))

        # add a tab for File --> open, close, save
        self.menuFile = QtGui.QMenu(self.menubar)
        self.menuFile.setTitle("Data File")

        self.menuModelFile = QtGui.QMenu(self.menubar)
        self.menuModelFile.setTitle("Response File")

        # add a tab for chaning the display
        self.menuDisplay = QtGui.QMenu(self.menubar)
        self.menuDisplay.setTitle("Display")

        MainWindow.setMenuBar(self.menubar)

        # add a status bar on the bottom of the main window
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))

        MainWindow.setStatusBar(self.statusbar)

        # set an open option that on click opens a modem file
        self.actionOpen = QtGui.QAction(MainWindow)
        self.actionOpen.setText("Open")
        self.actionOpen.triggered.connect(self.get_filename)

        # set a close that closes the main window
        self.actionClose = QtGui.QAction(MainWindow)
        self.actionClose.setText("Close")
        self.actionClose.triggered.connect(MainWindow.close)

        # set a save option that will eventually save the masked data
        self.actionSave = QtGui.QAction(MainWindow)
        self.actionSave.setText("Save")

        # add the action on the menu tab
        self.menuFile.addAction(self.actionOpen)
        self.menuFile.addAction(self.actionClose)
        self.menuFile.addAction(self.actionSave)
        self.menubar.addAction(self.menuFile.menuAction())

        self.actionModelOpen = QtGui.QAction(MainWindow)
        self.actionModelOpen.setText("Open")
        self.actionModelOpen.triggered.connect(self.get_resp_fn)
        self.menuModelFile.addAction(self.actionModelOpen)
        self.menubar.addAction(self.menuModelFile.menuAction())
        #
        # adding options for display plot type
        self.menu_plot_type = QtGui.QMenu(MainWindow)
        self.menu_plot_type.setTitle("Plot Type")
        self.menuDisplay.addMenu(self.menu_plot_type)
        self.menubar.addAction(self.menuDisplay.menuAction())

        # set plot impedance or resistivity and phase
        self.action_plot_z = QtGui.QAction(MainWindow)
        self.action_plot_z.setText("Impedance")
        self.action_plot_z.setCheckable(True)
        self.menu_plot_type.addAction(self.action_plot_z)
        self.action_plot_z.toggled.connect(self.status_checked_ptz)

        self.action_plot_rp = QtGui.QAction(MainWindow)
        self.action_plot_rp.setText("Resistivity-Phase")
        self.action_plot_rp.setCheckable(True)
        self.menu_plot_type.addAction(self.action_plot_rp)
        self.action_plot_rp.toggled.connect(self.status_checked_ptrp)

        self.action_plot_settings = QtGui.QAction(MainWindow)
        self.action_plot_settings.setText("Settings")
        self.action_plot_settings.triggered.connect(self.show_settings)
        self.menuDisplay.addAction(self.action_plot_settings)
        self.menubar.addAction(self.menuDisplay.menuAction())

        #        self.menuDisplay.addAction(self.menu_plot_style.menuAction())
        self.menuDisplay.addAction(self.menu_plot_type.menuAction())

        # self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def status_checked_ptz(self, toggled):
        """
        be sure that only one plot style is checked
        """

        self.plot_z = toggled
        if toggled == True:
            untoggled = False
        elif toggled == False:
            untoggled = True

        self.action_plot_z.setChecked(toggled)
        self.action_plot_rp.setChecked(untoggled)

        self.plot()

    def status_checked_ptrp(self, toggled):
        """
        be sure that only one plot style is checked
        """

        if toggled == True:
            untoggled = False
            self.plot_z = False
        elif toggled == False:
            untoggled = True
            self.plot_z = True

        self.action_plot_z.setChecked(untoggled)
        self.action_plot_rp.setChecked(toggled)

        self.plot()

    def get_filename(self):
        """
        get the filename from a file dialogue
        
        """

        fn_dialog = QtGui.QFileDialog()
        fn = str(fn_dialog.getOpenFileName(caption="Choose ModEM data file", filter="(*.dat);; (*.data)"))

        self.modem_data = modem.Data()
        self.modem_data.read_data_file(fn)

        self.dirpath = os.path.dirname(fn)

        print self.dirpath

        station_list = sorted(self.modem_data.mt_dict.keys())

        self.list_widget.clear()

        # this will add the station name for each station to the qwidget list
        for station in station_list:
            self.list_widget.addItem(station)

        self.station = str(station_list[0])
        self.plot()

    def get_station(self, widget_item):
        """
        get the station name from the clicked station 
        """
        self.station = str(widget_item.text())
        self.plot()

    def get_resp_fn(self):
        """
        get response file name
        """
        print self.dirpath
        fn_dialog = QtGui.QFileDialog(directory=self.dirpath)
        fn = str(fn_dialog.getOpenFileName(caption="Choose ModEM response file", filter="*.dat"))

        if fn is None:
            return

        self.modem_resp = modem.Data()
        self.modem_resp.read_data_file(fn)
        self.plot()

    def show_settings(self):

        self.settings_window = PlotSettings(None, **self.__dict__)
        self.settings_window.show()
        self.settings_window.settings_updated.connect(self.update_settings)

    def update_settings(self):

        for attr in sorted(self.settings_window.__dict__.keys()):
            setattr(self, attr, self.settings_window.__dict__[attr])

        self.plot()

    def plot(self):
        """
        plot the data
        """

        if self.station is None:
            return

        z_obj = self.modem_data.mt_dict[self.station].Z
        t_obj = self.modem_data.mt_dict[self.station].Tipper
        period = self.modem_data.period_list

        plt.rcParams["font.size"] = self.fs

        fontdict = {"size": self.fs + 2, "weight": "bold"}

        # --> make key word dictionaries for plotting
        kw_xx = {
            "color": self.cted,
            "marker": self.mted,
            "ms": self.ms,
            "ls": ":",
            "lw": self.lw,
            "e_capsize": self.e_capsize,
            "e_capthick": self.e_capthick,
        }

        kw_yy = {
            "color": self.ctmd,
            "marker": self.mtmd,
            "ms": self.ms,
            "ls": ":",
            "lw": self.lw,
            "e_capsize": self.e_capsize,
            "e_capthick": self.e_capthick,
        }

        kw_tr = {
            "color": self.ctrd,
            "marker": self.mtmd,
            "ms": self.ms,
            "ls": ":",
            "lw": self.lw,
            "e_capsize": self.e_capsize,
            "e_capthick": self.e_capthick,
        }

        kw_ti = {
            "color": self.ctid,
            "marker": self.mtmd,
            "ms": self.ms,
            "ls": ":",
            "lw": self.lw,
            "e_capsize": self.e_capsize,
            "e_capthick": self.e_capthick,
        }

        # convert to apparent resistivity and phase
        rp = mtplottools.ResPhase(z_object=z_obj)

        # find locations where points have been masked
        nzxx = np.nonzero(z_obj.z[:, 0, 0])[0]
        nzxy = np.nonzero(z_obj.z[:, 0, 1])[0]
        nzyx = np.nonzero(z_obj.z[:, 1, 0])[0]
        nzyy = np.nonzero(z_obj.z[:, 1, 1])[0]
        ntx = np.nonzero(t_obj.tipper[:, 0, 0])[0]
        nty = np.nonzero(t_obj.tipper[:, 0, 1])[0]

        self.figure.clf()
        self.figure.suptitle(str(self.station), fontdict=fontdict)

        # set the grid of subplots
        gs = gridspec.GridSpec(
            3,
            2,
            wspace=self.subplot_wspace,
            left=self.subplot_left,
            top=self.subplot_top,
            bottom=self.subplot_bottom,
            right=self.subplot_right,
            hspace=self.subplot_hspace,
            height_ratios=[1, 1, 0.4],
        )

        # od for off diagonal components, d for diagonal
        axrod = self.figure.add_subplot(gs[0, 0])
        axrd = self.figure.add_subplot(gs[0, 1], sharex=axrod)

        axpod = self.figure.add_subplot(gs[1, 0])
        axpd = self.figure.add_subplot(gs[1, 1], sharex=axrod)

        axtx = self.figure.add_subplot(gs[2, 0], sharex=axrod)
        axty = self.figure.add_subplot(gs[2, 1], sharex=axrod)

        if self.plot_z == False:
            # plot resistivity
            erxx = mtplottools.plot_errorbar(axrd, period[nzxx], rp.resxx[nzxx], rp.resxx_err[nzxx], **kw_xx)
            erxy = mtplottools.plot_errorbar(axrod, period[nzxy], rp.resxy[nzxy], rp.resxy_err[nzxy], **kw_xx)
            eryx = mtplottools.plot_errorbar(axrod, period[nzyx], rp.resyx[nzyx], rp.resyx_err[nzyx], **kw_yy)
            eryy = mtplottools.plot_errorbar(axrd, period[nzyy], rp.resyy[nzyy], rp.resyy_err[nzyy], **kw_yy)
            # plot phase
            erxx = mtplottools.plot_errorbar(axpd, period[nzxx], rp.phasexx[nzxx], rp.phasexx_err[nzxx], **kw_xx)
            erxy = mtplottools.plot_errorbar(axpod, period[nzxy], rp.phasexy[nzxy], rp.phasexy_err[nzxy], **kw_xx)
            eryx = mtplottools.plot_errorbar(axpod, period[nzyx], rp.phaseyx[nzyx], rp.phaseyx_err[nzyx], **kw_yy)
            eryy = mtplottools.plot_errorbar(axpd, period[nzyy], rp.phaseyy[nzyy], rp.phaseyy_err[nzyy], **kw_yy)
        elif self.plot_z == True:
            # plot real
            erxx = mtplottools.plot_errorbar(
                axrd, period[nzxx], z_obj.z[nzxx, 0, 0].real, z_obj.z_err[nzxx, 0, 0].real, **kw_xx
            )
            erxy = mtplottools.plot_errorbar(
                axrod, period[nzxy], z_obj.z[nzxy, 0, 1].real, z_obj.z_err[nzxy, 0, 1].real, **kw_xx
            )
            eryx = mtplottools.plot_errorbar(
                axrod, period[nzyx], z_obj.z[nzyx, 1, 0].real, z_obj.z_err[nzyx, 1, 0].real, **kw_yy
            )
            eryy = mtplottools.plot_errorbar(
                axrd, period[nzyy], z_obj.z[nzyy, 1, 1].real, z_obj.z_err[nzyy, 1, 1].real, **kw_yy
            )
            # plot phase
            erxx = mtplottools.plot_errorbar(
                axpd, period[nzxx], z_obj.z[nzxx, 0, 0].imag, z_obj.z_err[nzxx, 0, 0].real, **kw_xx
            )
            erxy = mtplottools.plot_errorbar(
                axpod, period[nzxy], z_obj.z[nzxy, 0, 1].imag, z_obj.z_err[nzxy, 0, 1].real, **kw_xx
            )
            eryx = mtplottools.plot_errorbar(
                axpod, period[nzyx], z_obj.z[nzyx, 1, 0].imag, z_obj.z_err[nzyx, 1, 0].real, **kw_yy
            )
            eryy = mtplottools.plot_errorbar(
                axpd, period[nzyy], z_obj.z[nzyy, 1, 1].imag, z_obj.z_err[nzyy, 1, 1].real, **kw_yy
            )

        # plot tipper
        ertxr = mtplottools.plot_errorbar(
            axtx, period[ntx], t_obj.tipper[ntx, 0, 0].real, t_obj.tipper_err[ntx, 0, 0], **kw_tr
        )
        ertxi = mtplottools.plot_errorbar(
            axtx, period[ntx], t_obj.tipper[ntx, 0, 0].imag, t_obj.tipper_err[ntx, 0, 1], **kw_ti
        )
        ertyr = mtplottools.plot_errorbar(
            axty, period[nty], t_obj.tipper[nty, 0, 1].real, t_obj.tipper_err[nty, 0, 0], **kw_tr
        )

        ertyi = mtplottools.plot_errorbar(
            axty, period[nty], t_obj.tipper[nty, 0, 1].imag, t_obj.tipper_err[nty, 0, 1], **kw_ti
        )
        ax_list = [axrod, axrd, axpod, axpd, axtx, axty]

        od_line_list = [erxy[0], eryx[0], ertxr[0], ertxi[0]]
        d_line_list = [erxx[0], eryy[0], ertyr[0], ertyi[0]]

        od_label_list = ["$Z_{xy}$", "$Z_{yx}$", "Re{$T_{x}$}", "Im{$T_{x}$}"]
        d_label_list = ["$Z_{xx}$", "$Z_{yy}$", "Re{$T_{y}$}", "Im{$T_{y}$}"]

        # --> set limits if input
        if self.res_xx_limits is not None:
            axrd.set_ylim(self.res_xx_limits)
        if self.res_xy_limits is not None:
            axrod.set_ylim(self.res_xy_limits)

        if self.phase_xx_limits is not None:
            axpd.set_ylim(self.phase_xx_limits)
        if self.phase_xy_limits is not None:
            axpod.set_ylim(self.phase_xy_limits)

        #        axtx.set_ylim((-1.1, 1.1))
        #        axty.set_ylim((-1.1, 1.1))

        # set axis properties
        for aa, ax in enumerate(ax_list):
            ax.tick_params(axis="y", pad=self.ylabel_pad)
            ylabels = ax.get_yticks().tolist()
            if aa == 2 or aa == 3 or aa == 4 or aa == 5:
                ylabels[-1] = ""
                ylabels[0] = ""
                ax.set_yticklabels(ylabels)

            if aa < 2:
                if self.plot_z == False:
                    ax.set_yscale("log")

            if aa < 4:
                plt.setp(ax.get_xticklabels(), visible=False)

            else:
                ax.set_xlabel("Period (s)", fontdict=fontdict)

            # set axes labels
            if aa == 0:
                if self.plot_z == False:
                    ax.set_ylabel("App. Res. ($\mathbf{\Omega \cdot m}$)", fontdict=fontdict)
                elif self.plot_z == True:
                    ax.set_ylabel("Re[Z (mV/km nT)]", fontdict=fontdict)

                ax.legend(
                    od_line_list,
                    od_label_list,
                    loc=self.legend_loc,
                    ncol=2,
                    bbox_to_anchor=self.legend_pos,
                    markerscale=self.legend_marker_scale,
                    borderaxespad=self.legend_border_axes_pad,
                    labelspacing=self.legend_label_spacing,
                    handletextpad=self.legend_handle_text_pad,
                    borderpad=self.legend_border_pad,
                    prop={"size": max([self.fs - 1, 5])},
                )

            elif aa == 1:
                ax.legend(
                    d_line_list,
                    d_label_list,
                    loc=self.legend_loc,
                    ncol=2,
                    bbox_to_anchor=self.legend_pos,
                    markerscale=self.legend_marker_scale,
                    borderaxespad=self.legend_border_axes_pad,
                    labelspacing=self.legend_label_spacing,
                    handletextpad=self.legend_handle_text_pad,
                    borderpad=self.legend_border_pad,
                    prop={"size": max([self.fs - 1, 5])},
                )
            elif aa == 2:
                if self.plot_z == False:
                    ax.set_ylabel("Phase (deg)", fontdict=fontdict)
                elif self.plot_z == True:
                    ax.set_ylabel("Im[Z (mV/km nT)]", fontdict=fontdict)

            elif aa == 4:
                ax.set_ylabel(r"W$_x$", fontdict=fontdict)

            elif aa == 5:
                ax.set_ylabel(r"W$_y$", fontdict=fontdict)

            ax.set_xscale("log")
            ax.set_xlim(
                xmin=10 ** (np.floor(np.log10(period[0]))) * 1.01, xmax=10 ** (np.ceil(np.log10(period[-1]))) * 0.99
            )
            ax.grid(True, alpha=0.25)

        # plot model response
        if self.modem_resp is not None:
            resp_z_obj = self.modem_resp.mt_dict[self.station].Z
            resp_z_err = np.nan_to_num((z_obj.z - resp_z_obj.z) / z_obj.z_err)

            resp_t_obj = self.modem_resp.mt_dict[self.station].Tipper

            rrp = mtplottools.ResPhase(resp_z_obj)

            rms = resp_z_err.std()
            rms_xx = resp_z_err[:, 0, 0].std()
            rms_xy = resp_z_err[:, 0, 1].std()
            rms_yx = resp_z_err[:, 1, 0].std()
            rms_yy = resp_z_err[:, 1, 1].std()

            # --> make key word dictionaries for plotting
            kw_xx = {
                "color": self.ctem,
                "marker": self.mtem,
                "ms": self.ms,
                "ls": ":",
                "lw": self.lw,
                "e_capsize": self.e_capsize,
                "e_capthick": self.e_capthick,
            }

            kw_yy = {
                "color": self.ctmm,
                "marker": self.mtmm,
                "ms": self.ms,
                "ls": ":",
                "lw": self.lw,
                "e_capsize": self.e_capsize,
                "e_capthick": self.e_capthick,
            }

            kw_tr = {
                "color": self.ctrm,
                "marker": self.mtmd,
                "ms": self.ms,
                "ls": ":",
                "lw": self.lw,
                "e_capsize": self.e_capsize,
                "e_capthick": self.e_capthick,
            }

            kw_ti = {
                "color": self.ctim,
                "marker": self.mtmd,
                "ms": self.ms,
                "ls": ":",
                "lw": self.lw,
                "e_capsize": self.e_capsize,
                "e_capthick": self.e_capthick,
            }

            if self.plot_z == False:
                # plot resistivity
                rerxx = mtplottools.plot_errorbar(axrd, period[nzxx], rrp.resxx[nzxx], **kw_xx)
                rerxy = mtplottools.plot_errorbar(axrod, period[nzxy], rrp.resxy[nzxy], **kw_xx)
                reryx = mtplottools.plot_errorbar(axrod, period[nzyx], rrp.resyx[nzyx], **kw_yy)
                reryy = mtplottools.plot_errorbar(axrd, period[nzyy], rrp.resyy[nzyy], **kw_yy)
                # plot phase
                rerxx = mtplottools.plot_errorbar(axpd, period[nzxx], rrp.phasexx[nzxx], **kw_xx)
                rerxy = mtplottools.plot_errorbar(axpod, period[nzxy], rrp.phasexy[nzxy], **kw_xx)
                reryx = mtplottools.plot_errorbar(axpod, period[nzyx], rrp.phaseyx[nzyx], **kw_yy)
                reryy = mtplottools.plot_errorbar(axpd, period[nzyy], rrp.phaseyy[nzyy], **kw_yy)
            elif self.plot_z == True:
                # plot real
                rerxx = mtplottools.plot_errorbar(axrd, period[nzxx], resp_z_obj.z[nzxx, 0, 0].real, **kw_xx)
                rerxy = mtplottools.plot_errorbar(axrod, period[nzxy], resp_z_obj.z[nzxy, 0, 1].real, **kw_xx)
                reryx = mtplottools.plot_errorbar(axrod, period[nzyx], resp_z_obj.z[nzyx, 1, 0].real, **kw_yy)
                reryy = mtplottools.plot_errorbar(axrd, period[nzyy], resp_z_obj.z[nzyy, 1, 1].real, **kw_yy)
                # plot phase
                rerxx = mtplottools.plot_errorbar(axpd, period[nzxx], resp_z_obj.z[nzxx, 0, 0].imag, **kw_xx)
                rerxy = mtplottools.plot_errorbar(axpod, period[nzxy], resp_z_obj.z[nzxy, 0, 1].imag, **kw_xx)
                reryx = mtplottools.plot_errorbar(axpod, period[nzyx], resp_z_obj.z[nzyx, 1, 0].imag, **kw_yy)
                reryy = mtplottools.plot_errorbar(axpd, period[nzyy], resp_z_obj.z[nzyy, 1, 1].imag, **kw_yy)

            rertx = mtplottools.plot_errorbar(axtx, period[ntx], resp_t_obj.tipper[ntx, 0, 0].real, **kw_tr)
            rerty = mtplottools.plot_errorbar(axtx, period[ntx], resp_t_obj.tipper[ntx, 0, 1].imag, **kw_ti)

            rertx = mtplottools.plot_errorbar(axty, period[nty], resp_t_obj.tipper[nty, 0, 0].real, **kw_tr)
            rerty = mtplottools.plot_errorbar(axty, period[nty], resp_t_obj.tipper[nty, 0, 1].imag, **kw_ti)

            # add laines and labels
            od_line_list += [rerxy[0], reryx[0], rertx[0], rerty[0]]
            d_line_list += [rerxx[0], reryy[0], rertx[0], rerty[0]]

            od_label_list += [
                "$Z^m_{xy}$" + "rms={0:.2f}".format(rms_xy),
                "$Z^m_{yx}$" + "rms={0:.2f}".format(rms_yx),
                "Re{$T^m_{x}$}",
                "Im{$T^m_{x}$}",
            ]
            d_label_list += [
                "$Z^m_{xx}$" + "rms={0:.2f}".format(rms_xx),
                "$Z^m_{yy}$" + "rms={0:.2f}".format(rms_yy),
                "Re{$T^m_{x}$}",
                "Im{$T^m_{x}$}",
            ]

            legend_ax_list = [axrod, axrd]
            od_label_list = od_label_list[0:2] + od_label_list[4:6] + od_label_list[2:4] + od_label_list[6:8]
            d_label_list = d_label_list[0:2] + d_label_list[4:6] + d_label_list[2:4] + d_label_list[6:8]

            od_line_list = od_line_list[0:2] + od_line_list[4:6] + od_line_list[2:4] + od_line_list[6:8]
            d_line_list = d_line_list[0:2] + d_line_list[4:6] + d_line_list[2:4] + d_line_list[6:8]

            legend_ll = [od_line_list, d_line_list]
            legend_tl = [od_label_list, d_label_list]

            for ax, ll, tl in zip(legend_ax_list, legend_ll, legend_tl):
                ax.legend(
                    ll,
                    tl,
                    loc=self.legend_loc,
                    ncol=4,
                    bbox_to_anchor=self.legend_pos,
                    markerscale=self.legend_marker_scale,
                    borderaxespad=self.legend_border_axes_pad,
                    labelspacing=self.legend_label_spacing,
                    handletextpad=self.legend_handle_text_pad,
                    borderpad=self.legend_border_pad,
                    prop={"size": max([self.fs - 1, 5])},
                )

        self.mpl_widget.draw()
예제 #8
0
class ValueWidget(QWidget, Ui_Widget):

    def __init__(self, iface):

        self.hasqwt=hasqwt
        self.hasmpl=hasmpl
        self.layerMap=dict()
        self.statsChecked=False
        self.ymin=0
        self.ymax=250
        self.isActive=False

        # Statistics (>=1.9)
        self.statsSampleSize = 2500000
        self.stats = {} # stats per layer

        self.layersSelected=[]
        self.layerBands=dict()

        self.iface=iface
        self.canvas=self.iface.mapCanvas
        self.legend=self.iface.legendInterface()
        self.logger = logging.getLogger('.'.join((__name__, 
                                        self.__class__.__name__)))

        QWidget.__init__(self)
        self.setupUi(self)
        self.tabWidget.setEnabled(False)
        self.cbxClick.setChecked( QSettings().value('plugins/valuetool/mouseClick', False, type=bool ) )

        #self.setupUi_plot()
        #don't setup plot until Plot tab is clicked - workaround for bug #7450
        #qgis will still crash in some cases, but at least the tool can be used in Table mode
        self.qwtPlot = None
        self.mplPlot = None
        self.mplLine = None

        QObject.connect(self.plotSelector, SIGNAL( "currentIndexChanged ( int )" ), self.changePlot )
        QObject.connect(self.tabWidget, SIGNAL( "currentChanged ( int )" ), self.tabWidgetChanged )
        QObject.connect(self.cbxLayers, SIGNAL( "currentIndexChanged ( int )" ), self.updateLayers )
        QObject.connect(self.cbxBands, SIGNAL( "currentIndexChanged ( int )" ), self.updateLayers )
        QObject.connect(self.tableWidget2, SIGNAL("cellChanged ( int , int )"), self.layerSelected)

    def setupUi_plot(self):

        # plot
        self.plotSelector.setVisible( False )
        self.cbxStats.setVisible( False )
        # stats by default because estimated are fast
        self.cbxStats.setChecked( True )
        self.plotSelector.addItem( 'Qwt' )
        self.plotSelector.addItem( 'mpl' )

        # Page 2 - qwt
        if self.hasqwt:
            self.qwtPlot = QwtPlot(self.stackedWidget)
            self.qwtPlot.setAutoFillBackground(False)
            self.qwtPlot.setObjectName("qwtPlot")
            self.curve = QwtPlotCurve()
            self.curve.setSymbol(
                QwtSymbol(QwtSymbol.Ellipse,
                          QBrush(Qt.white),
                          QPen(Qt.red, 2),
                          QSize(9, 9)))
            self.curve.attach(self.qwtPlot)
        else:
            self.qwtPlot = QtGui.QLabel("Need Qwt >= 5.0 or matplotlib >= 1.0 !")

        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.qwtPlot.sizePolicy().hasHeightForWidth())
        self.qwtPlot.setSizePolicy(sizePolicy)
        self.qwtPlot.updateGeometry()
        self.stackedWidget.addWidget(self.qwtPlot)

        #Page 3 - matplotlib
        self.mplLine = None #make sure to invalidate when layers change
        if self.hasmpl:
            # mpl stuff
            # should make figure light gray
            self.mplBackground = None #http://www.scipy.org/Cookbook/Matplotlib/Animations
            self.mplFig = plt.Figure(facecolor='w', edgecolor='w')
            self.mplFig.subplots_adjust(left=0.1, right=0.975, bottom=0.13, top=0.95)
            self.mplPlt = self.mplFig.add_subplot(111)   
            self.mplPlt.tick_params(axis='both', which='major', labelsize=12)
            self.mplPlt.tick_params(axis='both', which='minor', labelsize=10)                           
            # qt stuff
            self.pltCanvas = FigureCanvasQTAgg(self.mplFig)
            self.pltCanvas.setParent(self.stackedWidget)
            self.pltCanvas.setAutoFillBackground(False)
            self.pltCanvas.setObjectName("mplPlot")
            self.mplPlot = self.pltCanvas
        else:
            self.mplPlot = QtGui.QLabel("Need Qwt >= 5.0 or matplotlib >= 1.0 !")

        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.mplPlot.sizePolicy().hasHeightForWidth())
        self.mplPlot.setSizePolicy(sizePolicy)
        self.mplPlot.updateGeometry()
        self.stackedWidget.addWidget(self.mplPlot)

        if (self.hasqwt and self.hasmpl):
            self.plotSelector.setEnabled(True)
            self.plotSelector.setVisible(True)
            self.plotSelector.setCurrentIndex(0);
        else:
            if self.hasqwt:
                self.plotSelector.setCurrentIndex(0);
            else:
                self.plotSelector.setCurrentIndex(1);
        self.changePlot()

    def keyPressEvent( self, e ):
      if ( e.modifiers() == Qt.ControlModifier or e.modifiers() == Qt.MetaModifier ) and e.key() == Qt.Key_C:
        items = ''
        for rec in range( self.tableWidget.rowCount() ):
          items += '"' + self.tableWidget.item( rec, 0 ).text() + '",' + self.tableWidget.item( rec, 1 ).text() + "\n"
        if not items == '':
          clipboard = QApplication.clipboard()
          clipboard.setText( items )
      else:
        QWidget.keyPressEvent( self, e )

    def changePlot(self):
        if (self.plotSelector.currentText()=='mpl'):
            self.stackedWidget.setCurrentIndex(1)
        else:
            self.stackedWidget.setCurrentIndex(0)

    def changeActive(self,active,gui=True):
        self.isActive=active
        
        if (active):
            self.cbxEnable.setCheckState(Qt.Checked)
            QObject.connect(self.canvas, SIGNAL( "layersChanged ()" ), self.invalidatePlot )
            if not self.cbxClick.isChecked():
                QObject.connect(self.canvas, SIGNAL("xyCoordinates(const QgsPoint &)"), self.printValue)
        else:
            self.cbxEnable.setCheckState(Qt.Unchecked)
            QObject.disconnect(self.canvas, SIGNAL( "layersChanged ()" ), self.invalidatePlot )
            QObject.disconnect(self.canvas, SIGNAL("xyCoordinates(const QgsPoint &)"), self.printValue)

        if gui:
            self.tabWidget.setEnabled(active)
            if active:
                self.labelStatus.setText(self.tr("Value tool is enabled"))
                if self.tabWidget.currentIndex()==2:
                    self.updateLayers()
            else:
                self.labelStatus.setText(self.tr(""))
                #use this to clear plot when deactivated
                #self.values=[]
                #self.showValues()

    def activeRasterLayers(self, index=None):
        layers=[]
        allLayers=[]

        if not index: 
            index=self.cbxLayers.currentIndex()
        if index == 0:
            allLayers=self.canvas.layers()
        elif index == 1:
            allLayers=self.legend.getLayers()
        elif index == 2:
            for layer in self.legend.getLayers():
                if layer.id() in self.layersSelected:
                    allLayers.append(layer)
        
        for layer in allLayers:
            if layer!=None and layer.isValid() and \
                    layer.type()==QgsMapLayer.RasterLayer and \
                    layer.dataProvider() and \
                    (layer.dataProvider().capabilities() & QgsRasterDataProvider.IdentifyValue):
                  layers.append(layer)

        return layers

    def activeBandsForRaster(self,layer):
        activeBands=[]

        if self.cbxBands.currentIndex() == 1 and layer.renderer():
            activeBands = layer.renderer().usesBands()                 
        elif self.cbxBands.currentIndex() == 2:
            if layer.bandCount()==1:
                activeBands=[1]
            else:
                activeBands = self.layerBands[layer.id()] if (layer.id() in self.layerBands) else []
        else:
            activeBands = range(1,layer.bandCount()+1)
        
        return activeBands

    def printValue(self,position):

        if debug > 0:
            print(position)

        if not position:
            return
        if self.tabWidget.currentIndex()==2:
            return

        if debug > 0:
            print("%d active rasters, %d canvas layers" %(len(self.activeRasterLayers()),self.canvas.layerCount()))
        layers = self.activeRasterLayers()
        if len(layers) == 0:
            if self.canvas.layerCount() > 0:
                self.labelStatus.setText(self.tr("No valid layers to display - change layers in options"))
            else:
                self.labelStatus.setText(self.tr("No valid layers to display"))
            self.values=[]         
            self.showValues()
            return
        
        self.labelStatus.setText(self.tr('Coordinate:') + ' (%f, %f)' % (position.x(), position.y()))

        needextremum = (self.tabWidget.currentIndex()==1) # if plot is shown

        # count the number of requires rows and remember the raster layers
        nrow=0
        rasterlayers=[]
        layersWOStatistics=[]

        for layer in layers:

            nrow+=layer.bandCount()
            rasterlayers.append(layer)

            # check statistics for each band
            if needextremum:
                for i in range( 1,layer.bandCount()+1 ):
                    has_stats = self.getStats ( layer, i ) is not None
                    if not layer.id() in self.layerMap and not has_stats\
                            and not layer in layersWOStatistics:
                        layersWOStatistics.append(layer)

        if layersWOStatistics and not self.statsChecked:
          self.calculateStatistics(layersWOStatistics)
                  
        irow=0
        self.values=[]
        self.ymin=1e38
        self.ymax=-1e38

        mapCanvasSrs = self.iface.mapCanvas.mapRenderer().destinationCrs()

        # TODO - calculate the min/max values only once, instead of every time!!!
        # keep them in a dict() with key=layer.id()
        
        
        #pull out wavelength if it exists in metadata
        #piece to pull out wavelength information if present in metadata
        rasterMeta=rasterlayers[0].metadata()
        self.wavelengths={}
        self.wavelength_units=''
        if('wavelength' in rasterMeta):
            mdSplit=rasterMeta.split('</p>')
            for d in mdSplit:
                if ('Band_' in d and 'glossy' not in d and '=' in d):
                    variableName,valueWavelength=d.split('=')
                    bandNumber=int(variableName.split('_')[1])
                    self.wavelengths[bandNumber]=float(valueWavelength.split(' ')[-2].replace('(',''))
                elif('wavelength_units' in d):
                    variableName,v=d.split('=')
                    self.wavelength_units=v    
         ####         
        for layer in rasterlayers:
            
            layername=unicode(layer.name())
            layerSrs = layer.crs()

            pos = position         

            # if given no position, get dummy values
            if position is None:
                pos = QgsPoint(0,0)
            # transform points if needed
            elif not mapCanvasSrs == layerSrs and self.iface.mapCanvas.hasCrsTransformEnabled():
              srsTransform = QgsCoordinateTransform(mapCanvasSrs, layerSrs)
              try:
                pos = srsTransform.transform(position)
              except QgsCsException, err:
                # ignore transformation errors
                continue

            if True: # for QGIS >= 1.9
              if not layer.dataProvider():
                continue

              ident = None
              if position is not None:
                canvas = self.iface.mapCanvas
                # first test if point is within map layer extent 
                # maintain same behaviour as in 1.8 and print out of extent
                if not layer.dataProvider().extent().contains( pos ):
                  ident = dict()
                  for iband in range(1,layer.bandCount()+1):
                    ident[iband] = QVariant(self.tr('out of extent'))
                # we can only use context if layer is not projected
                elif canvas.hasCrsTransformEnabled() and layer.dataProvider().crs() != canvas.mapRenderer().destinationCrs():
                  ident = layer.dataProvider().identify(pos, QgsRaster.IdentifyFormatValue ).results()
                else:
                  extent = canvas.extent()
                  width = round(extent.width() / canvas.mapUnitsPerPixel());
                  height = round(extent.height() / canvas.mapUnitsPerPixel());

                  extent = canvas.mapRenderer().mapToLayerCoordinates( layer, extent );

                  ident = layer.dataProvider().identify(pos, QgsRaster.IdentifyFormatValue, canvas.extent(), width, height ).results()
                if not len( ident ) > 0:
                    continue

              # if given no position, set values to 0
              if position is None and ident is not None and ident.iterkeys() is not None:
                  for key in ident.iterkeys():
                      ident[key] = layer.dataProvider().noDataValue(key)

              # bands displayed depends on cbxBands (all / active / selected)
              activeBands = self.activeBandsForRaster(layer) 
                  
              for iband in activeBands: # loop over the active bands
                layernamewithband=layername
                if ident is not None and len(ident)>1:
                    layernamewithband+=' '+layer.bandName(iband)

                if not ident or not ident.has_key( iband ): # should not happen
                  bandvalue = "?"
                else:
                  bandvalue = ident[iband].toString()
                  if bandvalue is None:
                      bandvalue = "no data"
             
                self.values.append((layernamewithband,str(bandvalue)))

                if needextremum:
                  # estimated statistics
                  stats = self.getStats ( layer, iband )
                  if stats:
                    self.ymin=min(self.ymin,stats.minimumValue)
                    self.ymax=max(self.ymax,stats.maximumValue)

        if len(self.values) == 0:
            self.labelStatus.setText(self.tr("No valid bands to display"))

        self.showValues()
예제 #9
0
파일: GUI.py 프로젝트: jcemelanda/PyGPA
class ui_janela_principal(object):
    '''
    class ui_janela_principal
    
    Classe que define a interfacegráfica do programa PyGPA
    
    Métodos:
        setup_ui -> None
        retranslate_ui -> None
    '''
    def __init__(self, controle):
        self.controle = controle


    def setup_ui(self, janela_principal):
        '''
        setup_ui -> None
        
        Configura a interface gráfica, seus elementos e faz a ligação entre
        elementos gráficos e métodos do controle.
        '''
        
        janela_principal.setObjectName(_fromUtf8("janela_principal"))
        janela_principal.setWindowModality(QtCore.Qt.ApplicationModal)
        janela_principal.resize(1024, 768)
        
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8("icons/icon.png")),
                       QtGui.QIcon.Normal, QtGui.QIcon.Off)
        janela_principal.setWindowIcon(icon)
        
        self.widget_central = QtGui.QWidget(janela_principal)
        self.widget_central.setObjectName(_fromUtf8("widget_central"))
        self.gridLayout = QtGui.QGridLayout(self.widget_central)
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        self.Tabs = QtGui.QTabWidget(self.widget_central)
        self.Tabs.setObjectName(_fromUtf8("Tabs"))
        
        self.graphicPage1 = QtGui.QWidget()
        self.graphicPage1.setObjectName(_fromUtf8("graphicPage1"))
        self.gridLayout_3 = QtGui.QGridLayout(self.graphicPage1)
        self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3"))
        self.GPAGrid = QtGui.QGridLayout()
        self.GPAGrid.setObjectName(_fromUtf8("GPAGrid"))
        spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
        self.GPAGrid.addItem(spacerItem, 2, 0, 1, 1)
        spacerItem1 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
        self.GPAGrid.addItem(spacerItem1, 0, 0, 1, 1)
        self.GPAGroup = QtGui.QGroupBox(self.graphicPage1)
        self.GPAGroup.setObjectName(_fromUtf8("GPAGroup"))
        self.gridLayout_5 = QtGui.QGridLayout(self.GPAGroup)
        self.gridLayout_5.setObjectName(_fromUtf8("gridLayout_5"))
        self.GPALabel = QtGui.QLabel(self.GPAGroup)
        self.GPALabel.setObjectName(_fromUtf8("GPALabel"))
        self.gridLayout_5.addWidget(self.GPALabel, 0, 0, 1, 1)
        self.GPAGrid.addWidget(self.GPAGroup, 1, 0, 1, 1)
        self.gridLayout_3.addLayout(self.GPAGrid, 1, 2, 1, 1)
        
        self.delaunayGroup = QtGui.QGroupBox(self.graphicPage1)
        self.delaunayGroup.setObjectName(_fromUtf8("delaunayGroup"))
        self.gridLayout_4 = QtGui.QGridLayout(self.delaunayGroup)
        self.gridLayout_4.setObjectName(_fromUtf8("gridLayout_4"))
        
        self.delaunay_figure = Figure(dpi = 120)
        self.widget_delaunay = FigureWidget(self.delaunay_figure)
        self.widget_delaunay.setObjectName(_fromUtf8("widget_delaunay"))
        self.widget_delaunay.setParent(self.delaunayGroup)
        self.delaunay_axes = self.delaunay_figure.add_subplot(111, aspect = 'equal')
        self.gridLayout_4.addWidget(self.widget_delaunay, 0, 0, 1, 1)
        self.gridLayout_3.addWidget(self.delaunayGroup, 1, 1, 1, 1)
        self.vetfieldGroup = QtGui.QGroupBox(self.graphicPage1)
        self.vetfieldGroup.setObjectName(_fromUtf8("vetfieldGroup"))
        self.gridLayout_9 = QtGui.QGridLayout(self.vetfieldGroup)
        self.gridLayout_9.setObjectName(_fromUtf8("gridLayout_9"))
        
        self.vector_figure = Figure(dpi = 120)
        self.widget_vector = FigureWidget(self.vector_figure)
        self.widget_vector.setObjectName(_fromUtf8("widget_vector"))
        self.widget_vector.setParent(self.vetfieldGroup)
        self.vector_axes = self.vector_figure.add_subplot(111, aspect = 'equal')
        self.gridLayout_9.addWidget(self.widget_vector, 0, 0, 1, 1)
        self.gridLayout_3.addWidget(self.vetfieldGroup, 1, 0, 1, 1)
        self.gridLayout_3.setColumnStretch(0, 8)
        self.gridLayout_3.setColumnStretch(1, 8)
        self.gridLayout_3.setColumnStretch(2, 1)
        self.Tabs.addTab(self.graphicPage1, _fromUtf8(""))
        self.vectorTab = QtGui.QWidget()
        self.vectorTab.setObjectName(_fromUtf8("vectorTab"))
        self.gridLayout_6 = QtGui.QGridLayout(self.vectorTab)
        self.gridLayout_6.setObjectName(_fromUtf8("gridLayout_6"))
        self.vetGroupTab = QtGui.QGroupBox(self.vectorTab)
        self.vetGroupTab.setObjectName(_fromUtf8("vetGroupTab"))
        self.gridLayout_12 = QtGui.QGridLayout(self.vetGroupTab)
        self.gridLayout_12.setObjectName(_fromUtf8("gridLayout_12"))
        
        self.vector_figure_tab = Figure(dpi = 120)
        self.widget_vector_tab = FigureWidget(self.vector_figure_tab)
        self.widget_vector_tab.setObjectName(_fromUtf8("widget_vector_tab"))
        self.widget_vector_tab.setParent(self.vetGroupTab)
        self.vector_tab_axes = self.vector_figure_tab.add_subplot(111, aspect = 'equal')
        self.gridLayout_12.addWidget(self.widget_vector_tab, 0, 0, 1, 1)
        self.gridLayout_6.addWidget(self.vetGroupTab, 0, 0, 1, 1)
        self.toolGroupVet = QtGui.QGroupBox(self.vectorTab)
        self.toolGroupVet.setObjectName(_fromUtf8("toolGroupVet"))
        self.gridLayout_6.addWidget(self.toolGroupVet, 1, 0, 1, 1)
        self.gridLayout_6.setRowStretch(0, 5)
        self.gridLayout_6.setRowStretch(1, 1)
        self.Tabs.addTab(self.vectorTab, _fromUtf8(""))
        self.delaunayTab = QtGui.QWidget()
        self.delaunayTab.setObjectName(_fromUtf8("delaunayTab"))
        self.gridLayout_7 = QtGui.QGridLayout(self.delaunayTab)
        self.gridLayout_7.setObjectName(_fromUtf8("gridLayout_7"))
        self.delaunayGroupTab = QtGui.QGroupBox(self.delaunayTab)
        self.delaunayGroupTab.setObjectName(_fromUtf8("delaunayGroupTab"))
        self.gridLayout_11 = QtGui.QGridLayout(self.delaunayGroupTab)
        self.gridLayout_11.setObjectName(_fromUtf8("gridLayout_11"))
        
        self.delaunay_figure_tab = Figure(dpi = 120)
        self.widget_delaunay_tab = FigureWidget(self.delaunay_figure_tab)
        self.widget_delaunay_tab.setObjectName(_fromUtf8("widget_delaunay_tab"))
        self.widget_delaunay_tab.setParent(self.delaunayGroupTab)
        self.delaunay_tab_axes = self.delaunay_figure_tab.add_subplot(111, aspect = 'equal')
        self.gridLayout_11.addWidget(self.widget_delaunay_tab, 0, 0, 1, 1)
        self.gridLayout_7.addWidget(self.delaunayGroupTab, 0, 0, 1, 1)
        self.toolGroupDelaunay = QtGui.QGroupBox(self.delaunayTab)
        self.toolGroupDelaunay.setObjectName(_fromUtf8("toolGroupDelaunay"))
        self.gridLayout_7.addWidget(self.toolGroupDelaunay, 1, 0, 1, 1)
        self.gridLayout_7.setRowStretch(0, 5)
        self.gridLayout_7.setRowStretch(1, 1)
        self.Tabs.addTab(self.delaunayTab, _fromUtf8(""))
        self.gpaTab = QtGui.QWidget()
        self.gpaTab.setObjectName(_fromUtf8("gpaTab"))
        self.gridLayout_8 = QtGui.QGridLayout(self.gpaTab)
        self.gridLayout_8.setObjectName(_fromUtf8("gridLayout_8"))
        self.GPAGraphGroup = QtGui.QGroupBox(self.gpaTab)
        self.GPAGraphGroup.setObjectName(_fromUtf8("GPAGraphGroup"))
        self.gridLayout_10 = QtGui.QGridLayout(self.GPAGraphGroup)
        self.gridLayout_10.setObjectName(_fromUtf8("gridLayout_10"))
        
        self.GPA_figure = Figure(dpi = 120)
        self.widget_gpa_ev = FigureWidget(self.GPA_figure)
        self.widget_gpa_ev.setObjectName(_fromUtf8("widget_gpa_ev"))
        self.widget_gpa_ev.setParent(self.GPAGraphGroup)
        self.GPA_axes = self.GPA_figure.add_subplot(111, aspect = 'equal')
        self.gridLayout_10.addWidget(self.widget_gpa_ev, 0, 0, 1, 1)
        self.gridLayout_8.addWidget(self.GPAGraphGroup, 0, 0, 1, 1)
        self.Tabs.addTab(self.gpaTab, _fromUtf8(""))
        self.gridLayout.addWidget(self.Tabs, 0, 0, 1, 1)
        self.controGroup = QtGui.QGroupBox(self.widget_central)
        self.controGroup.setFlat(False)
        self.controGroup.setObjectName(_fromUtf8("controGroup"))
        self.gridLayout_2 = QtGui.QGridLayout(self.controGroup)
        self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
        self.horizontalSlider = QtGui.QSlider(self.controGroup)
        self.horizontalSlider.setMaximum(4)
        self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal)
        self.horizontalSlider.setTickPosition(QtGui.QSlider.TicksBothSides)
        self.horizontalSlider.setTickInterval(1)
        self.horizontalSlider.setObjectName(_fromUtf8("horizontalSlider"))
        self.gridLayout_2.addWidget(self.horizontalSlider, 0, 0, 1, 1)
        self.gridLayout.addWidget(self.controGroup, 1, 0, 1, 1)
        self.gridLayout.setRowStretch(0, 10)
        self.gridLayout.setRowStretch(1, 1)
        janela_principal.setCentralWidget(self.widget_central)
        self.menubar = QtGui.QMenuBar(janela_principal)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1024, 22))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        self.menu_Arquivo = QtGui.QMenu(self.menubar)
        self.menu_Arquivo.setObjectName(_fromUtf8("menu_Arquivo"))
        janela_principal.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(janela_principal)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        janela_principal.setStatusBar(self.statusbar)
        self.toolBar = QtGui.QToolBar(janela_principal)
        self.toolBar.setObjectName(_fromUtf8("toolBar"))
        janela_principal.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)
        self.actionAbrir_Matriz = QtGui.QAction(janela_principal)
        self.actionAbrir_Matriz.setObjectName(_fromUtf8("actionAbrir_Matriz"))
        self.actionAbrir_Conjunto_de_Matrizes = QtGui.QAction(janela_principal)
        self.actionAbrir_Conjunto_de_Matrizes.setObjectName(_fromUtf8("actionAbrir_Conjunto_de_Matrizes"))
        self.actionAbrir_Imagem = QtGui.QAction(janela_principal)
        self.actionAbrir_Imagem.setObjectName(_fromUtf8("actionAbrir_Imagem"))
        self.menu_Arquivo.addAction(self.actionAbrir_Matriz)
        self.menu_Arquivo.addAction(self.actionAbrir_Conjunto_de_Matrizes)
        self.menu_Arquivo.addAction(self.actionAbrir_Imagem)
        self.menubar.addAction(self.menu_Arquivo.menuAction())

        self.retranslateUi(janela_principal)
        self.Tabs.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(janela_principal)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
        self.GPAGroup.setTitle(QtGui.QApplication.translate("MainWindow", "GPA", None, QtGui.QApplication.UnicodeUTF8))
        self.GPALabel.setText(QtGui.QApplication.translate("MainWindow", "0,778", None, QtGui.QApplication.UnicodeUTF8))
        self.delaunayGroup.setTitle(QtGui.QApplication.translate("MainWindow", "Triangulação de Delaunay", None, QtGui.QApplication.UnicodeUTF8))
        self.vetfieldGroup.setTitle(QtGui.QApplication.translate("MainWindow", "Campo Vetorial", None, QtGui.QApplication.UnicodeUTF8))
        self.Tabs.setTabText(self.Tabs.indexOf(self.graphicPage1), QtGui.QApplication.translate("MainWindow", "Gráficos", None, QtGui.QApplication.UnicodeUTF8))
        self.vetGroupTab.setTitle(QtGui.QApplication.translate("MainWindow", "Gráfico", None, QtGui.QApplication.UnicodeUTF8))
        self.toolGroupVet.setTitle(QtGui.QApplication.translate("MainWindow", "Toolbox", None, QtGui.QApplication.UnicodeUTF8))
        self.Tabs.setTabText(self.Tabs.indexOf(self.vectorTab), QtGui.QApplication.translate("MainWindow", "Campo Vetorial", None, QtGui.QApplication.UnicodeUTF8))
        self.delaunayGroupTab.setTitle(QtGui.QApplication.translate("MainWindow", "Gráfico", None, QtGui.QApplication.UnicodeUTF8))
        self.toolGroupDelaunay.setTitle(QtGui.QApplication.translate("MainWindow", "Toolbox", None, QtGui.QApplication.UnicodeUTF8))
        self.Tabs.setTabText(self.Tabs.indexOf(self.delaunayTab), QtGui.QApplication.translate("MainWindow", "Triangulação de Delaunay", None, QtGui.QApplication.UnicodeUTF8))
        self.GPAGraphGroup.setTitle(QtGui.QApplication.translate("MainWindow", "Gráfico", None, QtGui.QApplication.UnicodeUTF8))
        self.Tabs.setTabText(self.Tabs.indexOf(self.gpaTab), QtGui.QApplication.translate("MainWindow", "Evolução do GPA", None, QtGui.QApplication.UnicodeUTF8))
        self.controGroup.setTitle(QtGui.QApplication.translate("MainWindow", "Controle", None, QtGui.QApplication.UnicodeUTF8))
        self.menu_Arquivo.setTitle(QtGui.QApplication.translate("MainWindow", "&Arquivo", None, QtGui.QApplication.UnicodeUTF8))
        self.toolBar.setWindowTitle(QtGui.QApplication.translate("MainWindow", "toolBar", None, QtGui.QApplication.UnicodeUTF8))
        self.actionAbrir_Matriz.setText(QtGui.QApplication.translate("MainWindow", "Abrir Matriz", None, QtGui.QApplication.UnicodeUTF8))
        self.actionAbrir_Conjunto_de_Matrizes.setText(QtGui.QApplication.translate("MainWindow", "Abrir Conjunto de Matrizes", None, QtGui.QApplication.UnicodeUTF8))
        self.actionAbrir_Imagem.setText(QtGui.QApplication.translate("MainWindow", "Abrir Imagem", None, QtGui.QApplication.UnicodeUTF8))

    def mostrar_sobre(self):
        sobre = QtGui.QDialog(self.janela)
        ui = ui_sobre()
        pix = QtGui.QPixmap(_fromUtf8("icons/icon.png"))
        text = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">'\
'<html><head><meta name="qrichtext" content="1" /><style type="text/css">'\
'p, li { white-space: pre-wrap; }'\
'</style></head><body style=" font-family:\'Sans Serif\'; font-size:10pt; font-weight:400; font-style:normal;">'\
'<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt; font-weight:600;">PyGPA</span></p>'\
'<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:12pt; font-weight:600;"></p>'\
'<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Versão 0.2</p>'\
'<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Copyleft Julio Cesar Eiras Melanda, 2011</p>'\
'<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>'\
'<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Este software é distribuído sob a GPL v3.</p>'\
'<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">http://www.gnu.org/licenses/gpl-3.0.txt</p>'\
'<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>'\
'<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Para mais informações acesse a página do projeto</p>'\
'<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#000000;"> </span><span style=" color:#000000;">http://gitorious.org/pygpa/pages/Home</span></a></p></body></html>'
        ui.setup_ui(sobre, pix, text)
        sobre.show()
예제 #10
0
class ValueWidget(QWidget, Ui_Widget):
    def __init__(self, iface):

        self.hasqwt = hasqwt
        self.hasmpl = hasmpl
        self.layerMap = dict()
        self.statsChecked = False
        self.ymin = 0
        self.ymax = 250
        self.isActive = False

        # Statistics (>=1.9)
        self.statsSampleSize = 2500000
        self.stats = {}  # stats per layer

        self.layersSelected = []
        self.layerBands = dict()

        self.iface = iface
        self.canvas = self.iface.mapCanvas
        self.legend = self.iface.legendInterface()
        self.logger = logging.getLogger('.'.join(
            (__name__, self.__class__.__name__)))

        QWidget.__init__(self)
        self.setupUi(self)
        self.tabWidget.setEnabled(False)
        self.cbxClick.setChecked(QSettings().value(
            'plugins/valuetool/mouseClick', False, type=bool))

        #self.setupUi_plot()
        #don't setup plot until Plot tab is clicked - workaround for bug #7450
        #qgis will still crash in some cases, but at least the tool can be used in Table mode
        self.qwtPlot = None
        self.mplPlot = None
        self.mplLine = None

        QObject.connect(self.plotSelector,
                        SIGNAL("currentIndexChanged ( int )"), self.changePlot)
        QObject.connect(self.tabWidget, SIGNAL("currentChanged ( int )"),
                        self.tabWidgetChanged)
        QObject.connect(self.cbxLayers, SIGNAL("currentIndexChanged ( int )"),
                        self.updateLayers)
        QObject.connect(self.cbxBands, SIGNAL("currentIndexChanged ( int )"),
                        self.updateLayers)
        QObject.connect(self.tableWidget2, SIGNAL("cellChanged ( int , int )"),
                        self.layerSelected)

    def setupUi_plot(self):

        # plot
        self.plotSelector.setVisible(False)
        self.cbxStats.setVisible(False)
        # stats by default because estimated are fast
        self.cbxStats.setChecked(True)
        self.plotSelector.addItem('Qwt')
        self.plotSelector.addItem('mpl')

        # Page 2 - qwt
        if self.hasqwt:
            self.qwtPlot = QwtPlot(self.stackedWidget)
            self.qwtPlot.setAutoFillBackground(False)
            self.qwtPlot.setObjectName("qwtPlot")
            self.curve = QwtPlotCurve()
            self.curve.setSymbol(
                QwtSymbol(QwtSymbol.Ellipse, QBrush(Qt.white), QPen(Qt.red, 2),
                          QSize(9, 9)))
            self.curve.attach(self.qwtPlot)
        else:
            self.qwtPlot = QtGui.QLabel(
                "Need Qwt >= 5.0 or matplotlib >= 1.0 !")

        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
                                       QtGui.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.qwtPlot.sizePolicy().hasHeightForWidth())
        self.qwtPlot.setSizePolicy(sizePolicy)
        self.qwtPlot.updateGeometry()
        self.stackedWidget.addWidget(self.qwtPlot)

        #Page 3 - matplotlib
        self.mplLine = None  #make sure to invalidate when layers change
        if self.hasmpl:
            # mpl stuff
            # should make figure light gray
            self.mplBackground = None  #http://www.scipy.org/Cookbook/Matplotlib/Animations
            self.mplFig = plt.Figure(facecolor='w', edgecolor='w')
            self.mplFig.subplots_adjust(left=0.1,
                                        right=0.975,
                                        bottom=0.13,
                                        top=0.95)
            self.mplPlt = self.mplFig.add_subplot(111)
            self.mplPlt.tick_params(axis='both', which='major', labelsize=12)
            self.mplPlt.tick_params(axis='both', which='minor', labelsize=10)
            # qt stuff
            self.pltCanvas = FigureCanvasQTAgg(self.mplFig)
            self.pltCanvas.setParent(self.stackedWidget)
            self.pltCanvas.setAutoFillBackground(False)
            self.pltCanvas.setObjectName("mplPlot")
            self.mplPlot = self.pltCanvas
        else:
            self.mplPlot = QtGui.QLabel(
                "Need Qwt >= 5.0 or matplotlib >= 1.0 !")

        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
                                       QtGui.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.mplPlot.sizePolicy().hasHeightForWidth())
        self.mplPlot.setSizePolicy(sizePolicy)
        self.mplPlot.updateGeometry()
        self.stackedWidget.addWidget(self.mplPlot)

        if (self.hasqwt and self.hasmpl):
            self.plotSelector.setEnabled(True)
            self.plotSelector.setVisible(True)
            self.plotSelector.setCurrentIndex(0)
        else:
            if self.hasqwt:
                self.plotSelector.setCurrentIndex(0)
            else:
                self.plotSelector.setCurrentIndex(1)
        self.changePlot()

    def keyPressEvent(self, e):
        if (e.modifiers() == Qt.ControlModifier
                or e.modifiers() == Qt.MetaModifier) and e.key() == Qt.Key_C:
            items = ''
            for rec in range(self.tableWidget.rowCount()):
                items += '"' + self.tableWidget.item(
                    rec, 0).text() + '",' + self.tableWidget.item(
                        rec, 1).text() + "\n"
            if not items == '':
                clipboard = QApplication.clipboard()
                clipboard.setText(items)
        else:
            QWidget.keyPressEvent(self, e)

    def changePlot(self):
        if (self.plotSelector.currentText() == 'mpl'):
            self.stackedWidget.setCurrentIndex(1)
        else:
            self.stackedWidget.setCurrentIndex(0)

    def changeActive(self, active, gui=True):
        self.isActive = active

        if (active):
            self.cbxEnable.setCheckState(Qt.Checked)
            QObject.connect(self.canvas, SIGNAL("layersChanged ()"),
                            self.invalidatePlot)
            if not self.cbxClick.isChecked():
                QObject.connect(self.canvas,
                                SIGNAL("xyCoordinates(const QgsPoint &)"),
                                self.printValue)
        else:
            self.cbxEnable.setCheckState(Qt.Unchecked)
            QObject.disconnect(self.canvas, SIGNAL("layersChanged ()"),
                               self.invalidatePlot)
            QObject.disconnect(self.canvas,
                               SIGNAL("xyCoordinates(const QgsPoint &)"),
                               self.printValue)

        if gui:
            self.tabWidget.setEnabled(active)
            if active:
                self.labelStatus.setText(self.tr("Value tool is enabled"))
                if self.tabWidget.currentIndex() == 2:
                    self.updateLayers()
            else:
                self.labelStatus.setText(self.tr(""))
                #use this to clear plot when deactivated
                #self.values=[]
                #self.showValues()

    def activeRasterLayers(self, index=None):
        layers = []
        allLayers = []

        if not index:
            index = self.cbxLayers.currentIndex()
        if index == 0:
            allLayers = self.canvas.layers()
        elif index == 1:
            allLayers = self.legend.getLayers()
        elif index == 2:
            for layer in self.legend.getLayers():
                if layer.id() in self.layersSelected:
                    allLayers.append(layer)

        for layer in allLayers:
            if layer!=None and layer.isValid() and \
                    layer.type()==QgsMapLayer.RasterLayer and \
                    layer.dataProvider() and \
                    (layer.dataProvider().capabilities() & QgsRasterDataProvider.IdentifyValue):
                layers.append(layer)

        return layers

    def activeBandsForRaster(self, layer):
        activeBands = []

        if self.cbxBands.currentIndex() == 1 and layer.renderer():
            activeBands = layer.renderer().usesBands()
        elif self.cbxBands.currentIndex() == 2:
            if layer.bandCount() == 1:
                activeBands = [1]
            else:
                activeBands = self.layerBands[layer.id()] if (
                    layer.id() in self.layerBands) else []
        else:
            activeBands = range(1, layer.bandCount() + 1)

        return activeBands

    def printValue(self, position):

        if debug > 0:
            print(position)

        if not position:
            return
        if self.tabWidget.currentIndex() == 2:
            return

        if debug > 0:
            print("%d active rasters, %d canvas layers" %
                  (len(self.activeRasterLayers()), self.canvas.layerCount()))
        layers = self.activeRasterLayers()
        if len(layers) == 0:
            if self.canvas.layerCount() > 0:
                self.labelStatus.setText(
                    self.tr(
                        "No valid layers to display - change layers in options"
                    ))
            else:
                self.labelStatus.setText(self.tr("No valid layers to display"))
            self.values = []
            self.showValues()
            return

        self.labelStatus.setText(
            self.tr('Coordinate:') + ' (%f, %f)' %
            (position.x(), position.y()))

        needextremum = (self.tabWidget.currentIndex() == 1)  # if plot is shown

        # count the number of requires rows and remember the raster layers
        nrow = 0
        rasterlayers = []
        layersWOStatistics = []

        for layer in layers:

            nrow += layer.bandCount()
            rasterlayers.append(layer)

            # check statistics for each band
            if needextremum:
                for i in range(1, layer.bandCount() + 1):
                    has_stats = self.getStats(layer, i) is not None
                    if not layer.id() in self.layerMap and not has_stats\
                            and not layer in layersWOStatistics:
                        layersWOStatistics.append(layer)

        if layersWOStatistics and not self.statsChecked:
            self.calculateStatistics(layersWOStatistics)

        irow = 0
        self.values = []
        self.ymin = 1e38
        self.ymax = -1e38

        mapCanvasSrs = self.iface.mapCanvas.mapRenderer().destinationCrs()

        # TODO - calculate the min/max values only once, instead of every time!!!
        # keep them in a dict() with key=layer.id()

        #pull out wavelength if it exists in metadata
        #piece to pull out wavelength information if present in metadata
        rasterMeta = rasterlayers[0].metadata()
        self.wavelengths = {}
        self.wavelength_units = ''
        if ('wavelength' in rasterMeta):
            mdSplit = rasterMeta.split('</p>')
            for d in mdSplit:
                if ('Band_' in d and 'glossy' not in d and '=' in d):
                    variableName, valueWavelength = d.split('=')
                    bandNumber = int(variableName.split('_')[1])
                    self.wavelengths[bandNumber] = float(
                        valueWavelength.split(' ')[-2].replace('(', ''))
                elif ('wavelength_units' in d):
                    variableName, v = d.split('=')
                    self.wavelength_units = v
        ####
        for layer in rasterlayers:

            layername = unicode(layer.name())
            layerSrs = layer.crs()

            pos = position

            # if given no position, get dummy values
            if position is None:
                pos = QgsPoint(0, 0)
            # transform points if needed
            elif not mapCanvasSrs == layerSrs and self.iface.mapCanvas.hasCrsTransformEnabled(
            ):
                srsTransform = QgsCoordinateTransform(mapCanvasSrs, layerSrs)
                try:
                    pos = srsTransform.transform(position)
                except QgsCsException, err:
                    # ignore transformation errors
                    continue

            if True:  # for QGIS >= 1.9
                if not layer.dataProvider():
                    continue

                ident = None
                if position is not None:
                    canvas = self.iface.mapCanvas
                    # first test if point is within map layer extent
                    # maintain same behaviour as in 1.8 and print out of extent
                    if not layer.dataProvider().extent().contains(pos):
                        ident = dict()
                        for iband in range(1, layer.bandCount() + 1):
                            ident[iband] = QVariant(self.tr('out of extent'))
                    # we can only use context if layer is not projected
                    elif canvas.hasCrsTransformEnabled(
                    ) and layer.dataProvider().crs() != canvas.mapRenderer(
                    ).destinationCrs():
                        ident = layer.dataProvider().identify(
                            pos, QgsRaster.IdentifyFormatValue).results()
                    else:
                        extent = canvas.extent()
                        width = round(extent.width() /
                                      canvas.mapUnitsPerPixel())
                        height = round(extent.height() /
                                       canvas.mapUnitsPerPixel())

                        extent = canvas.mapRenderer().mapToLayerCoordinates(
                            layer, extent)

                        ident = layer.dataProvider().identify(
                            pos, QgsRaster.IdentifyFormatValue,
                            canvas.extent(), width, height).results()
                    if not len(ident) > 0:
                        continue

                # if given no position, set values to 0
                if position is None and ident is not None and ident.iterkeys(
                ) is not None:
                    for key in ident.iterkeys():
                        ident[key] = layer.dataProvider().noDataValue(key)

                # bands displayed depends on cbxBands (all / active / selected)
                activeBands = self.activeBandsForRaster(layer)

                for iband in activeBands:  # loop over the active bands
                    layernamewithband = layername
                    if ident is not None and len(ident) > 1:
                        layernamewithband += ' ' + layer.bandName(iband)

                    if not ident or not ident.has_key(
                            iband):  # should not happen
                        bandvalue = "?"
                    else:
                        bandvalue = ident[iband].toString()
                        if bandvalue is None:
                            bandvalue = "no data"

                    self.values.append((layernamewithband, str(bandvalue)))

                    if needextremum:
                        # estimated statistics
                        stats = self.getStats(layer, iband)
                        if stats:
                            self.ymin = min(self.ymin, stats.minimumValue)
                            self.ymax = max(self.ymax, stats.maximumValue)

        if len(self.values) == 0:
            self.labelStatus.setText(self.tr("No valid bands to display"))

        self.showValues()
예제 #11
0
class Ui_Monitor(object):
    def setupUi(self, Monitor):
        Monitor.setObjectName(_fromUtf8("Monitor"))
        Monitor.resize(649, 388)
        self._plabel = []
        self._port = []
        self._display = []
        ## port
        self.SetPort(Monitor)
        # port label
        self.SetLabel(Monitor)
        # lcd number
        self.SetLcdDisplay(Monitor)

        font = QtGui.QFont()
        font.setPointSize(11)

        self._start = QtGui.QPushButton(Monitor)
        self._start.setGeometry(QtCore.QRect(10, 240, 91, 21))
        self._start.setFont(font)
        self._start.setObjectName(_fromUtf8("_start"))
        self._stop = QtGui.QPushButton(Monitor)
        self._stop.setGeometry(QtCore.QRect(10, 270, 91, 21))
        self._stop.setFont(font)
        self._stop.setObjectName(_fromUtf8("_stop"))
        self._quit = QtGui.QPushButton(Monitor)
        self._quit.setGeometry(QtCore.QRect(10, 300, 91, 21))
        self._quit.setFont(font)
        self._quit.setObjectName(_fromUtf8("_quit"))

        # matplotlib canvas
        self._fig = Figure(facecolor="whitesmoke")
        self.plot = FigureCanvas(self._fig)
        self.plot.setGeometry(QtCore.QRect(120, 10, 521, 371))
        self.plot.setObjectName(_fromUtf8("monitor"))
        self.plot.setParent(Monitor)

        self.retranslateUi(Monitor)
        QtCore.QObject.connect(self._quit, QtCore.SIGNAL(_fromUtf8("clicked()")), Monitor.close)
        QtCore.QMetaObject.connectSlotsByName(Monitor)

    def retranslateUi(self, Monitor):
        Monitor.setWindowTitle(_translate("Monitor", "Form", None))
        self._start.setText(_translate("Monitor", "Start", None))
        self._stop.setText(_translate("Monitor", "Stop", None))
        self._quit.setText(_translate("Monitor", "Quit", None))

    ## set port label
    def SetLabel(self, mainwin):
        numoflabel = 3
        font = QtGui.QFont()
        font.setPointSize(11)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(50)

        for i in range(numoflabel):
            self._plabel.append( QtGui.QLabel(mainwin) )
        self._plabel[0].setGeometry(QtCore.QRect(10, 30, 101, 21))
        self._plabel[1].setGeometry(QtCore.QRect(10, 70, 101, 21))
        self._plabel[2].setGeometry(QtCore.QRect(10, 110, 101, 21))

        for i in range(len(self._plabel)):
            self._plabel[i].setFont(font)
            self._plabel[i].setText(_fromUtf8( "Port %i" %(i+1) ))
            self._plabel[i].setTextFormat(QtCore.Qt.AutoText)
            self._plabel[i].setScaledContents(False)
            self._plabel[i].setAlignment(QtCore.Qt.AlignCenter)
            self._plabel[i].setWordWrap(False)
            self._plabel[i].setObjectName(_fromUtf8( "_pLabel%i" %(i+1) ))

    ## set port address
    def SetPort(self, mainwin):
        numofport = 3
        for i in range(numofport):
            self._port.append( QtGui.QSpinBox(mainwin) )

        self._port[0].setGeometry(QtCore.QRect(10, 10, 101, 21))
        self._port[0].setProperty("value", 20)
        self._port[1].setGeometry(QtCore.QRect(10, 50, 101, 21))
        self._port[1].setProperty("value", 6)
        self._port[2].setGeometry(QtCore.QRect(10, 90, 101, 21))
        self._port[2].setProperty("value", 12)
        for i in range(len(self._port)):
            self._port[i].setObjectName(_fromUtf8("_port%i" %(i+1)))


    ## set lcd display
    def SetLcdDisplay(self, mainwin):
        numoflcd = 3
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Symbol"))
        font.setPointSize(13)
        font.setBold(True)
        font.setWeight(75)

        for i in range(numoflcd):
            self._display.append( QtGui.QLCDNumber(mainwin) )

        self._display[0].setGeometry(QtCore.QRect(10, 140, 91, 16))
        self._display[1].setGeometry(QtCore.QRect(10, 160, 91, 16))
        self._display[2].setGeometry(QtCore.QRect(10, 180, 91, 16))

        for i in range(numoflcd):
            self._display[i].setFont(font)
            self._display[i].setSmallDecimalPoint(False)
            self._display[i].setNumDigits(14)
            self._display[i].setSegmentStyle(QtGui.QLCDNumber.Flat)
            self._display[i].setObjectName(_fromUtf8( "_num%i" %(i+1) ))
예제 #12
0
class Ui_ImageAnalyzer(object):
    

    def setupUi(self, ImageAnalyzer):
        ImageAnalyzer.setObjectName(_fromUtf8("ImageAnalyzer"))
        ImageAnalyzer.resize(640, 480)
        ImageAnalyzer.setStyleSheet(_fromUtf8("QDialog {\n"
"background-color: qradialgradient(spread:pad, cx:0.5, cy:0.5, radius:1.317, fx:0.5, fy:0.505773, stop:0 rgba(93, 99, 101, 255), stop:1 rgba(69, 76, 80, 255));\n"
"\n"
"}"))   
        self.frame = QtGui.QWidget(self)
        self.frame.setGeometry(QtCore.QRect(20, 170, 381, 251))
        self.frame.setObjectName(_fromUtf8("frame"))
        figuresize=[12,8]
        self.figure = plt.figure(figsize=(figuresize[0],figuresize[1]))
        self.figure.subplots_adjust(left=0.09,right=0.95,bottom=0.12,top=0.82,hspace=.4, wspace=.06)
        self.figure.suptitle("Analyze the files for the chart", fontsize=12)      
        self.figure.add_subplot(111)
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(self.frame)
        self.canvas.setObjectName(_fromUtf8("canvas"))
        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(self.canvas)  # the matplotlib canvas
        self.frame.setLayout(vbox)        
        self.canvas.draw()
        self.resultLabel = QtGui.QLabel(ImageAnalyzer)
        self.resultLabel.setGeometry(QtCore.QRect(417, 178, 211, 231))
        self.resultLabel.setStyleSheet(_fromUtf8("color:rgb(255, 255, 255);\n"
"font-weight:bold;\n"
"font-size: 17px;"))
        self.resultLabel.setScaledContents(False)
        self.resultLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.resultLabel.setWordWrap(True)
        self.resultLabel.setObjectName(_fromUtf8("resultLabel"))
        self.anamolyBox = QtGui.QGroupBox(ImageAnalyzer)
        self.anamolyBox.setGeometry(QtCore.QRect(20, 10, 611, 80))
        self.anamolyBox.setStyleSheet(_fromUtf8("QGroupBox {\n"
"    \n"
"    color: rgb(255, 255, 255);\n"
"}\n"
"\n"
"QRadioButton {\n"
"    color: rgb(255, 255, 255);\n"
"    font-weight: bold;\n"
"}\n"
"\n"
"QRadioButton::indicator {\n"
"    width:                  15px;\n"
"    height:                 15px;\n"
"    border-radius:          7px;\n"
"}\n"
"\n"
"\n"
"QRadioButton::indicator::unchecked {\n"
"    background-color: rgb(247, 247, 247);\n"
"}\n"
"\n"
"QRadioButton::indicator::checked {\n"
"    background-color: rgb(255, 14, 106);\n"
"}\n"
""))
        self.anamolyBox.setObjectName(_fromUtf8("anamolyBox"))
        self.oneClass = QtGui.QRadioButton(self.anamolyBox)
        self.oneClass.setGeometry(QtCore.QRect(20, 40, 161, 23))
        self.oneClass.setStyleSheet(_fromUtf8(""))
        self.oneClass.setChecked(True)
        self.oneClass.setObjectName(_fromUtf8("oneClass"))
        self.robustCovariance = QtGui.QRadioButton(self.anamolyBox)
        self.robustCovariance.setGeometry(QtCore.QRect(190, 40, 181, 23))
        self.robustCovariance.setObjectName(_fromUtf8("robustCovariance"))
        self.mad = QtGui.QRadioButton(self.anamolyBox)
        self.mad.setGeometry(QtCore.QRect(380, 40, 221, 23))
        self.mad.setObjectName(_fromUtf8("mad"))
        self.progressBar = QtGui.QProgressBar(ImageAnalyzer)
        self.progressBar.setEnabled(True)
        self.progressBar.setGeometry(QtCore.QRect(20, 140, 611, 23))
        self.progressBar.setStyleSheet(_fromUtf8("QProgressBar {\n"
"    border: 2px solid grey;\n"
"    border-radius: 5px;\n"
"    text-align: center;\n"
"}\n"
"\n"
"QProgressBar::chunk {\n"
"    background-color: rgb(255, 14, 106);\n"
"    width: 20px;\n"
"}"))
        self.progressBar.setProperty("value", 0)
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(0)
        self.progressBar.setObjectName(_fromUtf8("progressBar"))
        self.progressBar.setVisible(False)
        self.lineEdit = QtGui.QLineEdit(ImageAnalyzer)
        self.lineEdit.setGeometry(QtCore.QRect(20, 100, 481, 31))
        self.lineEdit.setReadOnly(True)
        self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
        self.pushButton = QtGui.QPushButton(ImageAnalyzer)
        self.pushButton.setGeometry(QtCore.QRect(510, 100, 121, 31))
        self.pushButton.setStyleSheet(_fromUtf8("QPushButton {\n"
"    border: 2px solid rgb(217, 11, 90);\n"
"    border-radius: 2px;\n"
"    background-color:  rgb(255, 14, 106);\n"
"    min-width: 80px;\n"
"    color: rgb(255, 255, 255);\n"
"    padding: 5px;\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
"    background-color:  rgb(217, 11, 90);\n"
"}\n"
"\n"
"QPushButton:flat {\n"
"    border: none; /* no border for a flat push button */\n"
"}\n"
"\n"
"QPushButton:default {\n"
"    border-color: navy; /* make the default button prominent */\n"
"}"))
        self.pushButton.setFlat(True)
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        
        self.analyze = QtGui.QPushButton(ImageAnalyzer)
        self.analyze.setGeometry(QtCore.QRect(410, 430, 221, 31))
        self.analyze.setStyleSheet(_fromUtf8("QPushButton {\n"
"    border: 2px solid rgb(217, 11, 90);\n"
"    border-radius: 2px;\n"
"    background-color:  rgb(255, 14, 106);\n"
"    min-width: 80px;\n"
"    color: rgb(255, 255, 255);\n"
"    padding: 5px;\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
"    background-color:  rgb(217, 11, 90);\n"
"}\n"
"\n"
"QPushButton:flat {\n"
"    border: none; /* no border for a flat push button */\n"
"}\n"
"\n"
"QPushButton:default {\n"
"    border-color: navy; /* make the default button prominent */\n"
"}"))
        self.analyze.setFlat(True)
        self.analyze.setObjectName(_fromUtf8("analyze"))
        
        self.quit = QtGui.QPushButton(ImageAnalyzer)
        self.quit.setGeometry(QtCore.QRect(280, 430, 121, 31))
        self.quit.setStyleSheet(_fromUtf8("QPushButton {\n"
"    border: 2px solid rgb(217, 11, 90);\n"
"    border-radius: 2px;\n"
"    background-color:  rgb(255, 14, 106);\n"
"    min-width: 80px;\n"
"    color: rgb(255, 255, 255);\n"
"    padding: 5px;\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
"    background-color:  rgb(217, 11, 90);\n"
"}\n"
"\n"
"QPushButton:flat {\n"
"    border: none; /* no border for a flat push button */\n"
"}\n"
"\n"
"QPushButton:default {\n"
"    border-color: navy; /* make the default button prominent */\n"
"}"))
        self.quit.setFlat(True)
        self.quit.setObjectName(_fromUtf8("quit"))
        

        self.retranslateUi(ImageAnalyzer)
        QtCore.QMetaObject.connectSlotsByName(ImageAnalyzer)

    
    
    def retranslateUi(self, ImageAnalyzer):
        ImageAnalyzer.setWindowTitle(_translate("ImageAnalyzer", "Image Analyzer", None))
        self.resultLabel.setText(_translate("ImageAnalyzer", "Run the analyzer for results", None))
        self.anamolyBox.setTitle(_translate("ImageAnalyzer", "Anamoly Detection Methods", None))
        self.oneClass.setText(_translate("ImageAnalyzer", "One Class SVM", None))
        self.robustCovariance.setText(_translate("ImageAnalyzer", "Robust Covariance", None))
        self.mad.setText(_translate("ImageAnalyzer", "Univariate MAD based", None))
        self.pushButton.setText(_translate("ImageAnalyzer", "Browse", None))
        self.analyze.setText(_translate("ImageAnalyzer", "Analyze", None))
        self.quit.setText(_translate("ImageAnalyzer", "Exit", None))