Exemplo n.º 1
0
    def processAlgorithm(self, progress):
        filename = self.getParameterValue(self.INPUT)
        inputLayer = QGisLayers.getObjectFromUri(filename)
        method = self.getParameterValue(self.METHOD)
        filename = self.getParameterValue(self.INTERSECT)
        selectLayer = QGisLayers.getObjectFromUri(filename)

        oldSelection = set(inputLayer.selectedFeaturesIds())
        index = spatialIndex = utils.createSpatialIndex(inputLayer)

        feat = QgsFeature()
        geom = QgsGeometry()
        selectedSet = []
        current = 0
        features = QGisLayers.features(selectLayer)
        total = 100.0 / float(len(features))
        for f in features:
            geom = QgsGeometry(f.geometry())
            intersects = index.intersects(geom.boundingBox())
            for i in intersects:
                request = QgsFeatureRequest().setFilterFid(i)
                feat = inputLayer.getFeatures(request).next()
                tmpGeom = QgsGeometry(feat.geometry())
                if geom.intersects(tmpGeom):
                    selectedSet.append(feat.id())
            current += 1
            progress.setPercentage(int(current * total))

        if method == 1:
            selectedSet = list(oldSelection.union(selectedSet))
        elif method == 2:
            selectedSet = list(oldSelection.difference(selectedSet))

        inputLayer.setSelectedFeatures(selectedSet)
        self.setOutputValue(self.OUTPUT, filename)
Exemplo n.º 2
0
 def exportVectorLayer(self, orgFilename):
     # TODO: improve this. We are now exporting if it is not a shapefile,
     # but the functionality of v.in.ogr could be used for this.
     # We also export if there is a selection
     if not os.path.exists(orgFilename) or not orgFilename.endswith("shp"):
         layer = QGisLayers.getObjectFromUri(orgFilename, False)
         if layer:
             filename = LayerExporter.exportVectorLayer(layer)
     else:
         layer = QGisLayers.getObjectFromUri(orgFilename, False)
         if layer:
             useSelection = ProcessingConfig.getSetting(ProcessingConfig.USE_SELECTED)
             if useSelection and layer.selectedFeatureCount() != 0:
                 filename = LayerExporter.exportVectorLayer(layer)
             else:
                 filename = orgFilename
         else:
             filename = orgFilename
     destFilename = self.getTempFilename()
     self.exportedLayers[orgFilename] = destFilename
     command = "v.in.ogr"
     min_area = self.getParameterValue(self.GRASS_MIN_AREA_PARAMETER)
     command += " min_area=" + str(min_area)
     snap = self.getParameterValue(self.GRASS_SNAP_TOLERANCE_PARAMETER)
     command += " snap=" + str(snap)
     command += ' dsn="' + os.path.dirname(filename) + '"'
     command += " layer=" + os.path.basename(filename)[:-4]
     command += " output=" + destFilename
     command += " --overwrite -o"
     return command
Exemplo n.º 3
0
 def calculateResamplingExtent(self):
     '''this method calculates the resampling extent, but it might set self.resample
     to false if, with the current layers, there is no need to resample'''
     auto = ProcessingConfig.getSetting(SagaUtils.SAGA_AUTO_RESAMPLING)
     if auto:
         first = True;
         self.inputExtentsCount = 0
         for param in self.parameters:
             if param.value:
                 if isinstance(param, ParameterRaster):
                     if isinstance(param.value, QgsRasterLayer):
                         layer = param.value
                     else:
                         layer = QGisLayers.getObjectFromUri(param.value)
                     self.addToResamplingExtent(layer, first)
                     first = False
                 if isinstance(param, ParameterMultipleInput):
                     if param.datatype == ParameterMultipleInput.TYPE_RASTER:
                         layers = param.value.split(";")
                         for layername in layers:
                             layer = QGisLayers.getObjectFromUri(layername)
                             self.addToResamplingExtent(layer, first)
                             first = False
         if self.inputExtentsCount < 2:
             self.resample = False
     else:
         self.xmin = ProcessingConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_XMIN)
         self.xmax = ProcessingConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_XMAX)
         self.ymin = ProcessingConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_YMIN)
         self.ymax = ProcessingConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_YMAX)
         self.cellsize = ProcessingConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_CELLSIZE)
Exemplo n.º 4
0
 def getSafeExportedLayers(self):
     '''Returns not the value entered by the user, but a string with semicolon-separated filenames
     which contains the data of the selected layers, but saved in a standard format (currently
     shapefiles for vector layers and GeoTiff for raster) so that they can be opened by most
     external applications.
     If there is a selection and QGIS is configured to use just the selection, if exports
     the layer even if it is already in a suitable format.
     Works only if the layer represented by the parameter value is currently loaded in QGIS.
     Otherwise, it will not perform any export and return the current value string.
     If the current value represents a layer in a suitable format, it does no export at all
     and returns that value.
     Currently, it works just for vector layer. In the case of raster layers, it returns the
     parameter value.
     The layers are exported just the first time the method is called. The method can be called
     several times and it will always return the same string, performing the export only the first time.'''
     if self.exported:
         return self.exported
     self.exported = self.value
     layers = self.value.split(";")
     if layers == None or len(layers) == 0:
         return self.value
     if self.datatype == ParameterMultipleInput.TYPE_RASTER:
         for layerfile in layers:
             layer = QGisLayers.getObjectFromUri(layerfile, False)
             if layer:
                 filename = LayerExporter.exportRasterLayer(layer)
                 self.exported = self.exported.replace(layerfile, filename)
         return self.exported
     else:
         for layerfile in layers:
             layer = QGisLayers.getObjectFromUri(layerfile, False)
             if layer:
                 filename = LayerExporter.exportVectorLayer(layer)
                 self.exported = self.exported.replace(layerfile, filename)
         return self.exported
Exemplo n.º 5
0
 def getMinCoveringExtent(self):
     first = True
     found = False
     for param in self.params:
         if param.value:
             if isinstance(param, (ParameterRaster, ParameterVector)):
                 if isinstance(param.value, (QgsRasterLayer, QgsVectorLayer)):
                     layer = param.value
                 else:
                     layer = QGisLayers.getObjectFromUri(param.value)
                 if layer:
                     found = True
                     self.addToRegion(layer, first)
                     first = False
             elif isinstance(param, ParameterMultipleInput):
                 layers = param.value.split(";")
                 for layername in layers:
                     layer = QGisLayers.getObjectFromUri(layername, first)
                     if layer:
                         found = True
                         self.addToRegion(layer, first)
                         first = False
     if found:
         return str(self.xmin) + "," + str(self.xmax) + "," + str(self.ymin) + "," + str(self.ymax)
     else:
         return None
Exemplo n.º 6
0
    def processAlgorithm(self, progress):
        inLayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT_LAYER))
        inField = self.getParameterValue(self.INPUT_FIELD)
        targetLayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.TARGET_LAYER))
        targetField = self.getParameterValue(self.TARGET_FIELD)
        matType = self.getParameterValue(self.MATRIX_TYPE)
        nPoints = self.getParameterValue(self.NEAREST_POINTS)

        outputFile = self.getOutputValue(self.DISTANCE_MATRIX)

        if nPoints < 1:
            nPoints = len(QGisLayers.features(targetLayer))

        # prepare CSV file writer
        csvFile = open(outputFile, "wb")
        self.writer = UnicodeWriter(csvFile)

        if matType == 0:  # Linear distance matrix
            self.linearMatrix(inLayer, inField, targetLayer, targetField, matType, nPoints, progress)
        elif matType == 1:  # Standard distance matrix
            self.regularMatrix(inLayer, inField, targetLayer, targetField, nPoints, progress)
        elif matType == 2:  # Summary distance matrix
            self.linearMatrix(inLayer, inField, targetLayer, targetField, matType, nPoints, progress)

        csvFile.close()
        del self.writer
Exemplo n.º 7
0
 def convertUnsupportedFormats(self, progress):
     i = 0
     progress.setText("Converting outputs")
     for out in self.outputs:
         if isinstance(out, OutputVector):
             if out.compatible is not None:
                 layer = QGisLayers.getObjectFromUri(out.compatible)
                 if layer is None: # for the case of memory layer, if the getCompatible method has been called
                     continue
                 provider = layer.dataProvider()
                 writer = out.getVectorWriter( provider.fields(), provider.geometryType(), layer.crs())
                 features = QGisLayers.features(layer)
                 for feature in features:
                     writer.addFeature(feature)
         elif isinstance(out, OutputRaster):
             if out.compatible is not None:
                 layer = QGisLayers.getObjectFromUri(out.compatible)
                 provider = layer.dataProvider()
                 writer = QgsRasterFileWriter(out.value)
                 format = self.getFormatShortNameFromFilename(out.value)
                 writer.setOutputFormat(format);
                 writer.writeRaster(layer.pipe(), layer.width(), layer.height(), layer.extent(), layer.crs())
         elif isinstance(out, OutputTable):
             if out.compatible is not None:
                 layer = QGisLayers.getObjectFromUri(out.compatible)
                 provider = layer.dataProvider()
                 writer = out.getTableWriter(provider.fields())
                 features = QGisLayers.features(layer)
                 for feature in features:
                     writer.addRecord(feature)
         progress.setPercentage(100 * i / float(len(self.outputs)))
    def processAlgorithm(self, progress):
        polyLayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.POLYGONS))
        pointLayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.POINTS))
        fieldName = self.getParameterValue(self.FIELD)
        fieldIdx = pointLayer.fieldNameIndex(self.getParameterValue(self.WEIGHT))

        polyProvider = polyLayer.dataProvider()

        idxCount, fieldList = utils.findOrCreateField(polyLayer, polyLayer.pendingFields(), fieldName)

        writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fieldList.toList(),
                     polyProvider.geometryType(), polyProvider.crs())

        spatialIndex = utils.createSpatialIndex(pointLayer)

        ftPoint = QgsFeature()
        outFeat = QgsFeature()
        geom = QgsGeometry()

        current = 0
        hasIntersections = False

        features = QGisLayers.features(polyLayer)
        total = 100.0 / float(len(features))
        for ftPoly in features:
            geom = ftPoly.geometry()
            attrs = ftPoly.attributes()

            count = 0
            hasIntersections = False
            points = spatialIndex.intersects(geom.boundingBox())
            if len(points) > 0:
                hasIntersections = True

            if hasIntersections:
                progress.setText(str(len(points)))
                for i in points:
                    request = QgsFeatureRequest().setFilterFid(i)
                    ftPoint = pointLayer.getFeatures(request).next()
                    tmpGeom = QgsGeometry(ftPoint.geometry())
                    if geom.contains(tmpGeom):
                        weight = str(ftPoint.attributes()[fieldIdx])
                        try:
                            count += float(weight)
                        except:
                            pass #ignore fields with non-numeric values

            outFeat.setGeometry(geom)
            if idxCount == len(attrs):
                attrs.append(count)
            else:
                attrs[idxCount] =  count
            outFeat.setAttributes(attrs)
            writer.addFeature(outFeat)

            current += 1
            progress.setPercentage(int(current * total))

        del writer
