Exemplo n.º 1
0
    def export(
        self,
        path,
        driver_name="ESRI Shapefile",
        overwrite=True,
        target_crs_id=None,
    ):
        """Write layer to file.

        Args:
            path (str): Path of the output file
            driver_name (str): Defaults to ESRI Shapefile.
            overwrite (bool): Defaults to True
            target_crs_id (int): Defaults to source CRS
        """
        if target_crs_id is None:
            target_crs = self.crs()
        else:
            target_crs = QgsCoordinateReferenceSystem.fromEpsgId(target_crs_id)
        if os.path.exists(path) and overwrite:
            if driver_name == "ESRI Shapefile":
                QgsVectorFileWriter.deleteShapeFile(path)
            else:
                os.remove(path)
        result = self.writeAsVectorFormat(path, driver_name, target_crs)
        try:
            return result[0] == QgsVectorFileWriter.NoError
        except TypeError:
            return result == QgsVectorFileWriter.NoError
Exemplo n.º 2
0
def overwrite_layers_merged(project_path):

    root = QgsProject.instance().layerTreeRoot()
    group = root.findGroup(PROJECT_GROUP[2])
    operators_path = join(project_path, PROJECT_GROUP[2])
    operators_content = get_elements_name(operators_path, True, None)
    layers = get_layers_from_folder('SHP_')
    if layers is not None:
        for i_op, item in enumerate(operators_content):
            # load vectors
            shp_path = join(operators_path, item, 'SHP')
            for shp_file in glob.glob(join(shp_path, '*.shp')):
                layer_name = basename(shp_file).replace(".shp", "")
                if '_' not in layer_name:
                    if group is not None:
                        for child in group.children():
                            QgsProject.instance().removeMapLayer(child.layerId())
                    root.removeChildNode(group)
                    if layers[i_op].isValid():
                        QgsVectorFileWriter.deleteShapeFile(shp_file)
                        export_layer_as(layers[i_op], layer_name, "ESRI Shapefile", dirname(shp_file))
                    else:
                        delete_unused_folder(project_path)
        load_unloaded_data(project_path)
    else:
        return
Exemplo n.º 3
0
    def create_layer(self, parameters, name, is_memory, dest_crs, layer_style=None):
        save_as = parameters.file_path
        file_format = parameters.file_format
        # save paramaters
        serialized = base64.b64encode(parameters.serialize(with_style=False, with_geometry=False))

        # save geometry
        layer = QgsVectorLayer("MultiPolygon?crs=%s" % dest_crs.authid(), name, "memory")
        pr = layer.dataProvider()
        layer.startEditing()
        layer.addAttribute(QgsField("params", QVariant.String))
        fet1 = QgsFeature(0)
        fet1.setFields(layer.fields())
        fet1.setAttribute("params", str(serialized)[2:-1])
        fet1.setGeometry(parameters.geometry)
        pr.addFeatures([fet1])
        layer.commitChanges()

        # copy layer style
        if layer_style is not None:
            self.set_layer_style(layer, layer_style)

        if is_memory:
            return layer

        if os.path.isfile(save_as):
            # delete first if already exists
            if save_as.endswith(".shp"):
                QgsVectorFileWriter.deleteShapeFile(save_as)
            else:
                os.unlink(save_as)

        # create the disk layer
        QgsMessageLog.logMessage("Mask saving '{}' as {}".format(save_as, file_format),
                                 'Extensions')
        error = QgsVectorFileWriter.writeAsVectorFormat(layer, save_as, "System", dest_crs,
                                                        file_format)

        if error == 0:
            nlayer = QgsVectorLayer(save_as, name, "ogr")
            if not nlayer.dataProvider().isValid():
                return None
            if not nlayer.hasGeometryType():
                return None
            # force CRS
            nlayer.setCrs(dest_crs)

            # copy layer style
            layer_style = self.get_layer_style(layer)
            self.set_layer_style(nlayer, layer_style)
            return nlayer
        else:
            raise RuntimeError(error)

        return None
Exemplo n.º 4
0
def removeLayer(path_layer):
    # remove layer from TOC if already loaded
    basefile = os.path.basename(path_layer)
    diff_layer = os.path.splitext(basefile)[0]
    directory = os.path.dirname(path_layer)
    extensions = [
        "shp", "shx", "dbf", "prj", "sbn", "sbx", "fbn", "fbx", "ain", "aih",
        "ixs", "mxs", "atx", "xml", "cpg", "qix"
    ]
    if len(QgsProject.instance().mapLayersByName(diff_layer)) > 0:
        lyr = QgsProject.instance().mapLayersByName(diff_layer)[0]
        print('removing layer1: ', lyr.id())
        QgsProject.instance().removeMapLayer(lyr.id())
        QgsVectorFileWriter.deleteShapeFile(path_layer)
Exemplo n.º 5
0
 def randomize(self, inLayer, outPath, minimum, design, value):
     outFeat = QgsFeature()
     outFeat.initAttributes(1)
     if design == self.tr("unstratified"):
         ext = inLayer.extent()
         if inLayer.type() == QgsMapLayer.RasterLayer:
             points = self.simpleRandom(int(value), ext, ext.xMinimum(),
                                        ext.xMaximum(), ext.yMinimum(),
                                        ext.yMaximum())
         else:
             points = self.vectorRandom(int(value), inLayer, ext.xMinimum(),
                                        ext.xMaximum(), ext.yMinimum(),
                                        ext.yMaximum())
     else:
         points, featErrors = self.loopThruPolygons(inLayer, value, design)
         if featErrors:
             if len(featErrors) >= 10:
                 err_msg = "Too many features couldn't be calculated due to conversion error. "
                 err_msg += "Please check out message log for more info."
                 msgLogInstance = QgsMessageLog.instance()
                 msgLogInstance.logMessage("WARNING - fTools: " +
                                           self.tr("Random Points"))
                 msgLogInstance.logMessage(
                     "The following feature ids should be checked.")
                 for feat in featErrors:
                     msgLogInstance.logMessage("Feature id: %d" % feat.id())
                 msgLogInstance.logMessage("End of features to be checked.")
             else:
                 features_ids = []
                 for feat in featErrors:
                     features_ids.append(unicode(feat.id()))
                 erroneous_ids = ', '.join(features_ids)
                 err_msg = "The following features IDs couldn't be calculated due to conversion error: %s" % erroneous_ids
             self.iface.messageBar().pushMessage("Errors", err_msg)
     if len(points):
         crs = self.iface.mapCanvas().mapRenderer().destinationCrs()
         if not crs.isValid():
             crs = None
         fields = QgsFields()
         fields.append(QgsField("ID", QVariant.Int))
         outFeat.setFields(fields)
         check = QFile(self.shapefileName)
         if check.exists():
             if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
                 return
         writer = QgsVectorFileWriter(self.shapefileName, self.encoding,
                                      fields, QGis.WKBPoint, crs)
         idVar = 0
         count = 70.00
         add = (100.00 - 70.00) / len(points)
         for i in points:
             outFeat.setGeometry(i)
             outFeat.setAttribute(0, idVar)
             writer.addFeature(outFeat)
             idVar = idVar + 1
             count = count + add
             self.progressBar.setValue(count)
         del writer
         return True
     return False
Exemplo n.º 6
0
    def accept(self):
        if self.inputFiles is None:
            workDir = QDir(self.leInputDir.text())
            workDir.setFilter(QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot)
            nameFilter = ["*.shp", "*.SHP"]
            workDir.setNameFilters(nameFilter)
            self.inputFiles = workDir.entryList()
            if len(self.inputFiles) == 0:
                QMessageBox.warning(
                    self, self.tr("No shapefiles found"),
                    self.tr("There are no shapefiles in this directory. Please select another one."))
                self.inputFiles = None
                return

        if self.outFileName is None:
            QMessageBox.warning(
                self, self.tr("No output file"),
                self.tr("Please specify output file."))
            return

        if self.chkListMode.isChecked():
            files = self.leInputDir.text().split(";")
            baseDir = QFileInfo(files[0]).absolutePath()
        else:
            baseDir = self.leInputDir.text()
            # look for shapes with specified geometry type
            self.inputFiles = ftools_utils.getShapesByGeometryType(baseDir, self.inputFiles, self.cmbGeometry.currentIndex())
            if self.inputFiles is None:
                QMessageBox.warning(
                    self, self.tr("No shapefiles found"),
                    self.tr("There are no shapefiles with the given geometry type. Please select an available geometry type."))
                return
            self.progressFiles.setRange(0, len(self.inputFiles))

        outFile = QFile(self.outFileName)
        if outFile.exists():
            if not QgsVectorFileWriter.deleteShapeFile(self.outFileName):
                QMessageBox.warning(self, self.tr("Delete error"), self.tr("Can't delete file %s") % (self.outFileName))
                return

        if self.inEncoding is None:
            self.inEncoding = "System"

        self.btnOk.setEnabled(False)

        self.mergeThread = ShapeMergeThread(baseDir, self.inputFiles, self.inEncoding, self.outFileName, self.encoding)
        QObject.connect(self.mergeThread, SIGNAL("rangeChanged( PyQt_PyObject )"), self.setFeatureProgressRange)
        QObject.connect(self.mergeThread, SIGNAL("checkStarted()"), self.setFeatureProgressFormat)
        QObject.connect(self.mergeThread, SIGNAL("checkFinished()"), self.resetFeatureProgressFormat)
        QObject.connect(self.mergeThread, SIGNAL("fileNameChanged( PyQt_PyObject )"), self.setShapeProgressFormat)
        QObject.connect(self.mergeThread, SIGNAL("featureProcessed()"), self.featureProcessed)
        QObject.connect(self.mergeThread, SIGNAL("shapeProcessed()"), self.shapeProcessed)
        QObject.connect(self.mergeThread, SIGNAL("processingFinished()"), self.processingFinished)
        QObject.connect(self.mergeThread, SIGNAL("processingInterrupted()"), self.processingInterrupted)

        self.btnClose.setText(self.tr("Cancel"))
        QObject.disconnect(self.buttonBox, SIGNAL("rejected()"), self.reject)
        QObject.connect(self.btnClose, SIGNAL("clicked()"), self.stopProcessing)

        self.mergeThread.start()
Exemplo n.º 7
0
 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
Exemplo n.º 8
0
    def run(self):
        self.mutex.lock()
        self.stopMe = 0
        self.mutex.unlock()

        interrupted = False

        outPath = self.outDir

        if outPath.find("\\") != -1:
            outPath.replace("\\", "/")

        if not outPath.endswith("/"):
            outPath = outPath + "/"

        provider = self.layer.dataProvider()
        index = provider.fieldNameIndex(self.field)
        unique = ftools_utils.getUniqueValues(provider, int(index))
        baseName = unicode(outPath + self.layer.name() + "_" + self.field +
                           "_")

        fieldList = ftools_utils.getFieldList(self.layer)
        sRs = provider.crs()
        geom = self.layer.wkbType()
        inFeat = QgsFeature()

        self.emit(SIGNAL("rangeCalculated(PyQt_PyObject)"), len(unique))

        for i in unique:
            check = QFile(baseName + "_" + unicode(i).strip() + ".shp")
            fName = check.fileName()
            if check.exists():
                if not QgsVectorFileWriter.deleteShapeFile(fName):
                    self.errors.append(fName)
                    continue

            writer = QgsVectorFileWriter(fName, self.encoding, fieldList, geom,
                                         sRs)

            fit = provider.getFeatures()
            while fit.nextFeature(inFeat):
                atMap = inFeat.attributes()
                if atMap[index] == i:
                    writer.addFeature(inFeat)
            del writer

            self.emit(SIGNAL("valueProcessed()"))

            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()"))
