Example #1
0
 def nearest_neighbour_analysis(self, vlayer):
     vprovider = vlayer.dataProvider()
     sumDist = 0.00
     distance = QgsDistanceArea()
     A = vlayer.extent()
     A = float(A.width() * A.height())
     index = ftools_utils.createIndex(vprovider)
     nFeat = vprovider.featureCount()
     nElement = 0
     if nFeat > 0:
         self.emit(SIGNAL("runStatus(PyQt_PyObject)"), 0)
         self.emit(SIGNAL("runRange(PyQt_PyObject)"), (0, nFeat))
     feat = QgsFeature()
     neighbour = QgsFeature()
     fit = vprovider.getFeatures()
     while fit.nextFeature(feat):
         neighbourID = index.nearestNeighbor(feat.geometry().asPoint(), 2)[1]
         vprovider.getFeatures(QgsFeatureRequest().setFilterFid(neighbourID).setSubsetOfAttributes([])).nextFeature(neighbour)
         nearDist = distance.measureLine(neighbour.geometry().asPoint(), feat.geometry().asPoint())
         sumDist += nearDist
         nElement += 1
         self.emit(SIGNAL("runStatus(PyQt_PyObject)"), nElement)
     nVal = vprovider.featureCount()
     do = float(sumDist) / nVal
     de = float(0.5 / math.sqrt(nVal / A))
     d = float(do / de)
     SE = float(0.26136 / math.sqrt((nVal * nVal) / A))
     zscore = float((do - de) / SE)
     lstStats = []
     lstStats.append(self.tr("Observed mean distance:") + unicode(do))
     lstStats.append(self.tr("Expected mean distance:") + unicode(de))
     lstStats.append(self.tr("Nearest neighbour index:") + unicode(d))
     lstStats.append(self.tr("N:") + unicode(nVal))
     lstStats.append(self.tr("Z-Score:") + unicode(zscore))
     return (lstStats, [])
Example #2
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 = 15.00
     add = 85.00 / polyProvider.featureCount()
     check = QFile(self.shapefileName)
     if check.exists():
         if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
             return
     writer = QgsVectorFileWriter(self.shapefileName,
                                  self.encoding, fieldList,
                                  polyProvider.geometryType(), sRs)
     spatialIndex = ftools_utils.createIndex(lineProvider)
     polyFit = polyProvider.getFeatures()
     while polyFit.nextFeature(inFeat):
         inGeom = QgsGeometry(inFeat.geometry())
         atMap = inFeat.attributes()
         lineList = []
         length = 0
         lineList = spatialIndex.intersects(inGeom.boundingBox())
         if len(lineList) > 0: check = 0
         else: check = 1
         if check == 0:
             for i in lineList:
                 lineProvider.getFeatures(QgsFeatureRequest().setFilterFid(
                     int(i))).nextFeature(inFeatB)
                 tmpGeom = QgsGeometry(inFeatB.geometry())
                 if inGeom.intersects(tmpGeom):
                     outGeom = inGeom.intersection(tmpGeom)
                     length = length + distArea.measure(outGeom)
         outFeat.setGeometry(inGeom)
         atMap.append(QVariant(length))
         outFeat.setAttributes(atMap)
         #outFeat.setAttribute(index, QVariant(length))
         writer.addFeature(outFeat)
         start = start + 1
         progressBar.setValue(start)
     del writer
Example #3
0
 def vectorRandom(self, n, layer, xmin, xmax, ymin, ymax):
     provider = layer.dataProvider()
     provider.select([])
     index = ftools_utils.createIndex(provider)
     seed()
     points = []
     feat = QgsFeature()
     i = 1
     count = 40.00
     add = (70.00 - 40.00) / n
     while i <= n:
         point = QgsPoint(xmin + (xmax - xmin) * random(),
                          ymin + (ymax - ymin) * random())
         pGeom = QgsGeometry().fromPoint(point)
         ids = index.intersects(pGeom.buffer(5, 5).boundingBox())
         for id in ids:
             provider.featureAtId(int(id), feat, True)
             tGeom = QgsGeometry(feat.geometry())
             if pGeom.intersects(tGeom):
                 points.append(pGeom)
                 i = i + 1
                 count = count + add
                 self.progressBar.setValue(count)
                 break
     return points