Exemplo n.º 9
0
    def processAlgorithm(self, progress):
        layerA = QGisLayers.getObjectFromUri(self.getParameterValue(Difference.INPUT))
        layerB = QGisLayers.getObjectFromUri(self.getParameterValue(Difference.OVERLAY))

        GEOS_EXCEPT = True

        FEATURE_EXCEPT = True

        writer = self.getOutputFromName(Difference.OUTPUT).getVectorWriter(layerA.pendingFields(),
                     layerA.dataProvider().geometryType(), layerA.dataProvider().crs())

        inFeatA = QgsFeature()
        inFeatB = QgsFeature()
        outFeat = QgsFeature()

        index = utils.createSpatialIndex(layerB)

        selectionA = QGisLayers.features(layerA)

        current = 0
        total = 100.0 / float(len(selectionA))

        for inFeatA in selectionA:
            add = True
            geom = QgsGeometry(inFeatA.geometry())
            diff_geom = QgsGeometry(geom)
            attrs = inFeatA.attributes()
            intersections = index.intersects(geom.boundingBox())
            for i in intersections:
                request = QgsFeatureRequest().setFilterFid(i)
                inFeatB = layerB.getFeatures(request).next()
                tmpGeom = QgsGeometry(inFeatB.geometry())
                try:
                    if diff_geom.intersects(tmpGeom):
                        diff_geom = QgsGeometry(diff_geom.difference(tmpGeom))
                except:
                    GEOS_EXCEPT = False
                    add = False
                    break

            if add:
                try:
                    outFeat.setGeometry(diff_geom)
                    outFeat.setAttributes(attrs)
                    writer.addFeature(outFeat)
                except:
                    FEATURE_EXCEPT = False
                    continue

            current += 1
            progress.setPercentage(int(current * total))

        del writer

        if not GEOS_EXCEPT:
            ProcessingLog.addToLog(ProcessingLog.LOG_WARNING, "Geometry exception while computing difference")
        if not FEATURE_EXCEPT:
            ProcessingLog.addToLog(ProcessingLog.LOG_WARNING, "Feature exception while computing difference")
Exemplo n.º 10
0
  def processAlgorithm(self, progress):

    layer1 = QGisLayers.getObjectFromUri(self.getParameterValue(self.LAYER1))
    layer2 = QGisLayers.getObjectFromUri(self.getParameterValue(self.LAYER2))

    fields = []
    layers = [layer1, layer2]
    totalfeaturecount = 0

    if (layer1.dataProvider().geometryType() != layer2.dataProvider().geometryType()):
      raise GeoAlgorithmExecutionException("Merged layers must all be same type of geometry (" + \
          mmqgisx_wkbtype_to_text(layer2.dataProvider().geometryType()) + " != " + \
          mmqgisx_wkbtype_to_text(layer2.dataProvider().geometryType()) + ")")

    for layer in layers:
      totalfeaturecount += layer.featureCount()

      # Add any fields not in the composite field list
      for sfield in layer.pendingFields():
        found = None
        for dfield in fields:
          if (dfield.name() == sfield.name()) and (dfield.type() == sfield.type()):
            found = dfield
            break

        if not found:
          fields.append(sfield)

    output = self.getOutputFromName(self.SAVENAME)
    out = output.getVectorWriter(fields, layer1.wkbType(), layer1.crs())

    # Copy layer features to output file
    featurecount = 0
    for layer in layers:
      idx = {}
      for dfield in fields:
        i = 0
        for sfield in layer.pendingFields():
          if (sfield.name() == dfield.name()) and (sfield.type() == dfield.type()):
            idx[dfield] = i
            break
          i += 1

      features = QGisLayers.features(layer)
      for feature in features:
        sattributes = feature.attributes()
        dattributes = []
        for dfield in fields:
          if (dfield in idx):
            dattributes.append(sattributes[idx[dfield]])
          else:
            dattributes.append(dfield.type())
        feature.setAttributes(dattributes)
        out.addFeature(feature)
        featurecount += 1
        progress.setPercentage(float(featurecount) / totalfeaturecount * 100)

    del out
Exemplo n.º 11
0
    def processAlgorithm(self, progress):
        polyLayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.POLYGONS))
        pointLayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.POINTS))
        fieldName = self.getParameterValue(self.FIELD)
        classFieldName = self.getParameterValue(self.CLASSFIELD)

        polyProvider = polyLayer.dataProvider()

        classFieldIndex = pointLayer.fieldNameIndex(classFieldName)
        idxCount, fieldList = utils.findOrCreateField(polyLayer, polyLayer.pendingFields(), fieldName)

        writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(
            fieldList.toList(), polyProvider.geometryType(), polyProvider.crs()
        )

        spatialIndex = utils.createSpatialIndex(pointLayer)

        ftPoint = QgsFeature()
        outFeat = QgsFeature()
        geom = QgsGeometry()

        current = 0
        hasIntersections = False

        features = QGisLayers.features(polyLayer)
        total = 100.0 / float(len(features))
        for ftPoly in features:
            geom = ftPoly.geometry()
            attrs = ftPoly.attributes()

            classes = []
            hasIntersections = False
            points = spatialIndex.intersects(geom.boundingBox())
            if len(points) > 0:
                hasIntersections = True

            if hasIntersections:
                for i in points:
                    request = QgsFeatureRequest().setFilterFid(i)
                    ftPoint = pointLayer.getFeatures(request).next()
                    tmpGeom = QgsGeometry(ftPoint.geometry())
                    if geom.contains(tmpGeom):
                        clazz = ftPoint.attributes()[classFieldIndex]
                        if not clazz in classes:
                            classes.append(clazz)

            outFeat.setGeometry(geom)
            if idxCount == len(attrs):
                attrs.append(len(classes))
            else:
                attrs[idxCount] = len(classes)
            outFeat.setAttributes(attrs)
            writer.addFeature(outFeat)

            current += 1
            progress.setPercentage(current / total)

        del writer
Exemplo n.º 12
0
  def processAlgorithm(self, progress):

    hublayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.HUBNAME))
    spokelayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.SPOKENAME))

    hubattr = self.getParameterValue(self.HUBATTRIBUTE)
    spokeattr = self.getParameterValue(self.SPOKEATTRIBUTE)


    if hublayer == spokelayer:
      raise GeoAlgorithmExecutionException ("Same layer given for both hubs and spokes")

    hubindex = hublayer.dataProvider().fieldNameIndex(hubattr)
    spokeindex = spokelayer.dataProvider().fieldNameIndex(spokeattr)

    outfields = spokelayer.pendingFields()

    output = self.getOutputFromName(self.SAVENAME)
    out = output.getVectorWriter(outfields, QGis.WKBLineString, spokelayer.crs())

    # Scan spoke points
    linecount = 0
    spokepoints = QGisLayers.features(spokelayer)
    i = 0
    for spokepoint in spokepoints:
      i += 1
      spokex = spokepoint.geometry().boundingBox().center().x()
      spokey = spokepoint.geometry().boundingBox().center().y()
      spokeid = unicode(spokepoint.attributes()[spokeindex])
      progress.setPercentage(float(i) / len(spokepoints) * 100)
      # Scan hub points to find first matching hub
      hubpoints = QGisLayers.features(hublayer)
      for hubpoint in hubpoints:
        hubid = unicode(hubpoint.attributes()[hubindex])
        if hubid == spokeid:
          hubx = hubpoint.geometry().boundingBox().center().x()
          huby = hubpoint.geometry().boundingBox().center().y()

          # Write line to the output file
          outfeature = QgsFeature()
          outfeature.setAttributes(spokepoint.attributes())

          polyline = []
          polyline.append(QgsPoint(spokex, spokey))
          polyline.append(QgsPoint(hubx, huby))
          geometry = QgsGeometry()
          outfeature.setGeometry(geometry.fromPolyline(polyline))
          out.addFeature(outfeature)
          linecount = linecount + 1
          break

    del out

    if linecount <= 0:
      raise GeoAlgorithmExecutionException("No spoke/hub matches found to create lines")
Exemplo n.º 13
0
    def processAlgorithm(self, progress):
        input = self.getParameterValue(self.INPUT_LAYER)
        input2 = self.getParameterValue(self.INPUT_LAYER_2)
        output = self.getOutputFromName(self.OUTPUT_LAYER)
        field = self.getParameterValue(self.TABLE_FIELD)
        field2 = self.getParameterValue(self.TABLE_FIELD_2)

        # Layer 1
        layer = QGisLayers.getObjectFromUri(input)
        provider = layer.dataProvider()
        joinField1Index = layer.fieldNameIndex(field)
        # Layer 2
        layer2 = QGisLayers.getObjectFromUri(input2)
        provider2 = layer2.dataProvider()

        joinField2Index = layer2.fieldNameIndex(field2)

        # Output
        outFields = []
        outFields.extend(provider.fields())
        outFields.extend(provider2.fields())

        writer = output.getVectorWriter(outFields, provider.geometryType(), layer.crs())

        inFeat = QgsFeature()
        inFeat2 = QgsFeature()
        outFeat = QgsFeature()

        # Create output vector layer with additional attribute
        features = QGisLayers.features(layer);
        for inFeat in features:
            inGeom = inFeat.geometry()
            attrs = inFeat.attributes()
            joinValue1 = attrs[joinField1Index]
            features2 = QGisLayers.features(layer2);
            for inFeat2 in features2:
                ## Maybe it should cache this entries...
                attrs2 = inFeat2.attributes()
                joinValue2 = attrs2[joinField2Index]
                if joinValue1 == joinValue2:
                    # create the new feature
                    outFeat.setGeometry(inGeom)
                    attrs.extend(attrs2)
                    break;
            outFeat.setAttributes(attrs)
            writer.addFeature(outFeat)

        del writer
