120 changes: 60 additions & 60 deletions python/plugins/sextante/algs/AddTableField.py
Original file line number Diff line number Diff line change
@@ -1,60 +1,60 @@
from sextante.core.GeoAlgorithm import GeoAlgorithm
from sextante.outputs.OutputVector import OutputVector
from sextante.parameters.ParameterVector import ParameterVector
from qgis.core import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from sextante.parameters.ParameterString import ParameterString
from sextante.parameters.ParameterSelection import ParameterSelection
from sextante.core.QGisLayers import QGisLayers
import os
from PyQt4 import QtGui


class AddTableField(GeoAlgorithm):

OUTPUT_LAYER = "OUTPUT_LAYER"
INPUT_LAYER = "INPUT_LAYER"
FIELD_NAME = "FIELD_NAME"
FIELD_TYPE = "FIELD_TYPE"
TYPE_NAMES = ["Integer", "Float", "String"]
TYPES = [QVariant.Int, QVariant.Double, QVariant.String]

def getIcon(self):
return QtGui.QIcon(os.path.dirname(__file__) + "/../images/toolbox.png")

def defineCharacteristics(self):
self.name = "Add field to attributes table"
self.group = "Algorithms for vector layers"
self.addParameter(ParameterVector(self.INPUT_LAYER, "Input layer", ParameterVector.VECTOR_TYPE_ANY, False))
self.addParameter(ParameterString(self.FIELD_NAME, "Field name"))
self.addParameter(ParameterSelection(self.FIELD_TYPE, "Field type", self.TYPE_NAMES))
self.addOutput(OutputVector(self.OUTPUT_LAYER, "Output layer"))

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() )
inFeat = QgsFeature()
outFeat = QgsFeature()
inGeom = QgsGeometry()
nFeat = vprovider.featureCount()
nElement = 0
while vprovider.nextFeature(inFeat):
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
from sextante.core.GeoAlgorithm import GeoAlgorithm
from sextante.outputs.OutputVector import OutputVector
from sextante.parameters.ParameterVector import ParameterVector
from qgis.core import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from sextante.parameters.ParameterString import ParameterString
from sextante.parameters.ParameterSelection import ParameterSelection
from sextante.core.QGisLayers import QGisLayers
import os
from PyQt4 import QtGui


class AddTableField(GeoAlgorithm):

OUTPUT_LAYER = "OUTPUT_LAYER"
INPUT_LAYER = "INPUT_LAYER"
FIELD_NAME = "FIELD_NAME"
FIELD_TYPE = "FIELD_TYPE"
TYPE_NAMES = ["Integer", "Float", "String"]
TYPES = [QVariant.Int, QVariant.Double, QVariant.String]

def getIcon(self):
return QtGui.QIcon(os.path.dirname(__file__) + "/../images/toolbox.png")

def defineCharacteristics(self):
self.name = "Add field to attributes table"
self.group = "Algorithms for vector layers"
self.addParameter(ParameterVector(self.INPUT_LAYER, "Input layer", ParameterVector.VECTOR_TYPE_ANY, False))
self.addParameter(ParameterString(self.FIELD_NAME, "Field name"))
self.addParameter(ParameterSelection(self.FIELD_TYPE, "Field type", self.TYPE_NAMES))
self.addOutput(OutputVector(self.OUTPUT_LAYER, "Output layer"))

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() )
inFeat = QgsFeature()
outFeat = QgsFeature()
inGeom = QgsGeometry()
nFeat = vprovider.featureCount()
nElement = 0
while vprovider.nextFeature(inFeat):
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

96 changes: 48 additions & 48 deletions python/plugins/sextante/algs/AutoincrementalField.py
Original file line number Diff line number Diff line change
@@ -1,48 +1,48 @@
from sextante.core.GeoAlgorithm import GeoAlgorithm
from PyQt4.QtCore import *
from qgis.core import *
from sextante.parameters.ParameterVector import ParameterVector
from sextante.core.QGisLayers import QGisLayers
from sextante.outputs.OutputVector import OutputVector
import os
from PyQt4 import QtGui

class AutoincrementalField(GeoAlgorithm):

INPUT = "INPUT"
OUTPUT = "OUTPUT"

def getIcon(self):
return QtGui.QIcon(os.path.dirname(__file__) + "/../images/toolbox.png")

def processAlgorithm(self, progress):
output = self.getOutputFromName(self.OUTPUT)
vlayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT))
vprovider = vlayer.dataProvider()
allAttrs = vprovider.attributeIndexes()
vprovider.select( allAttrs )
fields = vprovider.fields()
fields[len(fields)] = QgsField("AUTO", QVariant.Int)
writer = output.getVectorWriter(fields, vprovider.geometryType(), vprovider.crs() )
inFeat = QgsFeature()
outFeat = QgsFeature()
inGeom = QgsGeometry()
nFeat = vprovider.featureCount()
nElement = 0
while vprovider.nextFeature(inFeat):
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(nElement) )
writer.addFeature( outFeat )
del writer

def defineCharacteristics(self):
self.name = "Add autoincremental field"
self.group = "Algorithms for vector layers"
self.addParameter(ParameterVector(self.INPUT, "Input layer", ParameterVector.VECTOR_TYPE_ANY))
self.addOutput(OutputVector(self.OUTPUT, "Output layer"))
from sextante.core.GeoAlgorithm import GeoAlgorithm
from PyQt4.QtCore import *
from qgis.core import *
from sextante.parameters.ParameterVector import ParameterVector
from sextante.core.QGisLayers import QGisLayers
from sextante.outputs.OutputVector import OutputVector
import os
from PyQt4 import QtGui

class AutoincrementalField(GeoAlgorithm):

INPUT = "INPUT"
OUTPUT = "OUTPUT"

def getIcon(self):
return QtGui.QIcon(os.path.dirname(__file__) + "/../images/toolbox.png")

def processAlgorithm(self, progress):
output = self.getOutputFromName(self.OUTPUT)
vlayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT))
vprovider = vlayer.dataProvider()
allAttrs = vprovider.attributeIndexes()
vprovider.select( allAttrs )
fields = vprovider.fields()
fields[len(fields)] = QgsField("AUTO", QVariant.Int)
writer = output.getVectorWriter(fields, vprovider.geometryType(), vprovider.crs() )
inFeat = QgsFeature()
outFeat = QgsFeature()
inGeom = QgsGeometry()
nFeat = vprovider.featureCount()
nElement = 0
while vprovider.nextFeature(inFeat):
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(nElement) )
writer.addFeature( outFeat )
del writer

def defineCharacteristics(self):
self.name = "Add autoincremental field"
self.group = "Algorithms for vector layers"
self.addParameter(ParameterVector(self.INPUT, "Input layer", ParameterVector.VECTOR_TYPE_ANY))
self.addOutput(OutputVector(self.OUTPUT, "Output layer"))

120 changes: 60 additions & 60 deletions python/plugins/sextante/algs/EquivalentNumField.py
Original file line number Diff line number Diff line change
@@ -1,60 +1,60 @@
from sextante.core.GeoAlgorithm import GeoAlgorithm
from PyQt4.QtCore import *
from qgis.core import *
from sextante.parameters.ParameterVector import ParameterVector
from sextante.core.QGisLayers import QGisLayers
from sextante.outputs.OutputVector import OutputVector
import os
from PyQt4 import QtGui
from sextante.parameters.ParameterTableField import ParameterTableField

class AutoincrementalField(GeoAlgorithm):

INPUT = "INPUT"
OUTPUT = "OUTPUT"
FIELD = "FIELD"

def getIcon(self):
return QtGui.QIcon(os.path.dirname(__file__) + "/../images/toolbox.png")

def processAlgorithm(self, progress):
field_index = self.getParameterValue(self.FIELD)
output = self.getOutputFromName(self.OUTPUT)
vlayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT))
vprovider = vlayer.dataProvider()
allAttrs = vprovider.attributeIndexes()
vprovider.select( allAttrs )
fields = vprovider.fields()
fields[len(fields)] = QgsField("NUM_FIELD", QVariant.Int)
writer = output.getVectorWriter(fields, vprovider.geometryType(), vprovider.crs() )
inFeat = QgsFeature()
outFeat = QgsFeature()
inGeom = QgsGeometry()
nFeat = vprovider.featureCount()
nElement = 0
classes = {}
while vprovider.nextFeature(inFeat):
progress.setPercentage(int((100 * nElement)/nFeat))
nElement += 1
atMap = inFeat.attributeMap()
clazz = atMap[field_index]
if not clazz in classes.keys:
classes[clazz] = len(classes.keys())
while vprovider.nextFeature(inFeat):
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(nElement) )
writer.addFeature( outFeat )
del writer

def defineCharacteristics(self):
self.name = "Add autoincremental field"
self.group = "Algorithms for vector layers"
self.addParameter(ParameterVector(self.INPUT, "Input layer", ParameterVector.VECTOR_TYPE_ANY))
self.addParameter(ParameterTableField(self.FIELD, "Unique ID Field", self.INPUT))
self.addOutput(OutputVector(self.OUTPUT, "Output layer"))
from sextante.core.GeoAlgorithm import GeoAlgorithm
from PyQt4.QtCore import *
from qgis.core import *
from sextante.parameters.ParameterVector import ParameterVector
from sextante.core.QGisLayers import QGisLayers
from sextante.outputs.OutputVector import OutputVector
import os
from PyQt4 import QtGui
from sextante.parameters.ParameterTableField import ParameterTableField

class AutoincrementalField(GeoAlgorithm):

