Skip to content
Permalink
Browse files
minor edits to SEXTANTE algorithms and scripts
  • Loading branch information
volaya committed Jan 27, 2013
1 parent b231795 commit 158dadbb35557b7eab0400c3fa925629a7080dc6
@@ -25,12 +25,9 @@

import os, sys
import inspect

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from qgis.core import *

from sextante.core.Sextante import Sextante
from sextante.core.QGisLayers import QGisLayers
from sextante.core.SextanteUtils import SextanteUtils
@@ -94,14 +91,6 @@ def initGui(self):
self.resultsAction.triggered.connect(self.openResults)
self.menu.addAction(self.resultsAction)

#=======================================================================
# self.helpAction = QAction(QIcon(":/sextante/images/help.png"),
# QCoreApplication.translate("SEXTANTE", "&SEXTANTE help"),
# self.iface.mainWindow())
# self.helpAction.triggered.connect(self.openHelp)
# self.menu.addAction(self.helpAction)
#=======================================================================

menuBar = self.iface.mainWindow().menuBar()
menuBar.insertMenu(menuBar.actions()[-1], self.menu)

@@ -143,7 +132,3 @@ def openConfig(self):
dlg = ConfigDialog(self.toolbox)
dlg.exec_()

#===========================================================================
# def openHelp(self):
# QDesktopServices.openUrl(QUrl(os.path.dirname(__file__) + "/help/index.html"))
#===========================================================================
@@ -17,7 +17,7 @@
***************************************************************************
"""

from sextante.core.Sextante import runalg, runandload, alghelp, alglist, algoptions, load, loadFromAlg, extent, getObjectFromName, getObjectFromUri
from sextante.core.Sextante import runalg, runandload, alghelp, alglist, algoptions, load, loadFromAlg, extent, getObjectFromName, getObjectFromUri, features

__author__ = 'Victor Olaya'
__date__ = 'August 2012'
@@ -54,7 +54,7 @@ def defineCharacteristics(self):
with some other properties'''

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

#the branch of the toolbox under which the algorithm will appear
self.group = "Vector general tools"
@@ -78,7 +78,7 @@ def processAlgorithm(self, progress):
raise GeoAlgorithmExecutionException("Selected number is greater than feature count. Choose a lower value and try again.")
else:
if value > 100:
raise GeoAlgorithmExecutionException("Persentage can't be greater than 100. Set a different value and try again.")
raise GeoAlgorithmExecutionException("Percentage can't be greater than 100. Set a different value and try again.")
value = int(round((value / 100.0000), 4) * featureCount)

selran = random.sample(xrange(0, featureCount), value)
@@ -49,7 +49,7 @@ def defineCharacteristics(self):
self.group = "Vector general tools"

self.addParameter(ParameterVector(self.INPUT, "Input layer", ParameterVector.VECTOR_TYPE_ANY))
self.addParameter(ParameterCrs(self.TARGET_CRS, "Target CRS", "4326"))
self.addParameter(ParameterCrs(self.TARGET_CRS, "Target CRS", "EPSG:4326"))

self.addOutput(OutputVector(self.OUTPUT, "Reprojected layer"))

@@ -23,9 +23,6 @@
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

import os.path

from PyQt4 import QtGui
from PyQt4.QtCore import *

from qgis.core import *
@@ -39,14 +36,11 @@

from sextante.outputs.OutputVector import OutputVector

from sextante.algs.ftools import FToolsUtils as utils

class SelectByLocation(GeoAlgorithm):

INPUT = "INPUT"
INTERSECT = "INTERSECT"
METHOD = "METHOD"
USE_SELECTED = "USE_SELECTED"
METHOD = "METHOD"
OUTPUT = "OUTPUT"

METHODS = ["creating new selection",
@@ -61,63 +55,44 @@ class SelectByLocation(GeoAlgorithm):
def defineCharacteristics(self):
self.name = "Select by location"
self.group = "Vector selection tools"

self.addParameter(ParameterVector(self.INPUT, "Layer to select from", ParameterVector.VECTOR_TYPE_ANY))
self.addParameter(ParameterVector(self.INTERSECT, "Additional layer (intersection layer)", ParameterVector.VECTOR_TYPE_ANY))
self.addParameter(ParameterSelection(self.METHOD, "Modify current selection by", self.METHODS, 0))
self.addParameter(ParameterBoolean(self.USE_SELECTED, "Use only selected features", False))

self.addParameter(ParameterSelection(self.METHOD, "Modify current selection by", self.METHODS, 0))
self.addOutput(OutputVector(self.OUTPUT, "Selection", True))

def processAlgorithm(self, progress):
filename = self.getParameterValue(self.INPUT)
inputLayer = QGisLayers.getObjectFromUri(filename)
method = self.getParameterValue(self.METHOD)
selection = self.getParameterValue(self.USE_SELECTED)

filename = self.getParameterValue(self.INTERSECT)
selectLayer = QGisLayers.getObjectFromUri(filename)

inputProvider = inputLayer.dataProvider()
selectProvider = selectLayer.dataProvider()

index = utils.createSpatialIndex(inputLayer)

index = QgsSpatialIndex()
inputProvider.rewind()
inputProvider.select()
selectProvider.select()

feat = QgsFeature()
while inputProvider.nextFeature(feat):
index.insertFeature(feat)

selectProvider.select()
infeat = QgsFeature()
geom = QgsGeometry()
selectedSet = []

if selection:
features = selectLayer.selectedFeatures()
total = 100.0 / float(len(features))
current = 0
for feat in features:
geom = QgsGeometry(feat.geometry())
intersects = index.intersects(geom.boundingBox())
for i in intersects:
inputProvider.featureAtId(i, infeat, True)
tmpGeom = QgsGeometry(infeat.geometry())
if geom.intersects(tmpGeom):
selectedSet.append(infeat.id())
current += 1
progress.setPercentage(int(current * total))
else:
total = 100.0 / float(selectProvider.featureCount())
current = 0
while selectProvider.nextFeature(feat):
geom = QgsGeometry(feat.geometry())
intersects = index.intersects(geom.boundingBox())
for i in intersects:
inputProvider.featureAtId(i, infeat, True)
tmpGeom = QgsGeometry( infeat.geometry() )
if geom.intersects(tmpGeom):
selectedSet.append(infeat.id())
current += 1
progress.setPercentage(int(current * total))
selectedSet = []
current = 0
features = QGisLayers.features(selectLayer)
total = 100.0 / float(len(features))
for feat in features:
geom = QgsGeometry(feat.geometry())
intersects = index.intersects(geom.boundingBox())
for i in intersects:
inputProvider.featureAtId(i, infeat, True)
tmpGeom = QgsGeometry( infeat.geometry() )
if geom.intersects(tmpGeom):
selectedSet.append(infeat.id())
current += 1
progress.setPercentage(int(current * total))

if method == 1:
selectedSet = list(set(inputLayer.selectedFeaturesIds()).union(selectedSet))
@@ -16,6 +16,7 @@
* *
***************************************************************************
"""
from sextante.outputs.OutputString import OutputString