Example #4
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."))
     allAttrs = polyProvider.attributeIndexes()
     polyProvider.select(allAttrs)
     allAttrs = lineProvider.attributeIndexes()
     lineProvider.select(allAttrs)
     fieldList = ftools_utils.getFieldList(polyLayer)
     index = polyProvider.fieldNameIndex(unicode(inField))
     if index == -1:
         index = polyProvider.fieldCount()
         field = QgsField(unicode(inField), QVariant.Double, "real", 24, 15, self.tr("length field"))
         fieldList[index] = field
     sRs = polyProvider.crs()
     inFeat = QgsFeature()
     inFeatB = QgsFeature()
     outFeat = QgsFeature()
     inGeom = QgsGeometry()
     outGeom = QgsGeometry()
     distArea = QgsDistanceArea()
     lineProvider.rewind()
     start = 15.00
     add = 85.00 / polyProvider.featureCount()
     check = QFile(self.shapefileName)
     if check.exists():
         if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
             return
     writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fieldList, polyProvider.geometryType(), sRs)
     #writer = QgsVectorFileWriter(outPath, "UTF-8", fieldList, polyProvider.geometryType(), sRs)
     spatialIndex = ftools_utils.createIndex( lineProvider )
     while polyProvider.nextFeature(inFeat):
         inGeom = QgsGeometry(inFeat.geometry())
         atMap = inFeat.attributeMap()
         lineList = []
         length = 0
         #(check, lineList) = lineLayer.featuresInRectangle(inGeom.boundingBox(), True, False)
         #lineLayer.select(inGeom.boundingBox(), False)
         #lineList = lineLayer.selectedFeatures()
         lineList = spatialIndex.intersects(inGeom.boundingBox())
         if len(lineList) > 0: check = 0
         else: check = 1
         if check == 0:
             for i in lineList:
                 lineProvider.featureAtId( int( i ), inFeatB , True, allAttrs )
                 tmpGeom = QgsGeometry( inFeatB.geometry() )
                 if inGeom.intersects(tmpGeom):
                     outGeom = inGeom.intersection(tmpGeom)
                     length = length + distArea.measure(outGeom)
         outFeat.setGeometry(inGeom)
         outFeat.setAttributeMap(atMap)
         outFeat.addAttribute(index, QVariant(length))
         writer.addFeature(outFeat)
         start = start + 1
         progressBar.setValue(start)
     del writer
Example #5
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
Example #6
0
 def compute(self, inPoly, inPts, inField, outPath, progressBar):
     polyLayer = ftools_utils.getVectorLayerByName(inPoly)
     pointLayer = ftools_utils.getVectorLayerByName(inPts)
     polyProvider = polyLayer.dataProvider()
     pointProvider = pointLayer.dataProvider()
     if polyProvider.crs() <> pointProvider.crs():
         QMessageBox.warning(self, self.tr("CRS warning!"), self.tr("Warning: Input layers have non-matching CRS.\nThis may cause unexpected results."))
     allAttrs = polyProvider.attributeIndexes()
     polyProvider.select(allAttrs)
     allAttrs = pointProvider.attributeIndexes()
     pointProvider.select(allAttrs)
     fieldList = ftools_utils.getFieldList(polyLayer)
     index = polyProvider.fieldNameIndex(unicode(inField))
     if index == -1:
         index = polyProvider.fieldCount()
         field = QgsField(unicode(inField), QVariant.Double, "real", 24, 15, self.tr("point count field"))
         fieldList[index] = field
     sRs = polyProvider.crs()
     check = QFile(self.shapefileName)
     if check.exists():
         if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
             return
     writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fieldList, polyProvider.geometryType(), sRs)
     inFeat = QgsFeature()
     inFeatB = QgsFeature()
     outFeat = QgsFeature()
     inGeom = QgsGeometry()
     start = 15.00
     add = 85.00 / polyProvider.featureCount()
     spatialIndex = ftools_utils.createIndex( pointProvider )
     while polyProvider.nextFeature(inFeat):
         inGeom = inFeat.geometry()
         atMap = inFeat.attributeMap()
         outFeat.setAttributeMap(atMap)
         outFeat.setGeometry(inGeom)
         pointList = []
         count = 0
         #(check, pointList) = pointLayer.featuresInRectangle(inGeom.boundingBox(), True, True)
         #pointLayer.select(inGeom.boundingBox(), False)
         #pointList = pointLayer.selectedFeatures()
         pointList = spatialIndex.intersects(inGeom.boundingBox())
         if len(pointList) > 0: check = 0
         else: check = 1
         if check == 0:
             for i in pointList:
                 pointProvider.featureAtId( int( i ), inFeatB , True, allAttrs )
                 tmpGeom = QgsGeometry( inFeatB.geometry() )
                 if inGeom.contains(tmpGeom.asPoint()):
                     count = count + 1
         outFeat.setAttributeMap(atMap)
         outFeat.addAttribute(index, QVariant(count))
         writer.addFeature(outFeat)
         start = start + 1
         progressBar.setValue(start)
     del writer