INPUT = "INPUT"
OUTPUT = "OUTPUT"
FIELD = "FIELD"

def getIcon(self):
return QtGui.QIcon(os.path.dirname(__file__) + "/../images/toolbox.png")

def processAlgorithm(self, progress):
field_index = self.getParameterValue(self.FIELD)
output = self.getOutputFromName(self.OUTPUT)
vlayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT))
vprovider = vlayer.dataProvider()
allAttrs = vprovider.attributeIndexes()
vprovider.select( allAttrs )
fields = vprovider.fields()
fields[len(fields)] = QgsField("NUM_FIELD", QVariant.Int)
writer = output.getVectorWriter(fields, vprovider.geometryType(), vprovider.crs() )
inFeat = QgsFeature()
outFeat = QgsFeature()
inGeom = QgsGeometry()
nFeat = vprovider.featureCount()
nElement = 0
classes = {}
while vprovider.nextFeature(inFeat):
progress.setPercentage(int((100 * nElement)/nFeat))
nElement += 1
atMap = inFeat.attributeMap()
clazz = atMap[field_index]
if not clazz in classes.keys:
classes[clazz] = len(classes.keys())
while vprovider.nextFeature(inFeat):
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(nElement) )
writer.addFeature( outFeat )
del writer

def defineCharacteristics(self):
self.name = "Add autoincremental field"
self.group = "Algorithms for vector layers"
self.addParameter(ParameterVector(self.INPUT, "Input layer", ParameterVector.VECTOR_TYPE_ANY))
self.addParameter(ParameterTableField(self.FIELD, "Unique ID Field", self.INPUT))
self.addOutput(OutputVector(self.OUTPUT, "Output layer"))

138 changes: 69 additions & 69 deletions python/plugins/sextante/algs/Explode.py
Original file line number Diff line number Diff line change
@@ -1,69 +1,69 @@
from sextante.core.GeoAlgorithm import GeoAlgorithm
import os.path
from PyQt4 import QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from sextante.parameters.ParameterVector import ParameterVector
from sextante.core.QGisLayers import QGisLayers
from sextante.outputs.OutputVector import OutputVector

class Explode(GeoAlgorithm):

INPUT = "INPUT"
OUTPUT = "OUTPUT"

def getIcon(self):
return QtGui.QIcon(os.path.dirname(__file__) + "/../images/toolbox.png")

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
while vprovider.nextFeature( inFeat ):
nElement += 1
progress.setPercentage((nElement*100)/nFeat)
inGeom = inFeat.geometry()
atMap = inFeat.attributeMap()
segments = self.extractAsSingleSegments( inGeom )
outFeat.setAttributeMap( atMap )
for segment in segments:
outFeat.setGeometry(segment)
writer.addFeature(outFeat)
del writer


def extractAsSingleSegments( self, geom ):
segments = []
if geom.isMultipart():
multi = geom.asMultiPolyline()
for polyline in multi:
segments.extend( self.getPolylineAsSingleSegments(polyline))
else:
segments.extend( self.getPolylineAsSingleSegments(geom.asPolyline()))
return segments

def getPolylineAsSingleSegments(self, polyline):
segments = []
for i in range(len(polyline)-1):
ptA = polyline[i]
ptB = polyline[i+1]
segment = QgsGeometry.fromPolyline([ptA, ptB])
segments.append(segment)
return segments

def defineCharacteristics(self):
self.name = "Explode lines"
self.group = "Algorithms for vector layers"
self.addParameter(ParameterVector(self.INPUT, "Input layer",ParameterVector.VECTOR_TYPE_LINE))
self.addOutput(OutputVector(self.OUTPUT, "Output layer"))
from sextante.core.GeoAlgorithm import GeoAlgorithm
import os.path
from PyQt4 import QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from sextante.parameters.ParameterVector import ParameterVector
from sextante.core.QGisLayers import QGisLayers
from sextante.outputs.OutputVector import OutputVector

class Explode(GeoAlgorithm):

INPUT = "INPUT"
OUTPUT = "OUTPUT"

def getIcon(self):
return QtGui.QIcon(os.path.dirname(__file__) + "/../images/toolbox.png")

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
while vprovider.nextFeature( inFeat ):
nElement += 1
progress.setPercentage((nElement*100)/nFeat)
inGeom = inFeat.geometry()
atMap = inFeat.attributeMap()
segments = self.extractAsSingleSegments( inGeom )
outFeat.setAttributeMap( atMap )
for segment in segments:
outFeat.setGeometry(segment)
writer.addFeature(outFeat)
del writer


def extractAsSingleSegments( self, geom ):
segments = []
if geom.isMultipart():
multi = geom.asMultiPolyline()
for polyline in multi:
segments.extend( self.getPolylineAsSingleSegments(polyline))
else:
segments.extend( self.getPolylineAsSingleSegments(geom.asPolyline()))
return segments

def getPolylineAsSingleSegments(self, polyline):
segments = []
for i in range(len(polyline)-1):
ptA = polyline[i]
ptB = polyline[i+1]
segment = QgsGeometry.fromPolyline([ptA, ptB])
segments.append(segment)
return segments

def defineCharacteristics(self):
self.name = "Explode lines"
self.group = "Algorithms for vector layers"
self.addParameter(ParameterVector(self.INPUT, "Input layer",ParameterVector.VECTOR_TYPE_LINE))
self.addOutput(OutputVector(self.OUTPUT, "Output layer"))

428 changes: 214 additions & 214 deletions python/plugins/sextante/algs/FieldPyculator.py

Large diffs are not rendered by default.

142 changes: 71 additions & 71 deletions python/plugins/sextante/algs/FieldsCalculator.py
Original file line number Diff line number Diff line change
@@ -1,71 +1,71 @@
from sextante.core.GeoAlgorithm import GeoAlgorithm
from sextante.outputs.OutputVector import OutputVector
from sextante.parameters.ParameterVector import ParameterVector
from qgis.core import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from sextante.parameters.ParameterString import ParameterString
from sextante.core.QGisLayers import QGisLayers
import os
from PyQt4 import QtGui
from sextante.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException


class FieldsCalculator(GeoAlgorithm):

INPUT_LAYER = "INPUT_LAYER"
FIELD_NAME = "FIELD_NAME"
FORMULA = "FORMULA"
OUTPUT_LAYER ="OUTPUT_LAYER"

def getIcon(self):
return QtGui.QIcon(os.path.dirname(__file__) + "/../images/toolbox.png")

def defineCharacteristics(self):
self.name = "Field calculator"
self.group = "Algorithms for vector layers"
self.addParameter(ParameterVector(self.INPUT_LAYER, "Input layer", ParameterVector.VECTOR_TYPE_ANY, False))
self.addParameter(ParameterString(self.FIELD_NAME, "Result field name"))
self.addParameter(ParameterString(self.FORMULA, "Formula"))
self.addOutput(OutputVector(self.OUTPUT_LAYER, "Output layer"))

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() )
inFeat = QgsFeature()
outFeat = QgsFeature()
inGeom = QgsGeometry()
nFeat = vprovider.featureCount()
nElement = 0
while vprovider.nextFeature(inFeat):
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 checkParameterValuesBeforeExecuting(self):
##TODO check that formula is correct and fields exist
pass
from sextante.core.GeoAlgorithm import GeoAlgorithm
from sextante.outputs.OutputVector import OutputVector
from sextante.parameters.ParameterVector import ParameterVector
from qgis.core import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from sextante.parameters.ParameterString import ParameterString
from sextante.core.QGisLayers import QGisLayers
import os
from PyQt4 import QtGui
from sextante.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException


class FieldsCalculator(GeoAlgorithm):

INPUT_LAYER = "INPUT_LAYER"
FIELD_NAME = "FIELD_NAME"
FORMULA = "FORMULA"
OUTPUT_LAYER ="OUTPUT_LAYER"

def getIcon(self):
return QtGui.QIcon(os.path.dirname(__file__) + "/../images/toolbox.png")

def defineCharacteristics(self):
self.name = "Field calculator"
self.group = "Algorithms for vector layers"
self.addParameter(ParameterVector(self.INPUT_LAYER, "Input layer", ParameterVector.VECTOR_TYPE_ANY, False))
self.addParameter(ParameterString(self.FIELD_NAME, "Result field name"))
self.addParameter(ParameterString(self.FORMULA, "Formula"))
self.addOutput(OutputVector(self.OUTPUT_LAYER, "Output layer"))

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() )
inFeat = QgsFeature()
outFeat = QgsFeature()
inGeom = QgsGeometry()
nFeat = vprovider.featureCount()
nElement = 0
while vprovider.nextFeature(inFeat):
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 checkParameterValuesBeforeExecuting(self):
##TODO check that formula is correct and fields exist
pass

152 changes: 76 additions & 76 deletions python/plugins/sextante/algs/SaveSelectedFeatures.py
Original file line number Diff line number Diff line change
@@ -1,76 +1,76 @@
from sextante.core.GeoAlgorithm import GeoAlgorithm
from sextante.outputs.OutputVector import OutputVector
from sextante.parameters.ParameterVector import ParameterVector
from qgis.core import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from sextante.core.QGisLayers import QGisLayers
import os


class SaveSelectedFeatures(GeoAlgorithm):
'''This is an example algorithm that takes a vector layer and creates
a new one just with just those features of the input layer that are
selected.
It is meant to be used as an example of how to create your own SEXTANTE
algorithms and explain methods and variables used to do it.
An algorithm like this will be available in all SEXTANTE elements, and
there is not need for additional work.
All SEXTANTE algorithms should extend the GeoAlgorithm class'''