__author__ = 'Victor Olaya'
__date__ = 'August 2012'
@@ -37,6 +38,7 @@ class UniqueValues(GeoAlgorithm):
INPUT_LAYER = "INPUT_LAYER"
FIELD_NAME = "FIELD_NAME"
TOTAL_VALUES = "TOTAL_VALUES"
UNIQUE_VALUES = "UNIQUE_VALUES"
OUTPUT = "OUTPUT"

#===========================================================================
@@ -48,19 +50,19 @@ def defineCharacteristics(self):
self.name = "List unique values"
self.group = "Vector table tools"
self.addParameter(ParameterVector(self.INPUT_LAYER, "Input layer", ParameterVector.VECTOR_TYPE_ANY))
self.addParameter(ParameterTableField(self.FIELD_NAME, "Targer field", self.INPUT_LAYER, ParameterTableField.DATA_TYPE_ANY))
self.addParameter(ParameterTableField(self.FIELD_NAME, "Target field", self.INPUT_LAYER, ParameterTableField.DATA_TYPE_ANY))
self.addOutput(OutputHTML(self.OUTPUT, "Unique values"))
self.addOutput(OutputNumber(self.TOTAL_VALUES, "Total unique values"))
self.addOutput(OutputString(self.UNIQUE_VALUES, "Unique values"))

def processAlgorithm(self, progress):
layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT_LAYER))
fieldName = self.getParameterValue(self.FIELD_NAME)

outputFile = self.getOutputValue(self.OUTPUT)

values = layer.uniqueValues(layer.fieldNameIndex(fieldName))
self.createHTML(outputFile, values)
self.setOutputValue(self.TOTAL_VALUES, len(values))
self.setOutputValue(self.UNIQUE_VALUES, ";".join([unicode(v.toString()) for v in values]))

def createHTML(self, outputFile, algData):
f = codecs.open(outputFile, "w", encoding="utf-8")
@@ -629,7 +629,7 @@ class mmqgisx_select_algorithm(GeoAlgorithm):
ATTRIBUTE = "ATTRIBUTE"
COMPARISONVALUE = "COMPARISONVALUE"
COMPARISON = "COMPARISON"
SAVENAME = "SAVENAME"
RESULT = "RESULT"

def defineCharacteristics(self):
self.name = "Select by attribute"
@@ -641,7 +641,7 @@ def defineCharacteristics(self):
self.addParameter(ParameterSelection(self.COMPARISON, "Comparison", self.comparisons, default = 0))
self.addParameter(ParameterString(self.COMPARISONVALUE, "Value", default = "0"))

self.addOutput(OutputVector(self.SAVENAME, "Output"))
self.addOutput(OutputVector(self.RESULT, "Output", True))

#===========================================================================
# def getIcon(self):
@@ -650,17 +650,19 @@ def defineCharacteristics(self):

def processAlgorithm(self, progress):

layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.LAYERNAME))
filename = self.getParameterValue(self.LAYERNAME)
layer = QGisLayers.getObjectFromUri(filename)

attribute = self.getParameterValue(self.ATTRIBUTE)
comparison = self.comparisons [ self.getParameterValue(self.COMPARISON) ]
comparisonvalue = self.getParameterValue(self.COMPARISONVALUE)
savename = self.getOutputValue(self.SAVENAME)
comparison = self.comparisons [self.getParameterValue(self.COMPARISON)]
comparisonvalue = self.getParameterValue(self.COMPARISONVALUE)

message = mmqgisx_select(progress, layer, attribute, comparisonvalue, comparison, savename, False)
message = mmqgisx_select(progress, layer, attribute, comparisonvalue, comparison)

if message:
raise GeoAlgorithmExecutionException(message)

self.setOutputValue(self.RESULT, filename)

class mmqgisx_sort_algorithm(GeoAlgorithm):

@@ -1694,7 +1694,7 @@ def mmqgisx_merge(progress, layers, savename, addlayer):
# mmqgisx_select - Select features by attribute
# ----------------------------------------------------------

def mmqgisx_select(progress, layer, selectattributename, comparisonvalue, comparisonname, savename, addlayer):
def mmqgisx_select(progress, layer, selectattributename, comparisonvalue, comparisonname):

selectindex = layer.dataProvider().fieldNameIndex(selectattributename)
if selectindex < 0:
@@ -1703,25 +1703,13 @@ def mmqgisx_select(progress, layer, selectattributename, comparisonvalue, compar
if (not comparisonvalue) or (len(comparisonvalue) <= 0):
return "No comparison value given"

if (not savename) or (len(savename) <= 0):
return "No output filename given"

if QFile(savename).exists():
if not QgsVectorFileWriter.deleteShapeFile(QString(savename)):
return "Failure deleting existing shapefile: " + savename

outfile = QgsVectorFileWriter(QString(savename), QString("System"), layer.dataProvider().fields(),
layer.dataProvider().geometryType(), layer.dataProvider().crs())

if (outfile.hasError() != QgsVectorFileWriter.NoError):
return "Failure creating output shapefile: " + unicode(outfile.errorMessage())

readcount = 0
writecount = 0
feature = QgsFeature()
layer.dataProvider().select(layer.dataProvider().attributeIndexes())
layer.dataProvider().rewind()

selected = []
totalcount = layer.featureCount()
features = QGisLayers.features(layer)
for feature in features:
@@ -1754,12 +1742,11 @@ def mmqgisx_select(progress, layer, selectattributename, comparisonvalue, compar

readcount += 1
if (match):
outfile.addFeature(feature)
writecount += 1
selected.append(feature.id())

progress.setPercentage(float(readcount) / totalcount * 100)

del outfile
layer.setSelectedFeatures(selected)

return None

@@ -16,7 +16,6 @@
* *
***************************************************************************
"""

__author__ = 'Victor Olaya'
__date__ = 'August 2012'
__copyright__ = '(C) 2012, Victor Olaya'
@@ -139,7 +138,7 @@ def execute(self, progress):
Raises a GeoAlgorithmExecutionException in case anything goes wrong.'''

try:
self.setOutputCRSFromInputLayers()
self.setOutputCRS()
self.resolveTemporaryOutputs()
self.checkOutputFileExtensions()
self.runPreExecutionScript(progress)
@@ -259,7 +258,7 @@ def resolveTemporaryOutputs(self):
if (not out.hidden) and out.value == None:
SextanteUtils.setTempOutput(out, self)

def setOutputCRSFromInputLayers(self):
def setOutputCRS(self):
layers = QGisLayers.getAllLayers()
for param in self.parameters:
if isinstance(param, (ParameterRaster, ParameterVector, ParameterMultipleInput)):
@@ -270,7 +269,8 @@ def setOutputCRSFromInputLayers(self):
if layer.source() == inputlayer:
self.crs = layer.crs()
return

qgis = QGisLayers.iface
self.crs = qgis.mapCanvas().mapRenderer().destinationCrs()

def addOutput(self, output):
#TODO: check that name does not exist
@@ -320,8 +320,8 @@ def __str__(self):
for param in self.parameters:
s+=("\t" + str(param) + "\n")
for out in self.outputs:
if not out.hidden:
s+=("\t" + str(out) + "\n")
#if not out.hidden:
s+=("\t" + str(out) + "\n")
s+=("\n")
return s

@@ -335,10 +335,10 @@ def cancel():
return alg


##==========================================================
##This methods are here to be used from the python console,
##making it easy to use SEXTANTE from there
##==========================================================
##==========================================================
##This methods are here to be used from the python console,
##making it easy to use SEXTANTE from there
##==========================================================


def alglist(text=None):
@@ -374,12 +374,12 @@ def alghelp(name):

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

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


def extent(layers):
first = True
for layer in layers:
Loading

0 comments on commit 158dadb

Please sign in to comment.