Exemplo n.º 14
0
    def processAlgorithm(self, progress):
        layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT_LAYER))

        writer = self.getOutputFromName(self.OUTPUT_LAYER).getVectorWriter(
            layer.pendingFields().toList(), QGis.WKBPoint, layer.crs()
        )

        outFeat = QgsFeature()

        features = QGisLayers.features(layer)
        total = 100.0 / float(len(features))
        current = 0

        for inFeat in features:
            inGeom = inFeat.geometry()
            attrs = inFeat.attributes()

            outGeom = QgsGeometry(inGeom.centroid())
            if outGeom is None:
                raise GeoAlgorithmExecutionException("Error calculating centroid")

            outFeat.setGeometry(outGeom)
            outFeat.setAttributes(attrs)
            writer.addFeature(outFeat)
            current += 1
            progress.setPercentage(int(current * total))

        del writer
Exemplo n.º 15
0
    def processAlgorithm(self, progress):
        layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT))
        tolerance =self.getParameterValue(self.TOLERANCE)

        pointsBefore = 0
        pointsAfter = 0

        writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(layer.pendingFields().toList(),
                     layer.wkbType(), layer.crs())

        current = 0
        selection = QGisLayers.features(layer)
        total =  100.0 / float(len(selection))
        for f in selection:
            featGeometry = QgsGeometry(f.geometry())
            attrs = f.attributes()
            pointsBefore += self.geomVertexCount(featGeometry)
            newGeometry = featGeometry.simplify(tolerance)
            pointsAfter += self.geomVertexCount(newGeometry)
            feature = QgsFeature()
            feature.setGeometry(newGeometry)
            feature.setAttributes(attrs)
            writer.addFeature(feature)
            current += 1
            progress.setPercentage(int(current * total))

        del writer

        ProcessingLog.addToLog(ProcessingLog.LOG_INFO, "Simplify: Input geometries have been simplified from"
                             + str(pointsBefore) + " to "  + str(pointsAfter) + " points.")
    def processAlgorithm(self, progress):
        layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT))
        interval = self.getParameterValue(self.INTERVAL)

        isPolygon = layer.geometryType() == QGis.Polygon

        writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(layer.pendingFields().toList(),
                     layer.wkbType(), layer.crs())

        features = QGisLayers.features(layer)
        total = 100.0 / float(len(features))
        current = 0
        for f in features:
            featGeometry = QgsGeometry(f.geometry())
            attrs = f.attributes()
            newGeometry = self.densifyGeometry(featGeometry, interval, isPolygon)
            feature = QgsFeature()
            feature.setGeometry(newGeometry)
            feature.setAttributes(attrs)
            writer.addFeature(feature)

            current += 1
            progress.setPercentage(int(current * total))

        del writer
Exemplo n.º 17
0
    def processAlgorithm(self, progress):
        fieldType = self.getParameterValue(self.FIELD_TYPE)
        fieldName = self.getParameterValue(self.FIELD_NAME)
        fieldLength = self.getParameterValue(self.FIELD_LENGTH)
        fieldPrecision = self.getParameterValue(self.FIELD_PRECISION)
        output = self.getOutputFromName(self.OUTPUT_LAYER)

        layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT_LAYER))

        provider = layer.dataProvider()
        fields = provider.fields()
        fields.append(QgsField(fieldName, self.TYPES[fieldType], "", fieldLength, fieldPrecision))
        writer = output.getVectorWriter(fields, provider.geometryType(), layer.crs())
        outFeat = QgsFeature()
        inGeom = QgsGeometry()
        nElement = 0
        features = QGisLayers.features(layer)
        nFeat = len(features)
        for inFeat in features:
            progress.setPercentage(int((100 * nElement)/nFeat))
            nElement += 1
            inGeom = inFeat.geometry()
            outFeat.setGeometry( inGeom )
            atMap = inFeat.attributes()
            atMap.append(None)
            outFeat.setAttributes(atMap)
            writer.addFeature( outFeat )
        del writer
Exemplo n.º 18
0
    def processAlgorithm(self, progress):
        layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT))
        crsId = self.getParameterValue(self.TARGET_CRS)
        targetCrs = QgsCoordinateReferenceSystem(crsId)

        writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(layer.pendingFields().toList(),
                     layer.wkbType(), targetCrs)

        layerCrs = layer.crs()
        crsTransform = QgsCoordinateTransform(layerCrs, targetCrs)

        outFeat = QgsFeature()
        current = 0
        features = QGisLayers.features(layer)
        total = 100.0 / float(len(features))
        for f in features:
            geom = f.geometry()
            geom.transform(crsTransform)
            outFeat.setGeometry(geom)
            outFeat.setAttributes(f.attributes())
            writer.addFeature(outFeat)

            current += 1
            progress.setPercentage(int(current * total))

        del writer

        self.crs = targetCrs
Exemplo n.º 19
0
  def processAlgorithm(self, progress):
    layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.LAYERNAME))
    attribute = self.getParameterValue(self.ATTRIBUTE)
    idx = layer.fieldNameIndex(attribute)
    fields = layer.pendingFields()
    fields[idx] = QgsField(fields[idx].name(), QVariant.Double)
    output = self.getOutputFromName(self.SAVENAME)
    out = output.getVectorWriter(fields, layer.wkbType(), layer.crs())

    i = 0
    features = QGisLayers.features(layer)
    featurecount = len(features)
    for feature in features:
      i+=1
      progress.setPercentage(float(i) / featurecount * 100)
      attributes = feature.attributes()
      try:
        v = unicode(attributes[idx])
        if '%' in v:
          v = v.replace('%', "")
          attributes[idx] = float(attributes[idx]) / float(100)
        else:
          attributes[idx] = float(attributes[idx])
      except:
        attributes[idx] = None

      feature.setAttributes(attributes)
      out.addFeature(feature)

    del out
Exemplo n.º 20
0
    def processAlgorithm(self, progress):
        layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT_LAYER))
        valuesFieldName = self.getParameterValue(self.VALUES_FIELD_NAME)
        categoriesFieldName = self.getParameterValue(self.CATEGORIES_FIELD_NAME)

        output = self.getOutputFromName(self.OUTPUT)
        valuesField = layer.fieldNameIndex(valuesFieldName)
        categoriesField = layer.fieldNameIndex(categoriesFieldName)

        features = QGisLayers.features(layer)
        nFeats = len(features)
        values = {}
        nFeat = 0
        for feat in features:
            nFeat += 1
            progress.setPercentage(int((100 * nFeats) / nFeat))
            attrs = feat.attributes()
            try:
                value = float(attrs[valuesField])
                cat = unicode(attrs[categoriesField])
                if cat not in values:
                    values[cat] = []
                values[cat].append(value)
            except:
                pass

        fields = [QgsField("category", QVariant.String), QgsField("min", QVariant.Double),
                  QgsField("max", QVariant.Double), QgsField("mean", QVariant.Double),
                  QgsField("stddev", QVariant.Double)]
        writer = output.getTableWriter(fields)
        for cat, v in values.items():
            min, max, mean, stddev = calculateStats(v)
            record = [cat, min, max, mean, stddev]
            writer.addRecord(record)
Exemplo n.º 21
0
 def test_SagaVectorAlgorithWithUnsupportedInputAndOutputFormat(self):
     '''this tests both the exporting to shp and then the format change in the output layer'''
     layer = processing.getobject(polygonsGeoJson());
     feature = layer.getFeatures().next()
     selected = [feature.id()]
     layer.setSelectedFeatures(selected)
     outputs=processing.runalg("saga:polygoncentroids",polygonsGeoJson(),True, ProcessingUtils.getTempFilename("geojson"))
     layer.setSelectedFeatures([])
     output=outputs['CENTROIDS']
     layer=QGisLayers.getObjectFromUri(output, True)
     fields=layer.pendingFields()
     expectednames=['ID','POLY_NUM_A','POLY_ST_A']
     expectedtypes=['Real','Real','String']
     names=[str(f.name()) for f in fields]
     types=[str(f.typeName()) for f in fields]
     self.assertEqual(expectednames, names)
     self.assertEqual(expectedtypes, types)
     features=processing.getfeatures(layer)
     self.assertEqual(1, len(features))
     feature=features.next()
     attrs=feature.attributes()
     expectedvalues=["0","1.1","string a"]
     values=[str(attr) for attr in attrs]
     self.assertEqual(expectedvalues, values)
     wkt='POINT(270787.49991451 4458955.46775295)'
     self.assertEqual(wkt, str(feature.geometry().exportToWkt()))
Exemplo n.º 22
0
 def test_SagaVectorAlgorithmWithSelection(self):
     layer = processing.getobject(polygons2());
     feature = layer.getFeatures().next()
     selected = [feature.id()]
     layer.setSelectedFeatures(selected)
     outputs=processing.runalg("saga:polygoncentroids",polygons2(),True,None)
     layer.setSelectedFeatures([])
     output=outputs['CENTROIDS']
     layer=QGisLayers.getObjectFromUri(output, True)
     fields=layer.pendingFields()
     expectednames=['ID','POLY_NUM_B','POLY_ST_B']
     expectedtypes=['Real','Real','String']
     names=[str(f.name()) for f in fields]
     types=[str(f.typeName()) for f in fields]
     self.assertEqual(expectednames, names)
     self.assertEqual(expectedtypes, types)
     features=processing.getfeatures(layer)
     self.assertEqual(1, len(features))
     feature=features.next()
     attrs=feature.attributes()
     expectedvalues=["2","1","string a"]
     values=[str(attr) for attr in attrs]
     self.assertEqual(expectedvalues, values)
     wkt='POINT(270806.69221918 4458924.97720492)'
     self.assertEqual(wkt, str(feature.geometry().exportToWkt()))