Exemplo n.º 9
0
    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()
Exemplo n.º 10
0
    def run(self):
        self.mutex.lock()
        self.stopMe = 0
        self.mutex.unlock()

        interrupted = False

        outPath = self.outDir

        if outPath.find("\\") != -1:
            outPath.replace("\\", "/")

        if not outPath.endswith("/"):
            outPath = outPath + "/"

        provider = self.layer.dataProvider()
        index = provider.fieldNameIndex(self.field)
        unique = ftools_utils.getUniqueValues(provider, int(index))
        baseName = unicode( outPath + self.layer.name() + "_" + self.field + "_" )

        fieldList = ftools_utils.getFieldList(self.layer)
        sRs = provider.crs()
        geom = self.layer.wkbType()
        inFeat = QgsFeature()

        self.emit(SIGNAL("rangeCalculated(PyQt_PyObject)"), len(unique))


        for i in unique:
            check = QFile(baseName + "_" + unicode(i).strip() + ".shp")
            fName = check.fileName()
            if check.exists():
                if not QgsVectorFileWriter.deleteShapeFile(fName):
                    self.errors.append( fName )
                    continue

            writer = QgsVectorFileWriter(fName, self.encoding, fieldList, geom, sRs)

            fit = provider.getFeatures()
            while fit.nextFeature(inFeat):
                atMap = inFeat.attributes()
                if atMap[index] == i:
                    writer.addFeature(inFeat)
            del writer

            self.emit(SIGNAL("valueProcessed()"))

            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()"))
Exemplo n.º 11
0
 def deleteVectorFile(self, fileName):
     if QgsVectorFileWriter.deleteShapeFile(fileName) is False:
         QMessageBox.warning(self.iface.mainWindow(),
                             "VoGIS-Profiltool",
                             QApplication.translate("code", "Konnte vorhandene Datei nicht löschen") + ": " + fileName
                             )
         return False
     else:
         return True
Exemplo n.º 12
0
    def remove_generador_temp_files(self, message=False):
        """ Remove the Generador MMC's temporal files """
        # Sembla ser que hi ha un bug que impedeix esborrar els arxius .shp i .dbf si no es tanca i es torna
        # a obrir la finestra del plugin
        temp_list = os.listdir(GENERADOR_WORK_DIR)
        for temp in temp_list:
            if temp in TEMP_ENTITIES:
                try:
                    QgsVectorFileWriter.deleteShapeFile(
                        os.path.join(GENERADOR_WORK_DIR, temp))
                except Exception as error:
                    self.show_error_message(
                        "No s'han pogut esborrar els arxius temporals.")
                    QgsMessageLog.logMessage(error)
                    return

        if message:
            self.show_success_message('Arxius temporals esborrats.')
Exemplo n.º 13
0
 def randomize(self, inLayer, outPath, minimum, design, value):
     outFeat = QgsFeature()
     outFeat.initAttributes(1)
     if design == self.tr("unstratified"):
         ext = inLayer.extent()
         if inLayer.type() == QgsMapLayer.RasterLayer:
             points = self.simpleRandom(
                 int(value), ext, ext.xMinimum(),
                 ext.xMaximum(), ext.yMinimum(), ext.yMaximum())
         else:
             points = self.vectorRandom(
                 int(value), inLayer,
                 ext.xMinimum(), ext.xMaximum(), ext.yMinimum(), ext.yMaximum())
     else:
         points, featErrors = self.loopThruPolygons(inLayer, value, design)
         if featErrors:
             if len(featErrors) >= 10:
                 err_msg = "Too many features couldn't be calculated due to conversion error. "
                 err_msg += "Please check out message log for more info."
                 msgLogInstance = QgsMessageLog.instance()
                 msgLogInstance.logMessage("WARNING - fTools: " + self.tr("Random Points"))
                 msgLogInstance.logMessage("The following feature ids should be checked.")
                 for feat in featErrors:
                     msgLogInstance.logMessage("Feature id: %d" % feat.id())
                 msgLogInstance.logMessage("End of features to be checked.")
             else:
                 features_ids = []
                 for feat in featErrors:
                     features_ids.append(unicode(feat.id()))
                 erroneous_ids = ', '.join(features_ids)
                 err_msg = "The following features IDs couldn't be calculated due to conversion error: %s" % erroneous_ids
             self.iface.messageBar().pushMessage("Errors", err_msg)
     if len(points):
         crs = self.iface.mapCanvas().mapRenderer().destinationCrs()
         if not crs.isValid():
             crs = None
         fields = QgsFields()
         fields.append(QgsField("ID", QVariant.Int))
         outFeat.setFields(fields)
         check = QFile(self.shapefileName)
         if check.exists():
             if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
                 return
         writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fields, QGis.WKBPoint, crs)
         idVar = 0
         count = 70.00
         add = (100.00 - 70.00) / len(points)
         for i in points:
             outFeat.setGeometry(i)
             outFeat.setAttribute(0, idVar)
             writer.addFeature(outFeat)
             idVar = idVar + 1
             count = count + add
             self.progressBar.setValue(count)
         del writer
         return True
     return False
Exemplo n.º 14
0
def copyLayer( path, layer ):
    "returns the new layer"
    flType = _getFtype(path)

    if flType == "ESRI Shapefile":
        if os.path.exists(path): QgsVectorFileWriter.deleteShapeFile( path )
        error = QgsVectorFileWriter.writeAsVectorFormat(layer, path, "CP1250", None, flType)
    else:
        if os.path.exists(path): os.remove(path)
        error = QgsVectorFileWriter.writeAsVectorFormat(layer, path, "utf-8", None, flType)

    if error == QgsVectorFileWriter.NoError:
        layer_name = os.path.splitext( os.path.basename( path ))[0]
        newlayer = QgsVectorLayer(path, layer_name, "ogr")

        if newlayer.isValid(): return newlayer
        else: raise Exception("Could not read output")
    else:
        raise Exception("Could not write output")
Exemplo n.º 15
0
    def exportLayerAsShp(self,
                         layer,
                         time,
                         name="Apis_Export",
                         groupName="Temp",
                         styleName=None,
                         parent=None):
        # check if layer has features to be exported
        if layer.hasFeatures():
            # get previous directory
            saveDir = self.settings.value("APIS/working_dir",
                                          QDir.home().dirName())
            # save file dialog
            layerName = QFileDialog.getSaveFileName(
                parent, u"SHP Datei Export Speichern",
                saveDir + "\\" + "{0}_{1}".format(name, time), "*.shp")[0]

            if layerName:
                check = QFile(layerName)
                if check.exists():
                    if not QgsVectorFileWriter.deleteShapeFile(layerName):
                        QMessageBox.warning(
                            parent, "SHP Datei Export",
                            u"Es ist nicht möglich die SHP Datei {0} zu überschreiben!"
                            .format(layerName))
                        return

                error = QgsVectorFileWriter.writeAsVectorFormat(
                    layer, layerName, "UTF-8", layer.crs(), "ESRI Shapefile")
                if error[0] == QgsVectorFileWriter.NoError:
                    fof = FileOrFolder(parent=parent)
                    if fof == 0 or fof == 2:
                        # Shp Datei in QGIS laden
                        if styleName:
                            stylePath = self.stylesDir + self.__layers[
                                styleName]["style"]
                        self.requestShapeFile(layerName,
                                              groupName=groupName,
                                              addToCanvas=True,
                                              stylePath=stylePath)
                    if fof == 1 or fof == 2:
                        # Ordner öffnen
                        OpenFileOrFolder(os.path.split(layerName)[0])
                else:
                    QMessageBox.warning(
                        self, "SHP Datei Export",
                        u"Beim erstellen der SHP Datei ist ein Fehler aufgetreten: {0}"
                        .format(error))
        else:
            QMessageBox.warning(
                parent, "SHP Datei Export",
                u"Der zu exportierende Layer ({0}) hat keine Features.".format(
                    layer.name()))
            return
Exemplo n.º 16
0
 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
Exemplo n.º 17
0
 def runFinishedFromThread(self, success):
     self.testThread.stop()
     self.buttonOk.setEnabled(True)
     extra = ""
     if success == "math_error":
         QMessageBox.warning(self, self.tr("Geometry"),
                             self.tr("Error processing specified tolerance!\nPlease choose larger tolerance..."))
         if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
             QMessageBox.warning(self, self.tr("Geometry"),
                                 self.tr("Unable to delete incomplete shapefile."))
     elif success == "attr_error":
         QMessageBox.warning(self, self.tr("Geometry"),
                             self.tr("At least two features must have same attribute value!\nPlease choose another field..."))
         if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
             QMessageBox.warning(self, self.tr("Geometry"),
                                 self.tr("Unable to delete incomplete shapefile."))
     else:
         if success == "valid_error":
             extra = self.tr("One or more features in the output layer may have invalid "
                             + "geometry, please check using the check validity tool\n")
             success = True
         self.cancel_close.setText("Close")
         QObject.disconnect(self.cancel_close, SIGNAL("clicked()"), self.cancelThread)
         if success:
             if (self.myFunction == 5 and self.chkWriteShapefile.isChecked()) or self.myFunction != 5:
                 if self.addToCanvasCheck.isChecked():
                     addCanvasCheck = ftools_utils.addShapeToCanvas(unicode(self.shapefileName))
                     if not addCanvasCheck:
                         QMessageBox.warning(self, self.tr("Geometry"), self.tr("Error loading output shapefile:\n%s") % (unicode(self.shapefileName)))
                     self.populateLayers()
                 else:
                     QMessageBox.information(self, self.tr("Geometry"), self.tr("Created output shapefile:\n%s\n%s") % (unicode(self.shapefileName), extra))
             else:
                 QMessageBox.information(self, self.tr("Geometry"),
                                         self.tr("Layer '{0}' updated").format(self.inShape.currentText()))
         else:
             QMessageBox.warning(self, self.tr("Geometry"), self.tr("Error writing output shapefile."))
Exemplo n.º 18
0
 def runFinishedFromThread( self, success ):
   self.testThread.stop()
   self.buttonOk.setEnabled( True )
   extra = ""
   if success == "math_error":
     QMessageBox.warning( self, self.tr( "Geometry" ),
                          self.tr( "Error processing specified tolerance!\nPlease choose larger tolerance..." ) )
     if not QgsVectorFileWriter.deleteShapeFile( self.shapefileName ):
       QMessageBox.warning( self, self.tr( "Geometry" ),
                            self.tr( "Unable to delete incomplete shapefile." ) )
   elif success == "attr_error":
     QMessageBox.warning( self, self.tr( "Geometry" ),
                          self.tr( "At least two features must have same attribute value!\nPlease choose another field..." ) )
     if not QgsVectorFileWriter.deleteShapeFile( self.shapefileName ):
       QMessageBox.warning( self, self.tr( "Geometry" ),
                            self.tr( "Unable to delete incomplete shapefile." ) )
   else:
     if success == "valid_error":
       extra = self.tr( "One or more features in the output layer may have invalid "
                        + "geometry, please check using the check validity tool\n" )
       success = True
     self.cancel_close.setText( "Close" )
     QObject.disconnect( self.cancel_close, SIGNAL( "clicked()" ), self.cancelThread )
     if success:
       if ( self.myFunction == 5 and self.chkWriteShapefile.isChecked() ) or self.myFunction != 5:
         if self.addToCanvasCheck.isChecked():
           addCanvasCheck = ftools_utils.addShapeToCanvas(unicode(self.shapefileName))
           if not addCanvasCheck:
             QMessageBox.warning( self, self.tr("Geometry"), self.tr( "Error loading output shapefile:\n%s" ) % ( unicode( self.shapefileName ) ))
           self.populateLayers()
         else:
           QMessageBox.information(self, self.tr("Geometry"),self.tr("Created output shapefile:\n%s\n%s" ) % ( unicode( self.shapefileName ), extra ))
       else:
         QMessageBox.information( self, self.tr( "Geometry" ),
                                  self.tr( "Layer '{0}' updated" ).format( self.inShape.currentText() ) )
     else:
       QMessageBox.warning( self, self.tr( "Geometry" ), self.tr( "Error writing output shapefile." ) )
