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].toString())
				if '%' in v:
					v = v.replace('%', "")
					attributes[idx] = float(attributes[idx]) / float(100)
				else:
					attributes[idx] = float(attributes[idx])
			except:
				attributes[idx] = QVariant()

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

		del out
Example #2
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
Example #3
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
Example #4
0
 def processAlgorithm(self, progress):
     fieldname = self.getParameterValue(self.FIELD_NAME)
     formula = self.getParameterValue(self.FORMULA)
     output = self.getOutputFromName(self.OUTPUT_LAYER)
     vlayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT_LAYER))
     vprovider = vlayer.dataProvider()
     allAttrs = vprovider.attributeIndexes()
     vprovider.select(allAttrs)
     fields = vprovider.fields()
     fields[len(fields)] = QgsField(fieldname, QVariant.Double)
     writer = output.getVectorWriter(fields, vprovider.geometryType(), vprovider.crs())
     outFeat = QgsFeature()
     inGeom = QgsGeometry()
     nFeat = vprovider.featureCount()
     nElement = 0
     features = QGisLayers.features(vlayer)
     for inFeat in features:
         progress.setPercentage(int((100 * nElement) / nFeat))
         attrs = inFeat.attributeMap()
         expression = formula
         for (k, attr) in attrs.iteritems():
             expression = expression.replace(str(fields[k].name()), str(attr.toString()))
         try:
             result = eval(expression)
         except Exception:
             raise GeoAlgorithmExecutionException("Problem evaluation formula: Wrong field values or formula")
         nElement += 1
         inGeom = inFeat.geometry()
         outFeat.setGeometry(inGeom)
         atMap = inFeat.attributeMap()
         outFeat.setAttributeMap(atMap)
         outFeat.addAttribute(len(vprovider.fields()), QVariant(result))
         writer.addFeature(outFeat)
     del writer
    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
 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 SEXTANTE 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
Example #7
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

        SextanteLog.addToLog(
            SextanteLog.LOG_INFO,
            "Simplify: Input geometries have been simplified from" +
            str(pointsBefore) + " to " + str(pointsAfter) + " points.")
Example #8
0
    def processAlgorithm(self, progress):
        layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT))

        provider = layer.dataProvider()

        writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(
            layer.pendingFields(), QGis.WKBPoint, provider.crs()
        )

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

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

            points = utils.extractPoints(inGeom)
            outFeat.setAttributes(atMap)

            for i in points:
                outFeat.setGeometry(outGeom.fromPoint(i))
                writer.addFeature(outFeat)

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

        del writer
Example #9
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 = SextanteConfig.getSetting(SextanteConfig.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
Example #10
0
 def processAlgorithm(self, progress):
     inField = self.getParameterValue(PointsInPolygon.FIELD)
     polyLayer = QGisLayers.getObjectFromUri(
         self.getParameterValue(PointsInPolygon.POLYGONS))
     pointLayer = QGisLayers.getObjectFromUri(
         self.getParameterValue(PointsInPolygon.POINTS))
     polyProvider = polyLayer.dataProvider()
     pointProvider = pointLayer.dataProvider()
     if polyProvider.crs() <> pointProvider.crs():
         SextanteLog.addToLog(
             SextanteLog.LOG_WARNING,
             "CRS warning!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,
                          "point count field")
         fieldList[index] = field
     sRs = polyProvider.crs()
     writer = self.getOutputFromName(
         PointsInPolygon.OUTPUT).getVectorWriter(
             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):
                     count = count + 1
         outFeat.setAttributeMap(atMap)
         outFeat.addAttribute(index, QVariant(count))
         writer.addFeature(outFeat)
         start = start + add
         progress.setPercentage(start)
     del writer
    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.getOutputFromName(self.OUTPUT_LAYER)

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

        #And now we can process

        #First we create the output layer.
        #To do so, we call the getVectorWriter method in the Output object.
        #That will give as a SextanteVectorWriter, that we can later use to add features.
        provider = vectorLayer.dataProvider()
        writer = output.getVectorWriter( provider.fields(), provider.geometryType(), provider.crs() )

        #Now we take the selected features and add them to the output layer
        features = QGisLayers.features(vectorLayer)
        total = len(features)
        i = 0
        for feat in features:
            writer.addFeature(feat)
            progress.setPercentage(100 * i / float(total))
            i += 1
        del writer
Example #12
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)
Example #13
0
    def processAlgorithm(self, progress):
        layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT))
        vertices = self.getParameterValue(self.VERTICES)

        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, int(vertices),
                                               isPolygon)
            feature = QgsFeature()
            feature.setGeometry(newGeometry)
            feature.setAttributes(attrs)
            writer.addFeature(feature)
            current += 1
            progress.setPercentage(int(current * total))

        del writer
