Skip to content

Commit

Permalink
Port raster relief alg to new API
Browse files Browse the repository at this point in the history
  • Loading branch information
nyalldawson committed Aug 18, 2017
1 parent be46b75 commit f6600f2
Show file tree
Hide file tree
Showing 4 changed files with 111 additions and 121 deletions.
4 changes: 2 additions & 2 deletions python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py
Expand Up @@ -119,6 +119,7 @@
from .Rasterize import RasterizeAlgorithm
from .RasterLayerStatistics import RasterLayerStatistics
from .RegularPoints import RegularPoints
from .Relief import Relief
from .ReverseLineDirection import ReverseLineDirection
from .Ruggedness import Ruggedness
from .SaveSelectedFeatures import SaveSelectedFeatures
Expand Down Expand Up @@ -167,7 +168,6 @@
# from .DefineProjection import DefineProjection
# from .RectanglesOvalsDiamondsVariable import RectanglesOvalsDiamondsVariable
# from .RectanglesOvalsDiamondsFixed import RectanglesOvalsDiamondsFixed
# from .Relief import Relief
# from .IdwInterpolation import IdwInterpolation
# from .TinInterpolation import TinInterpolation
# from .RasterCalculator import RasterCalculator
Expand Down Expand Up @@ -197,7 +197,6 @@ def getAlgs(self):
# DefineProjection(),
# RectanglesOvalsDiamondsVariable(),
# RectanglesOvalsDiamondsFixed(),
# Relief(),
# IdwInterpolation(), TinInterpolation(),
# RasterCalculator(),
# ExecuteSQL(), FindProjection(),
Expand Down Expand Up @@ -281,6 +280,7 @@ def getAlgs(self):
RasterizeAlgorithm(),
RasterLayerStatistics(),
RegularPoints(),
Relief(),
ReverseLineDirection(),
Ruggedness(),
SaveSelectedFeatures(),
Expand Down
161 changes: 75 additions & 86 deletions python/plugins/processing/algs/qgis/Relief.py
Expand Up @@ -30,27 +30,66 @@
from qgis.PyQt.QtGui import QIcon, QColor

from qgis.analysis import QgsRelief
from qgis.core import QgsProcessingParameterDefinition
from qgis.core import (QgsProcessingParameterDefinition,
QgsProcessingParameterRasterLayer,
QgsProcessingParameterNumber,
QgsProcessingParameterBoolean,
QgsProcessingParameterRasterDestination,
QgsProcessingParameterFileDestination,
QgsRasterFileWriter,
QgsProcessingException)
from processing.algs.qgis.QgisAlgorithm import QgisAlgorithm
from processing.core.parameters import (Parameter,
ParameterRaster,
ParameterNumber,
ParameterBoolean,
_splitParameterOptions)
from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException
from processing.core.outputs import OutputRaster, OutputTable
from processing.tools import raster
from processing.tools.dataobjects import exportRasterLayer

pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0]


class ParameterReliefColors(QgsProcessingParameterDefinition):

def __init__(self, name='', description='', parent=None, optional=True):
super().__init__(name, description, None, optional)
self.parent = parent
self.setMetadata({'widget_wrapper': 'processing.algs.qgis.ui.ReliefColorsWidget.ReliefColorsWidgetWrapper'})

def type(self):
return 'relief_colors'

def clone(self):
return ParameterReliefColors(self.name(), self.description(), self.parent,
self.flags() & QgsProcessingParameterDefinition.FlagOptional)

@staticmethod
def valueToColors(value):
if value is None:
return None

if value == '':
return None

if isinstance(value, str):
return value.split(';')
else:
return ParameterReliefColors.colorsToString(value)

@staticmethod
def colorsToString(colors):
s = ''
for c in colors:
s += '{:f}, {:f}, {:d}, {:d}, {:d};'.format(c[0],
c[1],
c[2],
c[3],
c[4])
return s[:-1]


class Relief(QgisAlgorithm):

INPUT_LAYER = 'INPUT_LAYER'
INPUT = 'INPUT'
Z_FACTOR = 'Z_FACTOR'
AUTO_COLORS = 'AUTO_COLORS'
COLORS = 'COLORS'
OUTPUT_LAYER = 'OUTPUT_LAYER'
OUTPUT = 'OUTPUT'
FREQUENCY_DISTRIBUTION = 'FREQUENCY_DISTRIBUTION'