Exemplo n.º 19
0
    def run(self):
        """Create the output shapefile."""
        if os.path.isdir(self.filmPath) and len(self.images) > 0:
            check = QFile(self.shpFile)
            if check.exists():
                if not QgsVectorFileWriter.deleteShapeFile(self.shpFile):
                    self.iface.messageBar().pushMessage(u"Error",
                                                        u"Die Datei existiert bereits und kann nicht überschrieben werden (Eventuell in QGIS geladen!).",
                                                        level=Qgis.Critical, duration=10)
                    return None

            # fields
            fields = QgsFields()
            fields.append(QgsField("bildnr", QVariant.Int))
            fields.append(QgsField("lat", QVariant.Double))
            fields.append(QgsField("lon", QVariant.Double))
            fields.append(QgsField("alt", QVariant.Double))

            writer = QgsVectorFileWriter(str(self.shpFile), "UTF-8", fields, QgsWkbTypes.Point, QgsCoordinateReferenceSystem(4326, QgsCoordinateReferenceSystem.EpsgCrsId), "ESRI Shapefile")

            mb = self.iface.messageBar().createMessage(u"EXIF",
                                                       u"Die EXIF Daten (Geo Koordinaten und Höhe) werden aus den Bildern ausgelesen")
            progress = QProgressBar()
            progress.setMinimum(0)
            progress.setMaximum(0)
            progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
            mb.layout().addWidget(progress)
            self.iface.messageBar().pushWidget(mb, Qgis.Info)

            hasFeatures = False
            for feature in self.iter_images_as_features():
                writer.addFeature(feature)
                hasFeatures = True
            del writer

            if hasFeatures:
                self.iface.messageBar().clearWidgets()
                self.iface.messageBar().pushMessage(u"EXIF",
                                                    u"Die Shape Datei wurde erfolgreich erstellt und in QGIS geladen!",
                                                    level=Qgis.Success, duration=10)
                return self.shpFile
            else:
                QMessageBox.warning(None, "Bilder", u"Die vorhandenen Bilder enthalten keine GPS Information.")
                return None
        else:
            QMessageBox.warning(None, "Verzeichnis", u"Es wurde kein Bildverzeichnis für diesen Film gefunden.")
            return None
Exemplo n.º 20
0
 def regularize(self, bound, outPath, offset, value, gridType, inset, crs):
     area = bound.width() * bound.height()
     if offset:
         seed()
     if gridType:
         pointSpacing = value
     else:
         # Calculate grid spacing
         pointSpacing = sqrt(area / value)
     outFeat = QgsFeature()
     outFeat.initAttributes(1)
     fields = QgsFields()
     fields.append(QgsField("ID", QVariant.Int))
     outFeat.setFields(fields)
     check = QFile(self.shapefileName)
     if check.exists():
         if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
             return
     writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fields,
                                  QGis.WKBPoint, crs)
     idVar = 0
     count = 10.00
     add = 90.00 / (area / pointSpacing)
     y = bound.yMaximum() - inset
     while y >= bound.yMinimum():
         x = bound.xMinimum() + inset
         while x <= bound.xMaximum():
             if offset:
                 pGeom = QgsGeometry().fromPoint(
                     QgsPoint(
                         uniform(x - (pointSpacing / 2.0),
                                 x + (pointSpacing / 2.0)),
                         uniform(y - (pointSpacing / 2.0),
                                 y + (pointSpacing / 2.0))))
             else:
                 pGeom = QgsGeometry().fromPoint(QgsPoint(x, y))
             if pGeom.intersects(bound):
                 outFeat.setGeometry(pGeom)
                 outFeat.setAttribute(0, idVar)
                 writer.addFeature(outFeat)
                 idVar = idVar + 1
                 x = x + pointSpacing
                 count = count + add
                 self.progressBar.setValue(count)
         y = y - pointSpacing
     del writer
Exemplo n.º 21
0
    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()
Exemplo n.º 22
0
    def accept(self):
        self.buttonOk.setEnabled(False)

        if self.inShape.currentText() == "":
            QMessageBox.information(self, self.tr("Eliminate"),
                                    self.tr("No input shapefile specified"))
        else:
            outFileName = self.outShape.text()

            if outFileName == "":
                QMessageBox.information(
                    self, self.tr("Eliminate"),
                    self.tr("Please specify output shapefile"))
                self.buttonOk.setEnabled(True)
                return None
            else:
                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.buttonOk.setEnabled(True)
                        return None

                outFileName = unicode(outFileName)

            inLayer = ftools_utils.getVectorLayerByName(
                unicode(self.inShape.currentText()))

            if inLayer.selectedFeatureCount() == 0:
                QMessageBox.information(self, self.tr("Eliminate"),
                                        self.tr("No selection in input layer"))
            else:
                self.progressBar.setValue(5)
                boundary = self.boundary.isChecked()
                self.eliminate(inLayer, boundary, self.progressBar,
                               outFileName)
                self.progressBar.setValue(100)
                self.outShape.clear()

        self.progressBar.setValue(0)
        self.buttonOk.setEnabled(True)
Exemplo n.º 23
0
 def regularize(self, bound, outPath, offset, value, gridType, inset, crs):
     area = bound.width() * bound.height()
     if offset:
         seed()
     if gridType:
         pointSpacing = value
     else:
         # Calculate grid spacing
         pointSpacing = sqrt(area / value)
     outFeat = QgsFeature()
     outFeat.initAttributes(1)
     fields = QgsFields()
     fields.append( QgsField("ID", QVariant.Int) )
     outFeat.setFields( fields )
     check = QFile(self.shapefileName)
     if check.exists():
         if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
             return
     writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fields, QGis.WKBPoint, crs)
     idVar = 0
     count = 10.00
     add = 90.00 / (area / pointSpacing)
     y = bound.yMaximum() - inset
     while y >= bound.yMinimum():
         x = bound.xMinimum() + inset
         while x <= bound.xMaximum():
             if offset:
                 pGeom = QgsGeometry().fromPoint( QgsPoint(
                     uniform(x - (pointSpacing / 2.0), x + (pointSpacing / 2.0)),
                     uniform(y - (pointSpacing / 2.0), y + (pointSpacing / 2.0))
                 ))
             else:
                 pGeom = QgsGeometry().fromPoint(QgsPoint(x, y))
             if pGeom.intersects(bound):
                 outFeat.setGeometry(pGeom)
                 outFeat.setAttribute(0, idVar)
                 writer.addFeature(outFeat)
                 idVar = idVar + 1
                 x = x + pointSpacing
                 count = count + add
                 self.progressBar.setValue(count)
         y = y - pointSpacing
     del writer
Exemplo n.º 24
0
 def remove_result_layers(self, remove_all=False, delete_source=False):
     layers_to_remove = [
         layer for layer, flag in settings.l_result_layers_to_remove
         if remove_all or flag
     ]
     ins = QgsMapLayerRegistry.instance()
     ##layers = ins.mapLayersByName()
     layers = self.iface.legendInterface().layers()
     for layer in layers:
         source = layer.source()
         if layer.name() in layers_to_remove:
             print_log("remove layer {}".format(layer.name()), "d")
             ins.removeMapLayer(layer.id())
             if delete_source:
                 pass  # not sure if necessary
                 result = QgsVectorFileWriter.deleteShapeFile(source)
                 if not result:
                     print_log(
                         "Tool afgebroken! Kan resultaat ({}) niet verwijderen!"
                         .format(source), "e", self.iface)
                     return
Exemplo n.º 25
0
    def accept(self):
        self.buttonOk.setEnabled(False)

        if self.inShape.currentText() == "":
            QMessageBox.information(self, self.tr("Eliminate"), self.tr("No input shapefile specified"))
        else:
            outFileName = self.outShape.text()

            if outFileName == "":
                QMessageBox.information(self, self.tr("Eliminate"), self.tr("Please specify output shapefile"))
                self.buttonOk.setEnabled(True)
                return None
            else:
                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.buttonOk.setEnabled(True)
                        return None

                outFileName = unicode(outFileName)

            inLayer = ftools_utils.getVectorLayerByName(unicode(self.inShape.currentText()))

            if inLayer.selectedFeatureCount() == 0:
                QMessageBox.information(self, self.tr("Eliminate"), self.tr("No selection in input layer"))
            else:
                self.progressBar.setValue(5)
                boundary = self.boundary.isChecked()
                self.eliminate(inLayer, boundary, self.progressBar, outFileName)
                self.progressBar.setValue(100)
                self.outShape.clear()

        self.progressBar.setValue(0)
        self.buttonOk.setEnabled(True)
Exemplo n.º 26
0
  def geometry( self, myLayer, myParam, myField ):
    if self.myFunction == 9:
      vlayer = ftools_utils.getMapLayerByName( myLayer )
    else:
      vlayer = ftools_utils.getVectorLayerByName( myLayer )

    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()
Exemplo n.º 27
0
    def geometry(self, myLayer, myParam, myField):
        if self.myFunction == 9:
            vlayer = ftools_utils.getMapLayerByName(myLayer)
        else:
            vlayer = ftools_utils.getVectorLayerByName(myLayer)

        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()