#constants used to refer to parameters and outputs.
#They will be used when calling the algorithm from another algorithm,
#or when calling SEXTANTE from the QGIS console.
OUTPUT_LAYER = "OUTPUT_LAYER"
INPUT_LAYER = "INPUT_LAYER"

def defineCharacteristics(self):
'''Here we define the inputs and output of the algorithm, along
with some other properties'''

#the name that the user will see in the toolbox
self.name = "Create new layer with selected features"

#the branch of the toolbox under which the algorithm will appear
self.group = "Algorithms for vector layers"

#we add the input vector layer. It can have any kind of geometry
#It is a mandatory (not optional) one, hence the False argument
self.addParameter(ParameterVector(self.INPUT_LAYER, "Input layer", ParameterVector.VECTOR_TYPE_ANY, False))
# we add a vector layer as output
self.addOutput(OutputVector(self.OUTPUT_LAYER, "Output layer with selected features"))

def getIcon(self):
return QIcon(os.path.dirname(__file__) + "/../images/toolbox.png")

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
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
from sextante.core.GeoAlgorithm import GeoAlgorithm
from sextante.outputs.OutputVector import OutputVector
from sextante.parameters.ParameterVector import ParameterVector
from qgis.core import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from sextante.core.QGisLayers import QGisLayers
import os


class SaveSelectedFeatures(GeoAlgorithm):
'''This is an example algorithm that takes a vector layer and creates
a new one just with just those features of the input layer that are
selected.
It is meant to be used as an example of how to create your own SEXTANTE
algorithms and explain methods and variables used to do it.
An algorithm like this will be available in all SEXTANTE elements, and
there is not need for additional work.
All SEXTANTE algorithms should extend the GeoAlgorithm class'''

#constants used to refer to parameters and outputs.
#They will be used when calling the algorithm from another algorithm,
#or when calling SEXTANTE from the QGIS console.
OUTPUT_LAYER = "OUTPUT_LAYER"
INPUT_LAYER = "INPUT_LAYER"

def defineCharacteristics(self):
'''Here we define the inputs and output of the algorithm, along
with some other properties'''

#the name that the user will see in the toolbox
self.name = "Create new layer with selected features"

#the branch of the toolbox under which the algorithm will appear
self.group = "Algorithms for vector layers"

#we add the input vector layer. It can have any kind of geometry
#It is a mandatory (not optional) one, hence the False argument
self.addParameter(ParameterVector(self.INPUT_LAYER, "Input layer", ParameterVector.VECTOR_TYPE_ANY, False))
# we add a vector layer as output
self.addOutput(OutputVector(self.OUTPUT_LAYER, "Output layer with selected features"))

def getIcon(self):
return QIcon(os.path.dirname(__file__) + "/../images/toolbox.png")

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
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
76 changes: 38 additions & 38 deletions python/plugins/sextante/algs/SextanteAlgorithmProvider.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,39 @@
from sextante.core.AlgorithmProvider import AlgorithmProvider
from sextante.algs.AddTableField import AddTableField
from PyQt4 import QtGui
import os
from sextante.algs.FieldsCalculator import FieldsCalculator
from sextante.algs.SaveSelectedFeatures import SaveSelectedFeatures
from sextante.algs.Explode import Explode
from sextante.algs.AutoincrementalField import AutoincrementalField
from sextante.algs.FieldPyculator import FieldsPyculator

class SextanteAlgorithmProvider(AlgorithmProvider):

def __init__(self):
AlgorithmProvider.__init__(self)
self.alglist = [AddTableField(), FieldsCalculator(), SaveSelectedFeatures(),
AutoincrementalField(), Explode(), FieldsPyculator()]

def initializeSettings(self):
AlgorithmProvider.initializeSettings(self)


def unload(self):
AlgorithmProvider.unload(self)


def getName(self):
return "sextante"

def getDescription(self):
return "SEXTANTE geoalgorithms"

def getIcon(self):
return QtGui.QIcon(os.path.dirname(__file__) + "/../images/toolbox.png")

def _loadAlgorithms(self):
self.algs = self.alglist

def supportsNonFileBasedOutput(self):
from sextante.core.AlgorithmProvider import AlgorithmProvider
from sextante.algs.AddTableField import AddTableField
from PyQt4 import QtGui
import os
from sextante.algs.FieldsCalculator import FieldsCalculator
from sextante.algs.SaveSelectedFeatures import SaveSelectedFeatures
from sextante.algs.Explode import Explode
from sextante.algs.AutoincrementalField import AutoincrementalField
from sextante.algs.FieldPyculator import FieldsPyculator

class SextanteAlgorithmProvider(AlgorithmProvider):

def __init__(self):
AlgorithmProvider.__init__(self)
self.alglist = [AddTableField(), FieldsCalculator(), SaveSelectedFeatures(),
AutoincrementalField(), Explode(), FieldsPyculator()]

def initializeSettings(self):
AlgorithmProvider.initializeSettings(self)


def unload(self):
AlgorithmProvider.unload(self)


def getName(self):
return "sextante"

def getDescription(self):
return "SEXTANTE geoalgorithms"

def getIcon(self):
return QtGui.QIcon(os.path.dirname(__file__) + "/../images/toolbox.png")

def _loadAlgorithms(self):
self.algs = self.alglist

def supportsNonFileBasedOutput(self):
return True
170 changes: 85 additions & 85 deletions python/plugins/sextante/core/AlgorithmProvider.py
Original file line number Diff line number Diff line change
@@ -1,86 +1,86 @@
from sextante.core.SextanteConfig import Setting, SextanteConfig
import os
from PyQt4 import QtGui
from qgis.core import *

class AlgorithmProvider():
'''this is the base class for algorithms providers.
An algorithm provider is a set of related algorithms, typically from the same
external application or related to a common area of analysis.
'''

def __init__(self):
#indicates if the provider should be active by default.
#For provider relying on an external software, this should be
#false, so the user should activate them manually and install
#the required software in advance.
self.activate = True
self.actions = []
self.contextMenuActions = []


def loadAlgorithms(self):
self.algs = []
name = "ACTIVATE_" + self.getName().upper().replace(" ", "_")
if not SextanteConfig.getSetting(name):
return
else:
self._loadAlgorithms()
for alg in self.algs:
alg.provider = self

#methods to be overridden.
#==============================

def _loadAlgorithms(self):
'''Algorithm loading should take place here, filling self.algs, which is a list of
elements of class GeoAlgorithm. Use that class to create your own algorithms'''
pass

def initializeSettings(self):
'''this is the place where you should add config parameters to SEXTANTE using the SextanteConfig class.
this method is called when a provider is added to SEXTANTE.
By default it just adds a setting to activate or deactivate algorithms from the provider'''
SextanteConfig.settingIcons[self.getDescription()] = self.getIcon()
name = "ACTIVATE_" + self.getName().upper().replace(" ", "_")
SextanteConfig.addSetting(Setting(self.getDescription(), name, "Activate", self.activate))

def unload(self):
'''Do here anything that you want to be done when the provider is removed from the list of available ones.
This method is called when you remove the provider from Sextante.
Removal of config setting should be done here'''
name = "ACTIVATE_" + self.getName().upper().replace(" ", "_")
SextanteConfig.removeSetting(name)

def getName(self):
'''Returns the name to use to create the command-line name. Should be a short descriptive name of the provider'''
return "sextante"

def getDescription(self):
'''Returns the full name of the provider'''
return "Generic algorithm provider"


def getIcon(self):
return QtGui.QIcon(os.path.dirname(__file__) + "/../images/alg.png")

def getSupportedOutputRasterLayerExtensions(self):
return ["tif"]

def getSupportedOutputVectorLayerExtensions(self):
formats = QgsVectorFileWriter.supportedFiltersAndFormats()
extensions = ["shp"]#shp is the default, should be the first
for extension in formats.keys():
extension = str(extension)
extension = extension[extension.find('*.') + 2:]
extension = extension[:extension.find(" ")]
if extension.lower() != "shp":
extensions.append(extension)
return extensions
#return ["shp"]

def getSupportedOutputTableExtensions(self):
return ["dbf"]

def supportsNonFileBasedOutput(self):
from sextante.core.SextanteConfig import Setting, SextanteConfig
import os
from PyQt4 import QtGui
from qgis.core import *

class AlgorithmProvider():
'''this is the base class for algorithms providers.
An algorithm provider is a set of related algorithms, typically from the same
external application or related to a common area of analysis.
'''

def __init__(self):
#indicates if the provider should be active by default.
#For provider relying on an external software, this should be
#false, so the user should activate them manually and install
#the required software in advance.
self.activate = True
self.actions = []
self.contextMenuActions = []


def loadAlgorithms(self):
self.algs = []
name = "ACTIVATE_" + self.getName().upper().replace(" ", "_")
if not SextanteConfig.getSetting(name):
return
else:
self._loadAlgorithms()
for alg in self.algs:
alg.provider = self

#methods to be overridden.
#==============================

def _loadAlgorithms(self):
'''Algorithm loading should take place here, filling self.algs, which is a list of
elements of class GeoAlgorithm. Use that class to create your own algorithms'''
pass

def initializeSettings(self):
'''this is the place where you should add config parameters to SEXTANTE using the SextanteConfig class.
this method is called when a provider is added to SEXTANTE.
By default it just adds a setting to activate or deactivate algorithms from the provider'''
SextanteConfig.settingIcons[self.getDescription()] = self.getIcon()
name = "ACTIVATE_" + self.getName().upper().replace(" ", "_")
SextanteConfig.addSetting(Setting(self.getDescription(), name, "Activate", self.activate))