Example #7
0
 def compute(self, inPoly, inPts, modify, selection):
     inputLayer = ftools_utils.getVectorLayerByName(inPoly)
     selectLayer = ftools_utils.getVectorLayerByName(inPts)
     inputProvider = inputLayer.dataProvider()
     allAttrs = inputProvider.attributeIndexes()
     inputProvider.select(allAttrs, QgsRectangle())
     selectProvider = selectLayer.dataProvider()
     allAttrs = selectProvider.attributeIndexes()
     selectProvider.select(allAttrs, QgsRectangle())
     feat = QgsFeature()
     infeat = QgsFeature()
     geom = QgsGeometry()
     selectedSet = []
     index = ftools_utils.createIndex(inputProvider)
     inputProvider.rewind()
     inputProvider.select(inputProvider.attributeIndexes())
     if selection:
         features = selectLayer.selectedFeatures()
         self.progressBar.setMaximum(len(features))
         for feat in features:
             geom = QgsGeometry(feat.geometry())
             intersects = index.intersects(geom.boundingBox())
             for id in intersects:
                 inputProvider.featureAtId(int(id), infeat, True)
                 tmpGeom = QgsGeometry(infeat.geometry())
                 if geom.intersects(tmpGeom):
                     selectedSet.append(infeat.id())
             self.progressBar.setValue(self.progressBar.value() + 1)
     else:
         self.progressBar.setMaximum(selectProvider.featureCount())
         while selectProvider.nextFeature(feat):
             geom = QgsGeometry(feat.geometry())
             intersects = index.intersects(geom.boundingBox())
             for id in intersects:
                 inputProvider.featureAtId(int(id), infeat, True)
                 tmpGeom = QgsGeometry(infeat.geometry())
                 if geom.intersects(tmpGeom):
                     selectedSet.append(infeat.id())
             self.progressBar.setValue(self.progressBar.value() + 1)
     if modify == self.tr("adding to current selection"):
         selectedSet = list(
             set(inputLayer.selectedFeaturesIds()).union(selectedSet))
     elif modify == self.tr("removing from current selection"):
         selectedSet = list(
             set(inputLayer.selectedFeaturesIds()).difference(selectedSet))
     inputLayer.setSelectedFeatures(selectedSet)
 def compute(self, inPoly, inPts, modify, selection):
     inputLayer = ftools_utils.getVectorLayerByName(inPoly)
     selectLayer = ftools_utils.getVectorLayerByName(inPts)
     inputProvider = inputLayer.dataProvider()
     allAttrs = inputProvider.attributeIndexes()
     inputProvider.select(allAttrs, QgsRectangle())
     selectProvider = selectLayer.dataProvider()
     allAttrs = selectProvider.attributeIndexes()
     selectProvider.select(allAttrs, QgsRectangle())
     feat = QgsFeature()
     infeat = QgsFeature()
     geom = QgsGeometry()
     selectedSet = []
     index = ftools_utils.createIndex(inputProvider)
     inputProvider.rewind()
     inputProvider.select(inputProvider.attributeIndexes())
     if selection:
         features = selectLayer.selectedFeatures()
         self.progressBar.setMaximum(len(features))
         for feat in features:
             geom = QgsGeometry(feat.geometry())
             intersects = index.intersects(geom.boundingBox())
             for id in intersects:
                 inputProvider.featureAtId(int(id), infeat, True)
                 tmpGeom = QgsGeometry(infeat.geometry())
                 if geom.intersects(tmpGeom):
                     selectedSet.append(infeat.id())
             self.progressBar.setValue(self.progressBar.value()+1)
     else:
         self.progressBar.setMaximum(selectProvider.featureCount())
         while selectProvider.nextFeature(feat):
             geom = QgsGeometry(feat.geometry())
             intersects = index.intersects(geom.boundingBox())
             for id in intersects:
                 inputProvider.featureAtId(int(id), infeat, True)
                 tmpGeom = QgsGeometry( infeat.geometry() )
                 if geom.intersects(tmpGeom):
                     selectedSet.append(infeat.id())
             self.progressBar.setValue(self.progressBar.value()+1)
     if modify == self.tr("adding to current selection"):
         selectedSet = list(set(inputLayer.selectedFeaturesIds()).union(selectedSet))
     elif modify == self.tr("removing from current selection"):
         selectedSet = list(set(inputLayer.selectedFeaturesIds()).difference(selectedSet))
     inputLayer.setSelectedFeatures(selectedSet)