Example #14
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)
Example #15
0
 def processAlgorithm(self, progress):
     fieldtype = self.getParameterValue(self.FIELD_TYPE)
     fieldname = self.getParameterValue(self.FIELD_NAME)
     output = self.getOutputFromName(self.OUTPUT_LAYER)
     vlayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT_LAYER))
     vprovider = vlayer.dataProvider()
     allAttrs = vprovider.attributeIndexes()
     vprovider.select( allAttrs )
     fields = vprovider.fields()
     fields[len(fields)] = QgsField(fieldname, self.TYPES[fieldtype])
     writer = output.getVectorWriter(fields, vprovider.geometryType(), vprovider.crs() )        
     outFeat = QgsFeature()
     inGeom = QgsGeometry()
     nFeat = vprovider.featureCount()
     nElement = 0
     features = QGisLayers.features(vlayer)                    
     for inFeat in features:
         progress.setPercentage(int((100 * nElement)/nFeat))
         nElement += 1
         inGeom = inFeat.geometry()
         outFeat.setGeometry( inGeom )
         atMap = inFeat.attributeMap()
         outFeat.setAttributeMap( atMap )
         outFeat.addAttribute( len(vprovider.fields()), QVariant() )
         writer.addFeature( outFeat )
     del writer
Example #16
0
    def processAlgorithm(self, progress):
        layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT))

        provider = layer.dataProvider()

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

        outFeat = QgsFeature()

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

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

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

        del writer
Example #17
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
    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
Example #19
0
 def processAlgorithm(self, progress):
     output = self.getOutputFromName(self.OUTPUT)
     vlayer = QGisLayers.getObjectFromUri(self.getParameterValue(
         self.INPUT))
     vprovider = vlayer.dataProvider()
     fields = vprovider.fields()
     fields.append(QgsField("AUTO", QVariant.Int))
     writer = output.getVectorWriter(fields, vprovider.geometryType(),
                                     vlayer.crs())
     inFeat = QgsFeature()
     outFeat = QgsFeature()
     inGeom = QgsGeometry()
     nElement = 0
     features = QGisLayers.features(vlayer)
     nFeat = len(features)
     for inFeat in features:
         progress.setPercentage(int((100 * nElement) / nFeat))
         nElement += 1
         inGeom = inFeat.geometry()
         outFeat.setGeometry(inGeom)
         attrs = inFeat.attributes()
         attrs.append(nElement)
         outFeat.setAttributes(attrs)
         writer.addFeature(outFeat)
     del writer
    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)
        nFeat = len(features)
        values = {}
        for feat in features:
            attrs = feat.attributes()
            value = float(attrs[valuesField].toDouble()[0])
            cat = unicode(attrs[categoriesField].toString())
            if cat not in values:
                values[cat] = []
            values[cat].append(value)
        
        fields = [QgsField("category", QVariant.String), QgsField("mean", QVariant.Double), QgsField("variance", QVariant.Double)]
        writer = output.getTableWriter(fields)
        for cat, value in values.items():                       
            n, min_max, mean, var, skew, kurt = stats.describe(value)
            record = [cat, mean, math.sqrt(var)]            
            writer.addRecord(record)