Exemplo n.º 28
0
    def compute(self, line1, line2, field1, field2, outPath, progressBar):

        layer1 = ftools_utils.getVectorLayerByName(line1)
        provider1 = layer1.dataProvider()
        fieldList = ftools_utils.getFieldList(layer1)
        index1 = provider1.fieldNameIndex(field1)
        field1 = fieldList[index1]
        field1.setName(unicode(field1.name()) + "_1")

        layer2 = ftools_utils.getVectorLayerByName(line2)
        provider2 = layer2.dataProvider()
        fieldList = ftools_utils.getFieldList(layer2)
        index2 = provider2.fieldNameIndex(field2)
        field2 = fieldList[index2]
        field2.setName(unicode(field2.name()) + "_2")

        fieldList = QgsFields()
        fieldList.append(field1)
        fieldList.append(field2)
        sRs = provider1.crs()
        check = QFile(self.shapefileName)
        if check.exists():
            if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
                return

        writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fieldList, QGis.WKBPoint, sRs)
        inFeat = QgsFeature()
        inFeatB = QgsFeature()
        outFeat = QgsFeature()
        outFields = QgsFields()
        outFields.append(field1)
        outFields.append(field2)
        outFeat.setFields(outFields)
        start = 15.00
        add = 85.00 / layer1.featureCount()

        index = ftools_utils.createIndex(provider2)

        singlelayer_tempList = []
        fit1 = provider1.getFeatures(QgsFeatureRequest().setSubsetOfAttributes([index1]))
        while fit1.nextFeature(inFeat):
            inGeom = inFeat.geometry()
            v1 = inFeat.attributes()[index1]

            lineList = index.intersects(inGeom.boundingBox())
            for i in lineList:
                provider2.getFeatures(QgsFeatureRequest().setFilterFid(int(i)).setSubsetOfAttributes([index2])).nextFeature(inFeatB)
                tmpGeom = QgsGeometry(inFeatB.geometry())
                v2 = inFeatB.attributes()[index2]

                if inGeom.intersects(tmpGeom):
                    tempGeom = inGeom.intersection(tmpGeom)
                    if tempGeom.type() == QGis.Point:
                        tempList = []
                        if tempGeom.isMultipart():
                            tempList = tempGeom.asMultiPoint()
                        else:
                            tempList.append(tempGeom.asPoint())

                        for j in tempList:
                            # if same layer, avoid insert duplicated points
                            if line1 == line2:
                                if j not in singlelayer_tempList:
                                    singlelayer_tempList.append(j)
                                    outFeat.setGeometry(tempGeom.fromPoint(j))
                                    outFeat.setAttribute(0, v1)
                                    outFeat.setAttribute(1, v2)
                                    writer.addFeature(outFeat)
                            else:
                                outFeat.setGeometry(tempGeom.fromPoint(j))
                                outFeat.setAttribute(0, v1)
                                outFeat.setAttribute(1, v2)
                                writer.addFeature(outFeat)

            start = start + add
            progressBar.setValue(start)

        del writer
 def compute(self, inName, weightField="", times=1, uniqueField=""):
     vlayer = ftools_utils.getVectorLayerByName(inName)
     provider = vlayer.dataProvider()
     weightIndex = provider.fieldNameIndex(weightField)
     uniqueIndex = provider.fieldNameIndex(uniqueField)
     feat = QgsFeature()
     sRs = provider.crs()
     check = QFile(self.shapefileName)
     if check.exists():
         if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
             return
     if uniqueIndex != -1:
         uniqueValues = ftools_utils.getUniqueValues(provider, int( uniqueIndex ) )
         single = False
     else:
         uniqueValues = [1]
         single = True
     if self.function == 2:
         fieldList = QgsFields()
         fieldList.append( QgsField("STD_DIST", QVariant.Double) )
         fieldList.append( QgsField("UID", QVariant.String) )
         writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fieldList, QGis.WKBPolygon, sRs)
     else:
         fieldList = QgsFields()
         fieldList.append( QgsField("MEAN_X", QVariant.Double) )
         fieldList.append( QgsField("MEAN_Y", QVariant.Double) )
         fieldList.append( QgsField("UID", QVariant.String) )
         writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fieldList, QGis.WKBPoint, sRs)
     outfeat = QgsFeature()
     outfeat.setFields( fieldList )
     points = []
     weights = []
     nFeat = provider.featureCount() * len(uniqueValues)
     nElement = 0
     self.progressBar.setValue(0)
     self.progressBar.setRange(0, nFeat)
     for j in uniqueValues:
         cx = 0.00
         cy = 0.00
         points = []
         weights = []
         fit = provider.getFeatures()
         while fit.nextFeature(feat):
             nElement += 1
             self.progressBar.setValue(nElement)
             if single:
                 check = unicode(j).strip()
             else:
                 check = unicode(feat[uniqueIndex]).strip()
             if check == unicode(j).strip():
                 cx = 0.00
                 cy = 0.00
                 if weightIndex == -1:
                     weight = 1.00
                 else:
                     weight = float(feat[weightIndex])
                 geom = QgsGeometry(feat.geometry())
                 geom = ftools_utils.extractPoints(geom)
                 for i in geom:
                     cx += i.x()
                     cy += i.y()
                 points.append(QgsPoint((cx / len(geom)), (cy / len(geom))))
                 weights.append(weight)
         sumWeight = sum(weights)
         cx = 0.00
         cy = 0.00
         item = 0
         for item, i in enumerate(points):
             cx += i.x() * weights[item]
             cy += i.y() * weights[item]
         cx = cx / sumWeight
         cy = cy / sumWeight
         meanPoint = QgsPoint(cx, cy)
         if self.function == 2:
             values = []
             md = 0.00
             sd = 0.00
             dist = QgsDistanceArea()
             item = 0
             for i in points:
                 tempDist = dist.measureLine(i, meanPoint)
                 values.append(tempDist)
                 item += 1
                 md += tempDist
             md = md / item
             for i in values:
                 sd += (i-md)*(i-md)
             sd = sqrt(sd/item)
             outfeat.setGeometry(QgsGeometry.fromPoint(meanPoint).buffer(sd * times, 10))
             outfeat.setAttribute(0, sd)
             outfeat.setAttribute(1, j)
         else:
             outfeat.setGeometry(QgsGeometry.fromPoint(meanPoint))
             outfeat.setAttribute(0, cx)
             outfeat.setAttribute(1, cy)
             outfeat.setAttribute(2, j)
         writer.addFeature(outfeat)
         if single:
             break
     del writer
Exemplo n.º 30
0
    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
Exemplo n.º 31
0
    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
Exemplo n.º 32
0
 def compute(self, inName, weightField="", times=1, uniqueField=""):
     vlayer = ftools_utils.getVectorLayerByName(inName)
     provider = vlayer.dataProvider()
     weightIndex = provider.fieldNameIndex(weightField)
     uniqueIndex = provider.fieldNameIndex(uniqueField)
     feat = QgsFeature()
     sRs = provider.crs()
     check = QFile(self.shapefileName)
     if check.exists():
         if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
             return
     if uniqueIndex != -1:
         uniqueValues = ftools_utils.getUniqueValues(provider, int(uniqueIndex))
         single = False
     else:
         uniqueValues = [1]
         single = True
     if self.function == 2:
         fieldList = QgsFields()
         fieldList.append(QgsField("STD_DIST", QVariant.Double))
         fieldList.append(QgsField("UID", QVariant.String))
         writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fieldList, QGis.WKBPolygon, sRs)
     else:
         fieldList = QgsFields()
         fieldList.append(QgsField("MEAN_X", QVariant.Double))
         fieldList.append(QgsField("MEAN_Y", QVariant.Double))
         fieldList.append(QgsField("UID", QVariant.String))
         writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fieldList, QGis.WKBPoint, sRs)
     outfeat = QgsFeature()
     outfeat.setFields(fieldList)
     points = []
     weights = []
     nFeat = provider.featureCount() * len(uniqueValues)
     nElement = 0
     self.progressBar.setValue(0)
     self.progressBar.setRange(0, nFeat)
     for j in uniqueValues:
         cx = 0.00
         cy = 0.00
         points = []
         weights = []
         fit = provider.getFeatures()
         while fit.nextFeature(feat):
             nElement += 1
             self.progressBar.setValue(nElement)
             if single:
                 check = unicode(j).strip()
             else:
                 check = unicode(feat[uniqueIndex]).strip()
             if check == unicode(j).strip():
                 cx = 0.00
                 cy = 0.00
                 if weightIndex == -1:
                     weight = 1.00
                 else:
                     weight = float(feat[weightIndex])
                 geom = QgsGeometry(feat.geometry())
                 geom = ftools_utils.extractPoints(geom)
                 for i in geom:
                     cx += i.x()
                     cy += i.y()
                 points.append(QgsPoint((cx / len(geom)), (cy / len(geom))))
                 weights.append(weight)
         sumWeight = sum(weights)
         cx = 0.00
         cy = 0.00
         item = 0
         for item, i in enumerate(points):
             cx += i.x() * weights[item]
             cy += i.y() * weights[item]
         cx = cx / sumWeight
         cy = cy / sumWeight
         meanPoint = QgsPoint(cx, cy)
         if self.function == 2:
             values = []
             md = 0.00
             sd = 0.00
             dist = QgsDistanceArea()
             item = 0
             for i in points:
                 tempDist = dist.measureLine(i, meanPoint)
                 values.append(tempDist)
                 item += 1
                 md += tempDist
             md = md / item
             for i in values:
                 sd += (i - md) * (i - md)
             sd = sqrt(sd / item)
             outfeat.setGeometry(QgsGeometry.fromPoint(meanPoint).buffer(sd * times, 10))
             outfeat.setAttribute(0, sd)
             outfeat.setAttribute(1, j)
         else:
             outfeat.setGeometry(QgsGeometry.fromPoint(meanPoint))
             outfeat.setAttribute(0, cx)
             outfeat.setAttribute(1, cy)
             outfeat.setAttribute(2, j)
         writer.addFeature(outfeat)
         if single:
             break
     del writer
Exemplo n.º 33
0
    def run(self):
        self.mutex.lock()
        self.stopMe = 0
        self.mutex.unlock()

        interrupted = False

        polyProvider = self.layerPoly.dataProvider()
        pointProvider = self.layerPoints.dataProvider()

        fieldList = ftools_utils.getFieldList(self.layerPoly)
        index = polyProvider.fieldNameIndex(unicode(self.fieldName))
        if index == -1:
            index = polyProvider.fields().count()
            fieldList.append(
                QgsField(unicode(self.fieldName), QVariant.Int, "int", 10, 0,
                         self.tr("point count field")))

        # Add the selected vector fields to the output polygon vector layer
        selectedItems = self.attributeList.selectedItems()
        for item in selectedItems:
            global typeDouble
            columnName = unicode(item.text() + "_" + self.statistics)
            index = polyProvider.fieldNameIndex(unicode(columnName))
            if index == -1:
                if item.type(
                ) == typeDouble or self.statistics == "mean" or self.statistics == "stddev":
                    fieldList.append(
                        QgsField(columnName, QVariant.Double, "double", 24, 15,
                                 "Value"))
                else:
                    fieldList.append(
                        QgsField(columnName, QVariant.Int, "int", 10, 0,
                                 "Value"))

        sRs = polyProvider.crs()
        if QFile(self.outPath).exists():
            if not QgsVectorFileWriter.deleteShapeFile(self.outPath):
                return

        writer = QgsVectorFileWriter(self.outPath, self.encoding, fieldList,
                                     polyProvider.geometryType(), sRs)

        spatialIndex = ftools_utils.createIndex(pointProvider)

        self.emit(SIGNAL("rangeChanged(int)"), polyProvider.featureCount())

        polyFeat = QgsFeature()
        pntFeat = QgsFeature()
        outFeat = QgsFeature()
        inGeom = QgsGeometry()
        polyFit = polyProvider.getFeatures()
        while polyFit.nextFeature(polyFeat):
            inGeom = polyFeat.geometry()
            atMap = polyFeat.attributes()
            outFeat.setAttributes(atMap)
            outFeat.setGeometry(inGeom)

            count = 0
            pointList = []
            hasIntersection = True
            pointList = spatialIndex.intersects(inGeom.boundingBox())
            if len(pointList) > 0:
                hasIntersection = True
            else:
                hasIntersection = False

            if hasIntersection:
                valueList = {}
                for item in selectedItems:
                    valueList[item.text()] = []
                for p in pointList:
                    pointProvider.getFeatures(QgsFeatureRequest().setFilterFid(
                        p)).nextFeature(pntFeat)
                    tmpGeom = QgsGeometry(pntFeat.geometry())
                    if inGeom.intersects(tmpGeom):
                        count += 1
                        for item in selectedItems:
                            valueList[item.text()].append(
                                pntFeat.attribute(item.text()))

                    self.mutex.lock()
                    s = self.stopMe
                    self.mutex.unlock()
                    if s == 1:
                        interrupted = True
                        break

                atMap.append(count)

                # Compute the statistical values for selected vector attributes
                for item in selectedItems:
                    values = valueList[item.text()]
                    # Check if the input contains non-numeric values
                    non_numeric_values = False
                    for value in values:
                        if not isinstance(value, type(
                                float())) and not isinstance(
                                    value, type(int())):
                            non_numeric_values = True
                            break
                    # Jump over invalid values
                    if non_numeric_values is True:
                        continue

                    if values and len(values) > 0:
                        if self.statistics == "sum":
                            value = reduce(myAdder, values)
                        elif self.statistics == "mean":
                            value = reduce(myAdder, values) / float(
                                len(values))
                        elif self.statistics == "min":
                            values.sort()
                            value = values[0]
                        elif self.statistics == "max":
                            values.sort()
                            value = values[-1]
                        elif self.statistics == "stddev":
                            value = two_pass_variance(values)
                            value = math.sqrt(value)
                        atMap.append(value)

            outFeat.setAttributes(atMap)
            writer.addFeature(outFeat)

            self.emit(SIGNAL("updateProgress()"))

            self.mutex.lock()
            s = self.stopMe
            self.mutex.unlock()
            if s == 1:
                interrupted = True
                break

        del writer

        if not interrupted:
            self.emit(SIGNAL("processingFinished()"))
        else:
            self.emit(SIGNAL("processingInterrupted()"))