Exemplo n.º 23
0
    def processAlgorithm(self, progress):
        layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT))

        geomType = self.multiToSingleGeom(layer.dataProvider().geometryType())

        writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(layer.pendingFields().toList(),
                     geomType, layer.crs())

        outFeat = QgsFeature()
        inGeom = QgsGeometry()

        current = 0
        features = QGisLayers.features(layer)
        total = 100.0 / float(len(features))
        for f in features:
            inGeom = f.geometry()
            attrs = f.attributes()

            geometries = self.extractAsSingle(inGeom)
            outFeat.setAttributes(attrs)

            for g in geometries:
                outFeat.setGeometry(g)
                writer.addFeature(outFeat)

            current += 1
            progress.setPercentage(int(current * total))

        del writer
Exemplo n.º 24
0
    def processAlgorithm(self, progress):
        '''Here is where the processing itself takes place'''

        # the first thing to do is retrieve the values of the parameters
        # entered by the user
        inputFilename = self.getParameterValue(self.INPUT_LAYER)
        output = self.getOutputValue(self.OUTPUT_LAYER)

        # input layers vales are always a string with its location.
        # That string can be converted into a QGIS object (a QgsVectorLayer in
        # this case) using the Processing.getObjectFromUri() method.
        vectorLayer = QGisLayers.getObjectFromUri(inputFilename)

        # And now we can process

        # First we create the output layer. The output value entered by the user
        # is a string containing a filename, so we can use it directly
        settings = QSettings()
        systemEncoding = settings.value( "/UI/encoding", "System" )
        provider = vectorLayer.dataProvider()
        writer = QgsVectorFileWriter(output,
                                     systemEncoding,
                                     provider.fields(),
                                     provider.geometryType(),
                                     provider.crs()
                                    )

        # Now we take the features from input layer and add them to the output.
        # Method features() returns an iterator, considering the selection that
        # might exist in layer and the configuration that indicates
        # should algorithm use only selected features or all of them
        features = QGisLayers.features(vectorLayer)
        for f in features:
            writer.addFeature(f)
Exemplo n.º 25
0
    def processAlgorithm(self, progress):
        layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT_LAYER))
        byFeature = self.getParameterValue(self.BY_FEATURE)

        fields = [
            QgsField("MINX", QVariant.Double),
            QgsField("MINY", QVariant.Double),
            QgsField("MAXX", QVariant.Double),
            QgsField("MAXY", QVariant.Double),
            QgsField("CNTX", QVariant.Double),
            QgsField("CNTY", QVariant.Double),
            QgsField("AREA", QVariant.Double),
            QgsField("PERIM", QVariant.Double),
            QgsField("HEIGHT", QVariant.Double),
            QgsField("WIDTH", QVariant.Double),
        ]

        writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fields, QGis.WKBPolygon, layer.crs())

        if byFeature:
            self.featureExtent(layer, writer, progress)
        else:
            self.layerExtent(layer, writer, progress)

        del writer
 def processAlgorithm(self, progress):
     uri = self.getParameterValue(self.LAYER)
     layer = QGisLayers.getObjectFromUri(uri);
     self.setOutputValue(self.XMIN, layer.extent().xMinimum())
     self.setOutputValue(self.XMAX, layer.extent().xMaximum())
     self.setOutputValue(self.YMIN, layer.extent().yMinimum())
     self.setOutputValue(self.YMAX, layer.extent().yMaximum())
Exemplo n.º 27
0
    def processAlgorithm(self, progress):
        source = self.getParameterValue(self.INPUT)
        vlayer = QGisLayers.getObjectFromUri(source)
        output = self.getOutputFromName(self.OUTPUT)
        vprovider = vlayer.dataProvider()
        fields = vprovider.fields()
        writer = output.getVectorWriter(fields, QGis.WKBPoint, self.crs)
        xfieldindex = vlayer.fieldNameIndex(self.getParameterValue(self.XFIELD))
        yfieldindex = vlayer.fieldNameIndex(self.getParameterValue(self.YFIELD))

        crsId = self.getParameterValue(self.TARGET_CRS)
        targetCrs = QgsCoordinateReferenceSystem(crsId)
        self.crs = targetCrs

        outFeat = QgsFeature()
        nElement = 0
        features = QGisLayers.features(vlayer)
        nFeat = len(features)
        for feature in features:
            nElement += 1
            progress.setPercentage((nElement*100)/nFeat)
            attrs = feature.attributes()
            try:
                x =  float(attrs[xfieldindex])
                y =  float(attrs[yfieldindex])
            except:
                continue
            pt = QgsPoint(x, y)
            outFeat.setGeometry(QgsGeometry.fromPoint(pt))
            outFeat.setAttributes(attrs)
            writer.addFeature(outFeat)

        del writer
Exemplo n.º 28
0
    def processAlgorithm(self, progress):
        layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT))

        writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(layer.pendingFields().toList(),
                     QGis.WKBPolygon, layer.crs())

        outFeat = QgsFeature()

        current = 0
        features = QGisLayers.features(layer)
        total = 100.0 / float(len(features))
        for f in features:
            outGeomList = []
            if f.geometry().isMultipart():
                outGeomList = f.geometry().asMultiPolyline()
            else:
                outGeomList.append(f.geometry().asPolyline())

            polyGeom = self.removeBadLines(outGeomList)
            if len(polyGeom) <> 0:
                outFeat.setGeometry(QgsGeometry.fromPolygon(polyGeom))
                attrs = f.attributes()
                outFeat.setAttributes(attrs)
                writer.addFeature(outFeat)

            current += 1
            progress.setPercentage(int(current * total))

        del writer
Exemplo n.º 29
0
    def processAlgorithm(self, progress):
        layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT))

        writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(layer.pendingFields().toList(),
                     QGis.WKBLineString, layer.crs())

        outFeat = QgsFeature()
        inGeom = QgsGeometry()
        outGeom = QgsGeometry()

        current = 0
        features = QGisLayers.features(layer)
        total = 100.0 / float(len(features))
        for f in features:
            inGeom = f.geometry()
            attrs = f.attributes()
            lineList = self.extractAsLine(inGeom)
            outFeat.setAttributes(attrs)
            for h in lineList:
                outFeat.setGeometry(outGeom.fromPolyline(h))
                writer.addFeature(outFeat)

            current += 1
            progress.setPercentage(int(current * total))

        del writer
Exemplo n.º 30
0
  def processAlgorithm(self, progress):

    layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.LAYERNAME))
    idx = layer.fieldNameIndex(self.getParameterValue(self.COLUMN))
    output = self.getOutputFromName(self.SAVENAME)
    fields = layer.pendingFields()
    newFields = []
    i = 0
    for field in fields:
      if i != idx:
        newFields.append(field)
      i += 1
    outfile = output.getVectorWriter(newFields, layer.wkbType(), layer.crs() )
    features = QGisLayers.features(layer)
    featurecount = len(features)
    i = 0
    outFeat = QgsFeature()
    for feature in features:
      progress.setPercentage(float(i) /featurecount * 100)
      i += 1
      outFeat.setGeometry(feature.geometry())
      attributes = feature.attributes()
      newAttributes = []
      i = 0
      for attr in attributes:
        if i != idx:
          newAttributes.append(attr)
        i += 1
      feature.setAttributes(newAttributes)
      outfile.addFeature(feature)
Exemplo n.º 31
0
    def processAlgorithm(self, progress):
        outputFile = self.getOutputValue(self.OUTPUT_HTML_FILE)
        uri = self.getParameterValue(self.INPUT)
        layer = QGisLayers.getObjectFromUri(uri)
        values = raster.scanraster(layer, progress)

        n = 0
        nodata = 0
        mean = 0
        M2 = 0
        sum = 0
        minvalue = None
        maxvalue = None

        for v in values:
            if v is not None:
                sum += v
                n = n + 1
                delta = v - mean
                mean = mean + delta / n
                M2 = M2 + delta * (v - mean)
                if minvalue is None:
                    minvalue = v
                    maxvalue = v
                else:
                    minvalue = min(v, minvalue)
                    maxvalue = max(v, maxvalue)
            else:
                nodata += 1

        variance = M2 / (n - 1)
        stddev = math.sqrt(variance)

        data = []
        data.append("Valid cells: " + unicode(n))
        data.append("No-data cells: " + unicode(nodata))
        data.append("Minimum value: " + unicode(minvalue))
        data.append("Maximum value: " + unicode(maxvalue))
        data.append("Sum: " + unicode(sum))
        data.append("Mean value: " + unicode(mean))
        data.append("Standard deviation: " + unicode(stddev))

        self.createHTML(outputFile, data)

        self.setOutputValue(self.COUNT, n)
        self.setOutputValue(self.NO_DATA_COUNT, nodata)
        self.setOutputValue(self.MIN, minvalue)
        self.setOutputValue(self.MAX, maxvalue)
        self.setOutputValue(self.SUM, sum)
        self.setOutputValue(self.MEAN, mean)
        self.setOutputValue(self.STD_DEV, stddev)