Example #21
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)
Example #22
0
 def processAlgorithm(self, progress):
     fieldname = self.getParameterValue(self.FIELD)
     output = self.getOutputFromName(self.OUTPUT)
     vlayer = QGisLayers.getObjectFromUri(self.getParameterValue(
         self.INPUT))
     vprovider = vlayer.dataProvider()
     fieldindex = vlayer.fieldNameIndex(fieldname)
     fields = vprovider.fields()
     fields.append(QgsField("NUM_FIELD", QVariant.Int))
     writer = output.getVectorWriter(fields, vprovider.geometryType(),
                                     vlayer.crs())
     outFeat = QgsFeature()
     inGeom = QgsGeometry()
     nElement = 0
     classes = {}
     features = QGisLayers.features(vlayer)
     nFeat = len(features)
     for feature in features:
         progress.setPercentage(int((100 * nElement) / nFeat))
         nElement += 1
         inGeom = feature.geometry()
         outFeat.setGeometry(inGeom)
         atMap = feature.attributes()
         clazz = atMap[fieldindex]
         if clazz not in classes:
             classes[clazz] = len(classes.keys())
         atMap.append(classes[clazz])
         outFeat.setAttributes(atMap)
         writer.addFeature(outFeat)
     del writer
 def handleAlgorithmResults(alg, progress, showResults=True):
     wrongLayers = []
     htmlResults = False
     progress.setText("Loading resulting layers")
     i = 0
     for out in alg.outputs:
         progress.setPercentage(100 * i / float(len(alg.outputs)))
         if out.hidden or not out.open:
             continue
         if isinstance(out, (OutputRaster, OutputVector, OutputTable)):
             try:
                 if out.value.startswith("memory:"):
                     layer = out.memoryLayer
                     QgsMapLayerRegistry.instance().addMapLayers([layer])
                 else:
                     if SextanteConfig.getSetting(
                             SextanteConfig.USE_FILENAME_AS_LAYER_NAME):
                         name = os.path.basename(out.value)
                     else:
                         name = out.description
                     QGisLayers.load(
                         out.value, name, alg.crs,
                         RenderingStyles.getStyle(alg.commandLineName(),
                                                  out.name))
             except Exception, e:
                 wrongLayers.append(out)
                 #QMessageBox.critical(None, "Error", str(e))
         elif isinstance(out, OutputHTML):
             SextanteResults.addResult(out.description, out.value)
             htmlResults = True
Example #24
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(QVariant())
            outFeat.setAttributes(atMap)
            writer.addFeature( outFeat )
        del writer
	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].toString())
				if '%' in v:
					v = v.replace('%', "")
					attributes[idx] = float(attributes[idx]) / float(100)
				else:
					attributes[idx] = float(attributes[idx])
			except:
				attributes[idx] = QVariant()

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

		del out
Example #26
0
    def processAlgorithm(self, progress):
        layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT_LAYER))

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

        layer.select(layer.pendingAllAttributesList())

        outFeat = QgsFeature()

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

        for inFeat in features:
            inGeom = inFeat.geometry()
            attrMap = inFeat.attributeMap()

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

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

        del writer
	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)
    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(),
                     layer.wkbType(), layer.crs())


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

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

        del writer