def unload(self):
'''Do here anything that you want to be done when the provider is removed from the list of available ones.
This method is called when you remove the provider from Sextante.
Removal of config setting should be done here'''
name = "ACTIVATE_" + self.getName().upper().replace(" ", "_")
SextanteConfig.removeSetting(name)

def getName(self):
'''Returns the name to use to create the command-line name. Should be a short descriptive name of the provider'''
return "sextante"

def getDescription(self):
'''Returns the full name of the provider'''
return "Generic algorithm provider"


def getIcon(self):
return QtGui.QIcon(os.path.dirname(__file__) + "/../images/alg.png")

def getSupportedOutputRasterLayerExtensions(self):
return ["tif"]

def getSupportedOutputVectorLayerExtensions(self):
formats = QgsVectorFileWriter.supportedFiltersAndFormats()
extensions = ["shp"]#shp is the default, should be the first
for extension in formats.keys():
extension = str(extension)
extension = extension[extension.find('*.') + 2:]
extension = extension[:extension.find(" ")]
if extension.lower() != "shp":
extensions.append(extension)
return extensions
#return ["shp"]

def getSupportedOutputTableExtensions(self):
return ["dbf"]

def supportsNonFileBasedOutput(self):
return False
552 changes: 276 additions & 276 deletions python/plugins/sextante/core/GeoAlgorithm.py

Large diffs are not rendered by default.

10 changes: 5 additions & 5 deletions python/plugins/sextante/core/GeoAlgorithmExecutionException.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
class GeoAlgorithmExecutionException(Exception):

def __init__(self, msg):
Exception.__init__(self)
self.msg = msg
class GeoAlgorithmExecutionException(Exception):

def __init__(self, msg):
Exception.__init__(self)
self.msg = msg
134 changes: 67 additions & 67 deletions python/plugins/sextante/core/LayerExporter.py
Original file line number Diff line number Diff line change
@@ -1,67 +1,67 @@
from sextante.core.SextanteConfig import SextanteConfig
from sextante.core.SextanteUtils import SextanteUtils
from qgis.core import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from sextante.gdal.GdalUtils import GdalUtils

class LayerExporter():

'''This class provides method to export layers so they can be used by third party applications.
These method are used by the GeoAlgorithm class and allow the developer to use transparently
any layer that is loaded into QGIS, without having to worry about its origin'''

@staticmethod
def exportVectorLayer(layer):
'''Takes a QgsVectorLayer and returns the filename to refer to it, which allows external
apps which support only file-based layers to use it. It performs the necessary export
in case the input layer is not in a standard format suitable for most applications, it is
a remote one or db-based (non-file based) one, or if there is a selection and it should be
used, exporting just the selected features.
Currently, the output is restricted to shapefiles, so anything that is not in a shapefile
will get exported'''
settings = QSettings()
systemEncoding = settings.value( "/UI/encoding", "System" ).toString()
output = SextanteUtils.getTempFilename("shp")
provider = layer.dataProvider()
allAttrs = provider.attributeIndexes()
provider.select( allAttrs )
useSelection = SextanteConfig.getSetting(SextanteConfig.USE_SELECTED)
if useSelection and layer.selectedFeatureCount() != 0:
writer = QgsVectorFileWriter( output, systemEncoding,provider.fields(), provider.geometryType(), provider.crs() )
selection = layer.selectedFeatures()
for feat in selection:
writer.addFeature(feat)
del writer
return output
else:
if (not unicode(layer.source()).endswith("shp")):
writer = QgsVectorFileWriter( output, systemEncoding,provider.fields(), provider.geometryType(), provider.crs() )
feat = QgsFeature()
while provider.nextFeature(feat):
writer.addFeature(feat)
del writer
return output
else:
return unicode(layer.source())



@staticmethod
def exportRasterLayer(layer):
'''Takes a QgsRasterLayer and returns the filename to refer to it, which allows external
apps which support only file-based layers to use it. It performs the necessary export
in case the input layer is not in a standard format suitable for most applications, it is
a remote one or db-based (non-file based) one
Currently, the output is restricted to geotiff, but not all other formats are exported.
Only those formats not supported by GDAL are exported, so it is assumed that the external
app uses GDAL to read the layer'''
exts = GdalUtils.getSupportedRasterExtensions()
for ext in exts:
if (unicode(layer.source()).endswith(ext)):
return unicode(layer.source())

#TODO:Do the conversion here
return unicode(layer.source())

from sextante.core.SextanteConfig import SextanteConfig
from sextante.core.SextanteUtils import SextanteUtils
from qgis.core import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from sextante.gdal.GdalUtils import GdalUtils

class LayerExporter():

'''This class provides method to export layers so they can be used by third party applications.
These method are used by the GeoAlgorithm class and allow the developer to use transparently
any layer that is loaded into QGIS, without having to worry about its origin'''

@staticmethod
def exportVectorLayer(layer):
'''Takes a QgsVectorLayer and returns the filename to refer to it, which allows external
apps which support only file-based layers to use it. It performs the necessary export
in case the input layer is not in a standard format suitable for most applications, it is
a remote one or db-based (non-file based) one, or if there is a selection and it should be
used, exporting just the selected features.
Currently, the output is restricted to shapefiles, so anything that is not in a shapefile
will get exported'''
settings = QSettings()
systemEncoding = settings.value( "/UI/encoding", "System" ).toString()
output = SextanteUtils.getTempFilename("shp")
provider = layer.dataProvider()
allAttrs = provider.attributeIndexes()
provider.select( allAttrs )
useSelection = SextanteConfig.getSetting(SextanteConfig.USE_SELECTED)
if useSelection and layer.selectedFeatureCount() != 0:
writer = QgsVectorFileWriter( output, systemEncoding,provider.fields(), provider.geometryType(), provider.crs() )
selection = layer.selectedFeatures()
for feat in selection:
writer.addFeature(feat)
del writer
return output
else:
if (not unicode(layer.source()).endswith("shp")):
writer = QgsVectorFileWriter( output, systemEncoding,provider.fields(), provider.geometryType(), provider.crs() )
feat = QgsFeature()
while provider.nextFeature(feat):
writer.addFeature(feat)
del writer
return output
else:
return unicode(layer.source())



@staticmethod
def exportRasterLayer(layer):
'''Takes a QgsRasterLayer and returns the filename to refer to it, which allows external
apps which support only file-based layers to use it. It performs the necessary export
in case the input layer is not in a standard format suitable for most applications, it is
a remote one or db-based (non-file based) one
Currently, the output is restricted to geotiff, but not all other formats are exported.
Only those formats not supported by GDAL are exported, so it is assumed that the external
app uses GDAL to read the layer'''
exts = GdalUtils.getSupportedRasterExtensions()
for ext in exts:
if (unicode(layer.source()).endswith(ext)):
return unicode(layer.source())

#TODO:Do the conversion here
return unicode(layer.source())


308 changes: 154 additions & 154 deletions python/plugins/sextante/core/QGisLayers.py
Original file line number Diff line number Diff line change
@@ -1,154 +1,154 @@
from qgis.core import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import QtGui
from os import path
from sextante.core.SextanteConfig import SextanteConfig

class QGisLayers:
'''This class contains method to communicate SEXTANTE with the QGIS interface,
mostly for retrieving layers and adding new ones to the QGIS canvas'''

ALL_TYPES = -1
iface = None;

@staticmethod
def getRasterLayers():
layers = QGisLayers.iface.legendInterface().layers()
raster = list()

for layer in layers:
if layer.type() == layer.RasterLayer:
if layer.usesProvider() and layer.providerKey() == 'gdal':#only gdal file-based layers
raster.append(layer)
return raster

@staticmethod
def getVectorLayers(shapetype=-1):
layers = QGisLayers.iface.legendInterface().layers()
vector = list()
for layer in layers:
if layer.type() == layer.VectorLayer:
if shapetype == QGisLayers.ALL_TYPES or layer.geometryType() == shapetype:
uri = unicode(layer.source())
if not uri.endswith("csv") and not uri.endswith("dbf"):
vector.append(layer)
return vector

@staticmethod
def getAllLayers():
layers = []
layers += QGisLayers.getRasterLayers();
layers += QGisLayers.getVectorLayers();
return layers

@staticmethod
def getTables():
layers = QGisLayers.iface.legendInterface().layers()
tables = list()
for layer in layers:
if layer.type() == layer.VectorLayer :
uri = unicode(layer.source())
if uri.endswith("csv") or uri.endswith("dbf"):
tables.append(layer)
return tables

@staticmethod
def setInterface(iface):
QGisLayers.iface = iface


@staticmethod
def loadList(layers):
for layer in layers:
QGisLayers.load(layer)

