def compute(self, line1, line2, field1, field2, outPath, matType, nearest, progressBar): layer1 = ftools_utils.getVectorLayerByName(line1) layer2 = ftools_utils.getVectorLayerByName(line2) provider1 = layer1.dataProvider() provider2 = layer2.dataProvider() sindex = QgsSpatialIndex() inFeat = QgsFeature() fit2 = provider2.getFeatures() while fit2.nextFeature(inFeat): sindex.insertFeature(inFeat) if nearest < 1: nearest = layer2.featureCount() else: nearest = nearest index1 = provider1.fieldNameIndex(field1) index2 = provider2.fieldNameIndex(field2) sRs = provider1.crs() distArea = QgsDistanceArea() #use srs of the first layer (users should ensure that they are both in the same projection) #distArea.setSourceSRS(sRs) f = open(unicode(outPath), "wb") writer = UnicodeWriter(f) if matType <> "Standard": if matType == "Linear": writer.writerow(["InputID", "TargetID", "Distance"]) else: writer.writerow(["InputID", "MEAN", "STDDEV", "MIN", "MAX"]) self.linearMatrix(writer, provider1, provider2, index1, index2, nearest, distArea, matType, sindex, progressBar) else: self.regularMatrix(writer, provider1, provider2, index1, index2, nearest, distArea, sindex, progressBar) f.close()
def compute(self, inPoly, inLns, inField, outPath, progressBar): polyLayer = ftools_utils.getVectorLayerByName(inPoly) lineLayer = ftools_utils.getVectorLayerByName(inLns) polyProvider = polyLayer.dataProvider() lineProvider = lineLayer.dataProvider() if polyProvider.crs() <> lineProvider.crs(): QMessageBox.warning( self, self.tr("CRS warning!"), self. tr("Warning: Input layers have non-matching CRS.\nThis may cause unexpected results." )) fieldList = ftools_utils.getFieldList(polyLayer) index = polyProvider.fieldNameIndex(unicode(inField)) if index == -1: index = polyProvider.fields().count() fieldList.append( QgsField(unicode(inField), QVariant.Double, "real", 24, 15, self.tr("length field"))) sRs = polyProvider.crs() inFeat = QgsFeature() inFeatB = QgsFeature() outFeat = QgsFeature() inGeom = QgsGeometry() outGeom = QgsGeometry() distArea = QgsDistanceArea() start = 15.00 add = 85.00 / polyProvider.featureCount() check = QFile(self.shapefileName) if check.exists(): if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName): return writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fieldList, polyProvider.geometryType(), sRs) spatialIndex = ftools_utils.createIndex(lineProvider) polyFit = polyProvider.getFeatures() while polyFit.nextFeature(inFeat): inGeom = QgsGeometry(inFeat.geometry()) atMap = inFeat.attributes() lineList = [] length = 0 lineList = spatialIndex.intersects(inGeom.boundingBox()) if len(lineList) > 0: check = 0 else: check = 1 if check == 0: for i in lineList: lineProvider.getFeatures(QgsFeatureRequest().setFilterFid( int(i))).nextFeature(inFeatB) tmpGeom = QgsGeometry(inFeatB.geometry()) if inGeom.intersects(tmpGeom): outGeom = inGeom.intersection(tmpGeom) length = length + distArea.measure(outGeom) outFeat.setGeometry(inGeom) atMap.append(QVariant(length)) outFeat.setAttributes(atMap) #outFeat.setAttribute(index, QVariant(length)) writer.addFeature(outFeat) start = start + 1 progressBar.setValue(start) del writer
def compute(self, line1, line2, field1, field2, outPath, matType, nearest, progressBar): layer1 = ftools_utils.getVectorLayerByName(line1) layer2 = ftools_utils.getVectorLayerByName(line2) if layer1.id() == layer2.id(): if nearest > 0: nearest = nearest + 1 provider1 = layer1.dataProvider() provider2 = layer2.dataProvider() sindex = QgsSpatialIndex() inFeat = QgsFeature() fit2 = provider2.getFeatures() while fit2.nextFeature(inFeat): sindex.insertFeature(inFeat) if nearest < 1: nearest = layer2.featureCount() else: nearest = nearest index1 = provider1.fieldNameIndex(field1) index2 = provider2.fieldNameIndex(field2) sRs = provider1.crs() distArea = QgsDistanceArea() #use srs of the first layer (users should ensure that they are both in the same projection) #distArea.setSourceSRS(sRs) f = open(unicode(outPath), "wb") writer = UnicodeWriter(f) if matType <> "Standard": if matType == "Linear": writer.writerow(["InputID", "TargetID", "Distance"]) else: writer.writerow(["InputID", "MEAN", "STDDEV", "MIN", "MAX"]) self.linearMatrix(writer, provider1, provider2, index1, index2, nearest, distArea, matType, sindex, progressBar) else: self.regularMatrix(writer, provider1, provider2, index1, index2, nearest, distArea, sindex, progressBar) f.close()
def reProject(self, inName, outPath, outProj, predefined, progressBar): vlayer = ftools_utils.getVectorLayerByName(inName) provider = vlayer.dataProvider() feat = QgsFeature() allAttrs = provider.attributeIndexes() progressBar.setValue(2) provider.select(allAttrs) fieldList = ftools_utils.getFieldList(vlayer) crsDest = QgsCoordinateReferenceSystem() if predefined: crsDest.createFromProj4(outProj) else: destLayer = ftools_utils.getVectorLayerByName(outProj) crsDest = destLayer.dataProvider().crs() if not crsDest.isValid(): QMessageBox.information(self, self.tr("Export to new projection"), self.tr("Output spatial reference system is not valid")) return False else: progressBar.setValue(5) crsSrc = provider.crs() if crsSrc != crsDest: xform = QgsCoordinateTransform(crsSrc, crsDest) progressBar.setValue(10) check = QFile(self.shapefileName) if check.exists(): if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName): return error = QgsVectorFileWriter.writeAsShapefile(vlayer, self.shapefileName, self.encoding, crsDest, False) if error == QgsVectorFileWriter.NoError: return True else: return False else: QMessageBox.information(self, self.tr("Export to new projection"), self.tr("Identical output spatial reference system chosen")) return False
def compute(self, inPoly, inLns, inField, outPath, progressBar): polyLayer = ftools_utils.getVectorLayerByName(inPoly) lineLayer = ftools_utils.getVectorLayerByName(inLns) polyProvider = polyLayer.dataProvider() lineProvider = lineLayer.dataProvider() if polyProvider.crs() <> lineProvider.crs(): QMessageBox.warning(self, self.tr("CRS warning!"), self.tr("Warning: Input layers have non-matching CRS.\nThis may cause unexpected results.")) allAttrs = polyProvider.attributeIndexes() polyProvider.select(allAttrs) allAttrs = lineProvider.attributeIndexes() lineProvider.select(allAttrs) fieldList = ftools_utils.getFieldList(polyLayer) index = polyProvider.fieldNameIndex(unicode(inField)) if index == -1: index = polyProvider.fieldCount() field = QgsField(unicode(inField), QVariant.Double, "real", 24, 15, self.tr("length field")) fieldList[index] = field sRs = polyProvider.crs() inFeat = QgsFeature() inFeatB = QgsFeature() outFeat = QgsFeature() inGeom = QgsGeometry() outGeom = QgsGeometry() distArea = QgsDistanceArea() lineProvider.rewind() start = 15.00 add = 85.00 / polyProvider.featureCount() check = QFile(self.shapefileName) if check.exists(): if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName): return writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fieldList, polyProvider.geometryType(), sRs) #writer = QgsVectorFileWriter(outPath, "UTF-8", fieldList, polyProvider.geometryType(), sRs) spatialIndex = ftools_utils.createIndex( lineProvider ) while polyProvider.nextFeature(inFeat): inGeom = QgsGeometry(inFeat.geometry()) atMap = inFeat.attributeMap() lineList = [] length = 0 #(check, lineList) = lineLayer.featuresInRectangle(inGeom.boundingBox(), True, False) #lineLayer.select(inGeom.boundingBox(), False) #lineList = lineLayer.selectedFeatures() lineList = spatialIndex.intersects(inGeom.boundingBox()) if len(lineList) > 0: check = 0 else: check = 1 if check == 0: for i in lineList: lineProvider.featureAtId( int( i ), inFeatB , True, allAttrs ) tmpGeom = QgsGeometry( inFeatB.geometry() ) if inGeom.intersects(tmpGeom): outGeom = inGeom.intersection(tmpGeom) length = length + distArea.measure(outGeom) outFeat.setGeometry(inGeom) outFeat.setAttributeMap(atMap) outFeat.addAttribute(index, QVariant(length)) writer.addFeature(outFeat) start = start + 1 progressBar.setValue(start) del writer
def saveCalculation(self): import ftools_utils selected = self.ui.twCalculations.selectedItems() for item in selected: if item.column() == 0: cLyr = ftools_utils.getVectorLayerByName( self.ui.cbxPlanningGrid.currentText()) item.setText(cLyr.source()) elif item.column() == 1: item.setText(self.ui.cbxPuId.currentText()) elif item.column() == 2: if self.ui.rdoRaster.isChecked() == True: for key, value in QgsMapLayerRegistry.instance().mapLayers( ).iteritems(): if ('raster' in str(value.__class__).lower()) and \ (str(value.name()) == self.ui.cbxMeasureLayer.currentText()): item.setText(str(value.source())) else: cLyr = ftools_utils.getVectorLayerByName( self.ui.cbxMeasureLayer.currentText()) item.setText(cLyr.source()) elif item.column() == 3: if self.ui.rdoCalcSingle.isChecked() == True: item.setText('single') else: item.setText('multiple') elif item.column() == 4: if self.ui.rdoMeasure.isChecked() == True: item.setText('measure') elif self.ui.rdoCalculate.isChecked() == True: item.setText('calculate') else: item.setText('presence') elif item.column() == 5: if self.ui.cbxCalcField.isEnabled(): item.setText(self.ui.cbxCalcField.currentText()) else: item.setText = '' elif item.column() == 6: if self.ui.rdoSum.isChecked() == True: item.setText('sum') elif self.ui.rdoMean.isChecked() == True: item.setText('mean') elif self.ui.rdoMax.isChecked() == True: item.setText('max') elif self.ui.rdoMin.isChecked() == True: item.setText('min') else: item.setText('count') elif item.column() == 7: outText = self.ui.cbxSelectField.currentText() if outText == "--Create New--": item.setText(self.ui.leNewField.text()) else: item.setText(outText) self.cancelCalcEdit() if self.ui.twCalculations.rowCount() > 0: self.ui.pbRun.setEnabled(True)
def accept(self): if self.inPolygon.currentText() == "": QMessageBox.information( self, self.tr("Count Points In Polygon"), self.tr("Please specify input polygon vector layer")) elif self.inPoint.currentText() == "": QMessageBox.information( self, self.tr("Count Points In Polygon"), self.tr("Please specify input point vector layer")) elif self.lnField.text() == "": QMessageBox.information( self, self.tr("Count Points In Polygon"), self.tr("Please specify output count field")) elif self.outShape.text() == "": QMessageBox.information(self, self.tr("Count Points In Polygon"), self.tr("Please specify output shapefile")) else: inPoly = ftools_utils.getVectorLayerByName( self.inPolygon.currentText()) inPnts = ftools_utils.getVectorLayerByName( self.inPoint.currentText()) polyProvider = inPoly.dataProvider() pointProvider = inPnts.dataProvider() if polyProvider.crs() != pointProvider.crs(): QMessageBox.warning( self, self.tr("CRS warning!"), self. tr("Warning: Input layers have non-matching CRS.\nThis may cause unexpected results." )) self.btnOk.setEnabled(False) self.workThread = PointsInPolygonThread(inPoly, inPnts, self.lnField.text(), self.outShape.text(), self.encoding, self.attributeList, self.statisticSelector) QObject.connect(self.workThread, SIGNAL("rangeChanged(int)"), self.setProgressRange) QObject.connect(self.workThread, SIGNAL("updateProgress()"), self.updateProgress) QObject.connect(self.workThread, SIGNAL("processingFinished()"), self.processFinished) QObject.connect(self.workThread, SIGNAL("processingInterrupted()"), self.processInterrupted) self.btnClose.setText(self.tr("Cancel")) QObject.disconnect(self.buttonBox, SIGNAL("rejected()"), self.reject) QObject.connect(self.btnClose, SIGNAL("clicked()"), self.stopProcessing) self.workThread.start()
def compute(self, inPoly, inLns, inField, outPath, progressBar): polyLayer = ftools_utils.getVectorLayerByName(inPoly) lineLayer = ftools_utils.getVectorLayerByName(inLns) polyProvider = polyLayer.dataProvider() lineProvider = lineLayer.dataProvider() if polyProvider.crs() <> lineProvider.crs(): QMessageBox.warning( self, self.tr("CRS warning!"), self.tr("Warning: Input layers have non-matching CRS.\nThis may cause unexpected results."), ) fieldList = ftools_utils.getFieldList(polyLayer) index = polyProvider.fieldNameIndex(unicode(inField)) if index == -1: index = polyProvider.fields().count() fieldList.append(QgsField(unicode(inField), QVariant.Double, "real", 24, 15, self.tr("length field"))) sRs = polyProvider.crs() inFeat = QgsFeature() inFeatB = QgsFeature() outFeat = QgsFeature() inGeom = QgsGeometry() outGeom = QgsGeometry() distArea = QgsDistanceArea() start = 0.00 add = 100.00 / polyProvider.featureCount() check = QFile(self.shapefileName) if check.exists(): if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName): return writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fieldList, polyProvider.geometryType(), sRs) spatialIndex = ftools_utils.createIndex(lineProvider) polyFit = polyProvider.getFeatures() while polyFit.nextFeature(inFeat): inGeom = QgsGeometry(inFeat.geometry()) atMap = inFeat.attributes() lineList = [] length = 0 lineList = spatialIndex.intersects(inGeom.boundingBox()) if len(lineList) > 0: check = 0 else: check = 1 if check == 0: for i in lineList: lineProvider.getFeatures(QgsFeatureRequest().setFilterFid(int(i))).nextFeature(inFeatB) tmpGeom = QgsGeometry(inFeatB.geometry()) if inGeom.intersects(tmpGeom): outGeom = inGeom.intersection(tmpGeom) length = length + distArea.measure(outGeom) outFeat.setGeometry(inGeom) atMap.append(length) outFeat.setAttributes(atMap) writer.addFeature(outFeat) start = start + 1 progressBar.setValue(start * (add)) del writer
def saveCalculation(self): import ftools_utils selected = self.ui.twCalculations.selectedItems() for item in selected: if item.column() == 0: cLyr = ftools_utils.getVectorLayerByName(self.ui.cbxPlanningGrid.currentText()) item.setText(cLyr.source()) elif item.column() == 1: item.setText(self.ui.cbxPuId.currentText()) elif item.column() == 2: if self.ui.rdoRaster.isChecked() == True: for key, value in QgsMapLayerRegistry.instance().mapLayers().iteritems(): if ('raster' in str(value.__class__).lower()) and \ (str(value.name()) == self.ui.cbxMeasureLayer.currentText()): item.setText(str(value.source())) else: cLyr = ftools_utils.getVectorLayerByName(self.ui.cbxMeasureLayer.currentText()) item.setText(cLyr.source()) elif item.column() == 3: if self.ui.rdoCalcSingle.isChecked() == True: item.setText('single') else: item.setText('multiple') elif item.column() == 4: if self.ui.rdoMeasure.isChecked() == True: item.setText('measure') elif self.ui.rdoCalculate.isChecked() == True: item.setText('calculate') else: item.setText('presence') elif item.column() == 5: if self.ui.cbxCalcField.isEnabled(): item.setText(self.ui.cbxCalcField.currentText()) else: item.setText = '' elif item.column() == 6: if self.ui.rdoSum.isChecked() == True: item.setText('sum') elif self.ui.rdoMean.isChecked() == True: item.setText('mean') elif self.ui.rdoMax.isChecked() == True: item.setText('max') elif self.ui.rdoMin.isChecked() == True: item.setText('min') else: item.setText('count') elif item.column() == 7: outText = self.ui.cbxSelectField.currentText() if outText == "--Create New--": item.setText(self.ui.leNewField.text()) else: item.setText(outText) self.cancelCalcEdit() if self.ui.twCalculations.rowCount() > 0: self.ui.pbRun.setEnabled(True)
def compute(self, inPoly, inPts, inField, outPath, progressBar): polyLayer = ftools_utils.getVectorLayerByName(inPoly) pointLayer = ftools_utils.getVectorLayerByName(inPts) polyProvider = polyLayer.dataProvider() pointProvider = pointLayer.dataProvider() if polyProvider.crs() <> pointProvider.crs(): QMessageBox.warning(self, self.tr("CRS warning!"), self.tr("Warning: Input layers have non-matching CRS.\nThis may cause unexpected results.")) allAttrs = polyProvider.attributeIndexes() polyProvider.select(allAttrs) allAttrs = pointProvider.attributeIndexes() pointProvider.select(allAttrs) fieldList = ftools_utils.getFieldList(polyLayer) index = polyProvider.fieldNameIndex(unicode(inField)) if index == -1: index = polyProvider.fieldCount() field = QgsField(unicode(inField), QVariant.Double, "real", 24, 15, self.tr("point count field")) fieldList[index] = field sRs = polyProvider.crs() check = QFile(self.shapefileName) if check.exists(): if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName): return writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fieldList, polyProvider.geometryType(), sRs) inFeat = QgsFeature() inFeatB = QgsFeature() outFeat = QgsFeature() inGeom = QgsGeometry() start = 15.00 add = 85.00 / polyProvider.featureCount() spatialIndex = ftools_utils.createIndex( pointProvider ) while polyProvider.nextFeature(inFeat): inGeom = inFeat.geometry() atMap = inFeat.attributeMap() outFeat.setAttributeMap(atMap) outFeat.setGeometry(inGeom) pointList = [] count = 0 #(check, pointList) = pointLayer.featuresInRectangle(inGeom.boundingBox(), True, True) #pointLayer.select(inGeom.boundingBox(), False) #pointList = pointLayer.selectedFeatures() pointList = spatialIndex.intersects(inGeom.boundingBox()) if len(pointList) > 0: check = 0 else: check = 1 if check == 0: for i in pointList: pointProvider.featureAtId( int( i ), inFeatB , True, allAttrs ) tmpGeom = QgsGeometry( inFeatB.geometry() ) if inGeom.contains(tmpGeom.asPoint()): count = count + 1 outFeat.setAttributeMap(atMap) outFeat.addAttribute(index, QVariant(count)) writer.addFeature(outFeat) start = start + 1 progressBar.setValue(start) del writer
def accept( self ): vLayer = ftools_utils.getVectorLayerByName( self.cmbInputLayer.currentText() ) self.btnOk.setEnabled( False ) if self.chkWriteShapefile.isChecked(): outFileName = self.edOutputFile.text() outFile = QFile( outFileName ) if outFile.exists(): if not QgsVectorFileWriter.deleteShapeFile( outFileName ): QMessageBox.warning( self, self.tr( "Delete error" ), self.tr( "Can't delete file %1" ).arg( outFileName ) ) return self.workThread = GeomThread( self.myFunction, vLayer, self.chkUseSelection.isChecked(), self.spnTolerance.value(), True, outFileName, self.encoding ) else: self.workThread = GeomThread( self.myFunction, vLayer, self.chkUseSelection.isChecked(), self.spnTolerance.value(), False, None, None ) QObject.connect( self.workThread, SIGNAL( "rangeCalculated( PyQt_PyObject )" ), self.setProgressRange ) QObject.connect( self.workThread, SIGNAL( "featureProcessed()" ), self.featureProcessed ) QObject.connect( self.workThread, SIGNAL( "processingFinished( PyQt_PyObject )" ), self.processFinished ) QObject.connect( self.workThread, SIGNAL( "processingInterrupted()" ), self.processInterrupted ) self.btnClose.setText( self.tr( "Cancel" ) ) QObject.disconnect( self.buttonBox, SIGNAL( "rejected()" ), self.reject ) QObject.connect( self.btnClose, SIGNAL( "clicked()" ), self.stopProcessing ) self.workThread.start()
def accept( self ): vLayer = ftools_utils.getVectorLayerByName( self.cmbInputLayer.currentText() ) self.okButton.setEnabled( False ) if self.writeShapefileCheck.isChecked(): outFileName = self.outputFileEdit.text() outFile = QFile( outFileName ) if outFile.exists(): if not QgsVectorFileWriter.deleteShapeFile( outFileName ): QmessageBox.warning( self, self.tr( "Delete error" ), self.tr( "Can't delete file %1" ).arg( outFileName ) ) return self.simplifyThread = GeneralizationThread( vLayer, self.useSelectionCheck.isChecked(), self.toleranceSpin.value(), True, outFileName, self.encoding ) else: self.simplifyThread = GeneralizationThread( vLayer, self.useSelectionCheck.isChecked(), self.toleranceSpin.value(), False, None, None ) QObject.connect( self.simplifyThread, SIGNAL( "rangeCalculated( PyQt_PyObject )" ), self.setProgressRange ) QObject.connect( self.simplifyThread, SIGNAL( "featureProcessed()" ), self.featureProcessed ) QObject.connect( self.simplifyThread, SIGNAL( "generalizationFinished( PyQt_PyObject )" ), self.generalizationFinished ) QObject.connect( self.simplifyThread, SIGNAL( "generalizationInterrupted()" ), self.generalizationInterrupted ) self.closeButton.setText( self.tr( "Cancel" ) ) QObject.disconnect( self.buttonBox, SIGNAL( "rejected()" ), self.reject ) QObject.connect( self.closeButton, SIGNAL( "clicked()" ), self.stopProcessing ) self.simplifyThread.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 accept(self): self.buttonOk.setEnabled(False) if self.inShape.currentText() == "": QMessageBox.information(self, self.tr("Random Selection Tool"), self.tr("No input shapefile specified")) return else: self.progressBar.setValue(10) inName = self.inShape.currentText() self.progressBar.setValue(20) layer = ftools_utils.getVectorLayerByName(inName) self.progressBar.setValue(30) if self.rdoNumber.isChecked(): value = self.spnNumber.value() self.progressBar.setValue(60) else: value = self.spnPercent.value() self.progressBar.setValue(50) value = int( round((value / 100.0000), 4) * layer.featureCount()) self.progressBar.setValue(60) selran = random.sample(xrange(0, layer.featureCount()), value) self.progressBar.setValue(70) self.progressBar.setValue(80) self.progressBar.setValue(90) self.progressBar.setValue(100) layer.setSelectedFeatures(selran) self.progressBar.setValue(0) self.buttonOk.setEnabled(True)
def accept(self): inShape = self.inShape.currentText() outDir = self.outShape.text() if inShape == "": QMessageBox.information(self, self.tr("Vector Split"), self.tr("No input shapefile specified")) return elif outDir == "": QMessageBox.information(self, self.tr("Vector Split"), self.tr("Please specify output shapefile")) return self.btnOk.setEnabled( False ) vLayer = ftools_utils.getVectorLayerByName(unicode(self.inShape.currentText())) self.workThread = SplitThread(vLayer, self.inField.currentText(), self.encoding, outDir) QObject.connect(self.workThread, SIGNAL("rangeCalculated(PyQt_PyObject)"), self.setProgressRange) QObject.connect(self.workThread, SIGNAL("valueProcessed()"), self.valueProcessed) QObject.connect(self.workThread, SIGNAL("processFinished(PyQt_PyObject)"), self.processFinished) QObject.connect(self.workThread, SIGNAL("processInterrupted()"), self.processInterrupted) self.btnClose.setText(self.tr("Cancel")) QObject.disconnect(self.buttonBox_2, SIGNAL("rejected()"), self.reject) QObject.connect(self.btnClose, SIGNAL("clicked()"), self.stopProcessing) self.workThread.start()
def update2(self, inputLayer): self.inField2.clear() changedLayer = ftools_utils.getVectorLayerByName(unicode(inputLayer)) changedField = ftools_utils.getFieldList(changedLayer) for f in changedField: if f.type() == QVariant.Int or f.type() == QVariant.String: self.inField2.addItem(unicode(f.name()))
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 update1(self, inputLayer): self.inField1.clear() changedLayer = ftools_utils.getVectorLayerByName(unicode(inputLayer)) changedField = ftools_utils.getFieldList(changedLayer) for f in changedField: if f.type() == QVariant.Int or f.type() == QVariant.String: self.inField1.addItem(unicode(f.name()))
def accept(self): self.buttonOk.setEnabled( False ) if self.inShape.currentText() == "": QMessageBox.information(self, self.tr("Random Selection Tool"), self.tr("No input shapefile specified")) return else: self.progressBar.setValue(10) inName = self.inShape.currentText() self.progressBar.setValue(20) layer = ftools_utils.getVectorLayerByName(inName) self.progressBar.setValue(30) if self.rdoNumber.isChecked(): value = self.spnNumber.value() self.progressBar.setValue(60) else: value = self.spnPercent.value() self.progressBar.setValue(50) value = int(round((value / 100.0000), 4) * layer.featureCount()) self.progressBar.setValue(60) selran = random.sample(xrange(0, layer.featureCount()), value) self.progressBar.setValue(70) self.progressBar.setValue(80) self.progressBar.setValue(90) self.progressBar.setValue(100) layer.setSelectedFeatures(selran) 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 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("Vector Split"), self.tr("No input shapefile specified")) elif self.outShape.text() == "": QMessageBox.information(self, self.tr("Vector Split"), self.tr("Please specify output shapefile")) else: inField = self.inField.currentText() inLayer = ftools_utils.getVectorLayerByName( unicode(self.inShape.currentText())) self.progressBar.setValue(5) outPath = QString(self.folderName) self.progressBar.setValue(10) if outPath.contains("\\"): outPath.replace("\\", "/") self.progressBar.setValue(15) if not outPath.endsWith("/"): outPath = outPath + "/" self.split(inLayer, unicode(outPath), unicode(inField), self.progressBar) self.progressBar.setValue(100) self.outShape.clear() QMessageBox.information( self, self.tr("Vector Split"), self.tr("Created output shapefiles in folder:\n%1").arg( outPath)) self.progressBar.setValue(0) self.buttonOk.setEnabled(True)
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 visual(self, myLayer, myField, mySelection): vlayer = ftools_utils.getVectorLayerByName(myLayer) self.tblUnique.clearContents() self.tblUnique.setRowCount(0) self.lstCount.clear() self.buttonOk.setEnabled(False) self.testThread = visualThread(self.iface.mainWindow(), self, self.myFunction, vlayer, myField, mySelection) 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) QObject.connect(self.testThread, SIGNAL("runPartRange(PyQt_PyObject)"), self.runPartRangeFromThread) QObject.connect(self.testThread, SIGNAL("runPartStatus(PyQt_PyObject)"), self.runPartStatusFromThread) self.cancel_close.setText(self.tr("Cancel")) QObject.connect(self.cancel_close, SIGNAL("clicked()"), self.cancelThread) QApplication.setOverrideCursor(Qt.WaitCursor) self.testThread.start() return True
def accept(self): if not self.cmbInputLayer.currentText(): QMessageBox.warning(self, self.tr("Warning"), self.tr("Please specify an input layer")) return vLayer = ftools_utils.getVectorLayerByName( self.cmbInputLayer.currentText()) self.btnOk.setEnabled(False) if self.chkWriteShapefile.isChecked(): outFileName = self.edOutputFile.text() outFile = QFile(outFileName) if outFile.exists(): if not QgsVectorFileWriter.deleteShapeFile(outFileName): QMessageBox.warning( self, self.tr("Delete error"), self.tr("Can't delete file %s") % (outFileName)) self.btnOk.setEnabled(False) return self.workThread = GeomThread(self.myFunction, vLayer, self.chkUseSelection.isChecked(), self.spnTolerance.value(), True, outFileName, self.encoding) else: res = QMessageBox.warning( self, self.tr("Warning"), 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: self.btnOk.setEnabled(False) return self.workThread = GeomThread(self.myFunction, vLayer, self.chkUseSelection.isChecked(), self.spnTolerance.value(), False, None, None) QObject.connect(self.workThread, SIGNAL("rangeCalculated( PyQt_PyObject )"), self.setProgressRange) QObject.connect(self.workThread, SIGNAL("featureProcessed()"), self.featureProcessed) QObject.connect(self.workThread, SIGNAL("processingFinished( PyQt_PyObject )"), self.processFinished) QObject.connect(self.workThread, SIGNAL("processingInterrupted()"), self.processInterrupted) self.btnClose.setText(self.tr("Cancel")) QObject.disconnect(self.buttonBox, SIGNAL("rejected()"), self.reject) QObject.connect(self.btnClose, SIGNAL("clicked()"), self.stopProcessing) self.workThread.start()
def fillLayersList( self ): self.lstLayers.clear() layers = ftools_utils.getLayerNames( [ QGis.Line, QGis.Point, QGis.Polygon ] ) for lay in layers: source = ftools_utils.getVectorLayerByName( lay ).source() item = QListWidgetItem( lay, self.lstLayers ) item.setData( Qt.UserRole, source ) item.setData( Qt.ToolTipRole, source )
def accept( self ): if self.inShape.currentText() == "": QMessageBox.information( self, self.tr("Error!"), self.tr( "Please specify input vector layer" ) ) elif self.cmbField.isVisible() and self.cmbField.currentText() == "": QMessageBox.information( self, self.tr("Error!"), self.tr( "Please specify input field" ) ) else: self.vlayer = ftools_utils.getVectorLayerByName( self.inShape.currentText() ) self.validate( self.useSelected.checkState() )
def update1(self, inputLayer): self.inField1.clear() changedLayer = ftools_utils.getVectorLayerByName(unicode(inputLayer)) changedField = ftools_utils.getFieldList(changedLayer) for i in changedField: if changedField[i].type() == QVariant.Int or \ changedField[i].type() == QVariant.String: self.inField1.addItem(unicode(changedField[i].name()))
def jupdate(self): inputLayer = self.joinShape.currentText() if inputLayer != "": changedLayer = ftools_utils.getVectorLayerByName(unicode(inputLayer)) changedField = ftools_utils.getFieldList(changedLayer) self.joinField.clear() for i in changedField: self.joinField.addItem(unicode(changedField[i].name()))
def updateProj2(self, layerName): self.outRef.clear() tempLayer = ftools_utils.getVectorLayerByName(layerName) crs = tempLayer.dataProvider().crs() if crs.isValid(): self.outRef.insert(crs.authid() + " - " + crs.description()) else: self.outRef.insert( self.tr( "Missing or invalid CRS" ) )
def update(self, inputLayer): self.inField.clear() changedLayer = ftools_utils.getVectorLayerByName(inputLayer) changedField = ftools_utils.getFieldList(changedLayer) for f in changedField: self.inField.addItem(unicode(f.name())) maxFeatures = changedLayer.dataProvider().featureCount() self.spnNumber.setMaximum(maxFeatures)
def update2(self, inputLayer): self.inField2.clear() changedLayer = ftools_utils.getVectorLayerByName(unicode(inputLayer)) changedField = ftools_utils.getFieldList(changedLayer) for i in changedField: if changedField[i].type() == QVariant.Int or \ changedField[i].type() == QVariant.String: self.inField2.addItem(unicode(changedField[i].name()))
def updateProj2(self, layerName): self.outRef.clear() tempLayer = ftools_utils.getVectorLayerByName(layerName) crs = tempLayer.dataProvider().crs() if crs.isValid(): self.outRef.insert(crs.authid() + " - " + crs.description()) else: self.outRef.insert(self.tr("Missing or invalid CRS"))
def compute(self, inPoly, inPts, modify, selection): inputLayer = ftools_utils.getVectorLayerByName(inPoly) selectLayer = ftools_utils.getVectorLayerByName(inPts) inputProvider = inputLayer.dataProvider() allAttrs = inputProvider.attributeIndexes() inputProvider.select(allAttrs, QgsRectangle()) selectProvider = selectLayer.dataProvider() allAttrs = selectProvider.attributeIndexes() selectProvider.select(allAttrs, QgsRectangle()) feat = QgsFeature() infeat = QgsFeature() geom = QgsGeometry() selectedSet = [] index = ftools_utils.createIndex(inputProvider) inputProvider.rewind() inputProvider.select(inputProvider.attributeIndexes()) if selection: features = selectLayer.selectedFeatures() self.progressBar.setMaximum(len(features)) for feat in features: geom = QgsGeometry(feat.geometry()) intersects = index.intersects(geom.boundingBox()) for id in intersects: inputProvider.featureAtId(int(id), infeat, True) tmpGeom = QgsGeometry(infeat.geometry()) if geom.intersects(tmpGeom): selectedSet.append(infeat.id()) self.progressBar.setValue(self.progressBar.value() + 1) else: self.progressBar.setMaximum(selectProvider.featureCount()) while selectProvider.nextFeature(feat): geom = QgsGeometry(feat.geometry()) intersects = index.intersects(geom.boundingBox()) for id in intersects: inputProvider.featureAtId(int(id), infeat, True) tmpGeom = QgsGeometry(infeat.geometry()) if geom.intersects(tmpGeom): selectedSet.append(infeat.id()) self.progressBar.setValue(self.progressBar.value() + 1) if modify == self.tr("adding to current selection"): selectedSet = list( set(inputLayer.selectedFeaturesIds()).union(selectedSet)) elif modify == self.tr("removing from current selection"): selectedSet = list( set(inputLayer.selectedFeaturesIds()).difference(selectedSet)) inputLayer.setSelectedFeatures(selectedSet)
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 update( self ): self.cmbField.clear() inputLayer = unicode( self.inShape.currentText() ) if inputLayer != "": changedLayer = ftools_utils.getVectorLayerByName( inputLayer ) changedField = ftools_utils.getFieldList( changedLayer ) for f in changedField: self.cmbField.addItem( unicode( f.name() ) ) self.cmbField.addItem( "--- " + self.tr( "Merge all" ) + " ---" )
def accept(self): if self.inShape.currentText() == "": QMessageBox.information(self, "Voronoi/Thiessen tesselation", "Please specify input point layer") elif self.outShape.text() == "": QMessageBox.information(self, "Voronoi/Thiessen tesselations", "Please specify output polygon shapefile") else: self.outShape.clear() self.vlayer = ftools_utils.getVectorLayerByName( self.inShape.currentText() ) self.voronoi()
def compute(self, inPoly, inPts, modify, selection): inputLayer = ftools_utils.getVectorLayerByName(inPoly) selectLayer = ftools_utils.getVectorLayerByName(inPts) inputProvider = inputLayer.dataProvider() allAttrs = inputProvider.attributeIndexes() inputProvider.select(allAttrs, QgsRectangle()) selectProvider = selectLayer.dataProvider() allAttrs = selectProvider.attributeIndexes() selectProvider.select(allAttrs, QgsRectangle()) feat = QgsFeature() infeat = QgsFeature() geom = QgsGeometry() selectedSet = [] index = ftools_utils.createIndex(inputProvider) inputProvider.rewind() inputProvider.select(inputProvider.attributeIndexes()) if selection: features = selectLayer.selectedFeatures() self.progressBar.setMaximum(len(features)) for feat in features: geom = QgsGeometry(feat.geometry()) intersects = index.intersects(geom.boundingBox()) for id in intersects: inputProvider.featureAtId(int(id), infeat, True) tmpGeom = QgsGeometry(infeat.geometry()) if geom.intersects(tmpGeom): selectedSet.append(infeat.id()) self.progressBar.setValue(self.progressBar.value()+1) else: self.progressBar.setMaximum(selectProvider.featureCount()) while selectProvider.nextFeature(feat): geom = QgsGeometry(feat.geometry()) intersects = index.intersects(geom.boundingBox()) for id in intersects: inputProvider.featureAtId(int(id), infeat, True) tmpGeom = QgsGeometry( infeat.geometry() ) if geom.intersects(tmpGeom): selectedSet.append(infeat.id()) self.progressBar.setValue(self.progressBar.value()+1) if modify == self.tr("adding to current selection"): selectedSet = list(set(inputLayer.selectedFeaturesIds()).union(selectedSet)) elif modify == self.tr("removing from current selection"): selectedSet = list(set(inputLayer.selectedFeaturesIds()).difference(selectedSet)) inputLayer.setSelectedFeatures(selectedSet)
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 setCalcFields(self): import ftools_utils self.ui.cbxCalcField.clear() calcLayer = self.ui.cbxMeasureLayer.currentText() selectedLayer = ftools_utils.getVectorLayerByName(unicode(calcLayer)) if selectedLayer != None: fields = ftools_utils.getFieldList(selectedLayer) for i in fields: if fields[i].type() == QtCore.QVariant.Int or \ fields[i].type() == QtCore.QVariant.Double: self.ui.cbxCalcField.addItem(unicode(fields[i].name()))
def update(self, inputLayer): self.weightField.clear() self.uniqueField.clear() self.weightField.addItem(self.tr("(Optional) Weight field")) self.uniqueField.addItem(self.tr("(Optional) Unique ID field")) self.changedLayer = ftools_utils.getVectorLayerByName(inputLayer) changedField = ftools_utils.getFieldList(self.changedLayer) for f in changedField: if f.type() == QVariant.Int or f.type() == QVariant.Double: self.weightField.addItem(unicode(f.name())) self.uniqueField.addItem(unicode(f.name()))
def update(self, inputLayer): self.weightField.clear() self.uniqueField.clear() self.weightField.addItem( self.tr("(Optional) Weight field") ) self.uniqueField.addItem( self.tr("(Optional) Unique ID field") ) self.changedLayer = ftools_utils.getVectorLayerByName(inputLayer) changedField = ftools_utils.getFieldList(self.changedLayer) for i in changedField: if changedField[i].type() == QVariant.Int or changedField[i].type() == QVariant.Double: self.weightField.addItem(unicode(changedField[i].name())) self.uniqueField.addItem(unicode(changedField[i].name()))
def run(self): #from tools.doAbout import GdalToolsAboutDialog as About #d = About( self.iface ) #d.exec_() layer = ftools_utils.getVectorLayerByName('heighway') provider = layer.dataProvider() feat = QgsFeature() allAttrs = provider.attributeIndexes() provider.select(allAttrs) vfile = VissimData.VissimFile('d:/kuku_vissim.inp') wgs84 = QgsCoordinateReferenceSystem( 4326, QgsCoordinateReferenceSystem.EpsgCrsId) beijing = QgsCoordinateReferenceSystem( 2404, QgsCoordinateReferenceSystem.EpsgCrsId) i = 1 while provider.nextFeature(feat): #iterate all features geom = feat.geometry() if geom == None: QMessageBox.information(None, '', 'no geometry exist') break pline = geom.asPolyline() QMessageBox.information(None, '', ' pline points number: %d' % len(pline)) xform = QgsCoordinateTransform(wgs84, beijing) points = [] for p in pline: points.append(xform.transform(p)) link = VissimData.Link(i) link.setGeometry(points) link.lanes = 2 vfile.appendLink(link) i += 1 #add reverse link points.reverse() pointsReverse = [] for pt in points: pointsReverse.append(QgsPoint(pt.x(), pt.y() + 15)) link = VissimData.Link(i) link.lanes = 2 link.setGeometry(pointsReverse) vfile.appendLink(link) i += 1 vfile.save() QMessageBox.information(None, '', 'finished')
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 setFields(self, planningGrid): import ftools_utils self.ui.cbxSelectField.clear() self.ui.cbxIdField.clear() selectedLayer = ftools_utils.getVectorLayerByName(unicode(planningGrid)) if selectedLayer != None: self.ui.cbxSelectField.addItem(unicode("--Create New--")) fields = ftools_utils.getFieldList(selectedLayer) for i in fields: if fields[i].type() == QtCore.QVariant.Int or \ fields[i].type() == QtCore.QVariant.Double: self.ui.cbxSelectField.addItem(unicode(fields[i].name())) self.ui.cbxIdField.addItem(unicode(fields[i].name()))
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): if self.inPolygon.currentText() == "": QMessageBox.information(self, self.tr("Count Points In Polygon"), self.tr("Please specify input polygon vector layer")) elif self.inPoint.currentText() == "": QMessageBox.information(self, self.tr("Count Points In Polygon"), self.tr("Please specify input point vector layer")) elif self.lnField.text() == "": QMessageBox.information(self, self.tr("Count Points In Polygon"), self.tr("Please specify output count field")) elif self.outShape.text() == "": QMessageBox.information(self, self.tr("Count Points In Polygon"), self.tr("Please specify output shapefile")) else: inPoly = ftools_utils.getVectorLayerByName(self.inPolygon.currentText()) inPnts = ftools_utils.getVectorLayerByName(self.inPoint.currentText()) polyProvider = inPoly.dataProvider() pointProvider = inPnts.dataProvider() if polyProvider.crs() != pointProvider.crs(): QMessageBox.warning(self, self.tr("CRS warning!"), self.tr("Warning: Input layers have non-matching CRS.\nThis may cause unexpected results.")) self.btnOk.setEnabled(False) self.workThread = PointsInPolygonThread(inPoly, inPnts, self.lnField.text(), self.outShape.text(), self.encoding, self.attributeList, self.statisticSelector) QObject.connect(self.workThread, SIGNAL("rangeChanged(int)"), self.setProgressRange) QObject.connect(self.workThread, SIGNAL("updateProgress()"), self.updateProgress) QObject.connect(self.workThread, SIGNAL("processingFinished()"), self.processFinished) QObject.connect(self.workThread, SIGNAL("processingInterrupted()"), self.processInterrupted) self.btnClose.setText(self.tr("Cancel")) QObject.disconnect(self.buttonBox, SIGNAL("rejected()"), self.reject) QObject.connect(self.btnClose, SIGNAL("clicked()"), self.stopProcessing) self.workThread.start()
def update(self,inputLayer): self.inField.clear() self.idVariable.clear() inputLayer=unicode(self.inShape.currentText()) if inputLayer != "": changedLayer=ftools_utils.getVectorLayerByName(inputLayer) changedField=ftools_utils.getFieldList(changedLayer) changedID=ftools_utils.getFieldList(changedLayer) for i in changedField: if changedField[i].typeName() != "String": self.inField.addItem(unicode(changedField[i].name())) for i in changedID: if changedID[i].typeName() != "String": self.idVariable.addItem(unicode(changedID[i].name()))
def canvasPressEvent( self, event ): self.layers = [] #self.layers.append( ftools_utils.getVectorLayerByName( 'area' ) ) #self.layers.append( ftools_utils.getVectorLayerByName( 'Road_S' ) ) #self.layers.append( ftools_utils.getVectorLayerByName( 'Road_G' ) ) self.layers.append( ftools_utils.getVectorLayerByName( 'city' ) ) for layer in self.layers: if ( (layer == None) or ( layer.isEditable() is True ) ): QMessageBox.information( None, '', 'please make the layer editable') self.prepared = False return transform = self.canvas.getCoordinateTransform() self.origionPoint = transform.toMapCoordinates( event.pos().x(), event.pos().y())
def run(self): self.mutex.lock() self.stopMe = 0 self.mutex.unlock() interrupted = False if self.isFiles: for layer in self.layers: vl = QgsVectorLayer(layer, "tmp", "ogr") provider = vl.dataProvider() if provider.capabilities( ) & QgsVectorDataProvider.CreateSpatialIndex: if not provider.createSpatialIndex(): self.errors.append(layer) else: self.errors.append(layer) self.emit(SIGNAL("layerProcessed()")) self.mutex.lock() s = self.stopMe self.mutex.unlock() if s == 1: interrupted = True break else: for layer in self.layers: vl = ftools_utils.getVectorLayerByName(layer) provider = vl.dataProvider() if provider.capabilities( ) & QgsVectorDataProvider.CreateSpatialIndex: if not provider.createSpatialIndex(): self.errors.append(layer) else: self.errors.append(layer) self.emit(SIGNAL("layerProcessed()")) self.mutex.lock() s = self.stopMe self.mutex.unlock() if s == 1: interrupted = True break if not interrupted: self.emit(SIGNAL("processFinished( PyQt_PyObject )"), self.errors) else: self.emit(SIGNAL("processInterrupted()"))
def update(self, inputLayer): self.inField.clear() self.idVariable.clear() inputLayer = unicode(self.inShape.currentText()) if inputLayer != "": changedLayer = ftools_utils.getVectorLayerByName(inputLayer) changedField = ftools_utils.getFieldList(changedLayer) changedID = ftools_utils.getFieldList(changedLayer) for i in changedField: if changedField[i].typeName() != "String": self.inField.addItem(unicode(changedField[i].name())) for i in changedID: if changedID[i].typeName() != "String": self.idVariable.addItem(unicode(changedID[i].name()))
def exportPlanningUnitFile(self): import ftools_utils fname = os.path.join(self.outDir, 'pu.dat') nl = os.linesep tmpf = file(fname, 'w') tmpf.write("id\tcost\tstatus\txloc\tyloc%s" % nl) lname = self.ui.cbxPlanningGrid.currentText() plProv = ftools_utils.getVectorLayerByName(lname).dataProvider() # get count for posting progress fCount = plProv.featureCount() # get value indexes fidx = plProv.fieldNameIndex(self.ui.cbxIdField.currentText()) cidx = plProv.fieldNameIndex(self.ui.cbxCostField.currentText()) sidx = plProv.fieldNameIndex(self.ui.cbxStatusField.currentText()) x = 0 feature = QgsFeature() allAttrs = plProv.attributeIndexes() plProv.select(allAttrs) outVals = [] self.ui.lbExportAction.setText('Calculating PU values') while plProv.nextFeature(feature): # get id fidValue = feature.attributeMap()[fidx].toString() # get cost costValue = feature.attributeMap()[cidx].toString() # get status statusValue = feature.attributeMap()[sidx].toString() # get coords coords = feature.geometry().centroid().asPoint() outVals.append([int(fidValue),costValue,statusValue,coords]) # write records # progress update pval = (x*100/2)/fCount/self.exportCount self.progressStatus('update',pval) # increment counter x = x + 1 self.progressStatus('step',pval) outVals.sort() x = 0 self.ui.lbExportAction.setText('Writing PU file') for row in outVals: outText = str(row[0]) + '\t' + row[1] + '\t' + \ row[2] + '\t' + str(row[3][0]) + '\t' + \ str(row[3][1]) + nl tmpf.write(outText) x = x + 1 pval = (x*100/2)/fCount/self.exportCount self.progressStatus('update',pval) tmpf.close() self.progressStatus('step',pval)
def setIdAndMeasureFields(self, planningGrid): import ftools_utils self.ui.cbxSelectField.clear() self.ui.cbxPuId.clear() selectedLayer = ftools_utils.getVectorLayerByName( unicode(planningGrid)) if selectedLayer != None: self.ui.cbxSelectField.addItem(unicode("--Create New--")) fields = ftools_utils.getFieldList(selectedLayer) for i in fields: if fields[i].type() == QtCore.QVariant.Int or \ fields[i].type() == QtCore.QVariant.Double: self.ui.cbxSelectField.addItem(unicode(fields[i].name())) self.ui.cbxPuId.addItem(unicode(fields[i].name()))