Example #29
0
 def processAlgorithm(self, progress):
     fieldname = self.getParameterValue(self.FIELD)
     output = self.getOutputFromName(self.OUTPUT)
     vlayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT))
     vprovider = vlayer.dataProvider()
     fieldindex = vlayer.fieldNameIndex(fieldname)        
     fields = vprovider.fields()
     fields.append(QgsField("NUM_FIELD", QVariant.Int))
     writer = output.getVectorWriter(fields, vprovider.geometryType(), vprovider.crs() )        
     outFeat = QgsFeature()
     inGeom = QgsGeometry()        
     nElement = 0
     classes = {}
     features = QGisLayers.features(vlayer)
     nFeat = len(features)
     for feature in features:
         progress.setPercentage(int((100 * nElement)/nFeat))
         nElement += 1
         inGeom = feature.geometry()
         outFeat.setGeometry( inGeom )
         atMap = feature.attributes()
         clazz = atMap[fieldindex].toString()
         if clazz not in classes:
             classes[clazz] = len(classes.keys())
         atMap.append(QVariant(classes[clazz]))
         outFeat.setAttributes(atMap)                        
         writer.addFeature( outFeat )
     del writer
 def handleAlgorithmResults(alg, progress, showResults = True):
     wrongLayers = []
     htmlResults = False;
     progress.setText("Loading resulting layers")
     i =  0
     for out in alg.outputs:
         progress.setPercentage(100 * i / float(len(alg.outputs)))
         if out.hidden or not out.open:
             continue
         if isinstance(out, (OutputRaster, OutputVector, OutputTable)):
             try:
                 if out.value.startswith("memory:"):
                     layer = out.memoryLayer
                     QgsMapLayerRegistry.instance().addMapLayers([layer])
                 else:
                     if SextanteConfig.getSetting(SextanteConfig.USE_FILENAME_AS_LAYER_NAME):
                         name = os.path.basename(out.value)
                     else:
                         name = out.description
                     QGisLayers.load(out.value, name, alg.crs, RenderingStyles.getStyle(alg.commandLineName(),out.name))
             except Exception, e:
                 wrongLayers.append(out)
                 #QMessageBox.critical(None, "Error", str(e))
         elif isinstance(out, OutputHTML):
             SextanteResults.addResult(out.description, out.value)
             htmlResults = True
    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
Example #32
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 = SextanteConfig.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 = SextanteConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_XMIN)
         self.xmax = SextanteConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_XMAX)
         self.ymin = SextanteConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_YMIN)
         self.ymax = SextanteConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_YMAX)
         self.cellsize = SextanteConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_CELLSIZE)
    def processAlgorithm(self, progress):
        polyLayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.POLYGONS))
        pointLayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.POINTS))
        fieldName = self.getParameterValue(self.FIELD)

        polyProvider = polyLayer.dataProvider()
        pointProvider = pointLayer.dataProvider()
        if polyProvider.crs() != pointProvider.crs():
            SextanteLog.addToLog(SextanteLog.LOG_WARNING,
                                 "CRS warning: Input layers have non-matching CRS. This may cause unexpected results.")

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

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

        spatialIndex = utils.createSpatialIndex(pointLayer)

        pointProvider.rewind()
        pointProvider.select()

        allAttrs = polyLayer.pendingAllAttributesList()
        polyLayer.select(allAttrs)

        ftPoly = QgsFeature()
        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()
            atMap = ftPoly.attributeMap()

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

            if hasIntersections:
                for i in points:
                    pointLayer.featureAtId(int(i), ftPoint, True, False)
                    tmpGeom = QgsGeometry(ftPoint.geometry())
                    if geom.contains(tmpGeom):
                        count += 1

            outFeat.setGeometry(geom)
            outFeat.setAttributeMap(atMap)
            outFeat.addAttribute(idxCount, QVariant(count))
            writer.addFeature(outFeat)

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

        del writer
Example #34
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 Sextante.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, considiring the selection that
        # might exisist in layer and SEXTANTE configuration that indicates
        # should algorithm use only selected features or all of them
        features = QGisLayers.features(vectorLayer)
        for f in features:
            writer.addFeature(f)
    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.getOutputFromName(self.OUTPUT_LAYER)

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

        #And now we can process

        #First we create the output layer.
        #To do so, we call the getVectorWriter method in the Output object.
        #That will give as a SextanteVectorWriter, that we can later use to add features.
        provider = vectorLayer.dataProvider()
        writer = output.getVectorWriter( provider.fields(), provider.geometryType(), vectorLayer.crs() )

        #Now we take the selected features and add them to the output layer
        features = QGisLayers.features(vectorLayer)
        total = len(features)
        i = 0
        for feat in features:
            writer.addFeature(feat)
            progress.setPercentage(100 * i / float(total))
            i += 1
        del writer