Example #9
0
 def vectorRandom(self, n, layer, xmin, xmax, ymin, ymax):
     provider = layer.dataProvider()
     index = ftools_utils.createIndex(provider)
     seed()
     points = []
     feat = QgsFeature()
     i = 1
     count = 40.00
     add = ( 70.00 - 40.00 ) / n
     while i <= n:
         point = QgsPoint(xmin + (xmax-xmin) * random(), ymin + (ymax-ymin) * random())
         pGeom = QgsGeometry().fromPoint(point)
         ids = index.intersects(pGeom.buffer(5,5).boundingBox())
         for id in ids:
             provider.getFeatures( QgsFeatureRequest().setFilterFid( int(id) ) ).nextFeature( feat )
             tGeom = QgsGeometry(feat.geometry())
             if pGeom.intersects(tGeom):
                 points.append(pGeom)
                 i = i + 1
                 count = count + add
                 self.progressBar.setValue(count)
                 break
     return points
Example #10
0
    def compute(self, inLayer, selLayer, modify, selection):
        inputLayer = ftools_utils.getVectorLayerByName(inLayer)
        selectLayer = ftools_utils.getVectorLayerByName(selLayer)
        inputProvider = inputLayer.dataProvider()
        selectProvider = selectLayer.dataProvider()
        feat = QgsFeature()
        infeat = QgsFeature()
        geom = QgsGeometry()
        selectedSet = []
        index = ftools_utils.createIndex(inputProvider)

        def _points_op(geomA, geomB):
            return geomA.intersects(geomB)

        def _poly_lines_op(geomA, geomB):
            if geomA.disjoint(geomB):
                return False
            intersects = False
            if self.opFlags & self.INTERSECT:
                intersects |= geomA.intersects(geomB)
            if not intersects and (self.opFlags & self.TOUCH):
                intersects |= geomA.touches(geomB)
            if not intersects and (self.opFlags & self.OVERLAP):
                if geomB.type() == QGis.Line or geomA.type() == QGis.Line:
                    intersects |= geomA.crosses(geomB)
                else:
                    intersects |= geomA.overlaps(geomB)
            if not intersects and (self.opFlags & self.WITHIN):
                intersects |= geomA.contains(geomB)
            return intersects

        def _sp_operator():
            if inputLayer.geometryType() == QGis.Point:
                return _points_op
            else:
                return _poly_lines_op

        self.opFlags = 0
        if self.chkTouches.checkState() == Qt.Checked:
            self.opFlags |= self.TOUCH
        if self.chkOverlaps.checkState() == Qt.Checked:
            self.opFlags |= self.OVERLAP
        if self.chkContains.checkState() == Qt.Checked:
            self.opFlags |= self.WITHIN
        if self.chkIntersects.checkState() == Qt.Checked:
            self.opFlags |= self.INTERSECT

        sp_operator = _sp_operator()

        if selection:
            features = selectLayer.selectedFeatures()
            self.progressBar.setMaximum(len(features))
            for feat in features:
                geom = QgsGeometry(feat.geometry())
                intersects = index.intersects(geom.boundingBox())
                for id in intersects:
                    inputProvider.getFeatures(QgsFeatureRequest().setFilterFid(int(id))).nextFeature(infeat)
                    tmpGeom = QgsGeometry(infeat.geometry())
                    if sp_operator(geom, tmpGeom):
                        selectedSet.append(infeat.id())
                self.progressBar.setValue(self.progressBar.value() + 1)
        else:
            self.progressBar.setMaximum(selectProvider.featureCount())
            selectFit = selectProvider.getFeatures()
            while selectFit.nextFeature(feat):
                geom = QgsGeometry(feat.geometry())
                intersects = index.intersects(geom.boundingBox())
                for id in intersects:
                    inputProvider.getFeatures(QgsFeatureRequest().setFilterFid(int(id))).nextFeature(infeat)
                    tmpGeom = QgsGeometry(infeat.geometry())
                    if sp_operator(geom, tmpGeom):
                        selectedSet.append(infeat.id())
                self.progressBar.setValue(self.progressBar.value() + 1)
        if modify == self.tr("adding to current selection"):
            selectedSet = list(set(inputLayer.selectedFeaturesIds()).union(selectedSet))
        elif modify == self.tr("removing from current selection"):
            selectedSet = list(set(inputLayer.selectedFeaturesIds()).difference(selectedSet))
        inputLayer.setSelectedFeatures(selectedSet)