Exemplo n.º 34
0
    def run(self):
        self.mutex.lock()
        self.stopMe = 0
        self.mutex.unlock()

        interrupted = False

        polyProvider = self.layerPoly.dataProvider()
        pointProvider = self.layerPoints.dataProvider()

        fieldList = ftools_utils.getFieldList(self.layerPoly)
        index = polyProvider.fieldNameIndex(unicode(self.fieldName))
        if index == -1:
            index = polyProvider.fields().count()
            fieldList.append( QgsField(unicode(self.fieldName), QVariant.Int, "int", 10, 0, self.tr("point count field")) )

        sRs = polyProvider.crs()
        if QFile(self.outPath).exists():
            if not QgsVectorFileWriter.deleteShapeFile(self.outPath):
                return

        writer = QgsVectorFileWriter(self.outPath, self.encoding, fieldList,
                                     polyProvider.geometryType(), sRs)

        spatialIndex = ftools_utils.createIndex( pointProvider )

        self.emit(SIGNAL("rangeChanged(int)"), polyProvider.featureCount() )

        polyFeat = QgsFeature()
        pntFeat = QgsFeature()
        outFeat = QgsFeature()
        inGeom = QgsGeometry()
        polyFit = polyProvider.getFeatures()
        while polyFit.nextFeature(polyFeat):
            inGeom = polyFeat.geometry()
            atMap = polyFeat.attributes()
            outFeat.setAttributes(atMap)
            outFeat.setGeometry(inGeom)

            count = 0
            pointList = []
            hasIntersection = True
            pointList = spatialIndex.intersects(inGeom.boundingBox())
            if len(pointList) > 0:
                hasIntersection = True
            else:
                hasIntersection = False

            if hasIntersection:
                for p in pointList:
                    pointProvider.getFeatures( QgsFeatureRequest().setFilterFid( p ) ).nextFeature( pntFeat )
                    tmpGeom = QgsGeometry(pntFeat.geometry())
                    if inGeom.intersects(tmpGeom):
                        count += 1

                    self.mutex.lock()
                    s = self.stopMe
                    self.mutex.unlock()
                    if s == 1:
                        interrupted = True
                        break

            atMap.append(count)
            outFeat.setAttributes(atMap)
            writer.addFeature(outFeat)

            self.emit( SIGNAL( "updateProgress()" ) )

            self.mutex.lock()
            s = self.stopMe
            self.mutex.unlock()
            if s == 1:
                interrupted = True
                break

        del writer

        if not interrupted:
            self.emit( SIGNAL( "processingFinished()" ) )
        else:
            self.emit( SIGNAL( "processingInterrupted()" ) )
Exemplo n.º 35
0
 def delete_shp(path):
     QgsVectorFileWriter.deleteShapeFile(path)
     path = os.path.splitext(path)[0] + ".cpg"
     if os.path.exists(path):
         os.remove(path)
Exemplo n.º 36
0
    def run(self):
        self.mutex.lock()
        self.stopMe = 0
        self.mutex.unlock()

        interrupted = False

        polyProvider = self.layerPoly.dataProvider()
        pointProvider = self.layerPoints.dataProvider()

        fieldList = ftools_utils.getFieldList(self.layerPoly)
        index = polyProvider.fieldNameIndex(unicode(self.fieldName))
        if index == -1:
            index = polyProvider.fields().count()
            fieldList.append( QgsField(unicode(self.fieldName), QVariant.Int, "int", 10, 0, self.tr("point count field")) )

        # Add the selected vector fields to the output polygon vector layer
        selectedItems = self.attributeList.selectedItems()
        for item in selectedItems:
            global typeDouble
            columnName = unicode(item.text() + "_" + self.statistics)
            index = polyProvider.fieldNameIndex(unicode(columnName))
            if index == -1:
                if item.type() == typeDouble or self.statistics == "mean" or self.statistics == "stddev":
                    fieldList.append( QgsField(columnName, QVariant.Double, "double", 24, 15,  "Value") )
                else:
                    fieldList.append( QgsField(columnName, QVariant.Int, "int", 10, 0,  "Value") )

        sRs = polyProvider.crs()
        if QFile(self.outPath).exists():
            if not QgsVectorFileWriter.deleteShapeFile(self.outPath):
                return

        writer = QgsVectorFileWriter(self.outPath, self.encoding, fieldList,
                                     polyProvider.geometryType(), sRs)

        spatialIndex = ftools_utils.createIndex( pointProvider )

        self.emit(SIGNAL("rangeChanged(int)"), polyProvider.featureCount() )

        polyFeat = QgsFeature()
        pntFeat = QgsFeature()
        outFeat = QgsFeature()
        inGeom = QgsGeometry()
        polyFit = polyProvider.getFeatures()
        while polyFit.nextFeature(polyFeat):
            inGeom = polyFeat.geometry()
            atMap = polyFeat.attributes()
            outFeat.setAttributes(atMap)
            outFeat.setGeometry(inGeom)

            count = 0
            pointList = []
            hasIntersection = True
            pointList = spatialIndex.intersects(inGeom.boundingBox())
            if len(pointList) > 0:
                hasIntersection = True
            else:
                hasIntersection = False

            if hasIntersection:
                valueList = {}
                for item in selectedItems:
                    valueList[item.text()] = []
                for p in pointList:
                    pointProvider.getFeatures( QgsFeatureRequest().setFilterFid( p ) ).nextFeature( pntFeat )
                    tmpGeom = QgsGeometry(pntFeat.geometry())
                    if inGeom.intersects(tmpGeom):
                        count += 1
                        for item in selectedItems:
                            valueList[item.text()].append(pntFeat.attribute(item.text()))

                    self.mutex.lock()
                    s = self.stopMe
                    self.mutex.unlock()
                    if s == 1:
                        interrupted = True
                        break

                atMap.append(count)

                # Compute the statistical values for selected vector attributes
                for item in selectedItems:
                    values = valueList[item.text()]
                    # Check if the input contains non-numeric values
                    non_numeric_values = False
                    for value in values:
                        if not isinstance(value, type(float())) and not isinstance(value, type(int())):
                            non_numeric_values = True
                            break
                    # Jump over invalid values
                    if non_numeric_values is True:
                        continue

                    if values and len(values) > 0:
                        if self.statistics == "sum":
                            value = reduce(myAdder,  values)
                        elif self.statistics == "mean":
                            value = reduce(myAdder,  values) / float(len(values))
                        elif self.statistics == "min":
                            values.sort()
                            value = values[0]
                        elif self.statistics == "max":
                            values.sort()
                            value = values[-1]
                        elif self.statistics == "stddev":
                            value = two_pass_variance(values)
                            value = math.sqrt(value)
                        atMap.append(value)

            outFeat.setAttributes(atMap)
            writer.addFeature(outFeat)

            self.emit( SIGNAL( "updateProgress()" ) )

            self.mutex.lock()
            s = self.stopMe
            self.mutex.unlock()
            if s == 1:
                interrupted = True
                break

        del writer

        if not interrupted:
            self.emit( SIGNAL( "processingFinished()" ) )
        else:
            self.emit( SIGNAL( "processingInterrupted()" ) )
Exemplo n.º 37
0
 def abort():
     for writer in physicalWriter.values():
         QgsVectorFileWriter.deleteShapeFile(writer.path + ".shp")
         QFile.remove(writer.path + ".cpg")