Example #36
0
    def processAlgorithm(self, progress):
        layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT))        
        tolerance =self.getParameterValue(self.TOLERANCE)        

        pointsBefore = 0
        pointsAfter = 0

        provider = layer.dataProvider()
        layer.select(layer.pendingAllAttributesList())

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

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

        SextanteLog.addToLog(SextanteLog.LOG_INFO, "Simplify: Input geometries have been simplified from"
                             + str(pointsBefore) + " to "  + str(pointsAfter) + " points.")
Example #37
0
    def processAlgorithm(self, progress):
        # Include must be done here to avoid cyclic import
        from sextante.core.Sextante import Sextante
        qgis = Sextante.getInterface()

        layer = QGisLayers.getObjectFromUri(
            self.getParameterValue(self.LAYERNAME))
        layername = layer.name()

        table = QGisLayers.getObjectFromUri(
            self.getParameterValue(self.INFILENAME))
        infilename = table.name()

        joinfield = self.getParameterValue(self.JOINFIELD)
        joinattribute = self.getParameterValue(self.JOINATTRIBUTE)

        outfilename = self.getOutputValue(self.OUTFILENAME)
        notfoundname = self.getOutputValue(self.NOTFOUNDNAME)

        message = mmqgisx_attribute_join(qgis, layername, infilename,
                                         joinfield, joinattribute, outfilename,
                                         notfoundname, False)

        if message:
            raise GeoAlgorithmExecutionException(message)
    def getDefaultCellsize(self):
        cellsize = 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)
                    cellsize = max(cellsize,
                                   (layer.extent().xMaximum() -
                                    layer.extent().xMinimum()) / layer.width())

                elif isinstance(param, ParameterMultipleInput):
                    layers = param.value.split(";")
                    for layername in layers:
                        layer = QGisLayers.getObjectFromUri(layername)
                        if isinstance(layer, QgsRasterLayer):
                            cellsize = max(cellsize,
                                           (layer.extent().xMaximum() -
                                            layer.extent().xMinimum()) /
                                           layer.width())

        if cellsize == 0:
            cellsize = 1
        return cellsize
Example #39
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 Sextante.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, considiring the selection that
        # might exisist in layer and SEXTANTE configuration that indicates
        # should algorithm use only selected features or all of them
        features = QGisLayers.features(vectorLayer)
        for f in features:
            writer.addFeature(f)
Example #40
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
Example #41
0
    def processAlgorithm(self, progress):
        layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT))

        provider = layer.dataProvider()
        layer.select(layer.pendingAllAttributesList())

        geomType = self.multiToSingleGeom(provider.geometryType())

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

        outFeat = QgsFeature()
        inGeom = QgsGeometry()

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

            features = self.extractAsSingle(inGeom)
            outFeat.setAttributeMap(atMap)

            for f in features:
                outFeat.setGeometry(f)
                writer.addFeature(outFeat)

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

        del writer
    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))

        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].toString())
                y =  float(attrs[yfieldindex].toString())
            except:
                continue
            pt = QgsPoint(x, y)
            outFeat.setGeometry(QgsGeometry.fromPoint(pt))
            outFeat.setAttributes(attrs)
            writer.addFeature(outFeat)

        del writer
    def processAlgorithm(self, progress):
        filename = self.getParameterValue(self.INPUT)

        layer = QGisLayers.getObjectFromUri(filename)
        field = self.getParameterValue(self.FIELD)
        method = self.getParameterValue(self.METHOD)

        layer.removeSelection()
        index = layer.fieldNameIndex(field)

        unique = utils.getUniqueValues(layer, index)
        featureCount = layer.featureCount()

        value = int(self.getParameterValue(self.NUMBER))
        if method == 0:
            if value > featureCount:
                raise GeoAlgorithmExecutionException(
                    "Selected number is greater that feature count. Choose lesser value and try again."
                )
        else:
            if value > 100:
                raise GeoAlgorithmExecutionException(
                    "Persentage can't be greater than 100. Set corrent value and try again."
                )
            value = value / 100.0

        selran = []
        inFeat = QgsFeature()

        current = 0
        total = 100.0 / float(featureCount * len(unique))

        features = QGisLayers.features(layer)

        if not len(unique) == featureCount:
            for i in unique:
                FIDs = []
                for inFeat in features:
                    attrs = inFeat.attributes()
                    if attrs[index] == QVariant(i):
                        FIDs.append(inFeat.id())
                    current += 1
                    progress.setPercentage(int(current * total))

                if method == 1:
                    selValue = int(round(value * len(FIDs), 0))
                else:
                    selValue = value

                if selValue >= len(FIDs):
                    selFeat = FIDs
                else:
                    selFeat = random.sample(FIDs, selValue)

                selran.extend(selFeat)
            layer.setSelectedFeatures(selran)
        else:
            layer.setSelectedFeatures(range(0, featureCount))

        self.setOutputValue(self.OUTPUT, filename)
