Skip to content
Permalink
Browse files

[sextante] reorganized sextante tools and how they are exposed and ad…

…ded some tests
  • Loading branch information
volaya committed Apr 11, 2013
1 parent ac7201a commit 3d1e50ca5246bd5c5b78c11b6e4a5c9c1e4893a5
@@ -17,9 +17,9 @@
***************************************************************************
"""

from sextante.core.Sextante import runalg, runandload, alghelp, alglist, algoptions, load, \
extent, getObjectFromName, getObjectFromUri, getobject, getfeatures

from sextante.tools.general import runalg, runandload, alghelp, alglist, algoptions, load, extent, getobject
from sextante.tools.vector import getfeatures, spatialindex, values, uniquevalues
from sextante.tools.raster import scanraster
from sextante.tests.TestData import loadTestData

__author__ = 'Victor Olaya'
@@ -346,94 +346,3 @@ def cancel():
##==========================================================


def alglist(text=None):
s=""
for provider in Sextante.algs.values():
sortedlist = sorted(provider.values(), key= lambda alg: alg.name)
for alg in sortedlist:
if text == None or text.lower() in alg.name.lower():
s+=(alg.name.ljust(50, "-") + "--->" + alg.commandLineName() + "\n")
print s

def algoptions(name):
alg = Sextante.getAlgorithm(name)
if alg != None:
s =""
for param in alg.parameters:
if isinstance(param, ParameterSelection):
s+=param.name + "(" + param.description + ")\n"
i=0
for option in param.options:
s+= "\t" + str(i) + " - " + str(option) + "\n"
i+=1
print(s)
else:
print "Algorithm not found"

def alghelp(name):
alg = Sextante.getAlgorithm(name)
if alg != None:
print(str(alg))
algoptions(name)
else:
print "Algorithm not found"

def runalg(algOrName, *args):
alg = Sextante.runAlgorithm(algOrName, None, *args)
if alg is not None:
return alg.getOutputValuesAsDictionary()

def runandload(name, *args):
return Sextante.runAlgorithm(name, SextantePostprocessing.handleAlgorithmResults, *args)

def extent(layers):
first = True
for layer in layers:
if not isinstance(layer, (QgsRasterLayer, QgsVectorLayer)):
layer = QGisLayers.getObjectFromUri(layer)
if layer is None:
continue
if first:
xmin = layer.extent().xMinimum()
xmax = layer.extent().xMaximum()
ymin = layer.extent().yMinimum()
ymax = layer.extent().yMaximum()
else:
xmin = min(xmin, layer.extent().xMinimum())
xmax = max(xmax, layer.extent().xMaximum())
ymin = min(ymin, layer.extent().yMinimum())
ymax = max(ymax, layer.extent().yMaximum())
first = False
if first:
return "0,0,0,0"
else:
return str(xmin) + "," + str(xmax) + "," + str(ymin) + "," + str(ymax)

def getObjectFromName(name):
layers = QGisLayers.getAllLayers()
for layer in layers:
if layer.name() == name:
return layer

def getObjectFromUri(uri):
return QGisLayers.getObjectFromUri(uri, True)

def getobject(uriorname):
ret = getObjectFromName(uriorname)
if ret is None:
ret = getObjectFromUri(uriorname)
return ret

def load(path):
'''Loads a layer into QGIS'''
return QGisLayers.load(path)

def getfeatures(layer):
return QGisLayers.features(layer)

#===============================================================================
# def loadFromAlg(layersdict):
# '''Load all layer resulting from a given algorithm.
# Layers are passed as a dictionary, obtained from alg.getOutputValuesAsDictionary()'''
# QGisLayers.loadFromDict(layersdict)
#===============================================================================
@@ -28,7 +28,7 @@
##numpolygons=number 10
##polygons=output vector

input = sextante.getObjectFromUri(input)
input = sextante.getobject(input)
centerx = (input.extent().xMinimum() + input.extent().xMaximum()) / 2
centery = (input.extent().yMinimum() + input.extent().yMaximum()) / 2
width = (input.extent().xMaximum() - input.extent().xMinimum())
@@ -29,7 +29,7 @@
##grid=output vector
from sextante.core.QGisLayers import QGisLayers

input = QGisLayers.getObjectFromUri(input)
input = sextante.getobject(input)
centerx = (input.extent().xMinimum() + input.extent().xMaximum()) / 2
centery = (input.extent().yMinimum() + input.extent().yMaximum()) / 2
width = (input.extent().xMaximum() - input.extent().xMinimum())
@@ -29,14 +29,7 @@ def testRemoveAlgorithm(self):
model.provider = Providers.providers['model']
self.assertTrue(2, len(model.algs))
self.assertFalse(model.removeAlgorithm(0))
self.assertTrue(model.removeAlgorithm(len(model.algs) - 1));
from threading import settrace

import sys
sys.path.append("D:\eclipse\plugins\org.python.pydev_2.6.0.2012062818\pysrc")
from pydevd import *
settrace()

self.assertTrue(model.removeAlgorithm(len(model.algs) - 1));
model.execute(None)
outputs = model.outputs
self.assertEquals(1, len(outputs))
@@ -85,12 +85,12 @@ def test_SagaVectorAlgorithWithUnsupportedInputAndOutputFormat(self):
self.assertEqual(wkt, str(feature.geometry().exportToWkt()))

def test_SagaRasterAlgorithmWithUnsupportedOutputFormat(self):
outputs=sextante.runalg("saga:convergenceindex",raster(),0,0,None)
outputs=sextante.runalg("saga:convergenceindex",raster(),0,0,SextanteUtils.getTempFilename("img"))
output=outputs['RESULT']
self.assertTrue(os.path.isfile(output))
dataset=gdal.Open(output, GA_ReadOnly)
strhash=hash(str(dataset.ReadAsArray(0).tolist()))
self.assertEqual(strhash,-807227462)
self.assertEqual(strhash, 485390137)


def suite():
@@ -52,7 +52,9 @@ def test_scripthexgridfromlayerbounds(self):
def test_scriptascriptthatreturnsanumber(self):
outputs=sextante.runalg("script:ascriptthatreturnsanumber")
output=outputs['number']
self.assertTrue(10, output.value)
self.assertTrue(10, output)



def suite():
suite = unittest.makeSuite(ScriptTest, 'test')
@@ -7,12 +7,14 @@
from sextante.tests import ScriptTest
from sextante.tests import SagaTest
from sextante.tests import GeoAlgorithmTest
from sextante.tests import GdalTest

def suite():
suite = unittest.TestSuite()
suite.addTests(QgisAlgsTest.suite())
suite.addTests(ModelerAlgorithmTest.suite())
suite.addTests(SagaTest.suite())
suite.addTests(GdalTest.suite())
suite.addTests(ScriptTest.suite())
suite.addTests(SextanteToolsTest.suite())
#suite.addTests(ParametersTest.suite())
@@ -3,7 +3,8 @@
from sextante.tests.TestData import points, points2, polygons, polygons2, lines, union,\
table, polygonsGeoJson, raster
from sextante.core import Sextante
from sextante.tools.vector import getAttributeValues
from sextante.tools.vector import values
from sextante.tools.general import getfromname

class SextanteToolsTest(unittest.TestCase):
'''tests the method imported when doing an "import sextante", and also in sextante.tools.
@@ -17,7 +18,7 @@ def test_getobject(self):

def test_runandload(self):
sextante.runandload("qgis:countpointsinpolygon",polygons(),points(),"NUMPOINTS", None)
layer = Sextante.getObjectFromName("Result")
layer = getfromname("Result")
self.assertIsNotNone(layer)

def test_featuresWithoutSelection(self):
@@ -36,9 +37,9 @@ def test_featuresWithSelection(self):

def test_attributeValues(self):
layer = sextante.getobject(points())
values = getAttributeValues(layer, "ID")
attributeValues = values(layer, "ID")
i = 1
for value in values['ID']:
for value in attributeValues['ID']:
self.assertEqual(int(i), int(value))
i+=1
self.assertEquals(13,i)
@@ -23,5 +23,3 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from sextante.tools.vector import getAttributeValues
from sextante.tools.raster import scanraster
@@ -24,22 +24,63 @@
__revision__ = '$Format:%H$'

from sextante.core.QGisLayers import QGisLayers
from qgis.core import *

def uniquevalues(layer, attribute):
'''Returns a list of unique values for a given attribute.
Attribute can be defined using a field names or a zero-based field index.
It considers the existing selection'''
values = []
fieldIndex = resolveFieldIndex(layer, attribute)
features = QGisLayers.features(layer)
for feat in features:
if feat.attributes()[fieldIndex] not in values:
values.append(feat.attributes()[fieldIndex])
return values

def getAttributeValues(layer, *attributeNames):
ret = {}
for name in attributeNames:
values = []
features = QGisLayers.features(layer)
index = layer.fieldNameIndex(name)
def resolveFieldIndex(layer, attr):
'''This method takes an object and returns the index field it refers to in a layer.
If the passed object is an integer, it returns the same integer value.
If the passed value is not an integer, it returns the field whose name is the string
representation of the passed object.
Ir raises an exception if the int value is larger than the number of fields, or if
the passed object does not correspond to any field'''
if isinstance(attr, int):
return attr
else:
index = layer.fieldNameIndex(unicode(attr))
if index == -1:
raise ValueError('Wrong field name')
return index


def values(layer, *attributes):
'''Returns the values in the attributes table of a vector layer, for the passed fields.
Field can be passed as field names or as zero-based field indices.
Returns a dict of lists, with the passed field identifiers as keys.
It considers the existing selection'''
ret = {}
for attr in attributes:
index = resolveFieldIndex(layer, attr)
values = []
features = QGisLayers.features(layer)
for feature in features:
try:
v = float(feature.attributes()[index].toString())
values.append(v)
except:
values.append(None)
ret[name] = values;
ret[attr] = values;
return ret

def spatialindex(layer):
'''Creates a spatial index for the passed vector layer'''
idx = QgsSpatialIndex()
features = QGisLayers.features(layer)
for ft in features:
idx.insertFeature(ft)
return idx

def getfeatures(layer):
'''returns an iterator over the features of a vector layer, considering the existing selection'''
return QGisLayers.features(layer)

0 comments on commit 3d1e50c

Please sign in to comment.
You can’t perform that action at this time.