Exemplo n.º 38
0
    def compute(self, inName, joinName, outName, summary, sumList, keep,
                progressBar):
        layer1 = ftools_utils.getVectorLayerByName(inName)
        provider1 = layer1.dataProvider()
        fieldList1 = ftools_utils.getFieldList(layer1)

        layer2 = ftools_utils.getVectorLayerByName(joinName)
        provider2 = layer2.dataProvider()

        fieldList2 = ftools_utils.getFieldList(layer2)
        fieldList = QgsFields()
        if provider1.crs() != provider2.crs():
            QMessageBox.warning(
                self, self.tr("CRS warning!"),
                self.
                tr("Warning: Input layers have non-matching CRS.\nThis may cause unexpected results."
                   ))
        if not summary:
            fieldList2 = ftools_utils.testForUniqueness(fieldList1, fieldList2)
            seq = range(0, len(fieldList1) + len(fieldList2))
            fieldList1.extend(fieldList2)
            fieldList1 = dict(zip(seq, fieldList1))
        else:
            numFields = {}
            for j in xrange(len(fieldList2)):
                if fieldList2[j].type() == QVariant.Int or fieldList2[j].type(
                ) == QVariant.Double:
                    numFields[j] = []
                    for i in sumList:
                        field = QgsField(i + unicode(fieldList2[j].name()),
                                         QVariant.Double, "real", 24, 16,
                                         self.tr("Summary field"))
                        fieldList.append(field)
            field = QgsField("COUNT", QVariant.Double, "real", 24, 16,
                             self.tr("Summary field"))
            fieldList.append(field)
            fieldList2 = ftools_utils.testForUniqueness(fieldList1, fieldList)
            fieldList1.extend(fieldList)
            seq = range(0, len(fieldList1))
            fieldList1 = dict(zip(seq, fieldList1))

        sRs = provider1.crs()
        progressBar.setValue(13)
        check = QFile(self.shapefileName)
        if check.exists():
            if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
                QMessageBox.warning(
                    self, self.tr('Error deleting shapefile'),
                    self.tr("Can't delete existing shapefile\n%s") %
                    (self.shapefileName))
                return False
        fields = QgsFields()
        for f in fieldList1.values():
            fields.append(f)
        writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fields,
                                     provider1.geometryType(), sRs)
        #writer = QgsVectorFileWriter(outName, "UTF-8", fieldList1, provider1.geometryType(), sRs)
        inFeat = QgsFeature()
        outFeat = QgsFeature()
        inFeatB = QgsFeature()
        inGeom = QgsGeometry()
        progressBar.setValue(15)
        start = 15.00
        add = 85.00 / provider1.featureCount()

        index = ftools_utils.createIndex(provider2)

        # cache all features from provider2 to avoid huge number of feature requests in the inner loop
        mapP2 = {}
        for f in provider2.getFeatures():
            mapP2[f.id()] = QgsFeature(f)

        fit1 = provider1.getFeatures()
        while fit1.nextFeature(inFeat):
            inGeom = inFeat.geometry()
            atMap1 = inFeat.attributes()
            outFeat.setGeometry(inGeom)
            none = True
            joinList = []
            if inGeom.type() == QGis.Point:
                #(check, joinList) = layer2.featuresInRectangle(inGeom.buffer(10,2).boundingBox(), True, True)
                #layer2.select(inGeom.buffer(10,2).boundingBox(), False)
                #joinList = layer2.selectedFeatures()
                joinList = index.intersects(inGeom.buffer(10, 2).boundingBox())
                if len(joinList) > 0:
                    check = 0
                else:
                    check = 1
            else:
                #(check, joinList) = layer2.featuresInRectangle(inGeom.boundingBox(), True, True)
                #layer2.select(inGeom.boundingBox(), False)
                #joinList = layer2.selectedFeatures()
                joinList = index.intersects(inGeom.boundingBox())
                if len(joinList) > 0:
                    check = 0
                else:
                    check = 1
            if check == 0:
                count = 0
                for i in joinList:
                    inFeatB = mapP2[i]  # cached feature from provider2
                    if inGeom.intersects(inFeatB.geometry()):
                        count = count + 1
                        none = False
                        atMap2 = inFeatB.attributes()
                        if not summary:
                            atMap = atMap1
                            atMap2 = atMap2
                            atMap.extend(atMap2)
                            atMap = dict(zip(seq, atMap))
                            break
                        else:
                            for j in numFields.keys():
                                numFields[j].append(atMap2[j])
                if summary and not none:
                    atMap = atMap1
                    for j in numFields.keys():
                        for k in sumList:
                            if k == "SUM":
                                atMap.append(sum(filter_null(numFields[j])))
                            elif k == "MEAN":
                                try:
                                    nn_count = sum(
                                        1 for _ in filter_null(numFields[j]))
                                    atMap.append(
                                        sum(filter_null(numFields[j])) /
                                        nn_count)
                                except ZeroDivisionError:
                                    atMap.append(NULL)
                            elif k == "MIN":
                                try:
                                    atMap.append(min(filter_null(
                                        numFields[j])))
                                except ValueError:
                                    atMap.append(NULL)
                            elif k == "MED":
                                atMap.append(myself(numFields[j]))
                            else:
                                try:
                                    atMap.append(max(filter_null(
                                        numFields[j])))
                                except ValueError:
                                    atMap.append(NULL)

                        numFields[j] = []
                    atMap.append(count)
                    atMap = dict(zip(seq, atMap))
            if none:
                outFeat.setAttributes(atMap1)
            else:
                outFeat.setAttributes(atMap.values())
            if keep:  # keep all records
                writer.addFeature(outFeat)
            else:  # keep only matching records
                if not none:
                    writer.addFeature(outFeat)
            start = start + add
            progressBar.setValue(start)
        del writer
        return True
Exemplo n.º 39
0
    def compute(self, inName, joinName, outName, summary, sumList, keep, progressBar):
        layer1 = ftools_utils.getVectorLayerByName(inName)
        provider1 = layer1.dataProvider()
        fieldList1 = ftools_utils.getFieldList(layer1)

        layer2 = ftools_utils.getVectorLayerByName(joinName)
        provider2 = layer2.dataProvider()

        fieldList2 = ftools_utils.getFieldList(layer2)
        fieldList = QgsFields()
        if provider1.crs() != provider2.crs():
            QMessageBox.warning(self, self.tr("CRS warning!"), self.tr("Warning: Input layers have non-matching CRS.\nThis may cause unexpected results."))
        if not summary:
            fieldList2 = ftools_utils.testForUniqueness(fieldList1, fieldList2)
            seq = range(0, len(fieldList1) + len(fieldList2))
            fieldList1.extend(fieldList2)
            fieldList1 = dict(zip(seq, fieldList1))
        else:
            numFields = {}
            for j in xrange(len(fieldList2)):
                if fieldList2[j].type() == QVariant.Int or fieldList2[j].type() == QVariant.Double:
                    numFields[j] = []
                    for i in sumList:
                        field = QgsField(i + unicode(fieldList2[j].name()), QVariant.Double, "real", 24, 16, self.tr("Summary field"))
                        fieldList.append(field)
            field = QgsField("COUNT", QVariant.Double, "real", 24, 16, self.tr("Summary field"))
            fieldList.append(field)
            fieldList2 = ftools_utils.testForUniqueness(fieldList1, fieldList)
            fieldList1.extend(fieldList)
            seq = range(0, len(fieldList1))
            fieldList1 = dict(zip(seq, fieldList1))

        sRs = provider1.crs()
        progressBar.setValue(13)
        check = QFile(self.shapefileName)
        if check.exists():
            if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
                QMessageBox.warning(
                    self, self.tr('Error deleting shapefile'),
                    self.tr("Can't delete existing shapefile\n%s") % (self.shapefileName))
                return False
        fields = QgsFields()
        for f in fieldList1.values():
            fields.append(f)
        writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fields, provider1.geometryType(), sRs)
        #writer = QgsVectorFileWriter(outName, "UTF-8", fieldList1, provider1.geometryType(), sRs)
        inFeat = QgsFeature()
        outFeat = QgsFeature()
        inFeatB = QgsFeature()
        inGeom = QgsGeometry()
        progressBar.setValue(15)
        start = 15.00
        add = 85.00 / provider1.featureCount()

        index = ftools_utils.createIndex(provider2)

        # cache all features from provider2 to avoid huge number of feature requests in the inner loop
        mapP2 = {}
        for f in provider2.getFeatures():
            mapP2[f.id()] = QgsFeature(f)

        fit1 = provider1.getFeatures()
        while fit1.nextFeature(inFeat):
            inGeom = inFeat.geometry()
            atMap1 = inFeat.attributes()
            outFeat.setGeometry(inGeom)
            none = True
            joinList = []
            if inGeom.type() == QGis.Point:
                #(check, joinList) = layer2.featuresInRectangle(inGeom.buffer(10,2).boundingBox(), True, True)
                #layer2.select(inGeom.buffer(10,2).boundingBox(), False)
                #joinList = layer2.selectedFeatures()
                joinList = index.intersects(inGeom.buffer(10, 2).boundingBox())
                if len(joinList) > 0:
                    check = 0
                else:
                    check = 1
            else:
                #(check, joinList) = layer2.featuresInRectangle(inGeom.boundingBox(), True, True)
                #layer2.select(inGeom.boundingBox(), False)
                #joinList = layer2.selectedFeatures()
                joinList = index.intersects(inGeom.boundingBox())
                if len(joinList) > 0:
                    check = 0
                else:
                    check = 1
            if check == 0:
                count = 0
                for i in joinList:
                    inFeatB = mapP2[i]  # cached feature from provider2
                    if inGeom.intersects(inFeatB.geometry()):
                        count = count + 1
                        none = False
                        atMap2 = inFeatB.attributes()
                        if not summary:
                            atMap = atMap1
                            atMap2 = atMap2
                            atMap.extend(atMap2)
                            atMap = dict(zip(seq, atMap))
                            break
                        else:
                            for j in numFields.keys():
                                numFields[j].append(atMap2[j])
                if summary and not none:
                    atMap = atMap1
                    for j in numFields.keys():
                        for k in sumList:
                            if k == "SUM":
                                atMap.append(sum(filter_null(numFields[j])))
                            elif k == "MEAN":
                                try:
                                    nn_count = sum(1 for _ in filter_null(numFields[j]))
                                    atMap.append(sum(filter_null(numFields[j])) / nn_count)
                                except ZeroDivisionError:
                                    atMap.append(NULL)
                            elif k == "MIN":
                                try:
                                    atMap.append(min(filter_null(numFields[j])))
                                except ValueError:
                                    atMap.append(NULL)
                            elif k == "MED":
                                atMap.append(myself(numFields[j]))
                            else:
                                try:
                                    atMap.append(max(filter_null(numFields[j])))
                                except ValueError:
                                    atMap.append(NULL)

                        numFields[j] = []
                    atMap.append(count)
                    atMap = dict(zip(seq, atMap))
            if none:
                outFeat.setAttributes(atMap1)
            else:
                outFeat.setAttributes(atMap.values())
            if keep: # keep all records
                writer.addFeature(outFeat)
            else: # keep only matching records
                if not none:
                    writer.addFeature(outFeat)
            start = start + add
            progressBar.setValue(start)
        del writer
        return True
Exemplo n.º 40
0
    def compute(self, line1, line2, field1, field2, outPath, progressBar):

        layer1 = ftools_utils.getVectorLayerByName(line1)
        provider1 = layer1.dataProvider()
        fieldList = ftools_utils.getFieldList(layer1)
        index1 = provider1.fieldNameIndex(field1)
        field1 = fieldList[index1]
        field1.setName(unicode(field1.name()) + "_1")

        layer2 = ftools_utils.getVectorLayerByName(line2)
        provider2 = layer2.dataProvider()
        fieldList = ftools_utils.getFieldList(layer2)
        index2 = provider2.fieldNameIndex(field2)
        field2 = fieldList[index2]
        field2.setName(unicode(field2.name()) + "_2")

        fieldList = QgsFields()
        fieldList.append(field1)
        fieldList.append(field2)
        sRs = provider1.crs()
        check = QFile(self.shapefileName)
        if check.exists():
            if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
                return

        writer = QgsVectorFileWriter(self.shapefileName, self.encoding,
                                     fieldList, QGis.WKBPoint, sRs)
        inFeat = QgsFeature()
        inFeatB = QgsFeature()
        outFeat = QgsFeature()
        outFields = QgsFields()
        outFields.append(field1)
        outFields.append(field2)
        outFeat.setFields(outFields)
        start = 15.00
        add = 85.00 / layer1.featureCount()

        index = ftools_utils.createIndex(provider2)

        singlelayer_tempList = []
        fit1 = provider1.getFeatures(QgsFeatureRequest().setSubsetOfAttributes(
            [index1]))
        while fit1.nextFeature(inFeat):
            inGeom = inFeat.geometry()
            v1 = inFeat.attributes()[index1]

            lineList = index.intersects(inGeom.boundingBox())
            for i in lineList:
                provider2.getFeatures(QgsFeatureRequest().setFilterFid(
                    int(i)).setSubsetOfAttributes([index2
                                                   ])).nextFeature(inFeatB)
                tmpGeom = QgsGeometry(inFeatB.geometry())
                v2 = inFeatB.attributes()[index2]

                if inGeom.intersects(tmpGeom):
                    tempGeom = inGeom.intersection(tmpGeom)
                    if tempGeom.type() == QGis.Point:
                        tempList = []
                        if tempGeom.isMultipart():
                            tempList = tempGeom.asMultiPoint()
                        else:
                            tempList.append(tempGeom.asPoint())

                        for j in tempList:
                            # if same layer, avoid insert duplicated points
                            if line1 == line2:
                                if j not in singlelayer_tempList:
                                    singlelayer_tempList.append(j)
                                    outFeat.setGeometry(tempGeom.fromPoint(j))
                                    outFeat.setAttribute(0, v1)
                                    outFeat.setAttribute(1, v2)
                                    writer.addFeature(outFeat)
                            else:
                                outFeat.setGeometry(tempGeom.fromPoint(j))
                                outFeat.setAttribute(0, v1)
                                outFeat.setAttribute(1, v2)
                                writer.addFeature(outFeat)

            start = start + add
            progressBar.setValue(start)

        del writer