Example #44
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)))
Example #45
0
 def handleAlgorithmResults(alg, showResults=True):
     htmlResults = False
     for out in alg.outputs:
         if out.hidden or not out.open:
             continue
         if isinstance(out, (OutputRaster, OutputVector, OutputTable)):
             try:
                 if out.value.startswith("memory:"):
                     layer = out.memoryLayer
                     QgsMapLayerRegistry.instance().addMapLayer(layer)
                 else:
                     if SextanteConfig.getSetting(
                             SextanteConfig.USE_FILENAME_AS_LAYER_NAME):
                         name = os.path.basename(out.value)
                     else:
                         name = out.description
                     QGisLayers.load(
                         out.value, name, alg.crs,
                         RenderingStyles.getStyle(alg.commandLineName(),
                                                  out.name))
             except Exception, e:
                 QMessageBox.critical(None, "Error", str(e))
         elif isinstance(out, OutputHTML):
             SextanteResults.addResult(out.description, out.value)
             htmlResults = True
    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()
        pointProvider = pointLayer.dataProvider()
        if polyProvider.crs() != pointProvider.crs():
            SextanteLog.addToLog(SextanteLog.LOG_WARNING,
                                 "CRS warning: Input layers have non-matching CRS. This may cause unexpected results.")

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

        writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fieldList,
                     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()
            atMap = ftPoly.attributes()

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

            if hasIntersections:
                for i in points:
                    pointLayer.featureAtId(int(i), ftPoint, True, True)
                    tmpGeom = QgsGeometry(ftPoint.geometry())
                    if geom.contains(tmpGeom):
                        clazz = ftPoint.attributes()[classFieldIndex].toString()
                        if not clazz in classes:
                            classes.append(clazz)

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

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

        del writer
Example #47
0
    def processAlgorithm(self, progress):
        layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT))
        interval = self.getParameterValue(self.INTERVAL)

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

        provider = layer.dataProvider()
        layer.select(layer.pendingAllAttributesList())

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


        features = QGisLayers.features(layer)
        total = 100.0 / float(len(features))
        current = 0
        for f in features:
            featGeometry = QgsGeometry(f.geometry())
            attrMap = f.attributeMap()
            newGeometry = self.densifyGeometry(featGeometry, interval, isPolygon)

            feature = QgsFeature()
            feature.setGeometry(newGeometry)
            feature.setAttributeMap(attrMap)
            writer.addFeature(feature)

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

        del writer