@staticmethod
def load(layer, name = None, crs = None, style = None):
if layer == None:
return
prjSetting = None
settings = QSettings()
if crs != None:
prjSetting = settings.value("/Projections/defaultBehaviour")
settings.setValue("/Projections/defaultBehaviour", QVariant(""))
if name == None:
name = path.split(layer)[1]
qgslayer = QgsVectorLayer(layer, name , 'ogr')
if qgslayer.isValid():
if crs != None:
qgslayer.setCrs(crs,False)
if style == None:
if qgslayer.geometryType == 0:
style = SextanteConfig.getSetting(SextanteConfig.VECTOR_POINT_STYLE)
elif qgslayer.geometryType == 1:
style = SextanteConfig.getSetting(SextanteConfig.VECTOR_LINE_STYLE)
else:
style = SextanteConfig.getSetting(SextanteConfig.VECTOR_POLYGON_STYLE)
qgslayer.loadNamedStyle(style)
QgsMapLayerRegistry.instance().addMapLayer(qgslayer)
else:
qgslayer = QgsRasterLayer(layer, name)
if qgslayer.isValid():
if crs != None:
qgslayer.setCrs(crs,False)
if style == None:
style = SextanteConfig.getSetting(SextanteConfig.RASTER_STYLE)
qgslayer.loadNamedStyle(style)
QgsMapLayerRegistry.instance().addMapLayer(qgslayer)
QGisLayers.iface.legendInterface().refreshLayerSymbology(qgslayer)
else:
if prjSetting:
settings.setValue("/Projections/defaultBehaviour", prjSetting)
raise RuntimeError("Could not load layer: " + unicode(layer)
+"\nCheck the SEXTANTE log to look for errors in algorithm execution")
if prjSetting:
settings.setValue("/Projections/defaultBehaviour", prjSetting)


@staticmethod
def loadFromDict(layersdict, crs):
for name in layersdict.keys():
QGisLayers.load(layersdict[name], name, crs)


@staticmethod
def getObjectFromUri(uri, forceLoad = True):
if uri is None:
return None
layers = QGisLayers.getRasterLayers()
for layer in layers:
if layer.source() == uri:
return layer
layers = QGisLayers.getVectorLayers()
for layer in layers:
if layer.source() == uri:
return layer
if forceLoad:
settings = QSettings()
prjSetting = settings.value("/Projections/defaultBehaviour")
settings.setValue("/Projections/defaultBehaviour", QVariant(""))
#if is not opened, we open it
layer = QgsVectorLayer(uri, uri , 'ogr')
if layer.isValid():
if prjSetting:
settings.setValue("/Projections/defaultBehaviour", prjSetting)
return layer
layer = QgsRasterLayer(uri, uri)
if layer.isValid():
if prjSetting:
settings.setValue("/Projections/defaultBehaviour", prjSetting)
return layer
if prjSetting:
settings.setValue("/Projections/defaultBehaviour", prjSetting)
else:
return None








from qgis.core import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import QtGui
from os import path
from sextante.core.SextanteConfig import SextanteConfig

class QGisLayers:
'''This class contains method to communicate SEXTANTE with the QGIS interface,
mostly for retrieving layers and adding new ones to the QGIS canvas'''

ALL_TYPES = -1
iface = None;

@staticmethod
def getRasterLayers():
layers = QGisLayers.iface.legendInterface().layers()
raster = list()

for layer in layers:
if layer.type() == layer.RasterLayer:
if layer.usesProvider() and layer.providerKey() == 'gdal':#only gdal file-based layers
raster.append(layer)
return raster

@staticmethod
def getVectorLayers(shapetype=-1):
layers = QGisLayers.iface.legendInterface().layers()
vector = list()
for layer in layers:
if layer.type() == layer.VectorLayer:
if shapetype == QGisLayers.ALL_TYPES or layer.geometryType() == shapetype:
uri = unicode(layer.source())
if not uri.endswith("csv") and not uri.endswith("dbf"):
vector.append(layer)
return vector

@staticmethod
def getAllLayers():
layers = []
layers += QGisLayers.getRasterLayers();
layers += QGisLayers.getVectorLayers();
return layers

@staticmethod
def getTables():
layers = QGisLayers.iface.legendInterface().layers()
tables = list()
for layer in layers:
if layer.type() == layer.VectorLayer :
uri = unicode(layer.source())
if uri.endswith("csv") or uri.endswith("dbf"):
tables.append(layer)
return tables

@staticmethod
def setInterface(iface):
QGisLayers.iface = iface


@staticmethod
def loadList(layers):
for layer in layers:
QGisLayers.load(layer)

@staticmethod
def load(layer, name = None, crs = None, style = None):
if layer == None:
return
prjSetting = None
settings = QSettings()
if crs != None:
prjSetting = settings.value("/Projections/defaultBehaviour")
settings.setValue("/Projections/defaultBehaviour", QVariant(""))
if name == None:
name = path.split(layer)[1]
qgslayer = QgsVectorLayer(layer, name , 'ogr')
if qgslayer.isValid():
if crs != None:
qgslayer.setCrs(crs,False)
if style == None:
if qgslayer.geometryType == 0:
style = SextanteConfig.getSetting(SextanteConfig.VECTOR_POINT_STYLE)
elif qgslayer.geometryType == 1:
style = SextanteConfig.getSetting(SextanteConfig.VECTOR_LINE_STYLE)
else:
style = SextanteConfig.getSetting(SextanteConfig.VECTOR_POLYGON_STYLE)
qgslayer.loadNamedStyle(style)
QgsMapLayerRegistry.instance().addMapLayer(qgslayer)
else:
qgslayer = QgsRasterLayer(layer, name)
if qgslayer.isValid():
if crs != None:
qgslayer.setCrs(crs,False)
if style == None:
style = SextanteConfig.getSetting(SextanteConfig.RASTER_STYLE)
qgslayer.loadNamedStyle(style)
QgsMapLayerRegistry.instance().addMapLayer(qgslayer)
QGisLayers.iface.legendInterface().refreshLayerSymbology(qgslayer)
else:
if prjSetting:
settings.setValue("/Projections/defaultBehaviour", prjSetting)
raise RuntimeError("Could not load layer: " + unicode(layer)
+"\nCheck the SEXTANTE log to look for errors in algorithm execution")
if prjSetting:
settings.setValue("/Projections/defaultBehaviour", prjSetting)


@staticmethod
def loadFromDict(layersdict, crs):
for name in layersdict.keys():
QGisLayers.load(layersdict[name], name, crs)


@staticmethod
def getObjectFromUri(uri, forceLoad = True):
if uri is None:
return None
layers = QGisLayers.getRasterLayers()
for layer in layers:
if layer.source() == uri:
return layer
layers = QGisLayers.getVectorLayers()
for layer in layers:
if layer.source() == uri:
return layer
if forceLoad:
settings = QSettings()
prjSetting = settings.value("/Projections/defaultBehaviour")
settings.setValue("/Projections/defaultBehaviour", QVariant(""))
#if is not opened, we open it
layer = QgsVectorLayer(uri, uri , 'ogr')
if layer.isValid():
if prjSetting:
settings.setValue("/Projections/defaultBehaviour", prjSetting)
return layer
layer = QgsRasterLayer(uri, uri)
if layer.isValid():
if prjSetting:
settings.setValue("/Projections/defaultBehaviour", prjSetting)
return layer
if prjSetting:
settings.setValue("/Projections/defaultBehaviour", prjSetting)
else:
return None









706 changes: 353 additions & 353 deletions python/plugins/sextante/core/Sextante.py

Large diffs are not rendered by default.

256 changes: 128 additions & 128 deletions python/plugins/sextante/core/SextanteConfig.py
Original file line number Diff line number Diff line change
@@ -1,128 +1,128 @@
from sextante.core.SextanteUtils import SextanteUtils
import os.path
from PyQt4 import QtGui

class SextanteConfig():

TABLE_LIKE_PARAM_PANEL = "TABLE_LIKE_PARAM_PANEL"
OUTPUT_FOLDER = "OUTPUT_FOLDER"
RASTER_STYLE = "RASTER_STYLE"
VECTOR_POINT_STYLE = "VECTOR_POINT_STYLE"
VECTOR_LINE_STYLE = "VECTOR_LINE_STYLE"
VECTOR_POLYGON_STYLE = "VECTOR_POLYGON_STYLE"
SHOW_RECENT_ALGORITHMS = "SHOW_RECENT_ALGORITHMS"
USE_SELECTED = "USE_SELECTED"
USE_FILENAME_AS_LAYER_NAME = "USE_FILENAME_AS_LAYER_NAME"
KEEP_DIALOG_OPEN = "KEEP_DIALOG_OPEN"
USE_THREADS = "USE_THREADS"
SHOW_DEBUG_IN_DIALOG = "SHOW_DEBUG_IN_DIALOG"
RECENT_ALGORITHMS = "RECENT_ALGORITHMS"

settings = {}
settingIcons= {}

@staticmethod
def initialize():
icon = QtGui.QIcon(os.path.dirname(__file__) + "/../images/alg.png")
SextanteConfig.settingIcons["General"] = icon
SextanteConfig.addSetting(Setting("General", SextanteConfig.USE_THREADS, "Run algorithms in a new thread (still unstable)", False))
SextanteConfig.addSetting(Setting("General", SextanteConfig.SHOW_DEBUG_IN_DIALOG, "Show debug information and commands executed in the execution dialog's Log panel (threaded execution only)", True))
SextanteConfig.addSetting(Setting("General", SextanteConfig.KEEP_DIALOG_OPEN, "Keep dialog open after running an algorithm", False))
SextanteConfig.addSetting(Setting("General", SextanteConfig.USE_SELECTED, "Use only selected features in external applications", True))
SextanteConfig.addSetting(Setting("General", SextanteConfig.TABLE_LIKE_PARAM_PANEL, "Show table-like parameter panels", False))
SextanteConfig.addSetting(Setting("General", SextanteConfig.USE_FILENAME_AS_LAYER_NAME, "Use filename as layer name", True))
SextanteConfig.addSetting(Setting("General", SextanteConfig.SHOW_RECENT_ALGORITHMS, "Show recently executed algorithms", True))
SextanteConfig.addSetting(Setting("General", SextanteConfig.OUTPUT_FOLDER,
"Output folder", SextanteUtils.tempFolder()))
SextanteConfig.addSetting(Setting("General", SextanteConfig.RASTER_STYLE,"Style for raster layers",""))
SextanteConfig.addSetting(Setting("General", SextanteConfig.VECTOR_POINT_STYLE,"Style for point layers",""))
SextanteConfig.addSetting(Setting("General", SextanteConfig.VECTOR_LINE_STYLE,"Style for line layers",""))
SextanteConfig.addSetting(Setting("General", SextanteConfig.VECTOR_POLYGON_STYLE,"Style for polygon layers",""))
SextanteConfig.addSetting(Setting("General", SextanteConfig.RECENT_ALGORITHMS,"Recent algs","", hidden=True))