Exemplo n.º 32
0
    def __init__(self, alg, iterParam=None, parent=None):
        QThread.__init__(self, parent)
        self.algorithm = alg
        self.parameterToIterate = iterParam

        class Progress:
            def __init__(self, algex):
                self.algorithmExecutor = algex

            def setText(self, text):
                self.algorithmExecutor.textChanged.emit(text)

            def setPercentage(self, p):
                self.algorithmExecutor.percentageChanged.emit(p)

            def setInfo(self, info):
                self.algorithmExecutor.infoSet.emit(info)

            def setCommand(self, cmd):
                self.algorithmExecutor.commandSet.emit(cmd)

            def setDebugInfo(self, info):
                self.algorithmExecutor.debugInfoSet.emit(info)

            def setConsoleInfo(self, info):
                self.algorithmExecutor.consoleInfoSet.emit(info)

        self.progress = Progress(self)
        if self.parameterToIterate:
            self.run = self.runalgIterating

            #generate all single-feature layers
            settings = QSettings()
            systemEncoding = settings.value("/UI/encoding", "System")
            layerfile = alg.getParameterValue(self.parameterToIterate)
            layer = QGisLayers.getObjectFromUri(layerfile, False)
            provider = layer.dataProvider()
            features = getfeatures(layer)
            self.filelist = []
            for feat in features:
                output = ProcessingUtils.getTempFilename("shp")
                self.filelist.append(output)
                writer = QgsVectorFileWriter(output, systemEncoding,
                                             provider.fields(),
                                             provider.geometryType(),
                                             layer.crs())
                writer.addFeature(feat)
                del writer
        else:
            self.run = self.runalg
        self.internalError.connect(self.raiseInternalError)
Exemplo n.º 33
0
 def processAlgorithm(self, progress):
     uri = self.getParameterValue(self.INPUT)
     layer = QGisLayers.getObjectFromUri(uri)
     fieldname = self.getParameterValue(self.FIELD)
     output = self.getOutputValue(self.OUTPUT)
     values = vector.getAttributeValues(layer, fieldname)
     plt.close()
     bins = self.getParameterValue(self.BINS)
     plt.hist(values[fieldname], bins)
     plotFilename = output + ".png"
     lab.savefig(plotFilename)
     f = open(output, "w")
     f.write("<img src=\"" + plotFilename + "\"/>")
     f.close()
Exemplo n.º 34
0
    def processAlgorithm(self, progress):
        fieldName = self.getParameterValue(self.FIELD_NAME)
        fieldType = self.getParameterValue(self.FIELD_TYPE)
        fieldLength = self.getParameterValue(self.FIELD_LENGTH)
        fieldPrecision = self.getParameterValue(self.FIELD_PRECISION)
        formula = self.getParameterValue(self.FORMULA)
        output = self.getOutputFromName(self.OUTPUT_LAYER)

        layer = QGisLayers.getObjectFromUri(
            self.getParameterValue(self.INPUT_LAYER))
        provider = layer.dataProvider()
        fields = provider.fields()
        fields.append(
            QgsField(fieldName, self.TYPES[fieldType], "", fieldLength,
                     fieldPrecision))
        writer = output.getVectorWriter(fields, provider.geometryType(),
                                        layer.crs())

        outFeat = QgsFeature()
        inGeom = QgsGeometry()
        nFeat = provider.featureCount()
        nElement = 0
        features = QGisLayers.features(layer)

        fieldnames = [field.name() for field in provider.fields()]
        fieldnames.sort(key=len, reverse=False)
        fieldidx = [
            fieldnames.index(field.name()) for field in provider.fields()
        ]
        print fieldidx
        for inFeat in features:
            progress.setPercentage(int((100 * nElement) / nFeat))
            attrs = inFeat.attributes()
            expression = formula
            for idx in fieldidx:
                expression = expression.replace(unicode(fields[idx].name()),
                                                unicode(attrs[idx]))
            try:
                result = eval(expression)
            except Exception:
                result = None
            nElement += 1
            inGeom = inFeat.geometry()
            outFeat.setGeometry(inGeom)
            attrs = inFeat.attributes()
            attrs.append(result)
            outFeat.setAttributes(attrs)
            writer.addFeature(outFeat)
        del writer
Exemplo n.º 35
0
 def calculateResamplingExtent(self):
     '''this method calculates the resampling extent, but it might set self.resample
     to false if, with the current layers, there is no need to resample'''
     auto = ProcessingConfig.getSetting(SagaUtils.SAGA_AUTO_RESAMPLING)
     if auto:
         first = True
         self.inputExtentsCount = 0
         for param in self.parameters:
             if param.value:
                 if isinstance(param, ParameterRaster):
                     if isinstance(param.value, QgsRasterLayer):
                         layer = param.value
                     else:
                         layer = QGisLayers.getObjectFromUri(param.value)
                     self.addToResamplingExtent(layer, first)
                     first = False
                 if isinstance(param, ParameterMultipleInput):
                     if param.datatype == ParameterMultipleInput.TYPE_RASTER:
                         layers = param.value.split(";")
                         for layername in layers:
                             layer = QGisLayers.getObjectFromUri(layername)
                             self.addToResamplingExtent(layer, first)
                             first = False
         if self.inputExtentsCount < 2:
             self.resample = False
     else:
         self.xmin = ProcessingConfig.getSetting(
             SagaUtils.SAGA_RESAMPLING_REGION_XMIN)
         self.xmax = ProcessingConfig.getSetting(
             SagaUtils.SAGA_RESAMPLING_REGION_XMAX)
         self.ymin = ProcessingConfig.getSetting(
             SagaUtils.SAGA_RESAMPLING_REGION_YMIN)
         self.ymax = ProcessingConfig.getSetting(
             SagaUtils.SAGA_RESAMPLING_REGION_YMAX)
         self.cellsize = ProcessingConfig.getSetting(
             SagaUtils.SAGA_RESAMPLING_REGION_CELLSIZE)
Exemplo n.º 36
0
    def processAlgorithm(self, progress):
        uri = self.getParameterValue(self.INPUT)
        layer = QGisLayers.getObjectFromUri(uri)
        xfieldname = self.getParameterValue(self.YFIELD)
        yfieldname = self.getParameterValue(self.XFIELD)
        output = self.getOutputValue(self.OUTPUT)
        values = vector.getAttributeValues(layer, xfieldname, yfieldname)
        plt.close()

        plt.scatter(values[xfieldname], values[yfieldname])
        plotFilename = output + ".png"
        lab.savefig(plotFilename)
        f = open(output, "w")
        f.write("<img src=\"" + plotFilename + "\"/>")
        f.close()
    def processAlgorithm(self, progress):
        layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.POINTS))
        output = self.getOutputValue(self.OUTPUT)

        spatialIndex = utils.createSpatialIndex(layer)

        neighbour = QgsFeature()
        distance = QgsDistanceArea()

        sumDist = 0.00
        A = layer.extent()
        A = float(A.width() * A.height())

        current = 0
        features = QGisLayers.features(layer)
        count = len(features)
        total = 100.0 / float(len(features))
        for feat in features:
            neighbourID = spatialIndex.nearestNeighbor(feat.geometry().asPoint(), 2)[1]
            request = QgsFeatureRequest().setFilterFid(neighbourID)
            neighbour = layer.getFeatures(request).next()
            sumDist += distance.measureLine(neighbour.geometry().asPoint(), feat.geometry().asPoint())

            current += 1
            progress.setPercentage(int(current * total))

        do = float(sumDist) / count
        de = float(0.5 / math.sqrt(count / A))
        d = float(do / de)
        SE = float(0.26136 / math.sqrt(( count ** 2) / A))
        zscore = float((do - de) / SE)

        data = []
        data.append("Observed mean distance: " + unicode(do))
        data.append("Expected mean distance: " + unicode(de))
        data.append("Nearest neighbour index: " + unicode(d))
        data.append("Number of points: " + unicode(count))
        data.append("Z-Score: " + unicode(zscore))

        self.createHTML(output, data)

        self.setOutputValue(self.OBSERVED_MD, float( data[ 0 ].split( ": " )[ 1 ] ) )
        self.setOutputValue(self.EXPECTED_MD, float( data[ 1 ].split( ": " )[ 1 ] ) )
        self.setOutputValue(self.NN_INDEX, float( data[ 2 ].split( ": " )[ 1 ] ) )
        self.setOutputValue(self.POINT_COUNT, float( data[ 3 ].split( ": " )[ 1 ] ) )
        self.setOutputValue(self.Z_SCORE, float( data[ 4 ].split( ": " )[ 1 ] ) )
Exemplo n.º 38
0
    def processAlgorithm(self, progress):
        self.createCatalog()
        inputFilename = self.getParameterValue(self.INPUT)
        layer = QGisLayers.getObjectFromUri(inputFilename)
        workspaceName = self.getParameterValue(self.WORKSPACE)
        filename = LayerExporter.exportVectorLayer(layer)
        basefilename = os.path.basename(filename)
        basepathname = os.path.dirname(
            filename) + os.sep + basefilename[:basefilename.find('.')]
        connection = {
            'shp': basepathname + '.shp',
            'shx': basepathname + '.shx',
            'dbf': basepathname + '.dbf',
            'prj': basepathname + '.prj'
        }

        workspace = self.catalog.get_workspace(workspaceName)
        self.catalog.create_featurestore(basefilename, connection, workspace)