Example #11
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()"))
Example #12
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()
        start = 15.00
        add = 85.00 / layer1.featureCount()

        index = ftools_utils.createIndex( provider2 )

        fit1 = vprovider.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:
                            outFeat.setGeometry(tempGeom.fromPoint(j))
                            outFeat.setAttribute(0, v1)
                            outFeat.setAttribute(1, v2)
                            writer.addFeature(outFeat)

            start = start + add
            progressBar.setValue(start)

        del writer
Example #13
0
 def compute(self, inPoly, inPts, inField, outPath, progressBar):
     polyLayer = ftools_utils.getVectorLayerByName(inPoly)
     pointLayer = ftools_utils.getVectorLayerByName(inPts)
     polyProvider = polyLayer.dataProvider()
     pointProvider = pointLayer.dataProvider()
     if polyProvider.crs() <> pointProvider.crs():
         QMessageBox.warning(
             self, self.tr("CRS warning!"),
             self.
             tr("Warning: Input layers have non-matching CRS.\nThis may cause unexpected results."
                ))
     allAttrs = polyProvider.attributeIndexes()
     polyProvider.select(allAttrs)
     allAttrs = pointProvider.attributeIndexes()
     pointProvider.select(allAttrs)
     fieldList = ftools_utils.getFieldList(polyLayer)
     index = polyProvider.fieldNameIndex(unicode(inField))
     if index == -1:
         index = polyProvider.fieldCount()
         field = QgsField(unicode(inField), QVariant.Double, "real", 24, 15,
                          self.tr("point count field"))
         fieldList[index] = field
     sRs = polyProvider.crs()
     check = QFile(self.shapefileName)
     if check.exists():
         if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
             return
     writer = QgsVectorFileWriter(self.shapefileName,
                                  self.encoding, fieldList,
                                  polyProvider.geometryType(), sRs)
     #writer = QgsVectorFileWriter(outPath, "UTF-8", fieldList, polyProvider.geometryType(), sRs)
     inFeat = QgsFeature()
     inFeatB = QgsFeature()
     outFeat = QgsFeature()
     inGeom = QgsGeometry()
     start = 15.00
     add = 85.00 / polyProvider.featureCount()
     spatialIndex = ftools_utils.createIndex(pointProvider)
     while polyProvider.nextFeature(inFeat):
         inGeom = inFeat.geometry()
         atMap = inFeat.attributeMap()
         outFeat.setAttributeMap(atMap)
         outFeat.setGeometry(inGeom)
         pointList = []
         count = 0
         #(check, pointList) = pointLayer.featuresInRectangle(inGeom.boundingBox(), True, True)
         #pointLayer.select(inGeom.boundingBox(), False)
         #pointList = pointLayer.selectedFeatures()
         pointList = spatialIndex.intersects(inGeom.boundingBox())
         if len(pointList) > 0: check = 0
         else: check = 1
         if check == 0:
             for i in pointList:
                 pointProvider.featureAtId(int(i), inFeatB, True, allAttrs)
                 tmpGeom = QgsGeometry(inFeatB.geometry())
                 if inGeom.contains(tmpGeom.asPoint()):
                     count = count + 1
         outFeat.setAttributeMap(atMap)
         outFeat.addAttribute(index, QVariant(count))
         writer.addFeature(outFeat)
         start = start + 1
         progressBar.setValue(start)
     del writer