Exemplo n.º 41
0
    def on_btnRun_clicked(self):
                
        if self.inputfile == '':
            QMessageBox.critical(self,'Map Creator',
                                 'Please specify input coordinate file.')
            return
        
        if self.outputfile == '':
            QMessageBox.critical(self,'Map Creator',
                                 'Please specify output shapefile.')
            return
        
        self.setCursor(Qt.WaitCursor)

        #Open coordinate input file
        f = open(self.inputfile, 'r')
        lines = f.readlines()
        f.close()
        header = lines[0].split(',')[0]
        totfeat = len(lines) - 1
        lines.pop(0)
        lines.reverse() 
        
        #Create vector layer
        basename = os.path.basename(self.outputfile)
        vlayer = QgsVectorLayer("Polygon", basename, "memory")
        vprovider = vlayer.dataProvider()
        fld = QgsField(header,QVariant.String)
        flds = QgsFields()
        flds.append(fld)
        vprovider.addAttributes([fld])
        vlayer.startEditing()
                
        hull = []
        for cnt, line in enumerate(lines):
            line = line.rstrip().split(',')
            numcoords = int((len(line) - 1) / 2)
            hull[:] = []
            geom = QgsGeometry()
            feat = QgsFeature()
            feat.setFields(flds)
            for i in range(numcoords):
                hull.append(QgsPointXY(float(line[i*2+1]),float(line[i*2+2])))
            geom = geom.fromMultiPointXY(hull)
            geom = geom.convexHull()
            feat.setGeometry(geom)
            feat.setAttribute(header,str(line[0]))
            result = vlayer.addFeature(feat)
            if not result:
                self.setCursor(Qt.ArrowCursor)
                QMessageBox.critical(self,'Map Creator', 'Processing error.')
                return
            self.ui.ProgressBar.setValue(float(cnt+1)/float(totfeat) * 100.0)
            QApplication.processEvents()  
        vlayer.commitChanges()
        vlayer.updateExtents()
        
        #Write the output shapefile
        if os.path.exists(self.outputfile):
            QgsVectorFileWriter.deleteShapeFile(self.outputfile)
        voptions = QgsVectorFileWriter.SaveVectorOptions()
        voptions.driverName = 'ESRI Shapefile'
        voptions.fileEncoding = 'utf-8'
        result = QgsVectorFileWriter.writeAsVectorFormat(vlayer, 
                                                         self.outputfile, 
                                                         voptions)

        if result[0] != 0:
            QMessageBox.critical(self,'Map Creator','Error creating shapefile.')
        else: #Ask to add shapfile to map
            name = QFileInfo(self.outputfile).completeBaseName()
            result = QMessageBox.question(self,'Map Creator',
                                          'Add shapefile to map?',
                                          QMessageBox.Yes,
                                          QMessageBox.No)
            if result == QMessageBox.Yes:
                self.iface.addVectorLayer(self.outputfile, name, 'ogr')
                
        self.setCursor(Qt.ArrowCursor)
Exemplo n.º 42
0
    def on_btnRun_clicked(self):

        if self.ui.cmbProcessLayer.count() <= 0:
            return
        if self.ui.tbxOutput.text() == '':
            QMessageBox.critical(self, 'Raster to Vector Converter',
                                 'Please specify output shapefile.')
            return

        self.setCursor(Qt.WaitCursor)

        #Get raster properties
        numX = self.player.width()
        numY = self.player.height()
        pixsizeX = self.player.rasterUnitsPerPixelX()
        pixsizeY = self.player.rasterUnitsPerPixelY()
        extents = self.player.extent()
        LLX = extents.xMinimum()
        LLY = extents.yMinimum()
        URX = extents.xMaximum()
        URY = extents.yMaximum()
        rprovider = self.player.dataProvider()

        if LLX > URX or LLY > URY:
            self.setCursor(Qt.ArrowCursor)
            QMessageBox.critical(self, 'Raster to Vector Converter',
                                 'Unexpected image extents.')
            return

        #Create vector layer of pixel polygons or points at pixel centers
        #Assumes image extents are given as the LL coordinate of LL pixel
        #and UR coordinate of UR pixel.
        pfeat = QgsFeature()
        crsid = str(self.player.crs().authid())
        if self.ui.rbPoints.isChecked():
            pvlayer = QgsVectorLayer("Point?crs=" + crsid, "templayer",
                                     "memory")
        elif self.ui.rbPolygons.isChecked():
            pvlayer = QgsVectorLayer("Polygon?crs=" + crsid, "templayer",
                                     "memory")
        fields = [QgsField("ID", QVariant.Int)]
        for i in range(self.player.bandCount()):
            bandname = self.player.bandName(i + 1)
            fields.append(QgsField(bandname, QVariant.Double))
        pprovider = pvlayer.dataProvider()
        pprovider.addAttributes(fields)
        pvlayer.startEditing()
        count = 0
        attr = []
        totpix = float(numX * numY)
        for y in range(numY):
            for x in range(numX):
                newpt = QgsPoint(LLX + x * pixsizeX + pixsizeX / 2.0,
                                 LLY + y * pixsizeY + pixsizeY / 2.0)
                data = rprovider.identify(newpt, 1).results()
                if self.ui.rbPoints.isChecked():
                    pfeat.setGeometry(QgsGeometry.fromPoint(newpt))
                elif self.ui.rbPolygons.isChecked():
                    newrect = QgsRectangle(LLX + x * pixsizeX,
                                           LLY + y * pixsizeY,
                                           LLX + x * pixsizeX + pixsizeX,
                                           LLY + y * pixsizeY + pixsizeY)
                    pfeat.setGeometry(QgsGeometry.fromRect(newrect))
                attr = list(data.values())
                attr.insert(0, count)
                pfeat.setAttributes(attr)
                result = pvlayer.addFeature(pfeat)
                if not result:
                    self.setCursor(Qt.ArrowCursor)
                    QMessageBox.critical(self, 'Raster to Vector Converter',
                                         'Processing error 2.')
                    return
                del newpt
                if self.ui.rbPolygons.isChecked():
                    del newrect
                count += 1
                self.ui.ProgressBar.setValue(float(count) / totpix * 100.0)
                QApplication.processEvents()
        pvlayer.commitChanges()
        pvlayer.updateExtents()

        #Write the output shapefile
        if os.path.exists(self.outfile):
            QgsVectorFileWriter.deleteShapeFile(self.outfile)
        result = QgsVectorFileWriter.writeAsVectorFormat(
            pvlayer, self.outfile, 'utf-8', self.player.crs())
        if result != QgsVectorFileWriter.NoError:
            QMessageBox.critical(self, 'Raster to Vector Converter',
                                 'Error creating shapefile.')
        else:  #Ask to add shapfile to map
            name = QFileInfo(self.outfile).completeBaseName()
            result = QMessageBox.question(self, 'Raster to Vector Converter',
                                          'Add shapefile to map?',
                                          QMessageBox.Yes, QMessageBox.No)
            if result == QMessageBox.Yes:
                self.iface.addVectorLayer(self.outfile, name, 'ogr')

        self.setCursor(Qt.ArrowCursor)
        self.close()
Exemplo n.º 43
0
    def calculate(self):
        ''' Prepare environment to run the alg and run it. After run, merge produced 
        data basing on plugin configuration.
        Before calculation a parametere validation will be executed
        '''
        # perform validation
        if not self.gui.validate():
            return
        else:
            # notify successful validation
            message = self.tr("QTraffic: Parameters validation passed successfully")
            iface.messageBar().pushMessage(message, QgsMessageBar.SUCCESS)
        
        # set number of classes in the project config (that is the temporary one... but equal to the official one)
        fleetDistributionRoadTypes = self.gui.getRoadTypes()
        self.project.setValue('Processing.Parameters/maximum_type', len(fleetDistributionRoadTypes))
        self.project.sync()

        # create the algorithm
        self.alg = Algorithm()
        roadLayer = self.gui.getRoadLayer()
        
        # prepare layer where to add result
        addToInputLayer = self.gui.addToOriginaLayer_RButton.isChecked()
        newOutputLayer = self.gui.outFile_LEdit.text()

        if addToInputLayer:
            self.outLayer = roadLayer
            self.outLayerId = self.outLayer.id()
        else:
            # if layer is present... remove it
            # out layer would not be the same of input road layer... in thi scase don't remove it
            if self.outLayer and self.outLayer.isValid():
                # to be sure, remove only if roadLayer and outLayer are different
                if self.outLayer.publicSource() != roadLayer.publicSource():
                    self.outLayerRemoved = False
                    QgsMapLayerRegistry.instance().layerRemoved.connect(self.checkOutLayerRemoved)
                    QgsMapLayerRegistry.instance().removeMapLayer(self.outLayer.id())
                    
                    # remove file when it has been removed from qgis
                    while not self.outLayerRemoved:
                        sleep(0.1)
                    QgsMapLayerRegistry.instance().layerRemoved.disconnect(self.checkOutLayerRemoved)
                        
                    # reinit outLayer variables
                    # If not, under windws remain a locking of the related file creating
                    # an error during QgsVectorFileWriter.deleteShapeFile
                    self.outLayer = None
                    self.outLayerId = None

                    if os.path.exists(newOutputLayer):
                        if not QgsVectorFileWriter.deleteShapeFile(newOutputLayer):
                            message = self.tr("Error removing shape: {}".format(newOutputLayer))
                            iface.messageBar().pushMessage(message, QgsMessageBar.CRITICAL)
                            return
            
            # copy input layer to the new one
            writeError = QgsVectorFileWriter.writeAsVectorFormat(roadLayer, newOutputLayer, 'utf-8',  roadLayer.crs())
            if writeError != QgsVectorFileWriter.NoError:
                message = self.tr('Error writing vector file {}'.format(newOutputLayer))
                QgsMessageLog.logMessage(message, 'QTraffic', QgsMessageLog.CRITICAL)
                iface.messageBar().pushCritical('QTraffic', message)
                return
            
            # load the layer
            newLayerName =os.path.splitext(os.path.basename(  newOutputLayer ))[0]
            self.outLayer = QgsVectorLayer(newOutputLayer, newLayerName, 'ogr')
            if not self.outLayer.isValid():
                message = self.tr('Error loading vector file {}'.format(newOutputLayer))
                QgsMessageLog.logMessage(message, 'QTraffic', QgsMessageLog.CRITICAL)
                iface.messageBar().pushCritical('QTraffic', message)
                return
    
            self.outLayerId = self.outLayer.id()
            
        # prepare environment
        try:
            self.alg.setProject(self.project)
            self.alg.setLayer( roadLayer )
            self.alg.initConfig()
            self.alg.prepareRun()
        except Exception as ex:
            traceback.print_exc()
            message = self.tr('Error preparing running contex for the algoritm: %s' % str(ex))
            QgsMessageLog.logMessage(message, 'QTraffic', QgsMessageLog.CRITICAL)
            iface.messageBar().pushCritical('QTraffic', message)
            return
        
        # run the self.alg
        self.thread = QtCore.QThread(self)
        self.thread.started.connect(self.alg.run)
        self.thread.finished.connect(self.threadCleanup)
        self.thread.terminated.connect(self.threadCleanup)
        
        self.alg.moveToThread(self.thread)
        self.alg.started.connect(self.manageStarted)
        self.alg.progress.connect(self.manageProgress)
        self.alg.message.connect(self.manageMessage)
        self.alg.error.connect(self.manageError)
        self.alg.finished.connect(self.manageFinished)

        # set wait cursor and start
        QgsApplication.instance().setOverrideCursor(QtCore.Qt.WaitCursor)
        self.thread.start()