Exemplo n.º 39
0
 def getSafeExportedLayer(self):
     '''Returns not the value entered by the user, but a string with a filename which
     contains the data of this layer, but saved in a standard format (currently always
     a geotiff file) so that it can be opened by most external applications.
     Works only if the layer represented by the parameter value is currently loaded in QGIS.
     Otherwise, it will not perform any export and return the current value string.
     If the current value represents a layer in a suitable format, it does not export at all
     and returns that value.
     The layer is exported just the first time the method is called. The method can be called
     several times and it will always return the same file, performing the export only the first time.'''
     if self.exported:
         return self.exported
     layer = QGisLayers.getObjectFromUri(self.value, False)
     if layer:
         self.exported = LayerExporter.exportRasterLayer(layer)
     else:
         self.exported = self.value
     return self.exported
    def runalgIterating(alg, paramToIter, progress):
        #generate all single-feature layers
        settings = QSettings()
        systemEncoding = settings.value("/UI/encoding", "System")
        layerfile = alg.getParameterValue(paramToIter)
        layer = QGisLayers.getObjectFromUri(layerfile, False)
        feat = QgsFeature()
        filelist = []
        outputs = {}
        provider = layer.dataProvider()
        features = getfeatures(layer)
        for feat in features:
            output = ProcessingUtils.getTempFilename("shp")
            filelist.append(output)
            writer = QgsVectorFileWriter(output, systemEncoding,
                                         provider.fields(),
                                         provider.geometryType(), layer.crs())
            writer.addFeature(feat)
            del writer

        #store output values to use them later as basenames for all outputs
        for out in alg.outputs:
            outputs[out.name] = out.value

        #now run all the algorithms
        i = 1
        for f in filelist:
            alg.setParameterValue(paramToIter, f)
            for out in alg.outputs:
                filename = outputs[out.name]
                if filename:
                    filename = filename[:filename.rfind(".")] + "_" + str(
                        i) + filename[filename.rfind("."):]
                out.value = filename
            progress.setText("Executing iteration " + str(i) + "/" +
                             str(len(filelist)) + "...")
            progress.setPercentage((i * 100) / len(filelist))
            if UnthreadedAlgorithmExecutor.runalg(alg, SilentProgress()):
                Postprocessing.handleAlgorithmResults(alg, progress, False)
                i += 1
            else:
                return False

        return True
Exemplo n.º 41
0
 def testWrongformat(self):
     outputs=processing.runalg("qgis:countpointsinpolygon",polygons(),points(),"NUMPOINTS",ProcessingUtils.getTempFilename("wrongext"))
     output=outputs['OUTPUT']
     self.assertTrue(output.endswith('shp'))
     layer=QGisLayers.getObjectFromUri(output, True)
     fields=layer.pendingFields()
     expectednames=['ID','POLY_NUM_A','POLY_ST_A','NUMPOINTS']
     expectedtypes=['Integer','Real','String','Real']
     names=[str(f.name()) for f in fields]
     types=[str(f.typeName()) for f in fields]
     self.assertEqual(expectednames, names)
     self.assertEqual(expectedtypes, types)
     features=processing.getfeatures(layer)
     self.assertEqual(2, len(features))
     feature=features.next()
     attrs=feature.attributes()
     expectedvalues=["1","1.1","string a","6.0"]
     values=[str(attr) for attr in attrs]
     self.assertEqual(expectedvalues, values)
Exemplo n.º 42
0
 def exportRasterLayer(self, source):
     layer = QGisLayers.getObjectFromUri(source, False)
     if layer:
         filename = str(layer.name())
     else:
         filename = source.rstrip(".sgrd")
     validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:"
     filename = ''.join(c for c in filename if c in validChars)
     if len(filename) == 0:
         filename = "layer"
     destFilename = ProcessingUtils.getTempFilenameInTempFolder(filename +
                                                                ".sgrd")
     self.exportedLayers[source] = destFilename
     saga208 = ProcessingConfig.getSetting(SagaUtils.SAGA_208)
     if ProcessingUtils.isWindows() or ProcessingUtils.isMac(
     ) or not saga208:
         return "io_gdal 0 -GRIDS \"" + destFilename + "\" -FILES \"" + source + "\""
     else:
         return "libio_gdal 0 -GRIDS \"" + destFilename + "\" -FILES \"" + source + "\""
Exemplo n.º 43
0
    def processAlgorithm(self, progress):
        uri = self.getParameterValue(self.INPUT)
        layer = QGisLayers.getObjectFromUri(uri)
        namefieldname = self.getParameterValue(self.NAME_FIELD)
        valuefieldname = self.getParameterValue(self.VALUE_FIELD)
        output = self.getOutputValue(self.OUTPUT)
        values = vector.getAttributeValues(layer, namefieldname, valuefieldname)
        plt.close()

        ind = np.arange(len(values[namefieldname]))
        width = 0.8
        plt.bar(ind, values[valuefieldname], width, color='r')

        plt.xticks(ind, values[namefieldname], rotation = 45)
        plotFilename = output +".png"
        lab.savefig(plotFilename)
        f = open(output, "w")
        f.write("<img src=\"" + plotFilename + "\"/>")
        f.close()
Exemplo n.º 44
0
    def ogrConnectionString(self, uri):
        ogrstr = None

        layer = QGisLayers.getObjectFromUri(uri, False)
        if layer == None:
            return uri
        provider = layer.dataProvider().name()
        if provider == 'spatialite':
            #dbname='/geodata/osm_ch.sqlite' table="places" (Geometry) sql=
            regex = re.compile("dbname='(.+)'")
            r = regex.search(str(layer.source()))
            ogrstr = r.groups()[0]
        elif provider == 'postgres':
            #dbname='ktryjh_iuuqef' host=spacialdb.com port=9999 user='******' password='******' sslmode=disable key='gid' estimatedmetadata=true srid=4326 type=MULTIPOLYGON table="t4" (geom) sql=
            s = re.sub(''' sslmode=.+''', '', str(layer.source()))
            ogrstr = 'PG:%s' % s
        else:
            ogrstr = str(layer.source())
        return ogrstr
Exemplo n.º 45
0
 def test_gdalogrogr2ogrWrongExtension(self):
         outputs=processing.runalg("gdalogr:ogr2ogr",union(),3,"",ProcessingUtils.getTempFilename("wrongext"))
         output=outputs['OUTPUT_LAYER']
         layer=QGisLayers.getObjectFromUri(output, True)
         fields=layer.pendingFields()
         expectednames=['id','poly_num_a','poly_st_a','id_2','poly_num_b','poly_st_b']
         expectedtypes=['Integer','Real','String','Integer','Real','String']
         names=[str(f.name()) for f in fields]
         types=[str(f.typeName()) for f in fields]
         self.assertEqual(expectednames, names)
         self.assertEqual(expectedtypes, types)
         features=processing.getfeatures(layer)
         self.assertEqual(8, len(features))
         feature=features.next()
         attrs=feature.attributes()
         expectedvalues=["1","1.1","string a","2","1","string a"]
         values=[str(attr) for attr in attrs]
         self.assertEqual(expectedvalues, values)
         wkt='POLYGON((270807.08580285 4458940.1594565,270798.42294527 4458914.62661676,270780.81854858 4458914.21983449,270763.52289518 4458920.715993,270760.3449542 4458926.6570575,270763.78234766 4458958.22561242,270794.30290024 4458942.16424502,270807.08580285 4458940.1594565))'
         self.assertEqual(wkt, str(feature.geometry().exportToWkt()))
Exemplo n.º 46
0
 def test_modeleroptionalfield(self):
     outputs = processing.runalg("modeler:optionalfield", points(), None)
     output = outputs['OUTPUT_ALG0']
     layer = QGisLayers.getObjectFromUri(output, True)
     fields = layer.pendingFields()
     expectednames = ['id', 'value', 'area', 'perim']
     expectedtypes = ['Integer', 'String', 'Real', 'Real']
     names = [str(f.name()) for f in fields]
     types = [str(f.typeName()) for f in fields]
     self.assertEqual(expectednames, names)
     self.assertEqual(expectedtypes, types)
     features = processing.getfeatures(layer)
     self.assertEqual(1, len(features))
     feature = features.next()
     attrs = feature.attributes()
     expectedvalues = ["0", "all", "3592.818848", "230.989919"]
     values = [str(attr) for attr in attrs]
     self.assertEqual(expectedvalues, values)
     wkt = 'POLYGON((270839.46818665 4458921.97813894,270778.60197966 4458935.96883677,270786.54279065 4458980.04784113,270803.15756434 4458983.84880322,270839.65586926 4458983.16267036,270855.74530134 4458940.79948673,270839.46818665 4458921.97813894))'
     self.assertEqual(wkt, str(feature.geometry().exportToWkt()))
Exemplo n.º 47
0
 def test_modelersagagrass(self):
     outputs = processing.runalg("modeler:sagagrass", points(), None)
     output = outputs['CENTROIDS_ALG1']
     layer = QGisLayers.getObjectFromUri(output, True)
     fields = layer.pendingFields()
     expectednames = ['CAT']
     expectedtypes = ['Real']
     names = [str(f.name()) for f in fields]
     types = [str(f.typeName()) for f in fields]
     self.assertEqual(expectednames, names)
     self.assertEqual(expectedtypes, types)
     features = processing.getfeatures(layer)
     self.assertEqual(12, len(features))
     feature = features.next()
     attrs = feature.attributes()
     expectedvalues = ["1"]
     values = [str(attr) for attr in attrs]
     self.assertEqual(expectedvalues, values)
     wkt = 'POINT(270839.65586926 4458983.16267036)'
     self.assertEqual(wkt, str(feature.geometry().exportToWkt()))
Exemplo n.º 48
0
 def test_scripthexgridfromlayerbounds(self):
     outputs = processing.runalg("script:hexgridfromlayerbounds",
                                 polygons(), 10, None)
     output = outputs['grid']
     layer = QGisLayers.getObjectFromUri(output, True)
     fields = layer.pendingFields()
     expectednames = ['longitude', 'latitude']
     expectedtypes = ['Real', 'Real']
     names = [str(f.name()) for f in fields]
     types = [str(f.typeName()) for f in fields]
     self.assertEqual(expectednames, names)
     self.assertEqual(expectedtypes, types)
     features = processing.getfeatures(layer)
     self.assertEqual(117, len(features))
     feature = features.next()
     attrs = feature.attributes()
     expectedvalues = ["270765.621834001", "4458907.27146471"]
     values = [str(attr) for attr in attrs]
     self.assertEqual(expectedvalues, values)
     wkt = 'POLYGON((270771.39533669 4458907.27146471,270768.50858535 4458902.27146471,270762.73508265 4458902.27146471,270759.84833131 4458907.27146471,270762.73508265 4458912.27146471,270768.50858535 4458912.27146471,270771.39533669 4458907.27146471))'
     self.assertEqual(wkt, str(feature.geometry().exportToWkt()))