Example #14
0
    def compute(self, inLayer, selLayer, modify, selection):
        inputLayer = ftools_utils.getVectorLayerByName(inLayer)
        selectLayer = ftools_utils.getVectorLayerByName(selLayer)
        inputProvider = inputLayer.dataProvider()
        selectProvider = selectLayer.dataProvider()
        feat = QgsFeature()
        infeat = QgsFeature()
        geom = QgsGeometry()
        selectedSet = []
        index = ftools_utils.createIndex(inputProvider)

        def _points_op(geomA, geomB):
            return geomA.intersects(geomB)

        def _poly_lines_op(geomA, geomB):
            if geomA.disjoint(geomB):
                return False
            intersects = False
            if self.opFlags & self.TOUCH:
                intersects |= geomA.touches(geomB)
            if not intersects and (self.opFlags & self.OVERLAP):
                if geomB.type() == QGis.Line or geomA.type() == QGis.Line:
                    intersects |= geomA.crosses(geomB)
                else:
                    intersects |= geomA.overlaps(geomB)
            if not intersects and (self.opFlags & self.WITHIN):
                intersects |= geomA.contains(geomB)
            return intersects

        def _sp_operator():
            if inputLayer.geometryType() == QGis.Point:
                return _points_op
            else:
                return _poly_lines_op

        self.opFlags = 0
        if self.chkTouches.checkState() == Qt.Checked:
            self.opFlags |= self.TOUCH
        if self.chkOverlaps.checkState() == Qt.Checked:
            self.opFlags |= self.OVERLAP
        if self.chkContains.checkState() == Qt.Checked:
            self.opFlags |= self.WITHIN

        sp_operator = _sp_operator()

        if selection:
            features = selectLayer.selectedFeatures()
            self.progressBar.setMaximum(len(features))
            for feat in features:
                geom = QgsGeometry(feat.geometry())
                intersects = index.intersects(geom.boundingBox())
                for id in intersects:
                    inputProvider.getFeatures(QgsFeatureRequest().setFilterFid(
                        int(id))).nextFeature(infeat)
                    tmpGeom = QgsGeometry(infeat.geometry())
                    if sp_operator(geom, tmpGeom):
                        selectedSet.append(infeat.id())
                self.progressBar.setValue(self.progressBar.value() + 1)
        else:
            self.progressBar.setMaximum(selectProvider.featureCount())
            selectFit = selectProvider.getFeatures()
            while selectFit.nextFeature(feat):
                geom = QgsGeometry(feat.geometry())
                intersects = index.intersects(geom.boundingBox())
                for id in intersects:
                    inputProvider.getFeatures(QgsFeatureRequest().setFilterFid(
                        int(id))).nextFeature(infeat)
                    tmpGeom = QgsGeometry(infeat.geometry())
                    if sp_operator(geom, tmpGeom):
                        selectedSet.append(infeat.id())
                self.progressBar.setValue(self.progressBar.value() + 1)
        if modify == self.tr("adding to current selection"):
            selectedSet = list(
                set(inputLayer.selectedFeaturesIds()).union(selectedSet))
        elif modify == self.tr("removing from current selection"):
            selectedSet = list(
                set(inputLayer.selectedFeaturesIds()).difference(selectedSet))
        inputLayer.setSelectedFeatures(selectedSet)
Example #15
0
    def compute(self, inName, joinName, outName, summary, sumList, keep, progressBar):
        layer1 = ftools_utils.getVectorLayerByName(inName)
        provider1 = layer1.dataProvider()
        allAttrs = provider1.attributeIndexes()
        provider1.select(allAttrs)
        fieldList1 = ftools_utils.getFieldList(layer1).values()

        layer2 = ftools_utils.getVectorLayerByName(joinName)
        provider2 = layer2.dataProvider()
        allAttrs = provider2.attributeIndexes()
        provider2.select(allAttrs)
        fieldList2 = ftools_utils.getFieldList(layer2)
        fieldList = []
        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.values())
            seq = range(0, len(fieldList1) + len(fieldList2))
            fieldList1.extend(fieldList2)
            fieldList1 = dict(zip(seq, fieldList1))
        else:
            numFields = {}
            for j in fieldList2.keys():
                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))

        # check for correct field names
        longNames = ftools_utils.checkFieldNameLength( fieldList1 )
        if not longNames.isEmpty():
            QMessageBox.warning( self, self.tr( 'Incorrect field names' ),
                        self.tr( 'No output will be created.\nFollowing field names are longer than 10 characters:\n%1' )
                        .arg( longNames.join( '\n' ) ) )
            return False

        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%1" ).arg( self.shapefileName ) )
                return False
        writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fieldList1, 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()
        provider1.rewind()
        index = ftools_utils.createIndex(provider2)
        while provider1.nextFeature(inFeat):
            inGeom = inFeat.geometry()
            atMap1 = inFeat.attributeMap()
            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:
                    #tempGeom = i.geometry()
                    provider2.featureAtId(int(i), inFeatB , True, allAttrs)
                    tmpGeom = QgsGeometry( inFeatB.geometry() )
                    if inGeom.intersects(tmpGeom):
                        count = count + 1
                        none = False
                        atMap2 = inFeatB.attributeMap()
                        if not summary:
                            atMap = atMap1.values()
                            atMap2 = atMap2.values()
                            atMap.extend(atMap2)
                            atMap = dict(zip(seq, atMap))
                            break
                        else:
                            for j in numFields.keys():
                                numFields[j].append(atMap2[j].toDouble()[0])
                if summary and not none:
                    atMap = atMap1.values()
                    for j in numFields.keys():
                        for k in sumList:
                            if k == "SUM": atMap.append(QVariant(sum(numFields[j])))
                            elif k == "MEAN": atMap.append(QVariant(sum(numFields[j]) / count))
                            elif k == "MIN": atMap.append(QVariant(min(numFields[j])))
                            elif k == "MED": atMap.append(QVariant(myself(numFields[j])))
                            else: atMap.append(QVariant(max(numFields[j])))
                        numFields[j] = []
                    atMap.append(QVariant(count))
                    atMap = dict(zip(seq, atMap))
            if none:
                outFeat.setAttributeMap(atMap1)
            else:
                outFeat.setAttributeMap(atMap)
            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