@staticmethod
def setGroupIcon(group, icon):
SextanteConfig.settingIcons[group] = icon

@staticmethod
def getGroupIcon(group):
if group in SextanteConfig.settingIcons:
return SextanteConfig.settingIcons[group]
else:
return QtGui.QIcon(os.path.dirname(__file__) + "/../images/alg.png")

@staticmethod
def addSetting(setting):
SextanteConfig.settings[setting.name] = setting

@staticmethod
def removeSetting(name):
del SextanteConfig.settings[name]

@staticmethod
def getSettings():
settings={}
for setting in SextanteConfig.settings.values():
if not setting.group in settings:
group = []
settings[setting.group] = group
else:
group = settings[setting.group]
group.append(setting)
return settings

@staticmethod
def configFile():
return os.path.join(SextanteUtils.userFolder(), "sextante_qgis.conf")

@staticmethod
def loadSettings():
if not os.path.isfile(SextanteConfig.configFile()):
return
lines = open(SextanteConfig.configFile())
line = lines.readline().strip("\n")
while line != "":
tokens = line.split("=")
if tokens[0] in SextanteConfig.settings.keys():
setting = SextanteConfig.settings[tokens[0]]
if isinstance(setting.value, bool):
setting.value = (tokens[1].strip() == str(True))
else:
setting.value = tokens[1]
SextanteConfig.addSetting(setting)
line = lines.readline().strip("\n")
lines.close()

@staticmethod
def saveSettings():
fout = open(SextanteConfig.configFile(), "w")
for setting in SextanteConfig.settings.values():
fout.write(str(setting) + "\n")
fout.close()

@staticmethod
def getSetting(name):
if name in SextanteConfig.settings.keys():
return SextanteConfig.settings[name].value
else:
return None

@staticmethod
def setSettingValue(name, value):
if name in SextanteConfig.settings.keys():
SextanteConfig.settings[name].value = value
SextanteConfig.saveSettings()


class Setting():
'''A simple config parameter that will appear on the SEXTANTE config dialog'''
def __init__(self, group, name, description, default, hidden = False):
self.group=group
self.name = name
self.description = description
self.default = default
self.value = default
self.hidden = hidden

def __str__(self):
return self.name + "=" + str(self.value)
from sextante.core.SextanteUtils import SextanteUtils
import os.path
from PyQt4 import QtGui

class SextanteConfig():

TABLE_LIKE_PARAM_PANEL = "TABLE_LIKE_PARAM_PANEL"
OUTPUT_FOLDER = "OUTPUT_FOLDER"
RASTER_STYLE = "RASTER_STYLE"
VECTOR_POINT_STYLE = "VECTOR_POINT_STYLE"
VECTOR_LINE_STYLE = "VECTOR_LINE_STYLE"
VECTOR_POLYGON_STYLE = "VECTOR_POLYGON_STYLE"
SHOW_RECENT_ALGORITHMS = "SHOW_RECENT_ALGORITHMS"
USE_SELECTED = "USE_SELECTED"
USE_FILENAME_AS_LAYER_NAME = "USE_FILENAME_AS_LAYER_NAME"
KEEP_DIALOG_OPEN = "KEEP_DIALOG_OPEN"
USE_THREADS = "USE_THREADS"
SHOW_DEBUG_IN_DIALOG = "SHOW_DEBUG_IN_DIALOG"
RECENT_ALGORITHMS = "RECENT_ALGORITHMS"

settings = {}
settingIcons= {}

@staticmethod
def initialize():
icon = QtGui.QIcon(os.path.dirname(__file__) + "/../images/alg.png")
SextanteConfig.settingIcons["General"] = icon
SextanteConfig.addSetting(Setting("General", SextanteConfig.USE_THREADS, "Run algorithms in a new thread (still unstable)", False))
SextanteConfig.addSetting(Setting("General", SextanteConfig.SHOW_DEBUG_IN_DIALOG, "Show debug information and commands executed in the execution dialog's Log panel (threaded execution only)", True))
SextanteConfig.addSetting(Setting("General", SextanteConfig.KEEP_DIALOG_OPEN, "Keep dialog open after running an algorithm", False))
SextanteConfig.addSetting(Setting("General", SextanteConfig.USE_SELECTED, "Use only selected features in external applications", True))
SextanteConfig.addSetting(Setting("General", SextanteConfig.TABLE_LIKE_PARAM_PANEL, "Show table-like parameter panels", False))
SextanteConfig.addSetting(Setting("General", SextanteConfig.USE_FILENAME_AS_LAYER_NAME, "Use filename as layer name", True))
SextanteConfig.addSetting(Setting("General", SextanteConfig.SHOW_RECENT_ALGORITHMS, "Show recently executed algorithms", True))
SextanteConfig.addSetting(Setting("General", SextanteConfig.OUTPUT_FOLDER,
"Output folder", SextanteUtils.tempFolder()))
SextanteConfig.addSetting(Setting("General", SextanteConfig.RASTER_STYLE,"Style for raster layers",""))
SextanteConfig.addSetting(Setting("General", SextanteConfig.VECTOR_POINT_STYLE,"Style for point layers",""))
SextanteConfig.addSetting(Setting("General", SextanteConfig.VECTOR_LINE_STYLE,"Style for line layers",""))
SextanteConfig.addSetting(Setting("General", SextanteConfig.VECTOR_POLYGON_STYLE,"Style for polygon layers",""))
SextanteConfig.addSetting(Setting("General", SextanteConfig.RECENT_ALGORITHMS,"Recent algs","", hidden=True))

@staticmethod
def setGroupIcon(group, icon):
SextanteConfig.settingIcons[group] = icon

@staticmethod
def getGroupIcon(group):
if group in SextanteConfig.settingIcons:
return SextanteConfig.settingIcons[group]
else:
return QtGui.QIcon(os.path.dirname(__file__) + "/../images/alg.png")

@staticmethod
def addSetting(setting):
SextanteConfig.settings[setting.name] = setting

@staticmethod
def removeSetting(name):
del SextanteConfig.settings[name]

@staticmethod
def getSettings():
settings={}
for setting in SextanteConfig.settings.values():
if not setting.group in settings:
group = []
settings[setting.group] = group
else:
group = settings[setting.group]
group.append(setting)
return settings

@staticmethod
def configFile():
return os.path.join(SextanteUtils.userFolder(), "sextante_qgis.conf")

@staticmethod
def loadSettings():
if not os.path.isfile(SextanteConfig.configFile()):
return
lines = open(SextanteConfig.configFile())
line = lines.readline().strip("\n")
while line != "":
tokens = line.split("=")
if tokens[0] in SextanteConfig.settings.keys():
setting = SextanteConfig.settings[tokens[0]]
if isinstance(setting.value, bool):
setting.value = (tokens[1].strip() == str(True))
else:
setting.value = tokens[1]
SextanteConfig.addSetting(setting)
line = lines.readline().strip("\n")
lines.close()

@staticmethod
def saveSettings():
fout = open(SextanteConfig.configFile(), "w")
for setting in SextanteConfig.settings.values():
fout.write(str(setting) + "\n")
fout.close()

@staticmethod
def getSetting(name):
if name in SextanteConfig.settings.keys():
return SextanteConfig.settings[name].value
else:
return None

@staticmethod
def setSettingValue(name, value):
if name in SextanteConfig.settings.keys():
SextanteConfig.settings[name].value = value
SextanteConfig.saveSettings()


class Setting():
'''A simple config parameter that will appear on the SEXTANTE config dialog'''
def __init__(self, group, name, description, default, hidden = False):
self.group=group
self.name = name
self.description = description
self.default = default
self.value = default
self.hidden = hidden

def __str__(self):
return self.name + "=" + str(self.value)
220 changes: 110 additions & 110 deletions python/plugins/sextante/core/SextanteLog.py
Original file line number Diff line number Diff line change
@@ -1,110 +1,110 @@
import datetime
import os
from sextante.core.SextanteUtils import SextanteUtils
from sextante.core.SextanteConfig import SextanteConfig
import codecs
from PyQt4 import QtGui
class SextanteLog():

LOG_ERROR = "ERROR"
LOG_INFO = "INFO"
LOG_WARNING = "WARNING"
LOG_ALGORITHM = "ALGORITHM"
recentAlgs = []

@staticmethod
def startLogging():
if os.path.isfile(SextanteLog.logFilename()):
logfile = open(SextanteLog.logFilename(), "a")
else:
logfile = open(SextanteLog.logFilename(), "w")
logfile.write("Started logging at " + datetime.datetime.now().strftime("%a %b %d %Y %H:%M:%S") + "\n")
logfile.close()

@staticmethod
def logFilename():
batchfile = SextanteUtils.userFolder() + os.sep + "sextante_qgis.log"
return batchfile


