Skip to content

Commit

Permalink
minor edits to SEXTANTE algorithms and scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
volaya committed Jan 27, 2013
1 parent b231795 commit 158dadb
Show file tree
Hide file tree
Showing 18 changed files with 88 additions and 225 deletions.
15 changes: 0 additions & 15 deletions python/plugins/sextante/SextantePlugin.py
Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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"))
#===========================================================================
2 changes: 1 addition & 1 deletion python/plugins/sextante/__init__.py
Expand Up @@ -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'
Expand Down
2 changes: 1 addition & 1 deletion python/plugins/sextante/algs/SaveSelectedFeatures.py
Expand Up @@ -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"
Expand Down
2 changes: 1 addition & 1 deletion python/plugins/sextante/algs/ftools/RandomSelection.py
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion python/plugins/sextante/algs/ftools/ReprojectLayer.py
Expand Up @@ -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"))

Expand Down
71 changes: 23 additions & 48 deletions python/plugins/sextante/algs/ftools/SelectByLocation.py
Expand Up @@ -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 *
Expand All @@ -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",
Expand All @@ -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))
Expand Down
8 changes: 5 additions & 3 deletions python/plugins/sextante/algs/ftools/UniqueValues.py
Expand Up @@ -16,6 +16,7 @@
* *
***************************************************************************
"""
from sextante.outputs.OutputString import OutputString

__author__ = 'Victor Olaya'
__date__ = 'August 2012'
Expand All @@ -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"

#===========================================================================
Expand All @@ -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")
Expand Down
16 changes: 9 additions & 7 deletions python/plugins/sextante/algs/mmqgisx/MMQGISXAlgorithms.py
Expand Up @@ -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"
Expand All @@ -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):
Expand All @@ -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):

Expand Down
23 changes: 5 additions & 18 deletions python/plugins/sextante/algs/mmqgisx/mmqgisx_library.py
Expand Up @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -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

Expand Down
12 changes: 6 additions & 6 deletions python/plugins/sextante/core/GeoAlgorithm.py
Expand Up @@ -16,7 +16,6 @@
* *
***************************************************************************
"""

__author__ = 'Victor Olaya'
__date__ = 'August 2012'
__copyright__ = '(C) 2012, Victor Olaya'
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)):
Expand All @@ -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
Expand Down Expand Up @@ -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

Expand Down
12 changes: 6 additions & 6 deletions python/plugins/sextante/core/Sextante.py
Expand Up @@ -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):
Expand Down Expand Up @@ -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:
Expand Down

0 comments on commit 158dadb

Please sign in to comment.