Example #16
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()" ) )
Example #17
0
 def compute(self, line1, line2, field1, field2, outPath, progressBar):
     layer1 = ftools_utils.getVectorLayerByName(line1)
     layer2 = ftools_utils.getVectorLayerByName(line2)
     provider1 = layer1.dataProvider()
     provider2 = layer2.dataProvider()
     allAttrs = provider1.attributeIndexes()
     provider1.select(allAttrs)
     allAttrs = provider2.attributeIndexes()
     provider2.select(allAttrs)
     fieldList = ftools_utils.getFieldList(layer1)
     index1 = provider1.fieldNameIndex(field1)
     field1 = fieldList[index1]
     field1.setName(unicode(field1.name()) + "_1")
     fieldList = ftools_utils.getFieldList(layer2)
     index2 = provider2.fieldNameIndex(field2)
     field2 = fieldList[index2]
     field2.setName(unicode(field2.name()) + "_2")
     fieldList = {0:field1, 1: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)
     #writer = QgsVectorFileWriter(outPath, "UTF-8", fieldList, QGis.WKBPoint, sRs)
     inFeat = QgsFeature()
     inFeatB = QgsFeature()
     outFeat = QgsFeature()
     inGeom = QgsGeometry()
     tempGeom = QgsGeometry()
     start = 15.00
     add = 85.00 / layer1.featureCount()
     index = ftools_utils.createIndex( provider2 )
     while provider1.nextFeature(inFeat):
         inGeom = inFeat.geometry()
         lineList = []
         #(check, lineList) = layer2.featuresInRectangle(inGeom.boundingBox(), True, True)
         # Below is a work-around for featuresInRectangle
         # Which appears to have been removed for QGIS version 1.0
         #layer2.select(inGeom.boundingBox(), False)
         #lineList = layer2.selectedFeatures()
         lineList = index.intersects( inGeom.boundingBox() )
         if len(lineList) > 0: check = 0
         else: check = 1
         if check == 0:
             for i in lineList:
                 provider2.featureAtId( int( i ), inFeatB , True, allAttrs )
                 tmpGeom = QgsGeometry( inFeatB.geometry() )
                 #tempGeom = i.geometry()
                 tempList = []
                 atMap1 = inFeat.attributeMap()
                 atMap2 = inFeatB.attributeMap()
                 if inGeom.intersects(tmpGeom):
                     tempGeom = inGeom.intersection(tmpGeom)
                     if tempGeom.type() == QGis.Point:
                         if tempGeom.isMultipart():
                             tempList = tempGeom.asMultiPoint()
                         else:
                             tempList.append(tempGeom.asPoint())
                         for j in tempList:
                             outFeat.setGeometry(tempGeom.fromPoint(j))
                             outFeat.addAttribute(0, atMap1[index1])
                             outFeat.addAttribute(1, atMap2[index2])
                             writer.addFeature(outFeat)
         start = start + add
         progressBar.setValue(start)
     del writer