Example #48
0
 def exportVectorLayer(self, orgFilename):
     #only export to an intermediate shp if the layer is not file-based.
     #We assume that almost all file formats will be supported by ogr
     #We also export if there is a selection
     if not os.path.exists(orgFilename):
         layer = QGisLayers.getObjectFromUri(orgFilename, False)
         if layer:
             filename = LayerExporter.exportVectorLayer(layer)
     else:
         layer = QGisLayers.getObjectFromUri(orgFilename, False)
         if layer:
             useSelection = SextanteConfig.getSetting(
                 SextanteConfig.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"
     command += " min_area=-1"
     command += " dsn=\"" + os.path.dirname(filename) + "\""
     command += " layer=" + os.path.basename(filename)[:-4]
     command += " output=" + destFilename
     command += " --overwrite -o"
     return command
    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
 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
    def processAlgorithm(self, progress):
        layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT))

        provider = layer.dataProvider()

        geomType = self.multiToSingleGeom(provider.geometryType())

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

        outFeat = QgsFeature()
        inGeom = QgsGeometry()

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

            features = self.extractAsSingle(inGeom)
            outFeat.setAttributes(atMap)

            for f in features:
                outFeat.setGeometry(f)
                writer.addFeature(outFeat)

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

        del writer
Example #52
0
 def exportVectorLayer(self, orgFilename):
     #only export to an intermediate shp if the layer is not file-based.
     #We assume that almost all file formats will be supported by ogr
     #We also export if there is a selection
     if not os.path.exists(orgFilename):
         layer = QGisLayers.getObjectFromUri(orgFilename, False)
         if layer:
             filename = LayerExporter.exportVectorLayer(layer)
     else:
         layer = QGisLayers.getObjectFromUri(orgFilename, False)
         if layer:
             useSelection = SextanteConfig.getSetting(SextanteConfig.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"
     command += " min_area=-1"
     command +=" dsn=\"" + os.path.dirname(filename) + "\""
     command +=" layer=" + os.path.basename(filename)[:-4]
     command +=" output=" + destFilename;
     command +=" --overwrite -o"
     return command
 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
Example #54
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)))
Example #55
0
 def processAlgorithm(self, progress):
     vlayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT))
     output = self.getOutputFromName(self.OUTPUT)
     vprovider = vlayer.dataProvider()
     allAttrs = vprovider.attributeIndexes()
     vprovider.select( allAttrs )
     fields = vprovider.fields()
     writer = output.getVectorWriter(fields, QGis.WKBLineString, vprovider.crs() )
     inFeat = QgsFeature()
     outFeat = QgsFeature()
     inGeom = QgsGeometry()
     nFeat = vprovider.featureCount()
     nElement = 0
     features = QGisLayers.features(layer)
     for feature in features:
         nElement += 1
         progress.setPercentage((nElement*100)/nFeat)
         inGeom = feature.geometry()
         atMap = feature.attributeMap()
         segments = self.extractAsSingleSegments( inGeom )
         outFeat.setAttributeMap( atMap )
         for segment in segments:
             outFeat.setGeometry(segment)
             writer.addFeature(outFeat)
     del writer
	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)
 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 SEXTANTE 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
Example #58
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(),
                     layer.wkbType(), targetCrs)

        layer.select(layer.pendingAllAttributesList())

        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.setAttributeMap(f.attributeMap())
            writer.addFeature(outFeat)

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

        del writer
Example #59
0
 def processAlgorithm(self, progress):
     vlayer = QGisLayers.getObjectFromUri(self.getParameterValue(
         self.INPUT))
     output = self.getOutputFromName(self.OUTPUT)
     vprovider = vlayer.dataProvider()
     allAttrs = vprovider.attributeIndexes()
     vprovider.select(allAttrs)
     fields = vprovider.fields()
     writer = output.getVectorWriter(fields, QGis.WKBLineString,
                                     vprovider.crs())
     inFeat = QgsFeature()
     outFeat = QgsFeature()
     inGeom = QgsGeometry()
     nFeat = vprovider.featureCount()
     nElement = 0
     features = QGisLayers.features(layer)
     for feature in features:
         nElement += 1
         progress.setPercentage((nElement * 100) / nFeat)
         inGeom = feature.geometry()
         atMap = feature.attributeMap()
         segments = self.extractAsSingleSegments(inGeom)
         outFeat.setAttributeMap(atMap)
         for segment in segments:
             outFeat.setGeometry(segment)
             writer.addFeature(outFeat)
     del writer