Example #1
0
    def getVectorWriter(self, fields, geomType, crs, options=None):
        '''Returns a suitable writer to which features can be added as a
        result of the algorithm. Use this to transparently handle output
        values instead of creating your own method.

        Executing this method might modify the object, adding additional
        information to it, so the writer can be later accessed and processed
        within QGIS. It should be called just once, since a new call might
        result in previous data being replaced, thus rendering a previously
        obtained writer useless

        @param fields   a dict of int-QgsField
        @param geomType a suitable geometry type, as it would be passed
                        to a QgsVectorFileWriter constructor
        @param crs      the crs of the layer to create

        @return writer  instance of the vectoe writer class
        '''

        if self.encoding is None:
            settings = QSettings()
            self.encoding = settings.value("/SextanteQGIS/encoding",
                                           "System").toString()

        w = SextanteVectorWriter(self.value, self.encoding, fields, geomType,
                                 crs, options)
        self.memoryLayer = w.memLayer
        return w
Example #2
0
    def checkSagaIsInstalled(cls):
        if SextanteUtils.isWindows():
            path = SagaUtils.sagaPath()
            if path == "":
                return "SAGA folder is not configured.\nPlease configure it before running SAGA algorithms."
            cmdpath = os.path.join(path, "saga_cmd.exe")
            if not os.path.exists(cmdpath):
                return ("The specified SAGA folder does not contain a valid SAGA executable.\n" 
                        + "Please, go to the SEXTANTE settings dialog, and check that the SAGA\n" 
                        + "folder is correctly configured")
                                    
        SAGA_INSTALLED = "/SextanteQGIS/SagaInstalled"
        settings = QSettings()
        if settings.contains(SAGA_INSTALLED):
            return
        
        try:
            qgis = QGisLayers.iface
            crs = qgis.mapCanvas().mapRenderer().destinationCrs()
            fields = []
            fields.append(QgsField("NUM_FIELD", QVariant.Int))
            filename = SextanteUtils.getTempFilename("shp")
            writer = SextanteVectorWriter(filename, None, fields, QGis.WKBPoint, crs)
            for x in range(5):
                for y in range(5):
                    attrs = []
                    attrs.append(QVariant(x))
                    outFeat = QgsFeature()
                    pt = QgsPoint(x, y)
                    outFeat.setGeometry(QgsGeometry.fromPoint(pt))
                    outFeat.setAttributes(attrs)
                    writer.addFeature(outFeat)   
            del writer.writer
            del writer       
            from sextante.core.Sextante import runalg              
            result = runalg("saga:thiessenpolygons", filename, None)
            if not os.path.exists(result['POLYGONS']):
                return "It seems that SAGA is not correctly installed in your system.\nPlease install it before running SAGA algorithms."
        except:
            s = traceback.format_exc()
            return "Error while checking SAGA installation. SAGA might not be correctly configured.\n" + s;
            

        settings.setValue("/SextanteQGIS/SagaInstalled", True)        
        
#Here we define the input and outputs
#====================================
##[Example scripts]=group
##input=vector
##output=output vector

#And here is the body of the algorithm
#=======================================

#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.getObjectFromUri() method
vectorLayer = QGisLayers.getObjectFromUri(input)

#And now we can process

#First we create the output layer.
#To do so, we create a SextanteVectorWriter, that we can later use to add features.
provider = vectorLayer.dataProvider()
writer = SextanteVectorWriter(output, None, provider.fields(),
                              provider.geometryType(), provider.crs())

#Now we take the selected features and add them to the output layer
selection = vectorLayer.selectedFeatures()
for feat in selection:
    writer.addFeature(feat)
del writer

#There is nothing more to do here. We do not have to open the layer that we have created.
#SEXTANTE will take care of that, or will handle it if this algorithm is executed within
#a complex model
Example #4
0
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

##[Example scripts]=group
##input=vector
##output=output vector

from PyQt4.QtCore import *
from qgis.core import *

from sextante.core.SextanteVectorWriter import SextanteVectorWriter