Exemplo n.º 49
0
 def test_scriptcreatetilingfromvectorlayer(self):
     outputs = processing.runalg("script:createtilingfromvectorlayer",
                                 union(), 10, None)
     output = outputs['polygons']
     layer = QGisLayers.getObjectFromUri(output, True)
     fields = layer.pendingFields()
     expectednames = ['longitude', 'latitude']
     expectedtypes = ['Real', 'Real']
     names = [str(f.name()) for f in fields]
     types = [str(f.typeName()) for f in fields]
     self.assertEqual(expectednames, names)
     self.assertEqual(expectedtypes, types)
     features = processing.getfeatures(layer)
     self.assertEqual(10, len(features))
     feature = features.next()
     attrs = feature.attributes()
     expectedvalues = ["270761.415396242", "4458948.29588823"]
     values = [str(attr) for attr in attrs]
     self.assertEqual(expectedvalues, values)
     wkt = 'POLYGON((270755.54427424 4458901.23378639,270755.54427424 4458995.35799007,270767.28651824 4458995.35799007,270767.28651824 4458901.23378639,270755.54427424 4458901.23378639))'
     self.assertEqual(wkt, str(feature.geometry().exportToWkt()))
Exemplo n.º 50
0
    def processAlgorithm(self, progress):
        layer = QGisLayers.getObjectFromUri(
            self.getParameterValue(self.INPUT_LAYER))
        valuesFieldName = self.getParameterValue(self.VALUES_FIELD_NAME)
        categoriesFieldName = self.getParameterValue(
            self.CATEGORIES_FIELD_NAME)

        output = self.getOutputFromName(self.OUTPUT)
        valuesField = layer.fieldNameIndex(valuesFieldName)
        categoriesField = layer.fieldNameIndex(categoriesFieldName)

        features = QGisLayers.features(layer)
        nFeats = len(features)
        values = {}
        nFeat = 0
        for feat in features:
            nFeat += 1
            progress.setPercentage(int((100 * nFeats) / nFeat))
            attrs = feat.attributes()
            try:
                value = float(attrs[valuesField])
                cat = unicode(attrs[categoriesField])
                if cat not in values:
                    values[cat] = []
                values[cat].append(value)
            except:
                pass

        fields = [
            QgsField("category", QVariant.String),
            QgsField("min", QVariant.Double),
            QgsField("max", QVariant.Double),
            QgsField("mean", QVariant.Double),
            QgsField("stddev", QVariant.Double)
        ]
        writer = output.getTableWriter(fields)
        for cat, v in values.items():
            min, max, mean, stddev = calculateStats(v)
            record = [cat, min, max, mean, stddev]
            writer.addRecord(record)
Exemplo n.º 51
0
    def processAlgorithm(self, progress):
        uri = self.getParameterValue(self.INPUT)
        layer = QGisLayers.getObjectFromUri(uri)
        namefieldname = self.getParameterValue(self.NAME_FIELD)
        valuefieldname = self.getParameterValue(self.VALUE_FIELD)
        output = self.getOutputValue(self.OUTPUT)
        values = vector.getAttributeValues(layer, namefieldname,
                                           valuefieldname)
        plt.close()

        fig = figure(figsize=(8, 8))
        ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)
        N = len(values[valuefieldname])
        theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N)
        radii = values[valuefieldname]
        width = 2 * np.pi / N
        ax.bar(theta, radii, width=width, bottom=0.0)
        plotFilename = output + ".png"
        lab.savefig(plotFilename)
        f = open(output, "w")
        f.write("<img src=\"" + plotFilename + "\"/>")
        f.close()
Exemplo n.º 52
0
def extent(layers):
    first = True
    for layer in layers:
        if not isinstance(layer, (QgsRasterLayer, QgsVectorLayer)):
            layer = QGisLayers.getObjectFromUri(layer)
            if layer is None:
                continue
        if first:
            xmin = layer.extent().xMinimum()
            xmax = layer.extent().xMaximum()
            ymin = layer.extent().yMinimum()
            ymax = layer.extent().yMaximum()
        else:
            xmin = min(xmin, layer.extent().xMinimum())
            xmax = max(xmax, layer.extent().xMaximum())
            ymin = min(ymin, layer.extent().yMinimum())
            ymax = max(ymax, layer.extent().yMaximum())
        first = False
    if first:
        return "0,0,0,0"
    else:
        return str(xmin) + "," + str(xmax) + "," + str(ymin) + "," + str(ymax)
Exemplo n.º 53
0
 def processAlgorithm(self, progress):
     uri = self.getParameterValue(self.INPUT)
     layer = QGisLayers.getObjectFromUri(uri)
     outputplot = self.getOutputValue(self.PLOT)
     outputtable = self.getOutputFromName(self.TABLE)
     values = raster.scanraster(layer, progress)
     nbins = self.getParameterValue(self.BINS)
     #ALERT:this is potentially blocking if the layer is too big
     plt.close()
     valueslist = []
     for v in values:
         if v is not None:
             valueslist.append(v)
     n, bins, values = plt.hist(valueslist, nbins)
     fields = [QgsField("CENTER_VALUE", QVariant.Double), QgsField("NUM_ELEM", QVariant.Double)]
     writer = outputtable.getTableWriter(fields)
     for i in xrange(len(values)):
         writer.addRecord([str(bins[i]) + "-" + str(bins[i+1]) , n[i]])
     plotFilename = outputplot +".png"
     lab.savefig(plotFilename)
     f = open(outputplot, "w")
     f.write("<img src=\"" + plotFilename + "\"/>")
     f.close()
Exemplo n.º 54
0
 def processAlgorithm(self, progress):
     vlayer = QGisLayers.getObjectFromUri(self.getParameterValue(
         self.INPUT))
     output = self.getOutputFromName(self.OUTPUT)
     vprovider = vlayer.dataProvider()
     fields = vprovider.fields()
     writer = output.getVectorWriter(fields, QGis.WKBLineString,
                                     vlayer.crs())
     outFeat = QgsFeature()
     inGeom = QgsGeometry()
     nElement = 0
     features = QGisLayers.features(vlayer)
     nFeat = len(features)
     for feature in features:
         nElement += 1
         progress.setPercentage((nElement * 100) / nFeat)
         inGeom = feature.geometry()
         atMap = feature.attributes()
         segments = self.extractAsSingleSegments(inGeom)
         outFeat.setAttributes(atMap)
         for segment in segments:
             outFeat.setGeometry(segment)
             writer.addFeature(outFeat)
     del writer
Exemplo n.º 55
0
        try:
            db = postgis_utils.GeoDB(host=host, port=port, dbname=database, user=username, passwd=password)
        except postgis_utils.DbError, e:
            raise GeoAlgorithmExecutionException("Couldn't connect to database:\n"+e.message)

        uri = QgsDataSourceURI()
        uri.setConnection(host, str(port), database, username, password)
        uri.setDataSource("public", table, "the_geom", "")

        options = {}
        if overwrite:
            options['overwrite'] = True

        layerUri = self.getParameterValue(self.INPUT);
        layer = QGisLayers.getObjectFromUri(layerUri)
        ret, errMsg = QgsVectorLayerImport.importLayer(layer, uri.uri(), providerName, self.crs, False, False, options)
        if ret != 0:
            raise GeoAlgorithmExecutionException(u"Error importing to PostGIS\n%s" %  errMsg)

        if createIndex:
            db.create_spatial_index(table, "public", "the_geom")

        db.vacuum_analyze(table, "public")

    def defineCharacteristics(self):
        self.name = "Import into PostGIS"
        self.group = "PostGIS management tools"
        self.addParameter(ParameterVector(self.INPUT, "Layer to import"))
        self.addParameter(ParameterString(self.DATABASE, "Database (connection name)"))
        self.addParameter(ParameterString(self.TABLENAME, "Table to import to"))
Exemplo n.º 56
0
    def processAlgorithm(self, progress):
        layerA = QGisLayers.getObjectFromUri(
            self.getParameterValue(Difference.INPUT))
        layerB = QGisLayers.getObjectFromUri(
            self.getParameterValue(Difference.OVERLAY))

        GEOS_EXCEPT = True

        FEATURE_EXCEPT = True

        writer = self.getOutputFromName(Difference.OUTPUT).getVectorWriter(
            layerA.pendingFields(),
            layerA.dataProvider().geometryType(),
            layerA.dataProvider().crs())

        inFeatA = QgsFeature()
        inFeatB = QgsFeature()
        outFeat = QgsFeature()

        index = utils.createSpatialIndex(layerB)

        selectionA = QGisLayers.features(layerA)

        current = 0
        total = 100.0 / float(len(selectionA))

        for inFeatA in selectionA:
            add = True
            geom = QgsGeometry(inFeatA.geometry())
            diff_geom = QgsGeometry(geom)
            attrs = inFeatA.attributes()
            intersections = index.intersects(geom.boundingBox())
            for i in intersections:
                request = QgsFeatureRequest().setFilterFid(i)
                inFeatB = layerB.getFeatures(request).next()
                tmpGeom = QgsGeometry(inFeatB.geometry())
                try:
                    if diff_geom.intersects(tmpGeom):
                        diff_geom = QgsGeometry(diff_geom.difference(tmpGeom))
                except:
                    GEOS_EXCEPT = False
                    add = False
                    break

            if add:
                try:
                    outFeat.setGeometry(diff_geom)
                    outFeat.setAttributes(attrs)
                    writer.addFeature(outFeat)
                except:
                    FEATURE_EXCEPT = False
                    continue

            current += 1
            progress.setPercentage(int(current * total))

        del writer

        if not GEOS_EXCEPT:
            ProcessingLog.addToLog(
                ProcessingLog.LOG_WARNING,
                "Geometry exception while computing difference")
        if not FEATURE_EXCEPT:
            ProcessingLog.addToLog(
                ProcessingLog.LOG_WARNING,
                "Feature exception while computing difference")
