def run_numbering(self): """ Description ---------- """ # selected grid layer name grid_layer_name = self.listGridLayer.currentText() # Load input grid layer grid_layer = ftools_utils.getMapLayerByName( unicode( grid_layer_name ) ) res = qgridder_utils.rgrid_numbering(grid_layer) if res == True : QMessageBox.information(self, self.tr("Gridder"), self.tr("Numbering successful, refer to layer attribute table.") ) else : QMessageBox.information(self, self.tr("Gridder"), self.tr("Fail to number, your grid is probably not regular.") ) self.reject()
def geometry(self, myLayer, myParam, myField): if self.myFunction == 9: vlayer = ftools_utils.getMapLayerByName(myLayer) else: vlayer = ftools_utils.getVectorLayerByName(myLayer) error = False check = QFile(self.shapefileName) if check.exists(): if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName): QMessageBox.warning( self, self.tr("Geoprocessing"), self.tr("Unable to delete existing shapefile.")) return self.buttonOk.setEnabled(False) self.testThread = geometryThread(self.iface.mainWindow(), self, self.myFunction, vlayer, myParam, myField, self.shapefileName, self.encoding) QObject.connect(self.testThread, SIGNAL("runFinished(PyQt_PyObject)"), self.runFinishedFromThread) QObject.connect(self.testThread, SIGNAL("runStatus(PyQt_PyObject)"), self.runStatusFromThread) QObject.connect(self.testThread, SIGNAL("runRange(PyQt_PyObject)"), self.runRangeFromThread) self.cancel_close.setText(self.tr("Cancel")) QObject.connect(self.cancel_close, SIGNAL("clicked()"), self.cancelThread) self.testThread.start()
def compute(self, inVect, inField, value, perc, progressBar): mlayer = ftools_utils.getMapLayerByName(inVect) mlayer.removeSelection() vlayer = ftools_utils.getVectorLayerByName(inVect) vprovider = vlayer.dataProvider() index = vprovider.fieldNameIndex(inField) unique = ftools_utils.getUniqueValues(vprovider, int(index)) inFeat = QgsFeature() selran = [] nFeat = vprovider.featureCount() * len(unique) nElement = 0 self.progressBar.setValue(0) self.progressBar.setRange(0, nFeat) fit = vprovider.getFeatures() if not len(unique) == mlayer.featureCount(): for i in unique: fit.rewind() FIDs = [] while fit.nextFeature(inFeat): atMap = inFeat.attributes() if atMap[index] == i: FID = inFeat.id() FIDs.append(FID) nElement += 1 self.progressBar.setValue(nElement) if perc: selVal = int(round((value / 100.0000) * len(FIDs), 0)) else: selVal = value if selVal >= len(FIDs): selFeat = FIDs else: selFeat = random.sample(FIDs, selVal) selran.extend(selFeat) mlayer.setSelectedFeatures(selran) else: mlayer.setSelectedFeatures(range(0, mlayer.featureCount()))
def updateCanvas(self): canvas = self.iface.mapCanvas() boundBox = canvas.extent() # if "align extents and resolution..." button is checked if self.chkAlign.isChecked(): mLayerName = self.inShape.currentText() if not mLayerName == "": mLayer = ftools_utils.getMapLayerByName(unicode(mLayerName)) if not mLayer.type() == QgsMapLayer.RasterLayer: QMessageBox.information(self, self.tr("Vector grid"), self.tr("Please select a raster layer")) else: # get extents and pixel size boundBox2 = mLayer.extent() dx = math.fabs(boundBox2.xMaximum() - boundBox2.xMinimum()) / mLayer.width() dy = math.fabs(boundBox2.yMaximum() - boundBox2.yMinimum()) / mLayer.height() # get pixels from the raster that are closest to the desired extent newXMin = self.getClosestPixel(boundBox2.xMinimum(), boundBox.xMinimum(), dx, True) newXMax = self.getClosestPixel(boundBox2.xMaximum(), boundBox.xMaximum(), dx, False) newYMin = self.getClosestPixel(boundBox2.yMinimum(), boundBox.yMinimum(), dy, True) newYMax = self.getClosestPixel(boundBox2.yMaximum(), boundBox.yMaximum(), dy, False) # apply new values if found all min/max if newXMin is not None and newXMax is not None and newYMin is not None and newYMax is not None: boundBox.set(newXMin, newYMin, newXMax, newYMax) self.spnX.setValue(dx) self.spnY.setValue(dy) else: QMessageBox.information(self, self.tr("Vector grid"), self.tr("Unable to compute extents aligned on selected raster layer")) self.updateExtents(boundBox)
def compute(self, inVect, inField, value, perc, progressBar): mlayer = ftools_utils.getMapLayerByName(inVect) mlayer.removeSelection() vlayer = ftools_utils.getVectorLayerByName(inVect) vprovider = vlayer.dataProvider() index = vprovider.fieldNameIndex(inField) unique = ftools_utils.getUniqueValues(vprovider, int(index)) inFeat = QgsFeature() selran = [] nFeat = vprovider.featureCount() * len(unique) nElement = 0 self.progressBar.setValue(0) self.progressBar.setRange(0, nFeat) if not len(unique) == mlayer.featureCount(): for i in unique: fit = vprovider.getFeatures() FIDs= [] while fit.nextFeature(inFeat): atMap = inFeat.attributes() if atMap[index] == i: FID = inFeat.id() FIDs.append(FID) nElement += 1 self.progressBar.setValue(nElement) if perc: selVal = int(round((value / 100.0000) * len(FIDs), 0)) else: selVal = value if selVal >= len(FIDs): selFeat = FIDs else: selFeat = random.sample(FIDs, selVal) selran.extend(selFeat) mlayer.setSelectedFeatures(selran) else: mlayer.setSelectedFeatures(range(0, mlayer.featureCount()))
def geometry( self, myLayer, myParam, myField ): if self.myFunction == 9: vlayer = ftools_utils.getMapLayerByName( myLayer ) else: vlayer = ftools_utils.getVectorLayerByName( myLayer ) error = False if ( self.myFunction == 5 and self.chkWriteShapefile.isChecked() ) or self.myFunction != 5: check = QFile( self.shapefileName ) if check.exists(): if not QgsVectorFileWriter.deleteShapeFile( self.shapefileName ): QMessageBox.warning( self, self.tr( "Geometry"), self.tr( "Unable to delete existing shapefile." ) ) return if self.myFunction == 5 and not self.chkWriteShapefile.isChecked(): self.shapefileName = None self.encoding = None self.buttonOk.setEnabled( False ) self.testThread = geometryThread( self.iface.mainWindow(), self, self.myFunction, vlayer, myParam, myField, self.shapefileName, self.encoding, self.cmbCalcType.currentIndex(), self.chkWriteShapefile.isChecked(), self.chkByFeatures.isChecked(), self.chkUseSelection.isChecked() ) QObject.connect( self.testThread, SIGNAL( "runFinished( PyQt_PyObject )" ), self.runFinishedFromThread ) QObject.connect( self.testThread, SIGNAL( "runStatus( PyQt_PyObject )" ), self.runStatusFromThread ) QObject.connect( self.testThread, SIGNAL( "runRange( PyQt_PyObject )" ), self.runRangeFromThread ) self.cancel_close.setText( self.tr( "Cancel" ) ) QObject.connect( self.cancel_close, SIGNAL( "clicked()" ), self.cancelThread ) self.testThread.start()
def update_from_layer( self ): mLayerName = self.listSourceLayer.currentText() if not mLayerName == "" : mLayer = ftools_utils.getMapLayerByName( unicode( mLayerName ) ) # get layer extents boundBox = mLayer.extent() self.update_extents( boundBox )
def update_from_layer(self): mLayerName = self.listSourceLayer.currentText() if not mLayerName == "": mLayer = ftools_utils.getMapLayerByName(unicode(mLayerName)) # get layer extents boundBox = mLayer.extent() self.update_extents(boundBox)
def export_geometry(self) : """ Description ----------- Export grid to text file """ gridLayerName = self.listGridLayer.currentText() outTextFileName = self.textOutTextFileName.text() # settings delimiter = ',' lineterminator = '\r' max_decimals = 2 # Error checks if len(outTextFileName) <= 0: return "No output file given" gridLayer = ftools_utils.getMapLayerByName( unicode( gridLayerName ) ) if gridLayer == None: return "Layer " + gridLayerName + " not found" # Create the CSV file try: txtfile = open(outTextFileName, 'w') except ValueError: print "Writing Error. Try again..." # Iterate through each feature in the source layer feature_count = gridLayer.dataProvider().featureCount() # Initialize progress bar progress=QProgressDialog("Exporting attributes...", "Abort Export", 0, feature_count); progress.setWindowModality(Qt.WindowModal) # Select all features along with their attributes allAttrs = gridLayer.pendingAllAttributesList() gridLayer.select(allAttrs) # Iterate over grid cells for feat in gridLayer.getFeatures(): p0, p1, p2, p3 = ftools_utils.extractPoints(feat.geometry())[:4] txtfile.write(str(feat.id()) + ' AUTO' + lineterminator) for point in [p0,p1,p2,p3,p0]: xcoor = round(point.x(), max_decimals) ycoor = round(point.y(), max_decimals) txtfile.write('\t' + str(xcoor) + delimiter + str(ycoor) + lineterminator) txtfile.write('END' + lineterminator) progress.setValue(feat.id()) if (progress.wasCanceled()): return "Export canceled " txtfile.write('END' + lineterminator) progress.close() txtfile.close()
def updateLayer(self): import ftools_utils mLayerName = self.ui.inShape.currentText() if not mLayerName == "": self.mLayer = ftools_utils.getMapLayerByName(unicode(mLayerName)) boundBox = self.mLayer.extent() self.updateExtents(boundBox)
def updateLayer(self): mLayerName = self.inShape.currentText() if not mLayerName == "": mLayer = ftools_utils.getMapLayerByName(unicode(mLayerName)) if mLayer.crs() != self.iface.mapCanvas().mapRenderer( ).destinationCrs(): QMessageBox.warning( self, self.tr("Vector grid"), self. tr("Layer and project have different CRS!\nResults may be wrong." )) # get layer extents boundBox = mLayer.extent() # if "align extents and resolution..." button is checked if self.chkAlign.isChecked(): if not mLayer.type() == QgsMapLayer.RasterLayer: QMessageBox.information( self, self.tr("Vector grid"), self.tr("Please select a raster layer")) else: dx = math.fabs(boundBox.xMaximum() - boundBox.xMinimum()) / mLayer.width() dy = math.fabs(boundBox.yMaximum() - boundBox.yMinimum()) / mLayer.height() self.spnX.setValue(dx) self.spnY.setValue(dy) self.updateExtents(boundBox)
def accept(self): self.buttonOk.setEnabled( False ) if not self.rdoCoordinates.isChecked() and self.inShape.currentText() == "": QMessageBox.information(self, self.tr("Generate Regular Points"), self.tr("Please specify input layer")) elif self.rdoCoordinates.isChecked() and (self.xMin.text() == "" or self.xMax.text() == "" or self.yMin.text() == "" or self.yMax.text() == ""): QMessageBox.information(self, self.tr("Generate Regular Points"), self.tr("Please properly specify extent coordinates")) elif self.outShape.text() == "": QMessageBox.information(self, self.tr("Generate Regular Points"), self.tr("Please specify output shapefile")) else: inName = self.inShape.currentText() outPath = self.outShape.text() self.outShape.clear() if self.rdoSpacing.isChecked(): value = self.spnSpacing.value() else: value = self.spnNumber.value() if self.chkRandom.isChecked(): offset = True else: offset = False if self.rdoBoundary.isChecked(): mLayer = ftools_utils.getMapLayerByName(unicode(inName)) boundBox = mLayer.extent() crs = mLayer.crs() else: boundBox = QgsRectangle(float(self.xMin.text()), float(self.yMin.text()), float(self.xMax.text()), float(self.yMax.text())) crs = self.mapCanvas.mapRenderer().destinationCrs() print crs.isValid() if not crs.isValid(): crs = None self.regularize(boundBox, outPath, offset, value, self.rdoSpacing.isChecked(), self.spnInset.value(), crs) if self.addToCanvasCheck.isChecked(): addCanvasCheck = ftools_utils.addShapeToCanvas(unicode(outPath)) if not addCanvasCheck: QMessageBox.warning( self, self.tr("Generate Regular Points"), self.tr( "Error loading output shapefile:\n%s" ) % ( unicode( outPath ) )) self.populateLayers() else: QMessageBox.information(self, self.tr("Generate Regular Points"),self.tr("Created output shapefile:\n%s" ) % ( unicode( outPath ))) self.progressBar.setValue(0) self.buttonOk.setEnabled( True )
def updateCanvas( self ): canvas = self.iface.mapCanvas() boundBox = canvas.extent() # if "align extents and resolution..." button is checked if self.chkAlign.isChecked(): mLayerName = self.inShape.currentText() if not mLayerName == "": mLayer = ftools_utils.getMapLayerByName( unicode( mLayerName ) ) if not mLayer.type() == QgsMapLayer.RasterLayer: QMessageBox.information(self, self.tr("Vector grid"), self.tr("Please select a raster layer")) else: # get extents and pixel size xMin = boundBox.xMinimum() yMin = boundBox.yMinimum() xMax = boundBox.xMaximum() yMax = boundBox.yMaximum() boundBox2 = mLayer.extent() dx = math.fabs(boundBox2.xMaximum()-boundBox2.xMinimum()) / mLayer.width() dy = math.fabs(boundBox2.yMaximum()-boundBox2.yMinimum()) / mLayer.height() # get pixels from the raster that are closest to the desired extent newXMin = self.getClosestPixel( boundBox2.xMinimum(), boundBox.xMinimum(), dx, True ) newXMax = self.getClosestPixel( boundBox2.xMaximum(), boundBox.xMaximum(), dx, False ) newYMin = self.getClosestPixel( boundBox2.yMinimum(), boundBox.yMinimum(), dy, True ) newYMax = self.getClosestPixel( boundBox2.yMaximum(), boundBox.yMaximum(), dy, False ) # apply new values if found all min/max if newXMin is not None and newXMax is not None and newYMin is not None and newYMax is not None: boundBox.set( newXMin, newYMin, newXMax, newYMax ) self.spnX.setValue(dx) self.spnY.setValue(dy) else: QMessageBox.information(self, self.tr("Vector grid"), self.tr("Unable to compute extents aligned on selected raster layer")) self.updateExtents( boundBox )
def accept(self): self.buttonOk.setEnabled(False) if not self.rdoCoordinates.isChecked() and self.inShape.currentText( ) == "": QMessageBox.information(self, self.tr("Generate Regular Points"), self.tr("Please specify input layer")) elif self.rdoCoordinates.isChecked() and (self.xMin.text() == "" or self.xMax.text() == "" or self.yMin.text() == "" or self.yMax.text() == ""): QMessageBox.information( self, self.tr("Generate Regular Points"), self.tr("Please properly specify extent coordinates")) elif self.outShape.text() == "": QMessageBox.information(self, self.tr("Generate Regular Points"), self.tr("Please specify output shapefile")) else: inName = self.inShape.currentText() outPath = self.outShape.text() self.outShape.clear() if self.rdoSpacing.isChecked(): value = self.spnSpacing.value() else: value = self.spnNumber.value() if self.chkRandom.isChecked(): offset = True else: offset = False if self.rdoBoundary.isChecked(): mLayer = ftools_utils.getMapLayerByName(unicode(inName)) boundBox = mLayer.extent() crs = mLayer.crs() else: boundBox = QgsRectangle(float(self.xMin.text()), float(self.yMin.text()), float(self.xMax.text()), float(self.yMax.text())) crs = self.mapCanvas.mapRenderer().destinationCrs() print crs.isValid() if not crs.isValid(): crs = None self.regularize(boundBox, outPath, offset, value, self.rdoSpacing.isChecked(), self.spnInset.value(), crs) if self.addToCanvasCheck.isChecked(): addCanvasCheck = ftools_utils.addShapeToCanvas( unicode(outPath)) if not addCanvasCheck: QMessageBox.warning( self, self.tr("Generate Regular Points"), self.tr("Error loading output shapefile:\n%s") % (unicode(outPath))) self.populateLayers() else: QMessageBox.information( self, self.tr("Generate Regular Points"), self.tr("Created output shapefile:\n%s") % (unicode(outPath))) self.progressBar.setValue(0) self.buttonOk.setEnabled(True)
def run_numbering(self): """ Description ---------- """ # selected grid layer name grid_layer_name = self.listGridLayer.currentText() # Load input grid layer grid_layer = ftools_utils.getMapLayerByName(unicode(grid_layer_name)) res = qgridder_utils.rgrid_numbering(grid_layer) if res == True: QMessageBox.information( self, self.tr("Gridder"), self.tr( "Numbering successful, refer to layer attribute table.")) else: QMessageBox.information( self, self.tr("Gridder"), self.tr("Fail to number, your grid is probably not regular.")) self.reject()
def accept(self): self.buttonOk.setEnabled(False) if not self.rdoCoordinates.isChecked() and self.inShape.currentText( ) == "": QMessageBox.information(self, self.tr("Generate Regular Points"), self.tr("Please specify input layer")) elif self.rdoCoordinates.isChecked() and (self.xMin.text() == "" or self.xMax.text() == "" or self.yMin.text() == "" or self.yMax.text() == ""): QMessageBox.information( self, self.tr("Generate Regular Points"), self.tr("Please properly specify extent coordinates")) elif self.outShape.text() == "": QMessageBox.information(self, self.tr("Generate Regular Points"), self.tr("Please specify output shapefile")) else: inName = self.inShape.currentText() outPath = self.outShape.text() self.outShape.clear() if outPath.contains("\\"): outName = outPath.right((outPath.length() - outPath.lastIndexOf("\\")) - 1) else: outName = outPath.right((outPath.length() - outPath.lastIndexOf("/")) - 1) if outName.endsWith(".shp"): outName = outName.left(outName.length() - 4) if self.rdoSpacing.isChecked(): value = self.spnSpacing.value() else: value = self.spnNumber.value() if self.chkRandom.isChecked(): offset = True else: offset = False if self.rdoBoundary.isChecked(): mLayer = ftools_utils.getMapLayerByName(unicode(inName)) boundBox = mLayer.extent() crs = mLayer.crs() else: boundBox = QgsRectangle(float(self.xMin.text()), float(self.yMin.text()), float(self.xMax.text()), float(self.yMax.text())) crs = self.mapCanvas.mapRenderer().destinationSrs() print crs.isValid() if not crs.isValid(): crs = None self.regularize(boundBox, outPath, offset, value, self.rdoSpacing.isChecked(), self.spnInset.value(), crs) addToTOC = QMessageBox.question( self, self.tr("Generate Regular Points"), self. tr("Created output point shapefile:\n%1\n\nWould you like to add the new layer to the TOC?" ).arg(outPath), QMessageBox.Yes, QMessageBox.No, QMessageBox.NoButton) if addToTOC == QMessageBox.Yes: self.vlayer = QgsVectorLayer(outPath, unicode(outName), "ogr") QgsMapLayerRegistry.instance().addMapLayer(self.vlayer) self.populateLayers() self.progressBar.setValue(0) self.buttonOk.setEnabled(True)
def accept(self): self.buttonOk.setEnabled(False) if self.inShape.currentText() == "": QMessageBox.information(self, self.tr("Random Points"), self.tr("No input layer specified")) elif self.outShape.text() == "": QMessageBox.information(self, self.tr("Random Points"), self.tr("Please specify output shapefile")) else: inName = self.inShape.currentText() self.progressBar.setValue(1) outPath = self.outShape.text() self.progressBar.setValue(2.5) outName = ftools_utils.getShapefileName(outPath) self.progressBar.setValue(5) mLayer = ftools_utils.getMapLayerByName(unicode(inName)) if mLayer.type() == mLayer.VectorLayer: inLayer = ftools_utils.getVectorLayerByName(unicode(inName)) if self.rdoUnstratified.isChecked(): design = self.tr("unstratified") value = self.spnUnstratified.value() elif self.rdoStratified.isChecked(): design = self.tr("stratified") value = self.spnStratified.value() elif self.rdoDensity.isChecked(): design = self.tr("density") value = self.spnDensity.value() else: design = self.tr("field") value = unicode(self.cmbField.currentText()) elif mLayer.type() == mLayer.RasterLayer: inLayer = ftools_utils.getRasterLayerByName(unicode(inName)) design = self.tr("unstratified") value = self.spnUnstratified.value() else: QMessageBox.information(self, self.tr("Random Points"), self.tr("Unknown layer type...")) minimum = 0.00 self.progressBar.setValue(10) if self.randomize(inLayer, outPath, minimum, design, value): self.progressBar.setValue(100) self.outShape.clear() if self.addToCanvasCheck.isChecked(): addCanvasCheck = ftools_utils.addShapeToCanvas( unicode(outPath)) if not addCanvasCheck: QMessageBox.warning( self, self.tr("Random Points"), self.tr("Error loading output shapefile:\n%s") % (unicode(outPath))) self.populateLayers() else: QMessageBox.information( self, self.tr("Random Points"), self.tr("Created output shapefile:\n%s") % (unicode(outPath))) self.progressBar.setValue(0) self.buttonOk.setEnabled(True)
def accept(self): self.buttonOk.setEnabled(False) if self.inShape.currentText() == "": QMessageBox.information(self, self.tr("Random Points"), self.tr("No input layer specified")) elif self.outShape.text() == "": QMessageBox.information(self, self.tr("Random Points"), self.tr("Please specify output shapefile")) else: inName = self.inShape.currentText() self.progressBar.setValue(1) outPath = self.outShape.text() self.progressBar.setValue(2.5) outName = ftools_utils.getShapefileName(outPath) self.progressBar.setValue(5) mLayer = ftools_utils.getMapLayerByName(unicode(inName)) if mLayer.type() == mLayer.VectorLayer: inLayer = ftools_utils.getVectorLayerByName(unicode(inName)) if self.rdoUnstratified.isChecked(): design = self.tr("unstratified") value = self.spnUnstratified.value() elif self.rdoStratified.isChecked(): design = self.tr("stratified") value = self.spnStratified.value() elif self.rdoDensity.isChecked(): design = self.tr("density") value = self.spnDensity.value() else: design = self.tr("field") value = unicode(self.cmbField.currentText()) elif mLayer.type() == mLayer.RasterLayer: inLayer = ftools_utils.getRasterLayerByName(unicode(inName)) design = self.tr("unstratified") value = self.spnUnstratified.value() else: QMessageBox.information(self, self.tr("Random Points"), self.tr("Unknown layer type...")) minimum = 0.00 self.progressBar.setValue(10) if self.randomize(inLayer, outPath, minimum, design, value): self.progressBar.setValue(100) self.outShape.clear() addToTOC = QMessageBox.question( self, self.tr("Random Points"), self. tr("Created output point shapefile:\n%s\n\nWould you like to add the new layer to the TOC?" ) % (outPath), QMessageBox.Yes, QMessageBox.No, QMessageBox.NoButton) if addToTOC == QMessageBox.Yes: self.vlayer = QgsVectorLayer(outPath, unicode(outName), "ogr") QgsMapLayerRegistry.instance().addMapLayers([self.vlayer]) self.populateLayers() self.progressBar.setValue(0) self.buttonOk.setEnabled(True)
def geometry(self, myLayer, myParam, myField): if self.myFunction == 9: vlayer = ftools_utils.getMapLayerByName(myLayer) else: vlayer = ftools_utils.getVectorLayerByName(myLayer) error = False if (self.myFunction == 5 and self.chkWriteShapefile.isChecked()) or self.myFunction != 5: check = QFile(self.shapefileName) if check.exists(): if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName): QMessageBox.warning(self, self.tr("Geometry"), self.tr("Unable to delete existing shapefile.")) return if self.myFunction == 5 and not self.chkWriteShapefile.isChecked(): self.shapefileName = None self.encoding = None res = QMessageBox.warning( self, self.tr("Geometry"), self.tr( "Currently QGIS doesn't allow simultaneous access from \ different threads to the same datasource. Make sure your layer's \ attribute tables are closed. Continue?" ), QMessageBox.Yes | QMessageBox.No, ) if res == QMessageBox.No: return self.buttonOk.setEnabled(False) self.testThread = geometryThread( self.iface.mainWindow(), self, self.myFunction, vlayer, myParam, myField, self.shapefileName, self.encoding, self.cmbCalcType.currentIndex(), self.chkWriteShapefile.isChecked(), self.chkByFeatures.isChecked(), self.chkUseSelection.isChecked(), ) QObject.connect(self.testThread, SIGNAL("runFinished( PyQt_PyObject )"), self.runFinishedFromThread) QObject.connect(self.testThread, SIGNAL("runStatus( PyQt_PyObject )"), self.runStatusFromThread) QObject.connect(self.testThread, SIGNAL("runRange( PyQt_PyObject )"), self.runRangeFromThread) self.cancel_close.setText(self.tr("Cancel")) QObject.connect(self.cancel_close, SIGNAL("clicked()"), self.cancelThread) self.testThread.start()
def accept(self): self.buttonOk.setEnabled( False ) if self.inShape.currentText() == "": QMessageBox.information(self, self.tr("Random Points"), self.tr("No input layer specified")) elif self.outShape.text() == "": QMessageBox.information(self, self.tr("Random Points"), self.tr("Please specify output shapefile")) else: inName = self.inShape.currentText() self.progressBar.setValue(1) outPath = self.outShape.text() self.progressBar.setValue(2.5) if outPath.contains("\\"): outName = outPath.right((outPath.length() - outPath.lastIndexOf("\\")) - 1) else: outName = outPath.right((outPath.length() - outPath.lastIndexOf("/")) - 1) if outName.endsWith(".shp"): outName = outName.left(outName.length() - 4) self.progressBar.setValue(5) mLayer = ftools_utils.getMapLayerByName(unicode(inName)) if mLayer.type() == mLayer.VectorLayer: inLayer = ftools_utils.getVectorLayerByName(unicode(inName)) if self.rdoUnstratified.isChecked(): design = self.tr("unstratified") value = self.spnUnstratified.value() elif self.rdoStratified.isChecked(): design = self.tr("stratified") value = self.spnStratified.value() elif self.rdoDensity.isChecked(): design = self.tr("density") value = self.spnDensity.value() else: design = self.tr("field") value = unicode(self.cmbField.currentText()) elif mLayer.type() == mLayer.RasterLayer: inLayer = ftools_utils.getRasterLayerByName(unicode(inName)) design = self.tr("unstratified") value = self.spnUnstratified.value() else: QMessageBox.information(self, self.tr("Random Points"), self.tr("Unknown layer type...")) minimum = 0.00 self.progressBar.setValue(10) self.randomize(inLayer, outPath, minimum, design, value) self.progressBar.setValue(100) self.outShape.clear() addToTOC = QMessageBox.question(self, self.tr("Random Points"), self.tr("Created output point shapefile:\n%1\n\nWould you like to add the new layer to the TOC?").arg(outPath), QMessageBox.Yes, QMessageBox.No, QMessageBox.NoButton) if addToTOC == QMessageBox.Yes: self.vlayer = QgsVectorLayer(outPath, unicode(outName), "ogr") QgsMapLayerRegistry.instance().addMapLayers([self.vlayer]) self.populateLayers() self.progressBar.setValue(0) self.buttonOk.setEnabled( True )
def accept(self): self.buttonOk.setEnabled( False ) if self.inShape.currentText() == "": QMessageBox.information(self, self.tr("Random Points"), self.tr("No input layer specified")) elif self.outShape.text() == "": QMessageBox.information(self, self.tr("Random Points"), self.tr("Please specify output shapefile")) else: inName = self.inShape.currentText() self.progressBar.setValue(1) outPath = self.outShape.text() self.progressBar.setValue(2.5) if outPath.contains("\\"): outName = outPath.right((outPath.length() - outPath.lastIndexOf("\\")) - 1) else: outName = outPath.right((outPath.length() - outPath.lastIndexOf("/")) - 1) if outName.endsWith(".shp"): outName = outName.left(outName.length() - 4) self.progressBar.setValue(5) mLayer = ftools_utils.getMapLayerByName(unicode(inName)) if mLayer.type() == mLayer.VectorLayer: inLayer = QgsVectorLayer(unicode(mLayer.source()), unicode(mLayer.name()), unicode(mLayer.dataProvider().name())) if self.rdoUnstratified.isChecked(): design = self.tr("unstratified") value = self.spnUnstratified.value() elif self.rdoStratified.isChecked(): design = self.tr("stratified") value = self.spnStratified.value() elif self.rdoDensity.isChecked(): design = self.tr("density") value = self.spnDensity.value() else: design = self.tr("field") value = unicode(self.cmbField.currentText()) elif mLayer.type() == mLayer.RasterLayer: inLayer = QgsRasterLayer(unicode(mLayer.source()), unicode(mLayer.name())) design = self.tr("unstratified") value = self.spnUnstratified.value() else: QMessageBox.information(self, self.tr("Random Points"), self.tr("Unknown layer type...")) minimum = 0.00 self.progressBar.setValue(10) self.randomize(inLayer, outPath, minimum, design, value) self.progressBar.setValue(100) self.outShape.clear() addToTOC = QMessageBox.question(self, self.tr("Random Points"), self.tr("Created output point shapefile:\n%1\n\nWould you like to add the new layer to the TOC?").arg(outPath), QMessageBox.Yes, QMessageBox.No, QMessageBox.NoButton) if addToTOC == QMessageBox.Yes: self.vlayer = QgsVectorLayer(outPath, unicode(outName), "ogr") QgsMapLayerRegistry.instance().addMapLayer(self.vlayer) self.progressBar.setValue(0) self.buttonOk.setEnabled( True )
def geometry(self, myLayer, myParam, myField): if self.myFunction == 9: vlayer = ftools_utils.getMapLayerByName(myLayer) else: vlayer = ftools_utils.getVectorLayerByName(myLayer) error = False if (self.myFunction == 5 and self.chkWriteShapefile.isChecked()) or self.myFunction != 5: check = QFile(self.shapefileName) if check.exists(): if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName): QMessageBox.warning( self, self.tr("Geometry"), self.tr("Unable to delete existing shapefile.")) return if self.myFunction == 5 and not self.chkWriteShapefile.isChecked(): self.shapefileName = None self.encoding = None res = QMessageBox.warning( self, self.tr("Geometry"), self.tr( "Currently QGIS doesn't allow simultaneous access from \ different threads to the same datasource. Make sure your layer's \ attribute tables are closed. Continue?"), QMessageBox.Yes | QMessageBox.No) if res == QMessageBox.No: return self.buttonOk.setEnabled(False) self.testThread = geometryThread(self.iface.mainWindow(), self, self.myFunction, vlayer, myParam, myField, self.shapefileName, self.encoding, self.cmbCalcType.currentIndex(), self.chkWriteShapefile.isChecked(), self.chkByFeatures.isChecked(), self.chkUseSelection.isChecked()) QObject.connect(self.testThread, SIGNAL("runFinished( PyQt_PyObject )"), self.runFinishedFromThread) QObject.connect(self.testThread, SIGNAL("runStatus( PyQt_PyObject )"), self.runStatusFromThread) QObject.connect(self.testThread, SIGNAL("runRange( PyQt_PyObject )"), self.runRangeFromThread) self.cancel_close.setText(self.tr("Cancel")) QObject.connect(self.cancel_close, SIGNAL("clicked()"), self.cancelThread) self.testThread.start()
def run_undo_refine(self) : if len(self.settings.list_grid_bckup) > 0 : # selected grid layer name grid_layer_name = self.listGridLayer.currentText() # Load input grid layer grid_layer = ftools_utils.getMapLayerByName( unicode( grid_layer_name ) ) # retrieve last backup layer backup_grid_layer = self.settings.list_grid_bckup[-1] # remove all elements in grid layer grid_layer.dataProvider().deleteFeatures( [feat.id() for feat in grid_layer.getFeatures()] ) # populate grid layer with backup layer features grid_layer.dataProvider().addFeatures( [feat for feat in backup_grid_layer.getFeatures()] ) # remove last backup self.settings.list_grid_bckup.pop()
def run_check3D(self): allLayers = [] topoRules = {'model':'nested', 'nmax':2,'pmax':4} for row in range( self.listLayers3D.count() ) : vLayerName = self.listLayers3D.item(row).text() vLayer = ftools_utils.getMapLayerByName( unicode( vLayerName ) ) allLayers.append(vLayer) qgridder_utils.correct_pseudo3D_grid(allLayers, topoRules) QMessageBox.information(self, self.tr("Qgridder"), self.tr('pseudo-3D grid topology successfully checked and corrected') ) # Refresh map canvas self.iface.mapCanvas().refresh() return()
def run_check3D(self): allLayers = [] topoRules = {'model': 'newsam', 'nmax': 2, 'pmax': 4} for row in range(self.listLayers3D.count()): vLayerName = self.listLayers3D.item(row).text() vLayer = ftools_utils.getMapLayerByName(unicode(vLayerName)) allLayers.append(vLayer) qgridder_utils.correct_pseudo3D_grid(allLayers, topoRules) QMessageBox.information( self, self.tr("Qgridder"), self.tr( 'pseudo-3D grid topology successfully checked and corrected')) # Refresh map canvas self.iface.mapCanvas().refresh() return ()
def accept(self): self.buttonOk.setEnabled( False ) if self.inShape.currentText() == "": QMessageBox.information(self, self.tr("Random Points"), self.tr("No input layer specified")) elif self.outShape.text() == "": QMessageBox.information(self, self.tr("Random Points"), self.tr("Please specify output shapefile")) else: inName = self.inShape.currentText() self.progressBar.setValue(1) outPath = self.outShape.text() self.progressBar.setValue(2.5) outName = ftools_utils.getShapefileName( outPath ) self.progressBar.setValue(5) mLayer = ftools_utils.getMapLayerByName(unicode(inName)) if mLayer.type() == mLayer.VectorLayer: inLayer = ftools_utils.getVectorLayerByName(unicode(inName)) if self.rdoUnstratified.isChecked(): design = self.tr("unstratified") value = self.spnUnstratified.value() elif self.rdoStratified.isChecked(): design = self.tr("stratified") value = self.spnStratified.value() elif self.rdoDensity.isChecked(): design = self.tr("density") value = self.spnDensity.value() else: design = self.tr("field") value = unicode(self.cmbField.currentText()) elif mLayer.type() == mLayer.RasterLayer: inLayer = ftools_utils.getRasterLayerByName(unicode(inName)) design = self.tr("unstratified") value = self.spnUnstratified.value() else: QMessageBox.information(self, self.tr("Random Points"), self.tr("Unknown layer type...")) minimum = 0.00 self.progressBar.setValue(10) if self.randomize(inLayer, outPath, minimum, design, value): self.progressBar.setValue(100) self.outShape.clear() if self.addToCanvasCheck.isChecked(): addCanvasCheck = ftools_utils.addShapeToCanvas(unicode(outPath)) if not addCanvasCheck: QMessageBox.warning( self, self.tr("Random Points"), self.tr( "Error loading output shapefile:\n%s" ) % ( unicode( outPath ) )) self.populateLayers() else: QMessageBox.information(self, self.tr("Random Points"),self.tr("Created output shapefile:\n%s" ) % ( unicode( outPath ))) self.progressBar.setValue(0) self.buttonOk.setEnabled( True )
def updateLayer( self ): mLayerName = self.inShape.currentText() if not mLayerName == "": mLayer = ftools_utils.getMapLayerByName( unicode( mLayerName ) ) # get layer extents boundBox = mLayer.extent() # if "align extents and resolution..." button is checked if self.chkAlign.isChecked(): if not mLayer.type() == QgsMapLayer.RasterLayer: QMessageBox.information(self, self.tr("Vector grid"), self.tr("Please select a raster layer")) else: dx = math.fabs(boundBox.xMaximum()-boundBox.xMinimum()) / mLayer.width() dy = math.fabs(boundBox.yMaximum()-boundBox.yMinimum()) / mLayer.height() self.spnX.setValue(dx) self.spnY.setValue(dy) self.updateExtents( boundBox )
def updateLayer(self): mLayerName = self.inShape.currentText() if not mLayerName == "": mLayer = ftools_utils.getMapLayerByName(unicode(mLayerName)) if mLayer.crs() != self.iface.mapCanvas().mapRenderer().destinationCrs(): QMessageBox.warning(self, self.tr("Vector grid"), self.tr("Layer and project have different CRS!\nResults may be wrong.")) # get layer extents boundBox = mLayer.extent() # if "align extents and resolution..." button is checked if self.chkAlign.isChecked(): if not mLayer.type() == QgsMapLayer.RasterLayer: QMessageBox.information(self, self.tr("Vector grid"), self.tr("Please select a raster layer")) else: dx = math.fabs(boundBox.xMaximum() - boundBox.xMinimum()) / mLayer.width() dy = math.fabs(boundBox.yMaximum() - boundBox.yMinimum()) / mLayer.height() self.spnX.setValue(dx) self.spnY.setValue(dy) self.updateExtents(boundBox)
def geometry( self, myLayer, myParam, myField ): if self.myFunction == 9: vlayer = ftools_utils.getMapLayerByName( myLayer ) else: vlayer = ftools_utils.getVectorLayerByName( myLayer ) error = False check = QFile( self.shapefileName ) if check.exists(): if not QgsVectorFileWriter.deleteShapeFile( self.shapefileName ): QMessageBox.warning( self, self.tr("Geoprocessing"), self.tr( "Unable to delete existing shapefile." ) ) return self.buttonOk.setEnabled( False ) self.testThread = geometryThread( self.iface.mainWindow(), self, self.myFunction, vlayer, myParam, myField, self.shapefileName, self.encoding ) QObject.connect( self.testThread, SIGNAL( "runFinished(PyQt_PyObject)" ), self.runFinishedFromThread ) QObject.connect( self.testThread, SIGNAL( "runStatus(PyQt_PyObject)" ), self.runStatusFromThread ) QObject.connect( self.testThread, SIGNAL( "runRange(PyQt_PyObject)" ), self.runRangeFromThread ) self.cancel_close.setText( self.tr("Cancel") ) QObject.connect( self.cancel_close, SIGNAL( "clicked()" ), self.cancelThread ) self.testThread.start()
def update(self, inputLayer): self.cmbField.clear() changedLayer = ftools_utils.getMapLayerByName(unicode(inputLayer)) if changedLayer.type() == changedLayer.VectorLayer: self.rdoStratified.setEnabled(True) self.rdoDensity.setEnabled(True) self.rdoField.setEnabled(True) self.label_4.setEnabled(True) changedLayer = ftools_utils.getVectorLayerByName(inputLayer) changedFields = ftools_utils.getFieldList(changedLayer) for i in changedFields: self.cmbField.addItem(unicode(changedFields[i].name())) else: self.rdoUnstratified.setChecked(True) self.rdoStratified.setEnabled(False) self.rdoDensity.setEnabled(False) self.rdoField.setEnabled(False) self.spnStratified.setEnabled(False) self.spnDensity.setEnabled(False) self.cmbField.setEnabled(False) self.label_4.setEnabled(False)
def add_new_layer3D(self): # fetch reference grid from listReferenceGrid ReferenceGridLayerName = self.listReferenceGrid.currentText() if not ReferenceGridLayerName == "": ReferenceGridLayer = ftools_utils.getMapLayerByName( unicode(ReferenceGridLayerName)) # Copy reference grid to shapefile to user defined location OutFileName, Encoding = ftools_utils.saveDialog(self) if (OutFileName, OutFileName) == (None, None): return () # write new layer to shapefile ftools_utils.writeVectorLayerToShape(ReferenceGridLayer, OutFileName, self.encoding) # get new layer name file_info = QFileInfo(OutFileName) if file_info.exists(): newLayerName = file_info.completeBaseName() # check whether this layer name is already in the 3D list if len(self.listLayers3D.findItems(newLayerName, Qt.MatchFixedString)) != 0: QMessageBox.information( self, self.tr("Gridder"), self.tr("This layer is already in the list.")) return () # Load new layer into map canvas ... for (name, layer) in QgsMapLayerRegistry.instance().mapLayers().iteritems(): # Note : reload() doesn't work. if layer.source() == self.OutFileName: QgsMapLayerRegistry.instance().removeMapLayers(layer.id()) ftools_utils.addShapeToCanvas(OutFileName) # add new layer to listLayers3D self.listLayers3D.addItem(newLayerName)
def accept(self): self.buttonOk.setEnabled( False ) if not self.rdoCoordinates.isChecked() and self.inShape.currentText() == "": QMessageBox.information(self, self.tr("Generate Regular Points"), self.tr("Please specify input layer")) elif self.rdoCoordinates.isChecked() and (self.xMin.text() == "" or self.xMax.text() == "" or self.yMin.text() == "" or self.yMax.text() == ""): QMessageBox.information(self, self.tr("Generate Regular Points"), self.tr("Please properly specify extent coordinates")) elif self.outShape.text() == "": QMessageBox.information(self, self.tr("Generate Regular Points"), self.tr("Please specify output shapefile")) else: inName = self.inShape.currentText() outPath = self.outShape.text() self.outShape.clear() if outPath.contains("\\"): outName = outPath.right((outPath.length() - outPath.lastIndexOf("\\")) - 1) else: outName = outPath.right((outPath.length() - outPath.lastIndexOf("/")) - 1) if outName.endsWith(".shp"): outName = outName.left(outName.length() - 4) if self.rdoSpacing.isChecked(): value = self.spnSpacing.value() else: value = self.spnNumber.value() if self.chkRandom.isChecked(): offset = True else: offset = False if self.rdoBoundary.isChecked(): mLayer = ftools_utils.getMapLayerByName(unicode(inName)) boundBox = mLayer.extent() crs = mLayer.crs() else: boundBox = QgsRectangle(float(self.xMin.text()), float(self.yMin.text()), float(self.xMax.text()), float(self.yMax.text())) crs = self.mapCanvas.mapRenderer().destinationCrs() print crs.isValid() if not crs.isValid(): crs = None self.regularize(boundBox, outPath, offset, value, self.rdoSpacing.isChecked(), self.spnInset.value(), crs) addToTOC = QMessageBox.question(self, self.tr("Generate Regular Points"), self.tr("Created output point shapefile:\n%1\n\nWould you like to add the new layer to the TOC?").arg( outPath ), QMessageBox.Yes, QMessageBox.No, QMessageBox.NoButton) if addToTOC == QMessageBox.Yes: self.vlayer = QgsVectorLayer(outPath, unicode(outName), "ogr") QgsMapLayerRegistry.instance().addMapLayers([self.vlayer]) self.populateLayers() self.progressBar.setValue(0) self.buttonOk.setEnabled( True )
def add_new_layer3D(self): # fetch reference grid from listReferenceGrid ReferenceGridLayerName = self.listReferenceGrid.currentText() if not ReferenceGridLayerName == "": ReferenceGridLayer = ftools_utils.getMapLayerByName( unicode( ReferenceGridLayerName ) ) # Copy reference grid to shapefile to user defined location OutFileName, Encoding = ftools_utils.saveDialog( self ) if (OutFileName, OutFileName) == (None, None) : return() # write new layer to shapefile ftools_utils.writeVectorLayerToShape( ReferenceGridLayer, OutFileName, self.encoding ) # get new layer name file_info = QFileInfo( OutFileName ) if file_info.exists(): newLayerName = file_info.completeBaseName() # check whether this layer name is already in the 3D list if len(self.listLayers3D.findItems(newLayerName,Qt.MatchFixedString)) != 0 : QMessageBox.information(self, self.tr("Gridder"), self.tr("This layer is already in the list.")) return() # Load new layer into map canvas ... for (name,layer) in QgsMapLayerRegistry.instance().mapLayers().iteritems(): # Note : reload() doesn't work. if layer.source()==self.OutFileName: QgsMapLayerRegistry.instance().removeMapLayers( layer.id() ) ftools_utils.addShapeToCanvas( OutFileName ) # add new layer to listLayers3D self.listLayers3D.addItem(newLayerName)
def export_geometry(self): """ Description ----------- Export grid to text file """ gridLayerName = self.listGridLayer.currentText() outTextFileName = self.textOutTextFileName.text() # settings delimiter = ',' lineterminator = '\r' max_decimals = 2 # Error checks if len(outTextFileName) <= 0: return "No output file given" gridLayer = ftools_utils.getMapLayerByName(unicode(gridLayerName)) if gridLayer == None: return "Layer " + gridLayerName + " not found" # Create the CSV file try: txtfile = open(outTextFileName, 'w') except ValueError: print "Writing Error. Try again..." # Iterate through each feature in the source layer feature_count = gridLayer.dataProvider().featureCount() # Initialize progress bar progress = QProgressDialog("Exporting attributes...", "Abort Export", 0, feature_count) progress.setWindowModality(Qt.WindowModal) # Select all features along with their attributes allAttrs = gridLayer.pendingAllAttributesList() gridLayer.select(allAttrs) # Iterate over grid cells for feat in gridLayer.getFeatures(): p0, p1, p2, p3 = ftools_utils.extractPoints(feat.geometry())[:4] txtfile.write(str(feat.id()) + ' AUTO' + lineterminator) for point in [p0, p1, p2, p3, p0]: xcoor = round(point.x(), max_decimals) ycoor = round(point.y(), max_decimals) txtfile.write('\t' + str(xcoor) + delimiter + str(ycoor) + lineterminator) txtfile.write('END' + lineterminator) progress.setValue(feat.id()) if (progress.wasCanceled()): return "Export canceled " txtfile.write('END' + lineterminator) progress.close() txtfile.close()
def compute(self, bound, xOffset, yOffset, polygon): crs = ftools_utils.getMapLayerByName( unicode(self.inShape.currentText())).crs() if not crs.isValid(): crs = None if polygon: fields = { 0: QgsField("ID", QVariant.Int), 1: QgsField("XMIN", QVariant.Double), 2: QgsField("XMAX", QVariant.Double), 3: QgsField("YMIN", QVariant.Double), 4: QgsField("YMAX", QVariant.Double) } check = QFile(self.shapefileName) if check.exists(): if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName): return writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fields, QGis.WKBPolygon, crs) else: fields = { 0: QgsField("ID", QVariant.Int), 1: QgsField("COORD", QVariant.Double) } check = QFile(self.shapefileName) if check.exists(): if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName): return writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fields, QGis.WKBLineString, crs) outFeat = QgsFeature() outGeom = QgsGeometry() idVar = 0 # self.progressBar.setRange( 0, 0 ) self.progressBar.setValue(0) if not polygon: # counters for progressbar - update every 5% count = 0 count_max = (bound.yMaximum() - bound.yMinimum()) / yOffset count_update = count_max * 0.10 y = bound.yMaximum() while y >= bound.yMinimum(): pt1 = QgsPoint(bound.xMinimum(), y) pt2 = QgsPoint(bound.xMaximum(), y) line = [pt1, pt2] outFeat.setGeometry(outGeom.fromPolyline(line)) outFeat.addAttribute(0, QVariant(idVar)) outFeat.addAttribute(1, QVariant(y)) writer.addFeature(outFeat) y = y - yOffset idVar = idVar + 1 count += 1 if int(math.fmod(count, count_update)) == 0: prog = int(count / count_max * 50) self.progressBar.setValue(prog) self.progressBar.setValue(50) # counters for progressbar - update every 5% count = 0 count_max = (bound.xMaximum() - bound.xMinimum()) / xOffset count_update = count_max * 0.10 x = bound.xMinimum() while x <= bound.xMaximum(): pt1 = QgsPoint(x, bound.yMaximum()) pt2 = QgsPoint(x, bound.yMinimum()) line = [pt1, pt2] outFeat.setGeometry(outGeom.fromPolyline(line)) outFeat.addAttribute(0, QVariant(idVar)) outFeat.addAttribute(1, QVariant(x)) writer.addFeature(outFeat) x = x + xOffset idVar = idVar + 1 count += 1 if int(math.fmod(count, count_update)) == 0: prog = 50 + int(count / count_max * 50) self.progressBar.setValue(prog) else: # counters for progressbar - update every 5% count = 0 count_max = (bound.yMaximum() - bound.yMinimum()) / yOffset count_update = count_max * 0.05 y = bound.yMaximum() while y >= bound.yMinimum(): x = bound.xMinimum() while x <= bound.xMaximum(): pt1 = QgsPoint(x, y) pt2 = QgsPoint(x + xOffset, y) pt3 = QgsPoint(x + xOffset, y - yOffset) pt4 = QgsPoint(x, y - yOffset) pt5 = QgsPoint(x, y) polygon = [[pt1, pt2, pt3, pt4, pt5]] outFeat.setGeometry(outGeom.fromPolygon(polygon)) outFeat.addAttribute(0, QVariant(idVar)) outFeat.addAttribute(1, QVariant(x)) outFeat.addAttribute(2, QVariant(x + xOffset)) outFeat.addAttribute(3, QVariant(y - yOffset)) outFeat.addAttribute(4, QVariant(y)) writer.addFeature(outFeat) idVar = idVar + 1 x = x + xOffset y = y - yOffset count += 1 if int(math.fmod(count, count_update)) == 0: prog = int(count / count_max * 100) self.progressBar.setValue(100) #self.progressBar.setRange( 0, 100 ) del writer
def updateLayer( self ): mLayerName = self.inShape.currentText() if not mLayerName == "": mLayer = ftools_utils.getMapLayerByName( unicode( mLayerName ) ) boundBox = mLayer.extent() self.updateExtents( boundBox )
def run_write_grid(self): self.buttonWriteGrid.setEnabled(False) # Check input data if (self.textXmin.text() == "" or self.textXmax.text() == "" or self.textYmin.text() == "" or self.textYmax.text() == ""): QMessageBox.information( self, self.tr("Gridder"), self.tr("Please specify valid extent coordinates")) elif self.textOutFilename.text() == "": QMessageBox.information( self, self.tr("Gridder"), self.tr("Please specify valid output shapefile")) elif self.sboxXres.value() == 0: QMessageBox.information(self, self.tr("Gridder"), self.tr("Please specify valid resolution")) elif float( self.textXmin.text() ) >= float( self.textXmax.text() ) or \ float( self.textYmin.text() ) >= float( self.textYmax.text() ): QMessageBox.information(self, self.tr("Gridder"), self.tr("Check extent coordinates")) else: try: boundBox = QgsRectangle(float(self.textXmin.text()), float(self.textYmin.text()), float(self.textXmax.text()), float(self.textYmax.text())) except: QMessageBox.information( self, self.tr("Vector grid"), self.tr("Invalid extent coordinates entered")) Xres = self.sboxXres.value() Yres = self.sboxYres.value() # Compute number of elements n = int(round((boundBox.yMaximum() - boundBox.yMinimum()) / Yres)) m = int(round((boundBox.xMaximum() - boundBox.xMinimum()) / Xres)) # Adjust bounding box to respect Yres and Xres with linspace boundBox.setXMaximum(boundBox.xMinimum() + m * Xres) boundBox.setYMaximum(boundBox.yMinimum() + n * Yres) if n * m <= 0: QMessageBox.information( self, self.tr("Gridder"), self.tr("Invalid extent or resolution entered")) return # TO DO : Here, you should check whether elements is correct... # Or add it directly as information in the grid resolution frame QApplication.setOverrideCursor(Qt.WaitCursor) # ------------ Input data validated, build Grid # If a source layer is defined, retrieve CRS if ftools_utils.getMapLayerByName( unicode(self.listSourceLayer.currentText())) != None: crs = ftools_utils.getMapLayerByName( unicode(self.listSourceLayer.currentText())).crs() if not crs.isValid(): crs = None else: crs = None # Initialize field for base feature # TO DO : add useful attributes #fields = {0:QgsField("ID", QVariant.Int)} fields = QgsFields() fields.append(QgsField("ID", QVariant.Int)) # Initialize base rectangle feature rectFeat = QgsFeature() rectGeom = QgsGeometry() rectFeat.setGeometry(rectGeom.fromRect(boundBox)) #rectFeat.setAttributeMap(fields) rectFeat.initAttributes(1) idVar = 0 #rectFeat.addAttribute(0, QVariant(idVar)) rectFeat.setAttribute(0, idVar) # if the file exits, remove it check = QFile(self.OutFileName) if QFile(self.OutFileName).exists(): if not QgsVectorFileWriter.deleteShapeFile(self.OutFileName): return # Load shape file writer writer = QgsVectorFileWriter(unicode(self.textOutFilename.text()), self.encoding, fields, QGis.WKBPolygon, crs) # Call function to make grid qgridder_utils.make_rgrid(rectFeat, n, m, writer, self.progressBarBuildGrid) # Delete writer del writer # Post-operation information QApplication.restoreOverrideCursor() QMessageBox.information( self, self.tr("Generate Vector Grid"), "Created output shapefile:\n" + unicode(self.OutFileName) + "\n") # Load output layer if it is not already loaded if self.checkLoadLayer.isChecked(): # list currently loaded layer. If the layer is loaded, unload it. for (name, layer) in QgsMapLayerRegistry.instance().mapLayers( ).iteritems(): # Note : reload() doesn't work. if layer.source() == self.OutFileName: QgsMapLayerRegistry.instance().removeMapLayers( layer.id()) # load layer ftools_utils.addShapeToCanvas(self.OutFileName) # update layer list in plugin self.populate_layer_list(self.listSourceLayer) # Enable Write Grid button self.buttonWriteGrid.setEnabled(True)
def run_write_grid(self): self.buttonWriteGrid.setEnabled( False ) # Check input data if (self.textXmin.text() == "" or self.textXmax.text() == "" or self.textYmin.text() == "" or self.textYmax.text() == ""): QMessageBox.information(self, self.tr("Gridder"), self.tr("Please specify valid extent coordinates") ) elif self.textOutFilename.text() == "": QMessageBox.information(self, self.tr("Gridder"), self.tr("Please specify valid output shapefile") ) elif self.sboxXres.value() == 0: QMessageBox.information(self, self.tr("Gridder"), self.tr("Please specify valid resolution") ) elif float( self.textXmin.text() ) >= float( self.textXmax.text() ) or \ float( self.textYmin.text() ) >= float( self.textYmax.text() ): QMessageBox.information(self, self.tr("Gridder"), self.tr("Check extent coordinates") ) else: try: boundBox = QgsRectangle( float( self.textXmin.text() ), float( self.textYmin.text() ), float( self.textXmax.text() ), float( self.textYmax.text() ) ) except: QMessageBox.information(self, self.tr("Vector grid"), self.tr("Invalid extent coordinates entered") ) Xres = self.sboxXres.value() Yres = self.sboxYres.value() # Compute number of elements n = int( round( (boundBox.yMaximum() - boundBox.yMinimum()) / Yres ) ) m = int( round( (boundBox.xMaximum() - boundBox.xMinimum()) / Xres ) ) # Adjust bounding box to respect Yres and Xres with linspace boundBox.setXMaximum( boundBox.xMinimum() + m*Xres ) boundBox.setYMaximum( boundBox.yMinimum() + n*Yres ) if n*m <= 0 : QMessageBox.information(self, self.tr("Gridder"), self.tr("Invalid extent or resolution entered") ) return # TO DO : Here, you should check whether elements is correct... # Or add it directly as information in the grid resolution frame QApplication.setOverrideCursor(Qt.WaitCursor) # ------------ Input data validated, build Grid # If a source layer is defined, retrieve CRS if ftools_utils.getMapLayerByName(unicode(self.listSourceLayer.currentText())) != None : crs = ftools_utils.getMapLayerByName(unicode(self.listSourceLayer.currentText())).crs() if not crs.isValid(): crs = None else : crs = None # Initialize field for base feature # TO DO : add useful attributes #fields = {0:QgsField("ID", QVariant.Int)} fields = QgsFields() fields.append(QgsField("ID", QVariant.Int)) # Initialize base rectangle feature rectFeat = QgsFeature() rectGeom = QgsGeometry() rectFeat.setGeometry(rectGeom.fromRect(boundBox)) #rectFeat.setAttributeMap(fields) rectFeat.initAttributes(1) idVar = 0 #rectFeat.addAttribute(0, QVariant(idVar)) rectFeat.setAttribute(0, idVar) # if the file exits, remove it check = QFile(self.OutFileName) if QFile(self.OutFileName).exists(): if not QgsVectorFileWriter.deleteShapeFile(self.OutFileName): return # Load shape file writer writer = QgsVectorFileWriter(unicode(self.textOutFilename.text()), self.encoding, fields, QGis.WKBPolygon, crs) # Call function to make grid qgridder_utils.make_rgrid(rectFeat, n, m, writer, self.progressBarBuildGrid) # Delete writer del writer # Post-operation information QApplication.restoreOverrideCursor() QMessageBox.information(self, self.tr("Generate Vector Grid"), "Created output shapefile:\n" + unicode(self.OutFileName) + "\n" ) # Load output layer if it is not already loaded if self.checkLoadLayer.isChecked(): # list currently loaded layer. If the layer is loaded, unload it. for (name,layer) in QgsMapLayerRegistry.instance().mapLayers().iteritems(): # Note : reload() doesn't work. if layer.source()==self.OutFileName: QgsMapLayerRegistry.instance().removeMapLayers( layer.id() ) # load layer ftools_utils.addShapeToCanvas( self.OutFileName ) # update layer list in plugin self.populate_layer_list(self.listSourceLayer) # Enable Write Grid button self.buttonWriteGrid.setEnabled( True )
def compute(self, bound, xOffset, yOffset, polygon): crs = None layer = ftools_utils.getMapLayerByName(unicode(self.inShape.currentText())) if self.angle.value() != 0.0: bound = self.initRotation(bound) if layer is None: crs = self.iface.mapCanvas().mapRenderer().destinationCrs() else: crs = layer.crs() if not crs.isValid(): crs = None fields = QgsFields() fields.append(QgsField("ID", QVariant.Int)) fieldCount = 1 if polygon: fields.append(QgsField("X_MIN", QVariant.Double)) fields.append(QgsField("X_MAX", QVariant.Double)) fields.append(QgsField("Y_MIN", QVariant.Double)) fields.append(QgsField("Y_MAX", QVariant.Double)) fieldCount = 5 check = QFile(self.shapefileName) if check.exists(): if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName): return writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fields, QGis.WKBPolygon, crs) else: fields.append(QgsField("COORD", QVariant.Double)) fieldCount = 2 check = QFile(self.shapefileName) if check.exists(): if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName): return writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fields, QGis.WKBLineString, crs) outFeat = QgsFeature() outFeat.initAttributes(fieldCount) outFeat.setFields(fields) outGeom = QgsGeometry() idVar = 0 self.progressBar.setValue(0) if not polygon: # counters for progressbar - update every 5% count = 0 count_max = (bound.yMaximum() - bound.yMinimum()) / yOffset count_update = count_max * 0.10 y = bound.yMaximum() while y >= bound.yMinimum(): pt1 = QgsPoint(bound.xMinimum(), y) pt2 = QgsPoint(bound.xMaximum(), y) if self.angle.value() != 0.0: self.rotatePoint(pt1) self.rotatePoint(pt2) line = [pt1, pt2] outFeat.setGeometry(outGeom.fromPolyline(line)) outFeat.setAttribute(0, idVar) outFeat.setAttribute(1, y) writer.addFeature(outFeat) y = y - yOffset idVar = idVar + 1 count += 1 if int(math.fmod(count, count_update)) == 0: prog = int(count / count_max * 50) self.progressBar.setValue(prog) self.progressBar.setValue(50) # counters for progressbar - update every 5% count = 0 count_max = (bound.xMaximum() - bound.xMinimum()) / xOffset count_update = count_max * 0.10 x = bound.xMinimum() while x <= bound.xMaximum(): pt1 = QgsPoint(x, bound.yMaximum()) pt2 = QgsPoint(x, bound.yMinimum()) if self.angle.value() != 0.0: self.rotatePoint(pt1) self.rotatePoint(pt2) line = [pt1, pt2] outFeat.setGeometry(outGeom.fromPolyline(line)) outFeat.setAttribute(0, idVar) outFeat.setAttribute(1, x) writer.addFeature(outFeat) x = x + xOffset idVar = idVar + 1 count += 1 if int(math.fmod(count, count_update)) == 0: prog = 50 + int(count / count_max * 50) self.progressBar.setValue(prog) else: # counters for progressbar - update every 5% count = 0 count_max = (bound.yMaximum() - bound.yMinimum()) / yOffset count_update = count_max * 0.05 y = bound.yMaximum() while y >= bound.yMinimum(): x = bound.xMinimum() while x <= bound.xMaximum(): pt1 = QgsPoint(x, y) pt2 = QgsPoint(x + xOffset, y) pt3 = QgsPoint(x + xOffset, y - yOffset) pt4 = QgsPoint(x, y - yOffset) pt5 = QgsPoint(x, y) if self.angle.value() != 0.0: self.rotatePoint(pt1) self.rotatePoint(pt2) self.rotatePoint(pt3) self.rotatePoint(pt4) self.rotatePoint(pt5) polygon = [[pt1, pt2, pt3, pt4, pt5]] outFeat.setGeometry(outGeom.fromPolygon(polygon)) outFeat.setAttribute(0, idVar) outFeat.setAttribute(1, x) outFeat.setAttribute(2, x + xOffset) outFeat.setAttribute(3, y - yOffset) outFeat.setAttribute(4, y) writer.addFeature(outFeat) idVar = idVar + 1 x = x + xOffset y = y - yOffset count += 1 if int(math.fmod(count, count_update)) == 0: prog = int(count / count_max * 100) self.progressBar.setValue(100) del writer
def compute( self, bound, xOffset, yOffset, polygon ): crs = None layer = ftools_utils.getMapLayerByName(unicode(self.inShape.currentText())) if layer is None: crs = self.iface.mapCanvas().mapRenderer().destinationCrs() else: crs = layer.crs() if not crs.isValid(): crs = None fields = QgsFields() fields.append( QgsField("ID", QVariant.Int) ) fieldCount = 1 if polygon: fields.append( QgsField("X_MIN", QVariant.Double) ) fields.append( QgsField("X_MAX", QVariant.Double) ) fields.append( QgsField("Y_MIN", QVariant.Double) ) fields.append( QgsField("Y_MAX", QVariant.Double) ) fieldCount = 5 check = QFile(self.shapefileName) if check.exists(): if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName): return writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fields, QGis.WKBPolygon, crs) else: fields.append( QgsField("COORD", QVariant.Double) ) fieldCount = 2 check = QFile(self.shapefileName) if check.exists(): if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName): return writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fields, QGis.WKBLineString, crs) outFeat = QgsFeature() outFeat.initAttributes(fieldCount) outFeat.setFields(fields) outGeom = QgsGeometry() idVar = 0 self.progressBar.setValue( 0 ) if not polygon: # counters for progressbar - update every 5% count = 0 count_max = (bound.yMaximum() - bound.yMinimum()) / yOffset count_update = count_max * 0.10 y = bound.yMaximum() while y >= bound.yMinimum(): pt1 = QgsPoint(bound.xMinimum(), y) pt2 = QgsPoint(bound.xMaximum(), y) line = [pt1, pt2] outFeat.setGeometry(outGeom.fromPolyline(line)) outFeat.setAttribute(0, idVar) outFeat.setAttribute(1, y) writer.addFeature(outFeat) y = y - yOffset idVar = idVar + 1 count += 1 if int( math.fmod( count, count_update ) ) == 0: prog = int( count / count_max * 50 ) self.progressBar.setValue( prog ) self.progressBar.setValue( 50 ) # counters for progressbar - update every 5% count = 0 count_max = (bound.xMaximum() - bound.xMinimum()) / xOffset count_update = count_max * 0.10 x = bound.xMinimum() while x <= bound.xMaximum(): pt1 = QgsPoint(x, bound.yMaximum()) pt2 = QgsPoint(x, bound.yMinimum()) line = [pt1, pt2] outFeat.setGeometry(outGeom.fromPolyline(line)) outFeat.setAttribute(0, idVar) outFeat.setAttribute(1, x) writer.addFeature(outFeat) x = x + xOffset idVar = idVar + 1 count += 1 if int( math.fmod( count, count_update ) ) == 0: prog = 50 + int( count / count_max * 50 ) self.progressBar.setValue( prog ) else: # counters for progressbar - update every 5% count = 0 count_max = (bound.yMaximum() - bound.yMinimum()) / yOffset count_update = count_max * 0.05 y = bound.yMaximum() while y >= bound.yMinimum(): x = bound.xMinimum() while x <= bound.xMaximum(): pt1 = QgsPoint(x, y) pt2 = QgsPoint(x + xOffset, y) pt3 = QgsPoint(x + xOffset, y - yOffset) pt4 = QgsPoint(x, y - yOffset) pt5 = QgsPoint(x, y) polygon = [[pt1, pt2, pt3, pt4, pt5]] outFeat.setGeometry(outGeom.fromPolygon(polygon)) outFeat.setAttribute(0, idVar) outFeat.setAttribute(1, x) outFeat.setAttribute(2, x + xOffset) outFeat.setAttribute(3, y - yOffset) outFeat.setAttribute(4, y) writer.addFeature(outFeat) idVar = idVar + 1 x = x + xOffset y = y - yOffset count += 1 if int( math.fmod( count, count_update ) ) == 0: prog = int( count / count_max * 100 ) self.progressBar.setValue( 100 ) del writer
def run_regular_refine(self): # selected grid layer name grid_layer_name = self.listGridLayer.currentText() # number of elements, horizontally n = self.sboxDivideHoriz.value() # number of elements, vertically m = self.sboxDivideVert.value() # Check input data if (type(n) != int or type(m) != int or m<1 or n<1): QMessageBox.information(self, self.tr("Gridder"), self.tr("Can't divide features, please verify the number of elements") ) return elif (grid_layer_name == "") : QMessageBox.information(self, self.tr("Gridder"), self.tr("Please specify a valid vector layer shapefile") ) return if self.settings.dic_settings['model_type'] == 'Nested': if n != m : QMessageBox.information(self, self.tr("Qgridder"), self.tr("Only 1:1 ratio for Nested") ) return if n not in (2, 4) : QMessageBox.information(self, self.tr("Qgridder"), self.tr("For Nested, you can only divide cells by 2 or 4") ) return # Set up topo Rules if self.checkTopo.isChecked() : if self.settings.dic_settings['model_type'] == 'Modflow': topoRules = {'model':'modflow','nmax':1} elif self.settings.dic_settings['model_type'] == 'Nested': topoRules = {'model':'nested', 'nmax':2} else : QMessageBox.information(self, self.tr("Gridder"), self.tr("Unknown model name for topology check") ) return else : topoRules = {'model': None, 'nmax': None} # Load input grid layer grid_layer = ftools_utils.getMapLayerByName( unicode( grid_layer_name ) ) if (grid_layer.selectedFeatureCount() == 0): QMessageBox.information(self, self.tr("Gridder"), self.tr("No selected features in the chosen grid layer.") ) return # Set "wait" cursor and disable button QApplication.setOverrideCursor(Qt.WaitCursor) self.buttonRefine.setEnabled( False ) # Backup input grid layer if self.settings.dic_settings['grid_backup'] == 'True' : if len( self.settings.list_grid_bckup ) < int( self.settings.dic_settings['max_grid_backup'] ) : backup_grid_layer = QgsVectorLayer("Point?crs=" + grid_layer.crs().authid(), 'backupLayer', providerLib = 'memory') success, feature = backup_grid_layer.dataProvider().addFeatures( [feat for feat in grid_layer.getFeatures()] ) self.settings.list_grid_bckup.append( backup_grid_layer ) # Fetch selected features from input grid_layer selected_fIds = grid_layer.selectedFeaturesIds() # Clean user selection grid_layer.setSelectedFeatures([]) # Init labels self.labelIterations.show() self.labelIter.show() self.labelIter.setText(unicode(1)) # Refine grid qgridder_utils.refine_by_split(selected_fIds, n, m, topoRules, grid_layer, self.progressBarRegularRefine, self.labelIter) # Refresh refined grid layer self.iface.mapCanvas().refresh() # Post-operation information QMessageBox.information(self, self.tr("Gridder"), self.tr("Vector Grid Refined") ) # Enable Write Grid button and reset cursor self.buttonRefine.setEnabled( True ) QApplication.restoreOverrideCursor() # Enable undo button if self.settings.dic_settings['grid_backup'] == 'True' : self.buttonUndoRefine.setEnabled(True)