Example #18
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.Double, "real", 24,
                         15, 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(QVariant(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()"))
    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.Double, "real", 24, 15, 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()" ) )
Example #20
0
    def compute(self, inName, joinName, outName, summary, sumList, keep,
                progressBar):
        layer1 = ftools_utils.getVectorLayerByName(inName)
        provider1 = layer1.dataProvider()
        fieldList1 = ftools_utils.getFieldList(layer1).toList()

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

        fieldList2 = ftools_utils.getFieldList(layer2).toList()
        fieldList = []
        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))

        # check for correct field names
        print fieldList1
        longNames = ftools_utils.checkFieldNameLength(fieldList1.values())
        if not longNames.isEmpty():
            QMessageBox.warning(
                self, self.tr('Incorrect field names'),
                self.
                tr('No output will be created.\nFollowing field names are longer than 10 characters:\n%1'
                   ).arg(longNames.join('\n')))
            return False

        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%1").arg(
                        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)
        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:
                    #tempGeom = i.geometry()
                    provider2.getFeatures(QgsFeatureRequest().setFilterFid(
                        int(i))).nextFeature(inFeatB)
                    tmpGeom = QgsGeometry(inFeatB.geometry())
                    if inGeom.intersects(tmpGeom):
                        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].toDouble()[0])
                if summary and not none:
                    atMap = atMap1
                    for j in numFields.keys():
                        for k in sumList:
                            if k == "SUM":
                                atMap.append(QVariant(sum(numFields[j])))
                            elif k == "MEAN":
                                atMap.append(
                                    QVariant(sum(numFields[j]) / count))
                            elif k == "MIN":
                                atMap.append(QVariant(min(numFields[j])))
                            elif k == "MED":
                                atMap.append(QVariant(myself(numFields[j])))
                            else:
                                atMap.append(QVariant(max(numFields[j])))
                        numFields[j] = []
                    atMap.append(QVariant(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
Example #21
0
 def compute(self, line1, line2, field1, field2, outPath, progressBar):
     layer1 = ftools_utils.getVectorLayerByName(line1)
     layer2 = ftools_utils.getVectorLayerByName(line2)
     provider1 = layer1.dataProvider()
     provider2 = layer2.dataProvider()
     allAttrs = provider1.attributeIndexes()
     provider1.select(allAttrs)
     allAttrs = provider2.attributeIndexes()
     provider2.select(allAttrs)
     fieldList = ftools_utils.getFieldList(layer1)
     index1 = provider1.fieldNameIndex(field1)
     field1 = fieldList[index1]
     field1.setName(unicode(field1.name()) + "_1")
     fieldList = ftools_utils.getFieldList(layer2)
     index2 = provider2.fieldNameIndex(field2)
     field2 = fieldList[index2]
     field2.setName(unicode(field2.name()) + "_2")
     fieldList = {0: field1, 1: 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)
     #writer = QgsVectorFileWriter(outPath, "UTF-8", fieldList, QGis.WKBPoint, sRs)
     inFeat = QgsFeature()
     inFeatB = QgsFeature()
     outFeat = QgsFeature()
     inGeom = QgsGeometry()
     tempGeom = QgsGeometry()
     start = 15.00
     add = 85.00 / layer1.featureCount()
     index = ftools_utils.createIndex(provider2)
     while provider1.nextFeature(inFeat):
         inGeom = inFeat.geometry()
         lineList = []
         #(check, lineList) = layer2.featuresInRectangle(inGeom.boundingBox(), True, True)
         # Below is a work-around for featuresInRectangle
         # Which appears to have been removed for QGIS version 1.0
         #layer2.select(inGeom.boundingBox(), False)
         #lineList = layer2.selectedFeatures()
         lineList = index.intersects(inGeom.boundingBox())
         if len(lineList) > 0: check = 0
         else: check = 1
         if check == 0:
             for i in lineList:
                 provider2.featureAtId(int(i), inFeatB, True, allAttrs)
                 tmpGeom = QgsGeometry(inFeatB.geometry())
                 #tempGeom = i.geometry()
                 tempList = []
                 atMap1 = inFeat.attributeMap()
                 atMap2 = inFeatB.attributeMap()
                 if inGeom.intersects(tmpGeom):
                     tempGeom = inGeom.intersection(tmpGeom)
                     if tempGeom.type() == QGis.Point:
                         if tempGeom.isMultipart():
                             tempList = tempGeom.asMultiPoint()
                         else:
                             tempList.append(tempGeom.asPoint())
                         for j in tempList:
                             outFeat.setGeometry(tempGeom.fromPoint(j))
                             outFeat.addAttribute(0, atMap1[index1])
                             outFeat.addAttribute(1, atMap2[index2])
                             writer.addFeature(outFeat)
         start = start + add
         progressBar.setValue(start)
     del writer
Example #22
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