@staticmethod
def addToLog(msgtype, msg):
try: #it seems that this fails sometimes depending on the msg added:
#To avoid it stopping the normal functioning of the algorithm,
#we catch all errors, assuming that is better to miss some log info
#that breaking the algorithm.
if isinstance(msg, list):
a = "|".join(m.strip("\n") for m in msg)
text = a
else:
text = msg.replace("\n", "|")
line = msgtype + "|" + datetime.datetime.now().strftime("%a %b %d %Y %H:%M:%S") + "|" + text + "\n"
logfile = open(SextanteLog.logFilename(), "a")
#logfile = codecs.open(SextanteLog.logFilename(), "a", encoding='utf-8')
logfile.write(line)
logfile.close()
if msgtype==SextanteLog.LOG_ALGORITHM:
algname = text[len("Sextante.runalg(\""):]
algname = algname[:algname.index("\"")]
if algname not in SextanteLog.recentAlgs:
SextanteLog.recentAlgs.append(algname)
recentAlgsString = ';'.join(SextanteLog.recentAlgs[-6:])
SextanteConfig.setSettingValue(SextanteConfig.RECENT_ALGORITHMS, recentAlgsString)
except:
pass


@staticmethod
def getLogEntries():
entries={}
errors=[]
algorithms=[]
warnings=[]
info=[]
#lines = codecs.open(SextanteLog.logFilename(), encoding='utf-8')
lines = open(SextanteLog.logFilename())
line = lines.readline()
while line != "":
line = line.strip("\n").strip()
tokens = line.split("|")
text=""
for i in range(2, len(tokens)):
text+=tokens[i] + "|"
if line.startswith(SextanteLog.LOG_ERROR):
errors.append(LogEntry(tokens[1], text))
elif line.startswith(SextanteLog.LOG_ALGORITHM):
algorithms.append(LogEntry(tokens[1], tokens[2]))
elif line.startswith(SextanteLog.LOG_WARNING):
warnings.append(LogEntry(tokens[1], text))
elif line.startswith(SextanteLog.LOG_INFO):
info.append(LogEntry(tokens[1], text))
line = lines.readline()
lines.close()
entries[SextanteLog.LOG_ERROR] = errors
entries[SextanteLog.LOG_ALGORITHM] = algorithms
entries[SextanteLog.LOG_INFO] = info
entries[SextanteLog.LOG_WARNING] = warnings
return entries


@staticmethod
def getRecentAlgorithms():
recentAlgsSetting = SextanteConfig.getSetting(SextanteConfig.RECENT_ALGORITHMS)
try:
SextanteLog.recentAlgs = recentAlgsSetting.split(';')
except:
pass
return SextanteLog.recentAlgs


@staticmethod
def clearLog():
os.unlink(SextanteLog.logFilename())
SextanteLog.startLogging()



class LogEntry():
def __init__(self, date, text):
self.date = date
self.text = text
import datetime
import os
from sextante.core.SextanteUtils import SextanteUtils
from sextante.core.SextanteConfig import SextanteConfig
import codecs
from PyQt4 import QtGui
class SextanteLog():

LOG_ERROR = "ERROR"
LOG_INFO = "INFO"
LOG_WARNING = "WARNING"
LOG_ALGORITHM = "ALGORITHM"
recentAlgs = []

@staticmethod
def startLogging():
if os.path.isfile(SextanteLog.logFilename()):
logfile = open(SextanteLog.logFilename(), "a")
else:
logfile = open(SextanteLog.logFilename(), "w")
logfile.write("Started logging at " + datetime.datetime.now().strftime("%a %b %d %Y %H:%M:%S") + "\n")
logfile.close()

@staticmethod
def logFilename():
batchfile = SextanteUtils.userFolder() + os.sep + "sextante_qgis.log"
return batchfile


@staticmethod
def addToLog(msgtype, msg):
try: #it seems that this fails sometimes depending on the msg added:
#To avoid it stopping the normal functioning of the algorithm,
#we catch all errors, assuming that is better to miss some log info
#that breaking the algorithm.
if isinstance(msg, list):
a = "|".join(m.strip("\n") for m in msg)
text = a
else:
text = msg.replace("\n", "|")
line = msgtype + "|" + datetime.datetime.now().strftime("%a %b %d %Y %H:%M:%S") + "|" + text + "\n"
logfile = open(SextanteLog.logFilename(), "a")
#logfile = codecs.open(SextanteLog.logFilename(), "a", encoding='utf-8')
logfile.write(line)
logfile.close()
if msgtype==SextanteLog.LOG_ALGORITHM:
algname = text[len("Sextante.runalg(\""):]
algname = algname[:algname.index("\"")]
if algname not in SextanteLog.recentAlgs:
SextanteLog.recentAlgs.append(algname)
recentAlgsString = ';'.join(SextanteLog.recentAlgs[-6:])
SextanteConfig.setSettingValue(SextanteConfig.RECENT_ALGORITHMS, recentAlgsString)
except:
pass


@staticmethod
def getLogEntries():
entries={}
errors=[]
algorithms=[]
warnings=[]
info=[]
#lines = codecs.open(SextanteLog.logFilename(), encoding='utf-8')
lines = open(SextanteLog.logFilename())
line = lines.readline()
while line != "":
line = line.strip("\n").strip()
tokens = line.split("|")
text=""
for i in range(2, len(tokens)):
text+=tokens[i] + "|"
if line.startswith(SextanteLog.LOG_ERROR):
errors.append(LogEntry(tokens[1], text))
elif line.startswith(SextanteLog.LOG_ALGORITHM):
algorithms.append(LogEntry(tokens[1], tokens[2]))
elif line.startswith(SextanteLog.LOG_WARNING):
warnings.append(LogEntry(tokens[1], text))
elif line.startswith(SextanteLog.LOG_INFO):
info.append(LogEntry(tokens[1], text))
line = lines.readline()
lines.close()
entries[SextanteLog.LOG_ERROR] = errors
entries[SextanteLog.LOG_ALGORITHM] = algorithms
entries[SextanteLog.LOG_INFO] = info
entries[SextanteLog.LOG_WARNING] = warnings
return entries


@staticmethod
def getRecentAlgorithms():
recentAlgsSetting = SextanteConfig.getSetting(SextanteConfig.RECENT_ALGORITHMS)
try:
SextanteLog.recentAlgs = recentAlgsSetting.split(';')
except:
pass
return SextanteLog.recentAlgs


@staticmethod
def clearLog():
os.unlink(SextanteLog.logFilename())
SextanteLog.startLogging()



class LogEntry():
def __init__(self, date, text):
self.date = date
self.text = text
46 changes: 23 additions & 23 deletions python/plugins/sextante/core/SextanteResults.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
class SextanteResults():

results = []

@staticmethod
def addResult(name, result):
SextanteResults.results.append(Result(name, result))

@staticmethod
def getResults():
return SextanteResults.results


class Result():

def __init__(self, name, filename):
self.name = name
self.filename = filename




class SextanteResults():

results = []

@staticmethod
def addResult(name, result):
SextanteResults.results.append(Result(name, result))

@staticmethod
def getResults():
return SextanteResults.results


class Result():

def __init__(self, name, filename):
self.name = name
self.filename = filename





122 changes: 61 additions & 61 deletions python/plugins/sextante/core/SextanteUtils.py
Original file line number Diff line number Diff line change
@@ -1,61 +1,61 @@
import os
import time
import sys

class SextanteUtils:

NUM_EXPORTED = 1

@staticmethod
def userFolder():
userfolder = os.path.expanduser("~") + os.sep + "sextante"
mkdir(userfolder)

return userfolder

@staticmethod
def isWindows():
return os.name =="nt"

@staticmethod
def isMac():
return sys.platform == "darwin"

@staticmethod
def tempFolder():
tempfolder = os.path.expanduser("~") + os.sep + "sextante" + os.sep + "tempdata"
mkdir(tempfolder)

return tempfolder

@staticmethod
def setTempOutput(out, alg):
ext = out.getDefaultFileExtension(alg)
validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
safeCmdName = ''.join(c for c in alg.commandLineName() if c in validChars)
filename = SextanteUtils.tempFolder() + os.sep + safeCmdName + str(SextanteUtils.NUM_EXPORTED) + "." + ext
out.value = filename
SextanteUtils.NUM_EXPORTED += 1

@staticmethod
def getTempFilename(ext):
path = SextanteUtils.tempFolder()
filename = path + os.sep + str(time.time()) + str(SextanteUtils.getNumExportedLayers()) + "." + ext
return filename

@staticmethod
def getNumExportedLayers():
SextanteUtils.NUM_EXPORTED += 1
return SextanteUtils.NUM_EXPORTED

def mkdir(newdir):
if os.path.isdir(newdir):
pass
else:
head, tail = os.path.split(newdir)
if head and not os.path.isdir(head):
mkdir(head)
if tail:
os.mkdir(newdir)

import os
import time
import sys

class SextanteUtils:

NUM_EXPORTED = 1

@staticmethod
def userFolder():
userfolder = os.path.expanduser("~") + os.sep + "sextante"
mkdir(userfolder)

return userfolder

@staticmethod
def isWindows():
return os.name =="nt"

@staticmethod
def isMac():
return sys.platform == "darwin"

@staticmethod
def tempFolder():
tempfolder = os.path.expanduser("~") + os.sep + "sextante" + os.sep + "tempdata"
mkdir(tempfolder)

return tempfolder