Exemplo n.º 57
0
    def processAlgorithm(self, progress):
        vlayerA = QGisLayers.getObjectFromUri(self.getParameterValue(Union.INPUT))
        vlayerB = QGisLayers.getObjectFromUri(self.getParameterValue(Union.INPUT2))
        GEOS_EXCEPT = True
        FEATURE_EXCEPT = True
        vproviderA = vlayerA.dataProvider()

        fields = utils.combineVectorFields(vlayerA, vlayerB )
        names = [field.name() for field in fields]
        ProcessingLog.addToLog(ProcessingLog.LOG_INFO, str(names))
        writer = self.getOutputFromName(Union.OUTPUT).getVectorWriter(fields, vproviderA.geometryType(), vproviderA.crs() )
        inFeatA = QgsFeature()
        inFeatB = QgsFeature()
        outFeat = QgsFeature()
        indexA = utils.createSpatialIndex(vlayerB)
        indexB = utils.createSpatialIndex(vlayerA)

        count = 0
        nElement = 0
        featuresA = QGisLayers.features(vlayerA)
        nFeat = len(featuresA)
        for inFeatA in featuresA:
          progress.setPercentage(nElement/float(nFeat) * 50)
          nElement += 1
          found = False
          geom = QgsGeometry( inFeatA.geometry() )
          diff_geom = QgsGeometry( geom )
          atMapA = inFeatA.attributes()
          intersects = indexA.intersects( geom.boundingBox() )
          if len( intersects ) < 1:
            try:
              outFeat.setGeometry( geom )
              outFeat.setAttributes( atMapA )
              writer.addFeature( outFeat )
            except:
              # this really shouldn't happen, as we
              # haven't edited the input geom at all
              raise GeoAlgorithmExecutionException("Feature exception while computing union")
          else:
            for id in intersects:
                count += 1
                request = QgsFeatureRequest().setFilterFid(id)
                inFeatB = vlayerB.getFeatures(request).next()
                atMapB = inFeatB.attributes()
                tmpGeom = QgsGeometry( inFeatB.geometry() )

                if geom.intersects( tmpGeom ):
                  found = True
                  int_geom = geom.intersection( tmpGeom )

                  if int_geom is None:
                    # There was a problem creating the intersection
                    raise GeoAlgorithmExecutionException("Geometry exception while computing intersection")
                  else:
                    int_geom = QgsGeometry(int_geom)

                  if diff_geom.intersects( tmpGeom ):
                    diff_geom = diff_geom.difference( tmpGeom )
                    if diff_geom is None:
                      # It's possible there was an error here?
                      diff_geom = QgsGeometry()
                    else:
                      diff_geom = QgsGeometry(diff_geom)

                  if int_geom.wkbType() == 0:
                    # intersection produced different geomety types
                    temp_list = int_geom.asGeometryCollection()
                    for i in temp_list:
                      if i.type() == geom.type():
                          int_geom = QgsGeometry( i )
                  try:
                    outFeat.setGeometry( int_geom )
                    attrs = []
                    attrs.extend(atMapA)
                    attrs.extend(atMapB)
                    outFeat.setAttributes(attrs)
                    writer.addFeature( outFeat )
                  except Exception, err:
                    raise GeoAlgorithmExecutionException("Feature exception while computing union")
                else:
                  # this only happends if the bounding box
                  # intersects, but the geometry doesn't
                  try:
                    outFeat.setGeometry( geom )
                    outFeat.setAttributes( atMapA )
                    writer.addFeature( outFeat )
                  except:
                    # also shoudn't ever happen
                    raise GeoAlgorithmExecutionException("Feature exception while computing union")


            if found:
              try:
                if diff_geom.wkbType() == 0:
                  temp_list = diff_geom.asGeometryCollection()
                  for i in temp_list:
                    if i.type() == geom.type():
                        diff_geom = QgsGeometry( i )
                outFeat.setGeometry( diff_geom )
                outFeat.setAttributes( atMapA )
                writer.addFeature( outFeat )
              except Exception, err:
                raise GeoAlgorithmExecutionException("Feature exception while computing union")
Exemplo n.º 58
0
    def processAlgorithm(self, progress):
        lineLayer = QGisLayers.getObjectFromUri(
            self.getParameterValue(self.LINES))
        polyLayer = QGisLayers.getObjectFromUri(
            self.getParameterValue(self.POLYGONS))
        lengthFieldName = self.getParameterValue(self.LEN_FIELD)
        countFieldName = self.getParameterValue(self.COUNT_FIELD)

        polyProvider = polyLayer.dataProvider()

        idxLength, fieldList = utils.findOrCreateField(
            polyLayer, polyLayer.pendingFields(), lengthFieldName)
        idxCount, fieldList = utils.findOrCreateField(polyLayer, fieldList,
                                                      countFieldName)

        writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(
            fieldList.toList(), polyProvider.geometryType(),
            polyProvider.crs())

        spatialIndex = utils.createSpatialIndex(lineLayer)

        ftLine = QgsFeature()
        ftPoly = QgsFeature()
        outFeat = QgsFeature()
        inGeom = QgsGeometry()
        outGeom = QgsGeometry()
        distArea = QgsDistanceArea()

        current = 0
        features = QGisLayers.features(polyLayer)
        total = 100.0 / float(len(features))
        hasIntersections = False
        for ftPoly in features:
            inGeom = QgsGeometry(ftPoly.geometry())
            attrs = ftPoly.attributes()
            count = 0
            length = 0
            hasIntersections = False
            lines = spatialIndex.intersects(inGeom.boundingBox())
            if len(lines) > 0:
                hasIntersections = True

            if hasIntersections:
                for i in lines:
                    request = QgsFeatureRequest().setFilterFid(i)
                    ftLine = lineLayer.getFeatures(request).next()
                    tmpGeom = QgsGeometry(ftLine.geometry())
                    if inGeom.intersects(tmpGeom):
                        outGeom = inGeom.intersection(tmpGeom)
                        length += distArea.measure(outGeom)
                        count += 1

            outFeat.setGeometry(inGeom)
            if idxLength == len(attrs):
                attrs.append(length)
            else:
                attrs[idxLength] = length
            if idxCount == len(attrs):
                attrs.append(count)
            else:
                attrs[idxCount] = count
            outFeat.setAttributes(attrs)
            writer.addFeature(outFeat)

            current += 1
            progress.setPercentage(int(current * total))

        del writer
Exemplo n.º 59
0
    def processAlgorithm(self, progress):
        layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT))
        method = self.getParameterValue(self.METHOD)

        geometryType = layer.geometryType()

        idx1 = -1
        idx2 = -1
        fields = layer.pendingFields()

        if geometryType == QGis.Polygon:
            idx1, fields = utils.findOrCreateField(layer, fields, "area", 21, 6)
            idx2, fields = utils.findOrCreateField(layer, fields, "perimeter", 21, 6)
        elif geometryType == QGis.Line:
            idx1, fields = utils.findOrCreateField(layer, fields, "length", 21, 6)
            idx2 = idx1
        else:
            idx1, fields = utils.findOrCreateField(layer, fields, "xcoord", 21, 6)
            idx2, fields = utils.findOrCreateField(layer, fields, "ycoord", 21, 6)

        writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fields.toList(),
                     layer.dataProvider().geometryType(), layer.crs())

        print idx1, idx2

        ellips = None
        crs = None
        coordTransform = None

        # calculate with:
        # 0 - layer CRS
        # 1 - project CRS
        # 2 - ellipsoidal
        if method == 2:
            ellips = QgsProject.instance().readEntry("Measure", "/Ellipsoid", GEO_NONE)[0]
            crs = layer.crs().srsid()
        elif method == 1:
            mapCRS = QGisLayers.iface.mapCanvas().mapRenderer().destinationCrs()
            layCRS = layer.crs()
            coordTransform = QgsCoordinateTransform(layCRS, mapCRS)

        outFeat = QgsFeature()
        inGeom = QgsGeometry()

        outFeat.initAttributes(len(fields))
        outFeat.setFields(fields)

        current = 0
        features = QGisLayers.features(layer)
        total = 100.0 / float(len(features))
        for f in features:
            inGeom = f.geometry()

            if method == 1:
                inGeom.transform(coordTransform)

            (attr1, attr2) = utils.simpleMeasure(inGeom, method, ellips, crs)

            outFeat.setGeometry(inGeom)
            attrs = f.attributes()
            attrs.insert(idx1, attr1)
            if attr2 is not None:
                attrs.insert(idx2, attr2)
            outFeat.setAttributes(attrs)
            writer.addFeature(outFeat)

            current += 1
            progress.setPercentage(int(current * total))

        del writer
Exemplo n.º 60
0
    def processAlgorithm(self, progress):
        layerA = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT_A))
        layerB = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT_B))
        fieldA = self.getParameterValue(self.FIELD_A)
        fieldB = self.getParameterValue(self.FIELD_B)

        idxA = layerA.fieldNameIndex(fieldA)
        idxB = layerB.fieldNameIndex(fieldB)

        fieldList = [layerA.pendingFields()[idxA],
                     layerB.pendingFields()[idxB]
                    ]

        writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fieldList,
                     QGis.WKBPoint, layerA.dataProvider().crs())

        spatialIndex = utils.createSpatialIndex(layerB)

        inFeatA = QgsFeature()
        inFeatB = QgsFeature()
        outFeat = QgsFeature()
        inGeom = QgsGeometry()
        tmpGeom = QgsGeometry()

        features = QGisLayers.features(layerA)

        current = 0
        total = 100.0 / float(len(features))
        hasIntersections = False

        for inFeatA in features:
            inGeom = inFeatA.geometry()
            hasIntersections = False
            lines = spatialIndex.intersects(inGeom.boundingBox())

            if len(lines) > 0:
                hasIntersections = True

            if hasIntersections:
                for i in lines:
                    request = QgsFeatureRequest().setFilterFid(i)
                    inFeatB = layerB.getFeatures(request).next()
                    tmpGeom = QgsGeometry(inFeatB.geometry())

                    points = []
                    attrsA = inFeatA.attributes()
                    attrsB = inFeatB.attributes()

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

                            for j in points:
                                outFeat.setGeometry(tempGeom.fromPoint(j))
                                outFeat.setAttributes([attrsA[idxA], attrsB[idxB]])
                                writer.addFeature(outFeat)

            current += 1
            progress.setPercentage(int(current * total))

        del writer