'CALC_METHOD':1,\
'OUTPUT':floodIntersectionWithGeo })

iface.addVectorLayer(riverIntersectionWithGeo, '', 'ogr')
iface.addVectorLayer(floodIntersectionWithGeo, '', 'ogr')

print("Intersections created.")

#------------------------------------------------------------------------------------------------------------------
# deleting extra files

print("Delecting Extra file...")

for path in exFiles:
    print("deleting", path, "...")
    QgsVectorFileWriter.deleteShapeFile(path)

print("Extra files deleted.")

#------------------------------------------------------------------------------------------------------------------
# Calculating distances

print("Calculating distance...")

riverLayer = QgsProject.instance().mapLayersByName('RiverIntersectionWithGeo')
floodLayer = QgsProject.instance().mapLayersByName('FloodIntersectionWithGeo')

#print(lyr)

rRightBorder = []
rLeftBorder = []
Exemplo n.º 45
0
    def calculate(self):
        ''' Prepare environment to run the alg and run it. After run, merge produced 
        data basing on plugin configuration.
        Before calculation a parametere validation will be executed
        '''
        # perform validation
        if not self.gui.validate():
            return
        else:
            # notify successful validation
            message = self.tr(
                "QTraffic: Parameters validation passed successfully")
            iface.messageBar().pushMessage(message, QgsMessageBar.SUCCESS)

        # set number of classes in the project config (that is the temporary one... but equal to the official one)
        fleetDistributionRoadTypes = self.gui.getRoadTypes()
        self.project.setValue('Processing.Parameters/maximum_type',
                              len(fleetDistributionRoadTypes))
        self.project.sync()

        # create the algorithm
        self.alg = Algorithm()
        roadLayer = self.gui.getRoadLayer()

        # prepare layer where to add result
        addToInputLayer = self.gui.addToOriginaLayer_RButton.isChecked()
        newOutputLayer = self.gui.outFile_LEdit.text()

        if addToInputLayer:
            self.outLayer = roadLayer
            self.outLayerId = self.outLayer.id()
        else:
            # if layer is present... remove it
            # out layer would not be the same of input road layer... in thi scase don't remove it
            if self.outLayer and self.outLayer.isValid():
                # to be sure, remove only if roadLayer and outLayer are different
                if self.outLayer.publicSource() != roadLayer.publicSource():
                    self.outLayerRemoved = False
                    QgsMapLayerRegistry.instance().layerRemoved.connect(
                        self.checkOutLayerRemoved)
                    QgsMapLayerRegistry.instance().removeMapLayer(
                        self.outLayer.id())

                    # remove file when it has been removed from qgis
                    while not self.outLayerRemoved:
                        sleep(0.1)
                    QgsMapLayerRegistry.instance().layerRemoved.disconnect(
                        self.checkOutLayerRemoved)

                    # reinit outLayer variables
                    # If not, under windws remain a locking of the related file creating
                    # an error during QgsVectorFileWriter.deleteShapeFile
                    self.outLayer = None
                    self.outLayerId = None

                    if os.path.exists(newOutputLayer):
                        if not QgsVectorFileWriter.deleteShapeFile(
                                newOutputLayer):
                            message = self.tr(
                                "Error removing shape: {}".format(
                                    newOutputLayer))
                            iface.messageBar().pushMessage(
                                message, QgsMessageBar.CRITICAL)
                            return

            # copy input layer to the new one
            writeError = QgsVectorFileWriter.writeAsVectorFormat(
                roadLayer, newOutputLayer, 'utf-8', roadLayer.crs())
            if writeError != QgsVectorFileWriter.NoError:
                message = self.tr(
                    'Error writing vector file {}'.format(newOutputLayer))
                QgsMessageLog.logMessage(message, 'QTraffic',
                                         QgsMessageLog.CRITICAL)
                iface.messageBar().pushCritical('QTraffic', message)
                return

            # load the layer
            newLayerName = os.path.splitext(
                os.path.basename(newOutputLayer))[0]
            self.outLayer = QgsVectorLayer(newOutputLayer, newLayerName, 'ogr')
            if not self.outLayer.isValid():
                message = self.tr(
                    'Error loading vector file {}'.format(newOutputLayer))
                QgsMessageLog.logMessage(message, 'QTraffic',
                                         QgsMessageLog.CRITICAL)
                iface.messageBar().pushCritical('QTraffic', message)
                return

            self.outLayerId = self.outLayer.id()

        # prepare environment
        try:
            self.alg.setProject(self.project)
            self.alg.setLayer(roadLayer)
            self.alg.initConfig()
            self.alg.prepareRun()
        except Exception as ex:
            traceback.print_exc()
            message = self.tr(
                'Error preparing running contex for the algoritm: %s' %
                str(ex))
            QgsMessageLog.logMessage(message, 'QTraffic',
                                     QgsMessageLog.CRITICAL)
            iface.messageBar().pushCritical('QTraffic', message)
            return

        # run the self.alg
        self.thread = QtCore.QThread(self)
        self.thread.started.connect(self.alg.run)
        self.thread.finished.connect(self.threadCleanup)
        self.thread.terminated.connect(self.threadCleanup)

        self.alg.moveToThread(self.thread)
        self.alg.started.connect(self.manageStarted)
        self.alg.progress.connect(self.manageProgress)
        self.alg.message.connect(self.manageMessage)
        self.alg.error.connect(self.manageError)
        self.alg.finished.connect(self.manageFinished)

        # set wait cursor and start
        QgsApplication.instance().setOverrideCursor(QtCore.Qt.WaitCursor)
        self.thread.start()
Exemplo n.º 46
0
    def on_btnRun_clicked(self):
                
        if self.inputfile == '':
            QMessageBox.critical(self,'Map Creator',
                                 'Please specify input coordinate file.')
            return
        
        if self.outputfile == '':
            QMessageBox.critical(self,'Map Creator',
                                 'Please specify output shapefile.')
            return
        
        self.setCursor(Qt.WaitCursor)

        #Open coordinate input file
        f = open(self.inputfile, 'r')
        lines = f.readlines()
        f.close()
        header = lines[0].split(',')[0]
        totfeat = len(lines) - 1
        lines.pop(0)
        lines.reverse() 
        
        #Create vector layer
        basename = os.path.basename(self.outputfile)
        vlayer = QgsVectorLayer("Polygon", basename, "memory")
        vprovider = vlayer.dataProvider()
        fld = QgsField(header,QVariant.String)
        flds = QgsFields()
        flds.append(fld)
        vprovider.addAttributes([fld])
        vlayer.startEditing()
                
        hull = []
        for cnt, line in enumerate(lines):
            line = line.rstrip().split(',')
            numcoords = int((len(line) - 1) / 2)
            hull[:] = []
            geom = QgsGeometry()
            feat = QgsFeature()
            feat.setFields(flds)
            for i in range(numcoords):
                hull.append(QgsPoint(float(line[i*2+1]),float(line[i*2+2])))
            geom = geom.fromMultiPoint(hull)
            geom = geom.convexHull()
            feat.setGeometry(geom)
            feat.setAttribute(header,str(line[0]))
            result = vlayer.addFeature(feat)
            if not result:
                self.setCursor(Qt.ArrowCursor)
                QMessageBox.critical(self,'Map Creator', 'Processing error.')
                return
            self.ui.ProgressBar.setValue(float(cnt+1)/float(totfeat) * 100.0)
            QApplication.processEvents()  
        vlayer.commitChanges()
        vlayer.updateExtents()
        
        #Write the output shapefile
        if os.path.exists(self.outputfile):
            QgsVectorFileWriter.deleteShapeFile(self.outputfile)
        result = QgsVectorFileWriter.writeAsVectorFormat(vlayer, 
                                                         self.outputfile, 
                                                         'utf-8', 
                                                         vlayer.crs())
                
        if result != QgsVectorFileWriter.NoError:
            QMessageBox.critical(self,'Map Creator','Error creating shapefile.')
        else: #Ask to add shapfile to map
            name = QFileInfo(self.outputfile).completeBaseName()
            result = QMessageBox.question(self,'Map Creator',
                                          'Add shapefile to map?',
                                          QMessageBox.Yes,
                                          QMessageBox.No)
            if result == QMessageBox.Yes:
                self.iface.addVectorLayer(self.outputfile, name, 'ogr')
                
        self.setCursor(Qt.ArrowCursor)
Exemplo n.º 47
0
    def create_layer(self,
                     parameters,
                     name,
                     is_memory,
                     dest_crs,
                     layer_style=None):
        save_as = parameters.file_path
        file_format = parameters.file_format
        # save paramaters
        serialized = base64.b64encode(
            parameters.serialize(with_style=False, with_geometry=False))

        # save geometry
        layer = QgsVectorLayer("MultiPolygon?crs=%s" % dest_crs.authid(), name,
                               "memory")
        pr = layer.dataProvider()
        layer.startEditing()
        layer.addAttribute(QgsField("params", QVariant.String))
        fet1 = QgsFeature(0)
        fet1.setFields(layer.fields())
        fet1.setAttribute("params", str(serialized)[2:-1])
        fet1.setGeometry(parameters.geometry)
        pr.addFeatures([fet1])
        layer.commitChanges()

        # copy layer style
        if layer_style is not None:
            self.set_layer_style(layer, layer_style)

        if is_memory:
            return layer

        if os.path.isfile(save_as):
            # delete first if already exists
            if save_as.endswith(".shp"):
                QgsVectorFileWriter.deleteShapeFile(save_as)
            else:
                os.unlink(save_as)

        # create the disk layer
        QgsMessageLog.logMessage(
            "Mask saving '{}' as {}".format(save_as, file_format),
            "Extensions")
        error = QgsVectorFileWriter.writeAsVectorFormat(
            layer, save_as, "System", dest_crs, file_format)

        if error[0] == 0:
            QgsMessageLog.logMessage("Error = 0", "Extensions")
            nlayer = QgsVectorLayer(save_as, name, "ogr")
            if not nlayer.dataProvider().isValid():
                QgsMessageLog.logMessage("Invalid dataProvider", "Extensions")
                return None
            if not nlayer.isSpatial():
                QgsMessageLog.logMessage("No GeometryType", "Extensions")
                return None
            # force CRS
            nlayer.setCrs(dest_crs)

            # copy layer style
            layer_style = self.get_layer_style(layer)
            self.set_layer_style(nlayer, layer_style)
            return nlayer
        else:
            raise RuntimeError(error)

        return None