@staticmethod
def setTempOutput(out, alg):
ext = out.getDefaultFileExtension(alg)
validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
safeCmdName = ''.join(c for c in alg.commandLineName() if c in validChars)
filename = SextanteUtils.tempFolder() + os.sep + safeCmdName + str(SextanteUtils.NUM_EXPORTED) + "." + ext
out.value = filename
SextanteUtils.NUM_EXPORTED += 1

@staticmethod
def getTempFilename(ext):
path = SextanteUtils.tempFolder()
filename = path + os.sep + str(time.time()) + str(SextanteUtils.getNumExportedLayers()) + "." + ext
return filename

@staticmethod
def getNumExportedLayers():
SextanteUtils.NUM_EXPORTED += 1
return SextanteUtils.NUM_EXPORTED

def mkdir(newdir):
if os.path.isdir(newdir):
pass
else:
head, tail = os.path.split(newdir)
if head and not os.path.isdir(head):
mkdir(head)
if tail:
os.mkdir(newdir)


10 changes: 5 additions & 5 deletions python/plugins/sextante/core/WrongHelpFileException.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
class WrongHelpFileException(Exception):

def __init__(self, msg):
Exception.__init__(self)
self.msg = msg
class WrongHelpFileException(Exception):

def __init__(self, msg):
Exception.__init__(self)
self.msg = msg
380 changes: 190 additions & 190 deletions python/plugins/sextante/ftools/BasicStatistics.py

Large diffs are not rendered by default.

288 changes: 144 additions & 144 deletions python/plugins/sextante/ftools/Buffer.py
Original file line number Diff line number Diff line change
@@ -1,144 +1,144 @@
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from sextante.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException
from sextante.core.SextanteLog import SextanteLog

def buffering(progress, writer, distance, field, useSelection, useField, layer, dissolve, segments ):
GEOS_EXCEPT = True
FEATURE_EXCEPT = True
vproviderA = layer.dataProvider()
allAttrs = vproviderA.attributeIndexes()
vproviderA.select( allAttrs )
fields = vproviderA.fields()
if useField:
field = vproviderA.fieldNameIndex(field)
outFeat = QgsFeature()
inFeat = QgsFeature()
inGeom = QgsGeometry()
outGeom = QgsGeometry()
nElement = 0
# there is selection in input layer
if useSelection:
nFeat = layer.selectedFeatureCount()
selectionA = layer.selectedFeatures()
# with dissolve
if dissolve:
first = True
for inFeat in selectionA:
atMap = inFeat.attributeMap()
if useField:
value = atMap[ field ].doDouble()[ 0 ]
else:
value = distance
inGeom = QgsGeometry( inFeat.geometry() )
try:
outGeom = inGeom.buffer( float( value ), segments)
if first:
tempGeom = QgsGeometry( outGeom )
first = False
else:
try:
tempGeom = tempGeom.combine( outGeom )
except:
GEOS_EXCEPT = False
continue
except:
GEOS_EXCEPT = False
continue
nElement += 1
progress.setPercentage(int(nElement/nFeat * 100))
try:
outFeat.setGeometry( tempGeom )
writer.addFeature( outFeat )
except:
FEATURE_EXCEPT = False
# without dissolve
else:
for inFeat in selectionA:
atMap = inFeat.attributeMap()
if useField:
value = atMap[ field ].toDouble()[ 0 ]
else:
value = distance
inGeom = QgsGeometry( inFeat.geometry() )
try:
outGeom = inGeom.buffer( float( value ), segments )
try:
outFeat.setGeometry( outGeom )
outFeat.setAttributeMap( atMap )
writer.addFeature( outFeat )
except:
FEATURE_EXCEPT = False
continue
except:
GEOS_EXCEPT = False
continue
nElement += 1
progress.setPercentage(int(nElement/nFeat * 100))
# there is no selection in input layer
else:
nFeat = vproviderA.featureCount()
# with dissolve
if dissolve:
first = True
while vproviderA.nextFeature( inFeat ):
atMap = inFeat.attributeMap()
if useField:
value = atMap[ field ].toDouble()[ 0 ]
else:
value = distance
inGeom = QgsGeometry( inFeat.geometry() )
try:
outGeom = inGeom.buffer( float( value ), segments)
if first:
tempGeom = QgsGeometry( outGeom )
first = False
else:
try:
tempGeom = tempGeom.combine( outGeom )
except:
GEOS_EXCEPT = False
continue
except:
GEOS_EXCEPT = False
continue
nElement += 1
progress.setPercentage(int(nElement/nFeat * 100))
try:
outFeat.setGeometry( tempGeom )
writer.addFeature( outFeat )
except:
FEATURE_EXCEPT = False
# without dissolve
else:
vproviderA.rewind()
while vproviderA.nextFeature( inFeat ):
atMap = inFeat.attributeMap()
if useField:
value = atMap[ field ].toDouble()[ 0 ]
else:
value = distance
inGeom = QgsGeometry( inFeat.geometry() )
try:
outGeom = inGeom.buffer( float( value ),segments )
try:
outFeat.setGeometry( outGeom )
outFeat.setAttributeMap( atMap )
writer.addFeature( outFeat )
except:
FEATURE_EXCEPT = False
continue
except:
GEOS_EXCEPT = False
continue
nElement += 1
progress.setPercentage(int(nElement/nFeat * 100))
del writer
if not GEOS_EXCEPT:
SextanteLog.addToLog(SextanteLog.LOG_WARNING, "Geometry exception while computing buffer")
if not FEATURE_EXCEPT:
SextanteLog.addToLog(SextanteLog.LOG_WARNING, "Feature exception while computing buffer")


from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from sextante.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException
from sextante.core.SextanteLog import SextanteLog

def buffering(progress, writer, distance, field, useSelection, useField, layer, dissolve, segments ):
GEOS_EXCEPT = True
FEATURE_EXCEPT = True
vproviderA = layer.dataProvider()
allAttrs = vproviderA.attributeIndexes()
vproviderA.select( allAttrs )
fields = vproviderA.fields()
if useField:
field = vproviderA.fieldNameIndex(field)
outFeat = QgsFeature()
inFeat = QgsFeature()
inGeom = QgsGeometry()
outGeom = QgsGeometry()
nElement = 0
# there is selection in input layer
if useSelection:
nFeat = layer.selectedFeatureCount()
selectionA = layer.selectedFeatures()
# with dissolve
if dissolve:
first = True
for inFeat in selectionA:
atMap = inFeat.attributeMap()
if useField:
value = atMap[ field ].doDouble()[ 0 ]
else:
value = distance
inGeom = QgsGeometry( inFeat.geometry() )
try:
outGeom = inGeom.buffer( float( value ), segments)
if first:
tempGeom = QgsGeometry( outGeom )
first = False
else:
try:
tempGeom = tempGeom.combine( outGeom )
except:
GEOS_EXCEPT = False
continue
except:
GEOS_EXCEPT = False
continue
nElement += 1
progress.setPercentage(int(nElement/nFeat * 100))
try:
outFeat.setGeometry( tempGeom )
writer.addFeature( outFeat )
except:
FEATURE_EXCEPT = False
# without dissolve
else:
for inFeat in selectionA:
atMap = inFeat.attributeMap()
if useField:
value = atMap[ field ].toDouble()[ 0 ]
else:
value = distance
inGeom = QgsGeometry( inFeat.geometry() )
try:
outGeom = inGeom.buffer( float( value ), segments )
try:
outFeat.setGeometry( outGeom )
outFeat.setAttributeMap( atMap )
writer.addFeature( outFeat )
except:
FEATURE_EXCEPT = False
continue
except:
GEOS_EXCEPT = False
continue
nElement += 1
progress.setPercentage(int(nElement/nFeat * 100))
# there is no selection in input layer
else:
nFeat = vproviderA.featureCount()
# with dissolve
if dissolve:
first = True
while vproviderA.nextFeature( inFeat ):
atMap = inFeat.attributeMap()
if useField:
value = atMap[ field ].toDouble()[ 0 ]
else:
value = distance
inGeom = QgsGeometry( inFeat.geometry() )
try:
outGeom = inGeom.buffer( float( value ), segments)
if first:
tempGeom = QgsGeometry( outGeom )
first = False
else:
try:
tempGeom = tempGeom.combine( outGeom )
except:
GEOS_EXCEPT = False
continue
except:
GEOS_EXCEPT = False
continue
nElement += 1
progress.setPercentage(int(nElement/nFeat * 100))
try:
outFeat.setGeometry( tempGeom )
writer.addFeature( outFeat )
except:
FEATURE_EXCEPT = False
# without dissolve
else:
vproviderA.rewind()
while vproviderA.nextFeature( inFeat ):
atMap = inFeat.attributeMap()
if useField:
value = atMap[ field ].toDouble()[ 0 ]
else:
value = distance
inGeom = QgsGeometry( inFeat.geometry() )
try:
outGeom = inGeom.buffer( float( value ),segments )
try:
outFeat.setGeometry( outGeom )
outFeat.setAttributeMap( atMap )
writer.addFeature( outFeat )
except:
FEATURE_EXCEPT = False
continue
except:
GEOS_EXCEPT = False
continue
nElement += 1
progress.setPercentage(int(nElement/nFeat * 100))
del writer
if not GEOS_EXCEPT:
SextanteLog.addToLog(SextanteLog.LOG_WARNING, "Geometry exception while computing buffer")
if not FEATURE_EXCEPT:
SextanteLog.addToLog(SextanteLog.LOG_WARNING, "Feature exception while computing buffer")



Loading