inputLayer = sextante.getobject(input)
features = sextante.getfeatures(inputLayer)
fields = inputLayer.pendingFields().toList()
outputLayer = SextanteVectorWriter(output, None, fields, QGis.WKBPoint, inputLayer.crs())
count = 0
mean = [0 for field in fields]
x = 0
y = 0
for ft in features:
    c = ft.geometry().centroid().asPoint()
    x += c.x()
    y += c.y()
    attrs = ft.attributes()
    for f in range(len(fields)):
        try:
            mean[f] += float(attrs[f].toDouble()[0])
        except:
            pass
    count += 1
##value_field=field input
##output=output vector

# Algorithm body
# ==================================
from qgis.core import *
from PyQt4.QtCore import *
from sextante.core.SextanteVectorWriter import SextanteVectorWriter

# "input" contains the location of the selected layer.
# We get the actual object, so we can get its bounds
layer = getobject(input)
provider = layer.dataProvider()
fields = provider.fields()
fields.append(QgsField("UNIQ_COUNT", QVariant.Int))
writer = SextanteVectorWriter(output, None, fields, provider.geometryType(), provider.crs())

# Fields are defined by their names, but QGIS needs the index for the attributes map
class_field_index = layer.fieldNameIndex(class_field)
value_field_index = layer.fieldNameIndex(value_field)

inFeat = QgsFeature()
outFeat = QgsFeature()
inGeom = QgsGeometry()
nElement = 0
classes = {}

# Iterate over input layer to count unique values in each class

feats = getfeatures(layer)
nFeat = len(feates)
#Here we define the input and outputs
#====================================
##[Example scripts]=group
##input=vector
##output=output vector

#And here is the body of the algorithm
#=======================================

#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.getObjectFromUri() method
vectorLayer = QGisLayers.getObjectFromUri(input)

#And now we can process

#First we create the output layer.
#To do so, we create a SextanteVectorWriter, that we can later use to add features.
provider = vectorLayer.dataProvider()
writer = SextanteVectorWriter(output, None, provider.fields(), provider.geometryType(), provider.crs() )

#Now we take the selected features and add them to the output layer
selection = vectorLayer.selectedFeatures()
for feat in selection:
    writer.addFeature(feat)
del writer

#There is nothing more to do here. We do not have to open the layer that we have created.
#SEXTANTE will take care of that, or will handle it if this algorithm is executed within
#a complex model
Example #7
0
##input=vector
##output=output vector
from sextante.core.SextanteVectorWriter import SextanteVectorWriter
from qgis.core import *
from PyQt4.QtCore import *

inputLayer = sextante.getobject(input)
features = sextante.getfeatures(inputLayer)
fields = inputLayer.pendingFields().toList()
outputLayer = SextanteVectorWriter(output, None, fields, QGis.WKBPoint,
                                   inputLayer.crs())
count = 0
mean = [0 for field in fields]
x = 0
y = 0
for ft in features:
    c = ft.geometry().centroid().asPoint()
    x += c.x()
    y += c.y()
    attrs = ft.attributes()
    for f in range(len(fields)):
        try:
            mean[f] += float(attrs[f].toDouble()[0])
        except:
            pass
    count += 1
if count != 0:
    mean = [value / count for value in mean]
    x /= count
    y /= count
outFeat = QgsFeature()
fields = provider.fields()
writers = {}

# Fields are defined by their names, but QGIS needs the index for the attributes map
class_field_index = layer.fieldNameIndex(class_field)

inFeat = QgsFeature()
outFeat = QgsFeature()
inGeom = QgsGeometry()
nElement = 0
writers = {}

feats = sextante.getfeatures(layer)
nFeat = len(feats)
for inFeat in feats:
    progress.setPercentage(int((100 * nElement) / nFeat))
    nElement += 1
    atMap = inFeat.attributes()
    clazz = atMap[class_field_index].toString()
    if clazz not in writers:
        outputFile = output + "_" + str(len(writers)) + ".shp"
        writers[clazz] = SextanteVectorWriter(outputFile, None, fields,
                                              provider.geometryType(),
                                              layer.crs())
    inGeom = inFeat.geometry()
    outFeat.setGeometry(inGeom)
    outFeat.setAttributes(atMap)
    writers[clazz].addFeature(outFeat)

for writer in writers.values():
    del writer