def icon(self):
Expand All @@ -63,74 +102,22 @@ def __init__(self):
super().__init__()

def initAlgorithm(self, config=None):
class ParameterReliefColors(Parameter):
default_metadata = {
'widget_wrapper': 'processing.algs.qgis.ui.ReliefColorsWidget.ReliefColorsWidgetWrapper'
}

def __init__(self, name='', description='', parent=None, optional=True):
Parameter.__init__(self, name, description, None, optional)
self.parent = parent

def setValue(self, value):
if value is None:
if not self.flags() & QgsProcessingParameterDefinition.FlagOptional:
return False
self.value = None
return True

if value == '':
if not self.flags() & QgsProcessingParameterDefinition.FlagOptional:
return False

if isinstance(value, str):
self.value = value if value != '' else None
else:
self.value = ParameterReliefColors.colorsToString(value)
return True

def getValueAsCommandLineParameter(self):
return '"{}"'.format(self.value)

def getAsScriptCode(self):
param_type = ''
param_type += 'relief colors '
return '##' + self.name + '=' + param_type

@classmethod
def fromScriptCode(self, line):
isOptional, name, definition = _splitParameterOptions(line)
descName = QgsProcessingParameters.descriptionFromName(name)
parent = definition.lower().strip()[len('relief colors') + 1:]
return ParameterReliefColors(name, descName, parent)

@staticmethod
def colorsToString(colors):
s = ''
for c in colors:
s += '{:f}, {:f}, {:d}, {:d}, {:d};'.format(c[0],
c[1],
c[2],
c[3],
c[4])
return s[:-1]

self.addParameter(ParameterRaster(self.INPUT_LAYER,
self.tr('Elevation layer')))
self.addParameter(ParameterNumber(self.Z_FACTOR,
self.tr('Z factor'),
1.0, 999999.99, 1.0))
self.addParameter(ParameterBoolean(self.AUTO_COLORS,
self.tr('Generate relief classes automatically'),
False))
self.addParameter(QgsProcessingParameterRasterLayer(self.INPUT,
self.tr('Elevation layer')))
self.addParameter(QgsProcessingParameterNumber(self.Z_FACTOR,
self.tr('Z factor'), type=QgsProcessingParameterNumber.Double,
minValue=1.0, maxValue=999999.99, defaultValue=1.0))
self.addParameter(QgsProcessingParameterBoolean(self.AUTO_COLORS,
self.tr('Generate relief classes automatically'),
defaultValue=False))
self.addParameter(ParameterReliefColors(self.COLORS,
self.tr('Relief colors'),
self.INPUT_LAYER,
self.INPUT,
True))
self.addOutput(OutputRaster(self.OUTPUT_LAYER,
self.tr('Relief')))
self.addOutput(OutputTable(self.FREQUENCY_DISTRIBUTION,
self.tr('Frequency distribution')))
self.addParameter(QgsProcessingParameterRasterDestination(self.OUTPUT,
self.tr('Relief')))
self.addParameter(QgsProcessingParameterFileDestination(self.FREQUENCY_DISTRIBUTION,
self.tr('Frequency distribution'), 'CSV files (*.csv)', optional=True))

def name(self):
return 'relief'
Expand All @@ -139,26 +126,26 @@ def displayName(self):
return self.tr('Relief')

def processAlgorithm(self, parameters, context, feedback):
inputFile = self.getParameterValue(self.INPUT_LAYER)
zFactor = self.getParameterValue(self.Z_FACTOR)
automaticColors = self.getParameterValue(self.AUTO_COLORS)
colors = self.getParameterValue(self.COLORS)
outputFile = self.getOutputValue(self.OUTPUT_LAYER)
frequencyDistribution = self.getOutputValue(self.FREQUENCY_DISTRIBUTION)
inputFile = exportRasterLayer(self.parameterAsRasterLayer(parameters, self.INPUT, context))
zFactor = self.parameterAsDouble(parameters, self.Z_FACTOR, context)
automaticColors = self.parameterAsBool(parameters, self.AUTO_COLORS, context)
outputFile = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
frequencyDistribution = self.parameterAsFileOutput(parameters, self.FREQUENCY_DISTRIBUTION, context)

outputFormat = raster.formatShortNameFromFileName(outputFile)
outputFormat = QgsRasterFileWriter.driverForExtension(os.path.splitext(outputFile)[1])

