Adapt more python code to new API

This commit is contained in:
Nyall Dawson 2017-05-22 14:07:53 +10:00
parent 6517470ddd
commit 0c3ad14c79
53 changed files with 157 additions and 637 deletions

View File

@ -109,7 +109,7 @@ class translate(GdalAlgorithm):
outsize = str(self.getParameterValue(self.OUTSIZE))
outsizePerc = str(self.getParameterValue(self.OUTSIZE_PERC))
noData = self.getParameterValue(self.NO_DATA)
expand = self.getParameterFromName(self.EXPAND).options[self.getParameterValue(self.EXPAND)][1]
expand = parameters[self.EXPAND].options[self.getParameterValue(self.EXPAND)][1]
projwin = str(self.getParameterValue(self.PROJWIN))
if not projwin:
projwin = QgsProcessingUtils.combineLayerExtents([inLayer])

View File

@ -33,6 +33,7 @@ from processing.core.parameters import getParameterFromString
from processing.tools.system import isWindows
from ..Grass7Utils import Grass7Utils
from os import path
from copy import deepcopy
def multipleOutputDir(alg, field, basename=None):
@ -112,58 +113,44 @@ def regroupRasters(alg, parameters, field, groupField, subgroupField=None, extFi
:param parameters:
"""
# List of rasters names
new_parameters = deepcopy(parameters)
rasters = alg.getParameterFromName(field)
rastersList = rasters.value.split(';')
alg.parameters.remove(rasters)
del new_parameters[field]
# Insert a i.group command
group = getParameterFromString("ParameterString|{}|group of rasters|None|False|False".format(groupField))
group.value = alg.getTempFilename()
alg.addParameter(group)
new_parameters[group.name()] = alg.getTempFilename()
if subgroupField:
subgroup = getParameterFromString("ParameterString|{}|subgroup of rasters|None|False|False".format(subgroupField))
subgroup.value = alg.getTempFilename()
alg.addParameter(subgroup)
new_parameters[subgroup.name()] = alg.getTempFilename()
command = 'i.group group={}{} input={}'.format(
group.value,
' subgroup={}'.format(subgroup.value) if subgroupField else '',
new_parameters[group.name()],
' subgroup={}'.format(new_parameters[subgroup.name()]) if subgroupField else '',
','.join([alg.exportedLayers[f] for f in rastersList])
)
alg.commands.append(command)
# Handle external files
origExtParams = {}
if subgroupField and extFile:
for ext in list(extFile.keys()):
extFileName = alg.getParameterValue(ext)
extFileName = new_parameters[ext]
if extFileName:
shortFileName = path.basename(extFileName)
destPath = path.join(Grass7Utils.grassMapsetFolder(),
'PERMANENT',
'group', group.value,
'subgroup', subgroup.value,
'group', new_parameters[group.name()],
'subgroup', new_parameters[subgroup.name()],
extFile[ext], shortFileName)
copyFile(alg, extFileName, destPath)
origExtParams[ext] = extFileName
alg.setParameterValue(ext, shortFileName)
new_parameters[ext] = shortFileName
# modify parameters values
alg.processCommand()
# Re-add input rasters
alg.addParameter(rasters)
# replace external files value with original value
for param in list(origExtParams.keys()):
alg.setParameterValue(param, origExtParams[param])
# Delete group:
alg.parameters.remove(group)
if subgroupField:
alg.parameters.remove(subgroup)
return group.value, subgroup.value
alg.processCommand(new_parameters)
return group.value

View File

@ -27,6 +27,7 @@ __copyright__ = '(C) 2016, Médéric Ribreux'
__revision__ = '$Format:%H$'
import os
from copy import deepcopy
def checkParameterValuesBeforeExecuting(alg):
@ -74,32 +75,29 @@ def processInputs(alg):
def processCommand(alg, parameters):
# remove output before processCommand
new_parameters = deepcopy(parameters)
output = alg.getOutputFromName('output_dir')
alg.removeOutputFromName('output_dir')
color = alg.getParameterFromName('color')
if color.value == 0:
alg.parameters.remove(color)
if new_parameters[color.name()] == 0:
del new_parameters[color.name()]
# Handle rules
txtRules = alg.getParameterFromName('rules_txt')
if txtRules.value:
if new_parameters[txtRules.name()]:
# Creates a temporary txt file
tempRulesName = alg.getTempFilename()
# Inject rules into temporary txt file
with open(tempRulesName, "w") as tempRules:
tempRules.write(txtRules.value)
tempRules.write(new_parameters[txtRules.name()])
# Use temporary file as rules file
alg.setParameterValue('rules', tempRulesName)
alg.parameters.remove(txtRules)
new_parameters['rules'] = tempRulesName
del new_parameters[textRules.name()]
alg.processCommand()
# re-add the previous output
alg.addOutput(output)
alg.addParameter(color)
alg.addParameter(txtRules)
alg.processCommand(new_parameters)
def processOutputs(alg):

View File

@ -29,6 +29,7 @@ import shutil
from processing.tools.system import isWindows, mkdir
from processing.core.parameters import getParameterFromString
import os
from copy import deepcopy
# for MS-Windows users who have MBCS chars in their name:
if os.name == 'nt':
@ -83,29 +84,33 @@ def checkMovingWindow(alg, outputTxt=False):
return None
def configFile(alg, outputTxt=False):
""" Handle inline configuration """
def configFile(alg, parameters, outputTxt=False):
""" Handle inline configuration
:param parameters:
"""
# Where is the GRASS7 user directory ?
new_parameters = deepcopy(parameters)
userGrass7Path = rliPath()
if not os.path.isdir(userGrass7Path):
mkdir(userGrass7Path)
if not os.path.isdir(os.path.join(userGrass7Path, 'output')):
mkdir(os.path.join(userGrass7Path, 'output'))
origConfigFile = alg.getParameterValue('config')
origConfigFile = new_parameters['config']
# Handle inline configuration
configTxt = alg.getParameterFromName('config_txt')
if configTxt.value:
if new_parameters['config_txt']:
# Creates a temporary txt file in user r.li directory
tempConfig = alg.getTempFilename()
configFilePath = os.path.join(userGrass7Path, tempConfig)
# Inject rules into temporary txt file
with open(configFilePath, "w") as f:
f.write(configTxt.value)
f.write(new_parameters['config_txt'])
# Use temporary file as rules file
alg.setParameterValue('config', os.path.basename(configFilePath))
alg.parameters.remove(configTxt)
new_parameters['config'] = os.path.basename(configFilePath)
del new_parameters['config_txt']
# If we have a configuration file, we need to copy it into user dir
if origConfigFile:
@ -114,26 +119,21 @@ def configFile(alg, outputTxt=False):
shutil.copy(origConfigFile, configFilePath)
# Change the parameter value
alg.setParameterValue('config', os.path.basename(configFilePath))
new_parameters['config'] = os.path.basename(configFilePath)
origOutput = alg.getOutputFromName('output')
if outputTxt:
if new_parameters['output']:
param = getParameterFromString("ParameterString|output|txt output|None|False|True")
param.value = os.path.basename(origOutput.value)
alg.addParameter(param)
new_parameters[param.name()] = origOutput.value
alg.removeOutputFromName('output')
alg.processCommand()
alg.processCommand(new_parameters)
# Remove Config file:
removeConfigFile(alg)
# re-add configTxt
alg.addParameter(configTxt)
alg.setParameterValue('config', origConfigFile)
if outputTxt:
for param in [f for f in alg.parameters if f.name == 'output']:
alg.parameters.remove(param)
alg.addOutput(origOutput)

View File

@ -34,4 +34,4 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg)
configFile(alg, parameters)

View File

@ -34,7 +34,7 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg, True)
configFile(alg, parameters, True)
def processOutputs(alg):

View File

@ -34,4 +34,4 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg)
configFile(alg, parameters)

View File

@ -34,7 +34,7 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg, True)
configFile(alg, parameters, True)
def processOutputs(alg):

View File

@ -34,4 +34,4 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg)
configFile(alg, parameters)

View File

@ -34,7 +34,7 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg, True)
configFile(alg, parameters, True)
def processOutputs(alg):

View File

@ -34,4 +34,4 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg)
configFile(alg, parameters)

View File

@ -34,7 +34,7 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg, True)
configFile(alg, parameters, True)
def processOutputs(alg):

View File

@ -34,4 +34,4 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg)
configFile(alg, parameters)

View File

@ -34,7 +34,7 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg, True)
configFile(alg, parameters, True)
def processOutputs(alg):

View File

@ -28,6 +28,7 @@ __revision__ = '$Format:%H$'
import shutil
from processing.tools.system import isWindows, userFolder, mkdir
from os import path
from copy import deepcopy
def rliPath():
@ -73,26 +74,29 @@ def checkMovingWindow(alg):
return None
def configFile(alg, outputTxt=False):
""" Handle inline configuration """
def configFile(alg, parameters, outputTxt=False):
""" Handle inline configuration
:param parameters:
"""
new_parameters = deepcopy(parameters)
# Where is the GRASS7 user directory ?
userGrass7Path = rliPath()
mkdir(userGrass7Path)
origConfigFile = alg.getParameterValue('config')
origConfigFile = new_parameters['config']
# Handle inline configuration
configTxt = alg.getParameterFromName('config_txt')
if configTxt.value:
if new_parameters['config_txt']:
# Creates a temporary txt file in user r.li directory
tempConfig = alg.getTempFilename()
configFilePath = path.join(userGrass7Path, tempConfig)
# Inject rules into temporary txt file
with open(configFilePath, "w") as f:
f.write(configTxt.value)
f.write(new_parameters['config_txt'])
# Use temporary file as rules file
alg.setParameterValue('config', configFilePath)
alg.parameters.remove(configTxt)
new_parameters['config'] = configFilePath
del new_parameters['config_txt']
# If we have a configuration file, we need to copy it into user dir
if origConfigFile:
@ -101,21 +105,17 @@ def configFile(alg, outputTxt=False):
shutil.copy(origConfigFile, configFilePath)
# Change the parameter value
alg.setParameterValue('config', configFilePath)
new_parameters['config'] = configFilePath
if outputTxt:
origOutput = alg.getOutputValue('output')
alg.setOutputValue('output', path.basename(origOutput))
alg.processCommand()
alg.processCommand(new_parameters)
# Remove Config file:
removeConfigFile(alg)
# re-add configTxt
alg.addParameter(configTxt)
alg.setParameterValue('config', origConfigFile)
def moveOutputTxtFile(alg):
# Find output file name:

View File

@ -34,4 +34,4 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg)
configFile(alg, parameters)

View File

@ -34,7 +34,7 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg, True)
configFile(alg, parameters, True)
def processOutputs(alg):

View File

@ -34,4 +34,4 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg)
configFile(alg, parameters)

View File

@ -34,7 +34,7 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg, True)
configFile(alg, parameters, True)
def processOutputs(alg):

View File

@ -34,4 +34,4 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg)
configFile(alg, parameters)

View File

@ -34,7 +34,7 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg, True)
configFile(alg, parameters, True)
def processOutputs(alg):

View File

@ -34,4 +34,4 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg)
configFile(alg, parameters)

View File

@ -34,4 +34,4 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg)
configFile(alg, parameters)

View File

@ -34,7 +34,7 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg, True)
configFile(alg, parameters, True)
def processOutputs(alg):

View File

@ -34,4 +34,4 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg)
configFile(alg, parameters)

View File

@ -34,7 +34,7 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg, True)
configFile(alg, parameters, True)
def processOutputs(alg):

View File

@ -34,4 +34,4 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg)
configFile(alg, parameters)

View File

@ -34,7 +34,7 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg, True)
configFile(alg, parameters, True)
def processOutputs(alg):

View File

@ -34,4 +34,4 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg)
configFile(alg, parameters)

View File

@ -34,7 +34,7 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg, True)
configFile(alg, parameters, True)
def processOutputs(alg):

View File

@ -34,4 +34,4 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg)
configFile(alg, parameters)

View File

@ -34,7 +34,7 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg, True)
configFile(alg, parameters, True)
def processOutputs(alg):

View File

@ -34,4 +34,4 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg)
configFile(alg, parameters)

View File

@ -34,7 +34,7 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg, True)
configFile(alg, parameters, True)
def processOutputs(alg):

View File

@ -34,4 +34,4 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg)
configFile(alg, parameters)

View File

@ -34,7 +34,7 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
configFile(alg, True)
configFile(alg, parameters, True)
def processOutputs(alg):

View File

@ -30,31 +30,31 @@ __copyright__ = '(C) 2015, Médéric Ribreux'
__revision__ = '$Format:%H$'
import os
from copy import deepcopy
def incorporatePoints(alg, pointLayerName=u'points', networkLayerName=u'input'):
def incorporatePoints(alg, parameters, pointLayerName=u'points', networkLayerName=u'input'):
"""
incorporate points with lines to form a GRASS network
"""
paramsToDelete = []
new_parameters = deepcopy(parameters)
# Create an intermediate GRASS layer which is the combination of network + centers
intLayer = alg.getTempFilename()
# Grab the point layer and delete this parameter (not used by v.net.alloc)
pointLayer = alg.getParameterValue(pointLayerName)
pointLayer = new_parameters[pointLayerName]
if pointLayer:
pointLayer = alg.exportedLayers[pointLayer]
paramsToDelete.append(alg.getParameterFromName(u'points'))
new_parameters['points'] = pointLayer
# Grab the network layer and tell to v.net.alloc to use the temp layer instead
lineLayer = alg.getParameterValue(networkLayerName)
lineLayer = new_parameters[networkLayerName]
if lineLayer:
lineLayer = alg.exportedLayers[lineLayer]
alg.setParameterValue(networkLayerName, intLayer)
new_parameters[networkLayerName] = lineLayer
threshold = alg.getParameterValue(u'threshold')
paramsToDelete.append(alg.getParameterFromName(u'threshold'))
threshold = parameters['threshold']
# Create the v.net connect command for point layer integration
command = u"v.net -s input={} points={} out={} op=connect threshold={}".format(
@ -65,15 +65,7 @@ def incorporatePoints(alg, pointLayerName=u'points', networkLayerName=u'input'):
command = u"v.db.connect -o map={} table={} layer=2".format(intLayer, pointLayer)
alg.commands.append(command)
# Delete some unnecessary parameters
for param in paramsToDelete:
alg.parameters.remove(param)
alg.processCommand()
# Bring back the parameters:
for param in paramsToDelete:
alg.parameters.append(param)
alg.processCommand(new_parameters)
def variableOutput(alg, params, nocats=True):

View File

@ -30,7 +30,7 @@ from .v_net import incorporatePoints, variableOutput
def processCommand(alg, parameters):
incorporatePoints(alg)
incorporatePoints(alg, parameters)
def processOutputs(alg):

View File

@ -30,4 +30,4 @@ from .v_net import incorporatePoints
def processCommand(alg, parameters):
incorporatePoints(alg)
incorporatePoints(alg, parameters)

View File

@ -44,7 +44,7 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
incorporatePoints(alg)
incorporatePoints(alg, parameters)
def processOutputs(alg):

View File

@ -27,6 +27,7 @@ __revision__ = '$Format:%H$'
from processing.core.parameters import getParameterFromString
from copy import deepcopy
def processCommand(alg, parameters):
@ -36,12 +37,12 @@ def processCommand(alg, parameters):
* Delete the threshold parameter.
* If where statement, connect to the db
"""
paramsToDelete = []
new_parameters = deepcopy(parameters)
# Grab the threshold value for our v.net connect command
threshold = alg.getParameterValue(u'threshold')
if threshold:
paramsToDelete.append(alg.getParameterFromName(u'threshold'))
del new_parameters['threshold']
# Grab the network layer and tell to v.net.alloc to use the temp layer instead
line_layer = alg.getParameterValue(u'input')
@ -57,7 +58,7 @@ def processCommand(alg, parameters):
point_layer = alg.getParameterValue(layer + u'_points')
if point_layer:
point_layer = alg.exportedLayers[point_layer]
paramsToDelete.append(alg.getParameterFromName(layer + u'_points'))
del new_parameters[layer + u'_points']
# Create the v.net connect command for point layer integration
command = u"v.net -s input={} points={} out={} op=connect threshold={} arc_layer=1 node_layer={}".format(line_layer, point_layer, intLayer, threshold, i + 2)
@ -69,24 +70,11 @@ def processCommand(alg, parameters):
if not parameter:
parameter = getParameterFromString(u'ParameterNumber|{0}_layer|{0} layer number|1|3|2|False'.format(layer))
alg.addParameter(parameter)
parameter.setValue(i + 2)
new_parameters[parameter.name()] = i + 2
# Make the connection with attribute table
command = u"v.db.connect -o map={} table={} layer={}".format(line_layer, point_layer, i + 2)
alg.commands.append(command)
alg.setParameterValue(u'input', line_layer)
# Delete some unnecessary parameters
for param in paramsToDelete:
alg.parameters.remove(param)
alg.processCommand(parameters, context)
# Bring back the parameters:
for param in paramsToDelete:
alg.parameters.append(param)
# Delete from_layer and to_layer
for word in [u'from', u'to']:
alg.parameters.remove(alg.getParameterFromName(u'{}_layer'.format(word)))
new_parameters['input'] = line_layer
alg.processCommand(new_parameters, context)

View File

@ -44,7 +44,7 @@ def checkParameterValuesBeforeExecuting(alg):
def processCommand(alg, parameters):
incorporatePoints(alg)
incorporatePoints(alg, parameters)
def processOutputs(alg):

View File

@ -29,4 +29,4 @@ from .v_net import incorporatePoints
def processCommand(alg, parameters):
incorporatePoints(alg)
incorporatePoints(alg, parameters)

View File

@ -29,4 +29,4 @@ from .v_net import incorporatePoints
def processCommand(alg, parameters):
incorporatePoints(alg)
incorporatePoints(alg, parameters)

View File

@ -27,10 +27,12 @@ __revision__ = '$Format:%H$'
from processing.core.parameters import getParameterFromString
from .v_net import incorporatePoints
from copy import deepcopy
def processCommand(alg, parameters):
# We temporary remove the output 'sequence'
new_parameters = deepcopy(parameters)
sequence = alg.getOutputFromName(u'sequence')
sequenceFile = alg.getOutputValue(u'sequence')
alg.exportedLayers[sequence.value] = sequence.name + alg.uniqueSuffix
@ -38,12 +40,10 @@ def processCommand(alg, parameters):
# We create a new parameter with the same name
param = getParameterFromString(u"ParameterString|sequence|sequence|None|False|False")
param.setValue(sequenceFile)
alg.addParameter(param)
new_parameters[param.name()] = sequenceFile
# Let's do the incorporation and command generation
incorporatePoints(alg)
incorporatePoints(alg, new_parameters)
# then we delete the input parameter and add the old output
alg.parameters.remove(param)
alg.addOutput(sequence)

View File

@ -29,4 +29,4 @@ from .v_net import incorporatePoints
def processCommand(alg, parameters):
incorporatePoints(alg)
incorporatePoints(alg, parameters)

View File

@ -145,38 +145,38 @@ class SagaAlgorithm(GeoAlgorithm):
# 1: Export rasters to sgrd and vectors to shp
# Tables must be in dbf format. We check that.
for param in self.parameters:
for param in self.parameterDefinitions():
if isinstance(param, ParameterRaster):
if param.value is None:
if param.name() not in parameters or parameters[param.name()] is None:
continue
if param.value.endswith('sdat'):
param.value = param.value[:-4] + "sgrd"
elif not param.value.endswith('sgrd'):
exportCommand = self.exportRasterLayer(param.value)
if parameters[param.name()].endswith('sdat'):
parameters[param.name()] = parameters[param.name()][:-4] + "sgrd"
elif not parameters[param.name()].endswith('sgrd'):
exportCommand = self.exportRasterLayer(parameters[param.name()])
if exportCommand is not None:
commands.append(exportCommand)
if isinstance(param, ParameterVector):
if param.value is None:
if param.name() not in parameters or parameters[param.name()] is None:
continue
layer = QgsProcessingUtils.mapLayerFromString(param.value, context, False)
layer = QgsProcessingUtils.mapLayerFromString(parameters[param.name()], context, False)
if layer:
filename = dataobjects.exportVectorLayer(layer)
self.exportedLayers[param.value] = filename
elif not param.value.endswith('shp'):
elif not parameteres[param.name()].endswith('shp'):
raise GeoAlgorithmExecutionException(
self.tr('Unsupported file format'))
if isinstance(param, ParameterTable):
if param.value is None:
if param.name() not in parameters or parameters[param.name()] is None:
continue
table = QgsProcessingUtils.mapLayerFromString(param.value, context, False)
table = QgsProcessingUtils.mapLayerFromString(parameters[param.name()], context, False)
if table:
filename = dataobjects.exportTable(table)
self.exportedLayers[param.value] = filename
elif not param.value.endswith('shp'):
self.exportedLayers[parameters[param.name()]] = filename
elif not parameters[param.name()].endswith('shp'):
raise GeoAlgorithmExecutionException(
self.tr('Unsupported file format'))
if isinstance(param, ParameterMultipleInput):
if param.value is None:
if param.name() not in parameters or parameters[param.name()] is None:
continue
layers = param.value.split(';')
if layers is None or len(layers) == 0:
@ -212,23 +212,23 @@ class SagaAlgorithm(GeoAlgorithm):
command = self.undecoratedGroup + ' "' + self.cmdname + '"'
command += ' ' + ' '.join(self.hardcodedStrings)
for param in self.parameters:
if param.value is None:
for param in self.parameterDefinitions():
if not param.name() in parameters or parameters[param.name()] is None:
continue
if isinstance(param, (ParameterRaster, ParameterVector, ParameterTable)):
value = param.value
value = parameters[param.name()]
if value in list(self.exportedLayers.keys()):
command += ' -' + param.name() + ' "' \
+ self.exportedLayers[value] + '"'
else:
command += ' -' + param.name() + ' "' + value + '"'
elif isinstance(param, ParameterMultipleInput):
s = param.value
s = parameters[param.name()]
for layer in list(self.exportedLayers.keys()):
s = s.replace(layer, self.exportedLayers[layer])
command += ' -' + param.name() + ' "' + s + '"'
elif isinstance(param, ParameterBoolean):
if param.value:
if parameters[param.name()]:
command += ' -' + param.name().strip() + " true"
else:
command += ' -' + param.name().strip() + " false"
@ -236,7 +236,7 @@ class SagaAlgorithm(GeoAlgorithm):
tempTableFile = getTempFilename('txt')
with open(tempTableFile, 'w') as f:
f.write('\t'.join([col for col in param.cols]) + '\n')
values = param.value.split(',')
values = parameters[param.name()].split(',')
for i in range(0, len(values), 3):
s = values[i] + '\t' + values[i + 1] + '\t' + values[i + 2] + '\n'
f.write(s)
@ -244,9 +244,9 @@ class SagaAlgorithm(GeoAlgorithm):
elif isinstance(param, ParameterExtent):
# 'We have to substract/add half cell size, since SAGA is
# center based, not corner based
halfcell = self.getOutputCellsize() / 2
halfcell = self.getOutputCellsize(parameters) / 2
offset = [halfcell, -halfcell, halfcell, -halfcell]
values = param.value.split(',')
values = parameters[param.name()].split(',')
for i in range(4):
command += ' -' + self.extentParamNames[i] + ' ' \
+ str(float(values[i]) + offset[i])
@ -310,15 +310,16 @@ class SagaAlgorithm(GeoAlgorithm):
else:
return commands
def getOutputCellsize(self):
def getOutputCellsize(self, parameters):
"""Tries to guess the cell size of the output, searching for
a parameter with an appropriate name for it.
:param parameters:
"""
cellsize = 0
for param in self.parameters:
if param.value is not None and param.name == 'USER_SIZE':
cellsize = float(param.value)
for param in self.parameterDefinitions():
if param.name() in parameters and param.name() == 'USER_SIZE':
cellsize = float(parameters[param.name()])
break
return cellsize

View File

@ -55,9 +55,6 @@ class GeoAlgorithm(QgsProcessingAlgorithm):
def __init__(self):
super().__init__()
# Parameters needed by the algorithm
self.parameters = list()
# Outputs generated by the algorithm
self.outputs = list()
@ -241,7 +238,7 @@ class GeoAlgorithm(QgsProcessingAlgorithm):
def setOutputCRS(self):
context = dataobjects.createContext()
layers = QgsProcessingUtils.compatibleLayers(QgsProject.instance())
for param in self.parameters:
for param in self.parameterDefinitions():
if isinstance(param, (ParameterRaster, ParameterVector, ParameterMultipleInput)):
if param.value:
if isinstance(param, ParameterMultipleInput):
@ -265,23 +262,6 @@ class GeoAlgorithm(QgsProcessingAlgorithm):
except:
pass
def resolveDataObjects(self):
layers = QgsProcessingUtils.compatibleLayers(QgsProject.instance())
for param in self.parameters:
if isinstance(param, (ParameterRaster, ParameterVector, ParameterTable,
ParameterMultipleInput)):
if param.value:
if isinstance(param, ParameterMultipleInput):
inputlayers = param.value.split(';')
else:
inputlayers = [param.value]
for i, inputlayer in enumerate(inputlayers):
for layer in layers:
if layer.name() == inputlayer:
inputlayers[i] = layer.source()
break
param.setValue(";".join(inputlayers))
def checkInputCRS(self, context=None):
"""It checks that all input layers use the same CRS. If so,
returns True. False otherwise.
@ -289,7 +269,7 @@ class GeoAlgorithm(QgsProcessingAlgorithm):
if context is None:
context = dataobjects.createContext()
crsList = []
for param in self.parameters:
for param in self.parameterDefinitions():
if isinstance(param, (ParameterRaster, ParameterVector, ParameterMultipleInput)):
if param.value:
if isinstance(param, ParameterMultipleInput):
@ -312,11 +292,6 @@ class GeoAlgorithm(QgsProcessingAlgorithm):
if isinstance(param, Parameter):
self.parameters.append(param)
def setParameterValue(self, paramName, value):
for param in self.parameters:
if param.name == paramName:
return param.setValue(value)
def setOutputValue(self, outputName, value):
for out in self.outputs:
if out.name == outputName:
@ -337,16 +312,6 @@ class GeoAlgorithm(QgsProcessingAlgorithm):
d[out.name] = out.value
return d
def __str__(self):
s = 'ALGORITHM: ' + self.name() + '\n'
for param in self.parameters:
s += '\t' + str(param) + '\n'
for out in self.outputs:
if not out.flags() & QgsProcessingParameterDefinition.FlagHidden:
s += '\t' + str(out) + '\n'
s += '\n'
return s
def removeOutputFromName(self, name):
for out in self.outputs:
if out.name == name:
@ -357,11 +322,6 @@ class GeoAlgorithm(QgsProcessingAlgorithm):
if out.name == name:
return out
def getParameterFromName(self, name):
for param in self.parameters:
if param.name == name:
return param
def getParameterValue(self, name):
for param in self.parameters:
if param.name == name:
@ -383,7 +343,7 @@ class GeoAlgorithm(QgsProcessingAlgorithm):
"""
s = 'processing.run("' + self.id() + '",'
for param in self.parameters:
for param in self.parameterDefinitions():
s += param.getValueAsCommandLineParameter() + ','
for out in self.outputs:
if not out.flags() & QgsProcessingParameterDefinition.FlagHidden:

View File

@ -83,22 +83,6 @@ class Parameter(object):
metadata={}):
self.value = default
def setValue(self, obj):
"""
Sets the value of the parameter.
Returns true if the value passed is correct for the type
of parameter.
"""
if obj is None:
if not self.flags() & QgsProcessingParameterDefinition.FlagOptional:
return False
self.value = None
return True
self.value = str(obj)
return True
def __str__(self):
return u'{} <{}>'.format(self.name(), self.__class__.__name__)
@ -123,26 +107,9 @@ class Parameter(object):
class ParameterBoolean(Parameter):
default_metadata = {
'widget_wrapper': 'processing.gui.wrappers.BooleanWidgetWrapper'
}
def __init__(self, name='', description='', default=None, optional=False, metadata={}):
Parameter.__init__(self, name, description, parseBool(default), optional, metadata)
def setValue(self, value):
if value is None:
if not self.flags() & QgsProcessingParameterDefinition.FlagOptional:
return False
self.value = None
return True
if isinstance(value, str):
self.value = str(value).lower() == str(True).lower()
else:
self.value = bool(value)
return True
def getAsScriptCode(self):
param_type = ''
if self.flags() & QgsProcessingParameterDefinition.FlagOptional:
@ -169,10 +136,6 @@ class ParameterBoolean(Parameter):
class ParameterCrs(Parameter):
default_metadata = {
'widget_wrapper': 'processing.gui.wrappers.CrsWidgetWrapper'
}
def __init__(self, name='', description='', default=None, optional=False, metadata={}):
'''The value is a string that uniquely identifies the
coordinate reference system. Typically it is the auth id of the CRS
@ -182,35 +145,6 @@ class ParameterCrs(Parameter):
if self.value == 'ProjectCrs':
self.value = QgsProject.instance().crs().authid()
def setValue(self, value):
context = dataobjects.createContext()
if not bool(value):
if not self.flags() & QgsProcessingParameterDefinition.FlagOptional:
return False
self.value = None
return True
if isinstance(value, QgsCoordinateReferenceSystem):
self.value = value.authid()
return True
if isinstance(value, QgsMapLayer):
self.value = value.crs().authid()
return True
try:
layer = QgsProcessingUtils.mapLayerFromString(value, context)
if layer is not None:
self.value = layer.crs().authid()
return True
except:
pass
if value == 'ProjectCrs':
self.value = QgsProject.instance().crs().authid()
return True
# TODO: check it is a valid authid
self.value = value
return True
def getValueAsCommandLineParameter(self):
return '"' + str(self.value) + '"'
@ -248,10 +182,6 @@ class ParameterDataObject(Parameter):
class ParameterExtent(Parameter):
default_metadata = {
'widget_wrapper': 'processing.gui.wrappers.ExtentWidgetWrapper'
}
USE_MIN_COVERING_EXTENT = 'USE_MIN_COVERING_EXTENT'
def __init__(self, name='', description='', default=None, optional=True):
@ -259,43 +189,6 @@ class ParameterExtent(Parameter):
# The value is a string in the form "xmin, xmax, ymin, ymax"
self.skip_crs_check = False
def setValue(self, value):
context = dataobjects.createContext()
if not value:
if not self.flags() & QgsProcessingParameterDefinition.FlagOptional:
return False
self.value = None
return True
if isinstance(value, QgsMapLayer):
rect = value.extent()
self.value = '{},{},{},{}'.format(
rect.xMinimum(), rect.xMaximum(), rect.yMinimum(), rect.yMaximum())
return True
try:
layer = QgsProcessingUtils.mapLayerFromString(value, context)
if layer is not None:
rect = layer.extent()
self.value = '{},{},{},{}'.format(
rect.xMinimum(), rect.xMaximum(), rect.yMinimum(), rect.yMaximum())
return True
except:
pass
tokens = str(value).split(',')
if len(tokens) != 4:
return False
try:
float(tokens[0])
float(tokens[1])
float(tokens[2])
float(tokens[3])
self.value = value
return True
except:
return False
def getValueAsCommandLineParameter(self):
if self.value is not None:
return '"' + str(self.value) + '"'
@ -320,32 +213,10 @@ class ParameterExtent(Parameter):
class ParameterPoint(Parameter):
default_metadata = {
'widget_wrapper': 'processing.gui.wrappers.PointWidgetWrapper'
}
def __init__(self, name='', description='', default=None, optional=False):
Parameter.__init__(self, name, description, default, optional)
# The value is a string in the form "x, y"
def setValue(self, text):
if text is None:
if not self.flags() & QgsProcessingParameterDefinition.FlagOptional:
return False
self.value = None
return True
tokens = str(text).split(',')
if len(tokens) != 2:
return False
try:
float(tokens[0])
float(tokens[1])
self.value = text
return True
except:
return False
def getValueAsCommandLineParameter(self):
return '"' + str(self.value) + '"'
@ -367,10 +238,6 @@ class ParameterPoint(Parameter):
class ParameterFile(Parameter):
default_metadata = {
'widget_wrapper': 'processing.gui.wrappers.FileWidgetWrapper'
}
def __init__(self, name='', description='', isFolder=False, optional=True, ext=None):
Parameter.__init__(self, name, description, None, parseBool(optional))
self.ext = ext
@ -379,18 +246,6 @@ class ParameterFile(Parameter):
def getValueAsCommandLineParameter(self):
return '"' + str(self.value) + '"'
def setValue(self, obj):
if obj is None or obj.strip() == '':
if not self.flags() & QgsProcessingParameterDefinition.FlagOptional:
return False
self.value = None if obj is None else obj.strip()
return True
if self.ext is not None and obj != '' and not obj.endswith(self.ext):
return False
self.value = str(obj)
return True
def getAsScriptCode(self):
param_type = ''
if self.flags() & QgsProcessingParameterDefinition.FlagOptional:
@ -420,20 +275,6 @@ class ParameterFixedTable(Parameter):
self.numRows = int(numRows)
self.fixedNumOfRows = parseBool(fixedNumOfRows)
def setValue(self, obj):
if obj is None:
if not self.flags() & QgsProcessingParameterDefinition.FlagOptional:
return False
self.value = None
return True
# TODO: check that it contains a correct number of elements
if isinstance(obj, str):
self.value = obj
else:
self.value = ParameterFixedTable.tableToString(obj)
return True
def getValueAsCommandLineParameter(self):
return '"' + str(self.value) + '"'
@ -469,10 +310,6 @@ class ParameterMultipleInput(ParameterDataObject):
each of which represents the data source location of each element.
"""
default_metadata = {
'widget_wrapper': 'processing.gui.wrappers.MultipleInputWidgetWrapper'
}
exported = None
def __init__(self, name='', description='', datatype=-1, optional=False, metadata={}):
@ -512,31 +349,6 @@ class ParameterMultipleInput(ParameterDataObject):
def getMinNumInputs(self):
return self.minNumInputs
def setValue(self, obj):
self.exported = None
if obj is None:
if not self.flags() & QgsProcessingParameterDefinition.FlagOptional:
return False
self.value = None
return True
if isinstance(obj, list):
if len(obj) == 0:
if self.flags() & QgsProcessingParameterDefinition.FlagOptional:
self.value = None
return True
else:
return False
# prevent setting value if we didn't provide required minimal number of inputs
elif len(obj) < self.minNumInputs:
return False
self.value = ";".join([self.getAsString(lay) for lay in obj])
return True
else:
self.value = str(obj)
return True
def getSafeExportedLayers(self):
"""
Returns not the value entered by the user, but a string with
@ -667,10 +479,6 @@ class ParameterMultipleInput(ParameterDataObject):
class ParameterNumber(Parameter):
default_metadata = {
'widget_wrapper': 'processing.gui.wrappers.NumberWidgetWrapper'
}
def __init__(self, name='', description='', minValue=None, maxValue=None,
default=None, optional=False, metadata={}):
Parameter.__init__(self, name, description, default, optional, metadata)
@ -695,39 +503,6 @@ class ParameterNumber(Parameter):
self.max = None
self.value = self.default
def setValue(self, n):
if n is None:
if not self.flags() & QgsProcessingParameterDefinition.FlagOptional:
return False
self.value = None
return True
if isinstance(n, str):
try:
self.value = float(n)
if self.isInteger:
self.value = int(math.floor(self.value))
return True
except:
return False
else:
try:
if float(n) - int(float(n)) == 0:
value = int(float(n))
else:
value = float(n)
if self.min is not None:
if value < self.min:
return False
if self.max is not None:
if value > self.max:
return False
self.value = value
return True
except:
raise
return False
def getAsScriptCode(self):
param_type = ''
if self.flags() & QgsProcessingParameterDefinition.FlagOptional:
@ -812,34 +587,12 @@ class ParameterRange(Parameter):
else:
self.isInteger = False
def setValue(self, text):
if text is None:
if not self.flags() & QgsProcessingParameterDefinition.FlagOptional:
return False
self.value = None
return True
tokens = text.split(',')
if len(tokens) != 2:
return False
try:
float(tokens[0])
float(tokens[1])
self.value = text
return True
except:
return False
def getValueAsCommandLineParameter(self):
return '"' + str(self.value) + '"' if self.value is not None else str(None)
class ParameterRaster(ParameterDataObject):
default_metadata = {
'widget_wrapper': 'processing.gui.wrappers.RasterWidgetWrapper'
}
def __init__(self, name='', description='', optional=False, showSublayersDialog=True):
ParameterDataObject.__init__(self, name, description, None, optional)
self.showSublayersDialog = parseBool(showSublayersDialog)
@ -874,21 +627,6 @@ class ParameterRaster(ParameterDataObject):
self.exported = self.value
return self.exported
def setValue(self, obj):
self.exported = None
if obj is None:
if not self.flags() & QgsProcessingParameterDefinition.FlagOptional:
return False
self.value = None
return True
if isinstance(obj, QgsRasterLayer):
self.value = str(obj.dataProvider().dataSourceUri())
return True
else:
self.value = str(obj)
return True
def getFileFilter(self):
exts = dataobjects.getSupportedOutputRasterLayerExtensions()
for i in range(len(exts)):
@ -912,10 +650,6 @@ class ParameterRaster(ParameterDataObject):
class ParameterSelection(Parameter):
default_metadata = {
'widget_wrapper': 'processing.gui.wrappers.SelectionWidgetWrapper'
}
def __init__(self, name='', description='', options=[], default=None, isSource=False,
multiple=False, optional=False):
Parameter.__init__(self, name, description, default, optional)
@ -947,47 +681,6 @@ class ParameterSelection(Parameter):
self.values = [option[0] for option in options]
self.value = None
if default is not None:
self.setValue(self.defaultValue())
def setValue(self, value):
if value is None:
if not self.flags() & QgsProcessingParameterDefinition.FlagOptional:
return False
self.value = None
return True
if isinstance(value, list):
if not self.multiple:
return False
values = []
for v in value:
if v in self.values:
values.append(v)
continue
try:
v = int(v)
except:
pass
if v not in self.values:
return False
values.append(v)
if not self.flags() & QgsProcessingParameterDefinition.FlagOptional and len(values) == 0:
return False
self.value = values
return True
else:
if value in self.values:
self.value = value
return True
try:
value = int(value)
except:
pass
if value not in self.values:
return False
self.value = value
return True
@classmethod
def fromScriptCode(self, line):
@ -1017,10 +710,6 @@ class ParameterEvaluationException(Exception):
class ParameterString(Parameter):
default_metadata = {
'widget_wrapper': 'processing.gui.wrappers.StringWidgetWrapper'
}
NEWLINE = '\n'
ESCAPED_NEWLINE = '\\n'
@ -1029,19 +718,6 @@ class ParameterString(Parameter):
Parameter.__init__(self, name, description, default, optional, metadata)
self.multiline = parseBool(multiline)
def setValue(self, obj):
if not bool(obj):
if not self.flags() & QgsProcessingParameterDefinition.FlagOptional:
return False
self.value = None
return True
self.value = str(obj).replace(
ParameterString.ESCAPED_NEWLINE,
ParameterString.NEWLINE
)
return True
def getValueAsCommandLineParameter(self):
return ('"' + str(self.value.replace(ParameterString.NEWLINE,
ParameterString.ESCAPED_NEWLINE)) + '"'
@ -1078,10 +754,6 @@ class ParameterString(Parameter):
class ParameterExpression(Parameter):
default_metadata = {
'widget_wrapper': 'processing.gui.wrappers.ExpressionWidgetWrapper'
}
NEWLINE = '\n'
ESCAPED_NEWLINE = '\\n'
@ -1089,19 +761,6 @@ class ParameterExpression(Parameter):
Parameter.__init__(self, name, description, default, optional)
self.parent_layer = parent_layer
def setValue(self, obj):
if not bool(obj):
if not self.flags() & QgsProcessingParameterDefinition.FlagOptional:
return False
self.value = None
return True
self.value = str(obj).replace(
ParameterString.ESCAPED_NEWLINE,
ParameterString.NEWLINE
)
return True
def getValueAsCommandLineParameter(self):
return ('"' + str(self.value.replace(ParameterExpression.NEWLINE,
ParameterExpression.ESCAPED_NEWLINE)) + '"'
@ -1130,38 +789,10 @@ class ParameterExpression(Parameter):
class ParameterTable(ParameterDataObject):
default_metadata = {
'widget_wrapper': 'processing.gui.wrappers.TableWidgetWrapper'
}
def __init__(self, name='', description='', optional=False):
ParameterDataObject.__init__(self, name, description, None, optional)
self.exported = None
def setValue(self, obj):
self.exported = None
if obj is None:
if not self.flags() & QgsProcessingParameterDefinition.FlagOptional:
return False
self.value = None
return True
if isinstance(obj, QgsVectorLayer):
source = str(obj.source())
self.value = source
return True
else:
self.value = str(obj)
layers = QgsProcessingUtils.compatibleVectorLayers(QgsProject.instance())
for layer in layers:
if layer.name() == self.value or layer.source() == self.value:
source = str(layer.source())
self.value = source
return True
val = str(obj)
self.value = val
return os.path.exists(self.value)
def getSafeExportedTable(self):
"""Returns not the value entered by the user, but a string with
a filename which contains the data of this table, but saved in
@ -1217,10 +848,6 @@ class ParameterTableField(Parameter):
Its value is a string that represents the name of the field.
"""
default_metadata = {
'widget_wrapper': 'processing.gui.wrappers.TableFieldWidgetWrapper'
}
DATA_TYPE_NUMBER = 0
DATA_TYPE_STRING = 1
DATA_TYPE_DATETIME = 2
@ -1236,22 +863,6 @@ class ParameterTableField(Parameter):
def getValueAsCommandLineParameter(self):
return '"' + str(self.value) + '"' if self.value is not None else str(None)
def setValue(self, value):
if not bool(value):
if not self.flags() & QgsProcessingParameterDefinition.FlagOptional:
return False
self.value = None
return True
if isinstance(value, list):
if not self.multiple and len(value) > 1:
return False
self.value = ";".join(value)
return True
else:
self.value = str(value)
return True
def __str__(self):
return self.name() + ' <' + self.__module__.split('.')[-1] + ' from ' \
+ self.parent + '>'
@ -1296,10 +907,6 @@ class ParameterTableField(Parameter):
class ParameterVector(ParameterDataObject):
default_metadata = {
'widget_wrapper': 'processing.gui.wrappers.VectorWidgetWrapper'
}
def __init__(self, name='', description='', datatype=[-1],
optional=False):
ParameterDataObject.__init__(self, name, description, None, optional)
@ -1311,21 +918,6 @@ class ParameterVector(ParameterDataObject):
self.exported = None
self.allowOnlyOpenedLayers = False
def setValue(self, obj):
self.exported = None
if obj is None:
if not self.flags() & QgsProcessingParameterDefinition.FlagOptional:
return False
self.value = None
return True
if isinstance(obj, QgsVectorLayer):
self.value = str(obj.source())
return True
else:
self.value = str(obj)
return True
def getSafeExportedLayer(self):
"""Returns not the value entered by the user, but a string with
a filename which contains the data of this layer, but saved in

View File

@ -424,8 +424,8 @@ class ModelerAlgorithm(GeoAlgorithm):
value = param.defaultValue()
# We allow unexistent filepaths, since that allows
# algorithms to skip some conversion routines
if not param.setValue(value) and not isinstance(param,
ParameterDataObject):
if not param.checkValueIsAcceptable(value) and not isinstance(param,
ParameterDataObject):
raise GeoAlgorithmExecutionException(
self.tr('Wrong value {0} for {1} {2}', 'ModelerAlgorithm').format(
value, param.__class__.__name__, param.name()

View File

@ -30,6 +30,7 @@ import os
from qgis.core import (QgsProcessingAlgorithm,
QgsApplication)
from processing.core.GeoAlgorithm import GeoAlgorithm
from copy import deepcopy
import json
@ -57,10 +58,11 @@ class PreconfiguredAlgorithm(GeoAlgorithm):
return QgsProcessingAlgorithm.FlagHideFromModeler
def execute(self, parameters, context=None, feedback=None, model=None):
new_parameters = deepcopy(parameters)
self.alg = QgsApplication.processingRegistry().algorithmById(self.description["algname"])
for name, value in list(self.description["parameters"].items()):
self.alg.setParameterValue(name, value)
new_parameters[name] = value
for name, value in list(self.description["outputs"].items()):
self.alg.setOutputValue(name, value)
self.alg.execute(parameters, feedback)
self.alg.execute(new_parameters, feedback)
self.outputs = self.alg.outputs

View File

@ -174,8 +174,8 @@ class ScriptAlgorithm(GeoAlgorithm):
ns['scriptDescriptionFile'] = self.descriptionFile
ns['context'] = context
for param in self.parameters:
ns[param.name] = param.value
for param in self.parameterDefinitions():
ns[param.name] = parameters[param.name()]
for out in self.outputs:
ns[out.name] = out.value
@ -230,9 +230,9 @@ class ScriptAlgorithm(GeoAlgorithm):
with open(helpFile) as f:
try:
descriptions = json.load(f)
for param in self.parameters:
if param.name in descriptions:
descs[param.name] = str(descriptions[param.name])
for param in self.parameterDefinitions():
if param.name() in descriptions:
descs[param.name()] = str(descriptions[param.name()])
except:
return descs
return descs

View File

@ -105,8 +105,8 @@ class AlgorithmsTest(object):
parameters = {}
if isinstance(params, list):
for param in zip(alg.parameters, params):
parameters[param[0].name] = param[1]
for param in zip(alg.parameterDefinitions(), params):
parameters[param[0].name()] = param[1]
else:
for k, p in list(params.items()):
parameters[k] = p