relief = QgsRelief(inputFile, outputFile, outputFormat)

if automaticColors:
reliefColors = relief.calculateOptimizedReliefClasses()
else:
if colors is None:
raise GeoAlgorithmExecutionException(
colors = ParameterReliefColors.valueToColors(parameters[self.COLORS])
if colors is None or len(colors) == 0:
raise QgsProcessingException(
self.tr('Specify relief colors or activate "Generate relief classes automatically" option.'))

reliefColors = []
for c in colors.split(';'):
for c in colors:
v = c.split(',')
color = QgsRelief.ReliefColor(QColor(int(v[2]), int(v[3]), int(v[4])),
float(v[0]),
Expand All @@ -169,3 +156,5 @@ def processAlgorithm(self, parameters, context, feedback):
relief.setZFactor(zFactor)
relief.exportFrequencyDistributionToCsv(frequencyDistribution)
relief.processRaster(None)

return {self.OUTPUT: outputFile, self.FREQUENCY_DISTRIBUTION: frequencyDistribution}
3 changes: 0 additions & 3 deletions python/plugins/processing/script/snippets.py
Expand Up @@ -12,6 +12,3 @@
writer = processing.VectorWriter(output_file, None, fields,
processing.geomtype(layer), layer.crs()
)

##Create a new table
writer = processing.TableWriter(output_file, None, ['field1', 'field2'])
64 changes: 34 additions & 30 deletions python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml
Expand Up @@ -1388,36 +1388,40 @@ tests:
- 75cca4c1a870a1e21185a2d85b33b6d9958a69fc6ebb04e4d6ceb8a3
type: rasterhash

# - algorithm: qgis:relief
# name: Relief (automatic colors generation)
# params:
# AUTO_COLORS: true
# INPUT_LAYER:
# name: dem.tif
# type: raster
# Z_FACTOR: 1.0
# results:
# OUTPUT_LAYER:
# hash: 7fe0e0174185fd743e23760f33615adf10f771b4275f320db6f7f4f8
# type: rasterhash
#
# - algorithm: qgis:relief
# name: Relief (custom colors)
# params:
# AUTO_COLORS: false
# COLORS: 85.000000, 104.436508, 7, 165, 144;104.436508, 104.436508, 12, 221, 162;104.436508,
# 104.436508, 33, 252, 183;104.436508, 104.436508, 247, 252, 152;104.436508, 104.436508,
# 252, 196, 8;104.436508, 190.333333, 252, 166, 15;190.333333, 226.698413, 175,
# 101, 15;226.698413, 226.698413, 255, 133, 92;226.698413, 243.000000, 204, 204,
# 204
# INPUT_LAYER:
# name: dem.tif
# type: raster
# Z_FACTOR: 1.0
# results:
# OUTPUT_LAYER:
# hash: 7fe0e0174185fd743e23760f33615adf10f771b4275f320db6f7f4f8
# type: rasterhash
- algorithm: qgis:relief
name: Relief (automatic colors generation)
params:
AUTO_COLORS: true
INPUT:
name: dem.tif
type: raster
Z_FACTOR: 1.0
results:
OUTPUT:
hash:
- 7fe0e0174185fd743e23760f33615adf10f771b4275f320db6f7f4f8
- 094a2d0dea250690084e0812bf1e8f8666043d17d6a71de278810bb9
type: rasterhash

- algorithm: qgis:relief
name: Relief (custom colors)
params:
AUTO_COLORS: false
COLORS: 85.000000, 104.436508, 7, 165, 144;104.436508, 104.436508, 12, 221, 162;104.436508,
104.436508, 33, 252, 183;104.436508, 104.436508, 247, 252, 152;104.436508, 104.436508,
252, 196, 8;104.436508, 190.333333, 252, 166, 15;190.333333, 226.698413, 175,
101, 15;226.698413, 226.698413, 255, 133, 92;226.698413, 243.000000, 204, 204,
204
INPUT:
name: dem.tif
type: raster
Z_FACTOR: 1.0
results:
OUTPUT:
hash:
- 7fe0e0174185fd743e23760f33615adf10f771b4275f320db6f7f4f8
- 094a2d0dea250690084e0812bf1e8f8666043d17d6a71de278810bb9
type: rasterhash

- algorithm: qgis:createconstantrasterlayer
name: Create constant raster
Expand Down

0 comments on commit f6600f2

Please sign in to comment.