Skip to content

Commit f6600f2

Browse files
committedAug 18, 2017
Port raster relief alg to new API
1 parent be46b75 commit f6600f2

File tree

4 files changed

+111
-121
lines changed

4 files changed

+111
-121
lines changed
 

‎python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,7 @@
119119
from .Rasterize import RasterizeAlgorithm
120120
from .RasterLayerStatistics import RasterLayerStatistics
121121
from .RegularPoints import RegularPoints
122+
from .Relief import Relief
122123
from .ReverseLineDirection import ReverseLineDirection
123124
from .Ruggedness import Ruggedness
124125
from .SaveSelectedFeatures import SaveSelectedFeatures
@@ -167,7 +168,6 @@
167168
# from .DefineProjection import DefineProjection
168169
# from .RectanglesOvalsDiamondsVariable import RectanglesOvalsDiamondsVariable
169170
# from .RectanglesOvalsDiamondsFixed import RectanglesOvalsDiamondsFixed
170-
# from .Relief import Relief
171171
# from .IdwInterpolation import IdwInterpolation
172172
# from .TinInterpolation import TinInterpolation
173173
# from .RasterCalculator import RasterCalculator
@@ -197,7 +197,6 @@ def getAlgs(self):
197197
# DefineProjection(),
198198
# RectanglesOvalsDiamondsVariable(),
199199
# RectanglesOvalsDiamondsFixed(),
200-
# Relief(),
201200
# IdwInterpolation(), TinInterpolation(),
202201
# RasterCalculator(),
203202
# ExecuteSQL(), FindProjection(),
@@ -281,6 +280,7 @@ def getAlgs(self):
281280
RasterizeAlgorithm(),
282281
RasterLayerStatistics(),
283282
RegularPoints(),
283+
Relief(),
284284
ReverseLineDirection(),
285285
Ruggedness(),
286286
SaveSelectedFeatures(),

‎python/plugins/processing/algs/qgis/Relief.py

Lines changed: 75 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -30,27 +30,66 @@
3030
from qgis.PyQt.QtGui import QIcon, QColor
3131

3232
from qgis.analysis import QgsRelief
33-
from qgis.core import QgsProcessingParameterDefinition
33+
from qgis.core import (QgsProcessingParameterDefinition,
34+
QgsProcessingParameterRasterLayer,
35+
QgsProcessingParameterNumber,
36+
QgsProcessingParameterBoolean,
37+
QgsProcessingParameterRasterDestination,
38+
QgsProcessingParameterFileDestination,
39+
QgsRasterFileWriter,
40+
QgsProcessingException)
3441
from processing.algs.qgis.QgisAlgorithm import QgisAlgorithm
35-
from processing.core.parameters import (Parameter,
36-
ParameterRaster,
37-
ParameterNumber,
38-
ParameterBoolean,
39-
_splitParameterOptions)
40-
from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException
41-
from processing.core.outputs import OutputRaster, OutputTable
42-
from processing.tools import raster
42+
from processing.tools.dataobjects import exportRasterLayer
4343

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

4646

47+
class ParameterReliefColors(QgsProcessingParameterDefinition):
48+
49+
def __init__(self, name='', description='', parent=None, optional=True):
50+
super().__init__(name, description, None, optional)
51+
self.parent = parent
52+
self.setMetadata({'widget_wrapper': 'processing.algs.qgis.ui.ReliefColorsWidget.ReliefColorsWidgetWrapper'})
53+
54+
def type(self):
55+
return 'relief_colors'
56+
57+
def clone(self):
58+
return ParameterReliefColors(self.name(), self.description(), self.parent,
59+
self.flags() & QgsProcessingParameterDefinition.FlagOptional)
60+
61+
@staticmethod
62+
def valueToColors(value):
63+
if value is None:
64+
return None
65+
66+
if value == '':
67+
return None
68+
69+
if isinstance(value, str):
70+
return value.split(';')
71+
else:
72+
return ParameterReliefColors.colorsToString(value)
73+
74+
@staticmethod
75+
def colorsToString(colors):
76+
s = ''
77+
for c in colors:
78+
s += '{:f}, {:f}, {:d}, {:d}, {:d};'.format(c[0],
79+
c[1],
80+
c[2],
81+
c[3],
82+
c[4])
83+
return s[:-1]
84+
85+
4786
class Relief(QgisAlgorithm):
4887

49-
INPUT_LAYER = 'INPUT_LAYER'
88+
INPUT = 'INPUT'
5089
Z_FACTOR = 'Z_FACTOR'
5190
AUTO_COLORS = 'AUTO_COLORS'
5291
COLORS = 'COLORS'
53-
OUTPUT_LAYER = 'OUTPUT_LAYER'
92+
OUTPUT = 'OUTPUT'
5493
FREQUENCY_DISTRIBUTION = 'FREQUENCY_DISTRIBUTION'
5594

5695
def icon(self):
@@ -63,74 +102,22 @@ def __init__(self):
63102
super().__init__()
64103

65104
def initAlgorithm(self, config=None):
66-
class ParameterReliefColors(Parameter):
67-
default_metadata = {
68-
'widget_wrapper': 'processing.algs.qgis.ui.ReliefColorsWidget.ReliefColorsWidgetWrapper'
69-
}
70-
71-
def __init__(self, name='', description='', parent=None, optional=True):
72-
Parameter.__init__(self, name, description, None, optional)
73-
self.parent = parent
74-
75-
def setValue(self, value):
76-
if value is None:
77-
if not self.flags() & QgsProcessingParameterDefinition.FlagOptional:
78-
return False
79-
self.value = None
80-
return True
81-
82-
if value == '':
83-
if not self.flags() & QgsProcessingParameterDefinition.FlagOptional:
84-
return False
85-
86-
if isinstance(value, str):
87-
self.value = value if value != '' else None
88-
else:
89-
self.value = ParameterReliefColors.colorsToString(value)
90-
return True
91-
92-
def getValueAsCommandLineParameter(self):
93-
return '"{}"'.format(self.value)
94-
95-
def getAsScriptCode(self):
96-
param_type = ''
97-
param_type += 'relief colors '
98-
return '##' + self.name + '=' + param_type
99-
100-
@classmethod
101-
def fromScriptCode(self, line):
102-
isOptional, name, definition = _splitParameterOptions(line)
103-
descName = QgsProcessingParameters.descriptionFromName(name)
104-
parent = definition.lower().strip()[len('relief colors') + 1:]
105-
return ParameterReliefColors(name, descName, parent)
106-
107-
@staticmethod
108-
def colorsToString(colors):
109-
s = ''
110-
for c in colors:
111-
s += '{:f}, {:f}, {:d}, {:d}, {:d};'.format(c[0],
112-
c[1],
113-
c[2],
114-
c[3],
115-
c[4])
116-
return s[:-1]
117-
118-
self.addParameter(ParameterRaster(self.INPUT_LAYER,
119-
self.tr('Elevation layer')))
120-
self.addParameter(ParameterNumber(self.Z_FACTOR,
121-
self.tr('Z factor'),
122-
1.0, 999999.99, 1.0))
123-
self.addParameter(ParameterBoolean(self.AUTO_COLORS,
124-
self.tr('Generate relief classes automatically'),
125-
False))
105+
self.addParameter(QgsProcessingParameterRasterLayer(self.INPUT,
106+
self.tr('Elevation layer')))
107+
self.addParameter(QgsProcessingParameterNumber(self.Z_FACTOR,
108+
self.tr('Z factor'), type=QgsProcessingParameterNumber.Double,
109+
minValue=1.0, maxValue=999999.99, defaultValue=1.0))
110+
self.addParameter(QgsProcessingParameterBoolean(self.AUTO_COLORS,
111+
self.tr('Generate relief classes automatically'),
112+
defaultValue=False))
126113
self.addParameter(ParameterReliefColors(self.COLORS,
127114
self.tr('Relief colors'),
128-
self.INPUT_LAYER,
115+
self.INPUT,
129116
True))
130-
self.addOutput(OutputRaster(self.OUTPUT_LAYER,
131-
self.tr('Relief')))
132-
self.addOutput(OutputTable(self.FREQUENCY_DISTRIBUTION,
133-
self.tr('Frequency distribution')))
117+
self.addParameter(QgsProcessingParameterRasterDestination(self.OUTPUT,
118+
self.tr('Relief')))
119+
self.addParameter(QgsProcessingParameterFileDestination(self.FREQUENCY_DISTRIBUTION,
120+
self.tr('Frequency distribution'), 'CSV files (*.csv)', optional=True))
134121

135122
def name(self):
136123
return 'relief'
@@ -139,26 +126,26 @@ def displayName(self):
139126
return self.tr('Relief')
140127

141128
def processAlgorithm(self, parameters, context, feedback):
142-
inputFile = self.getParameterValue(self.INPUT_LAYER)
143-
zFactor = self.getParameterValue(self.Z_FACTOR)
144-
automaticColors = self.getParameterValue(self.AUTO_COLORS)
145-
colors = self.getParameterValue(self.COLORS)
146-
outputFile = self.getOutputValue(self.OUTPUT_LAYER)
147-
frequencyDistribution = self.getOutputValue(self.FREQUENCY_DISTRIBUTION)
129+
inputFile = exportRasterLayer(self.parameterAsRasterLayer(parameters, self.INPUT, context))
130+
zFactor = self.parameterAsDouble(parameters, self.Z_FACTOR, context)
131+
automaticColors = self.parameterAsBool(parameters, self.AUTO_COLORS, context)
132+
outputFile = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
133+
frequencyDistribution = self.parameterAsFileOutput(parameters, self.FREQUENCY_DISTRIBUTION, context)
148134

149-
outputFormat = raster.formatShortNameFromFileName(outputFile)
135+
outputFormat = QgsRasterFileWriter.driverForExtension(os.path.splitext(outputFile)[1])
150136

151137
relief = QgsRelief(inputFile, outputFile, outputFormat)
152138

153139
if automaticColors:
154140
reliefColors = relief.calculateOptimizedReliefClasses()
155141
else:
156-
if colors is None:
157-
raise GeoAlgorithmExecutionException(
142+
colors = ParameterReliefColors.valueToColors(parameters[self.COLORS])
143+
if colors is None or len(colors) == 0:
144+
raise QgsProcessingException(
158145
self.tr('Specify relief colors or activate "Generate relief classes automatically" option.'))
159146

160147
reliefColors = []
161-
for c in colors.split(';'):
148+
for c in colors:
162149
v = c.split(',')
163150
color = QgsRelief.ReliefColor(QColor(int(v[2]), int(v[3]), int(v[4])),
164151
float(v[0]),
@@ -169,3 +156,5 @@ def processAlgorithm(self, parameters, context, feedback):
169156
relief.setZFactor(zFactor)
170157
relief.exportFrequencyDistributionToCsv(frequencyDistribution)
171158
relief.processRaster(None)
159+
160+
return {self.OUTPUT: outputFile, self.FREQUENCY_DISTRIBUTION: frequencyDistribution}

‎python/plugins/processing/script/snippets.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,3 @@
1212
writer = processing.VectorWriter(output_file, None, fields,
1313
processing.geomtype(layer), layer.crs()
1414
)
15-
16-
##Create a new table
17-
writer = processing.TableWriter(output_file, None, ['field1', 'field2'])

‎python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml

Lines changed: 34 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1388,36 +1388,40 @@ tests:
13881388
- 75cca4c1a870a1e21185a2d85b33b6d9958a69fc6ebb04e4d6ceb8a3
13891389
type: rasterhash
13901390

1391-
# - algorithm: qgis:relief
1392-
# name: Relief (automatic colors generation)
1393-
# params:
1394-
# AUTO_COLORS: true
1395-
# INPUT_LAYER:
1396-
# name: dem.tif
1397-
# type: raster
1398-
# Z_FACTOR: 1.0
1399-
# results:
1400-
# OUTPUT_LAYER:
1401-
# hash: 7fe0e0174185fd743e23760f33615adf10f771b4275f320db6f7f4f8
1402-
# type: rasterhash
1403-
#
1404-
# - algorithm: qgis:relief
1405-
# name: Relief (custom colors)
1406-
# params:
1407-
# AUTO_COLORS: false
1408-
# COLORS: 85.000000, 104.436508, 7, 165, 144;104.436508, 104.436508, 12, 221, 162;104.436508,
1409-
# 104.436508, 33, 252, 183;104.436508, 104.436508, 247, 252, 152;104.436508, 104.436508,
1410-
# 252, 196, 8;104.436508, 190.333333, 252, 166, 15;190.333333, 226.698413, 175,
1411-
# 101, 15;226.698413, 226.698413, 255, 133, 92;226.698413, 243.000000, 204, 204,
1412-
# 204
1413-
# INPUT_LAYER:
1414-
# name: dem.tif
1415-
# type: raster
1416-
# Z_FACTOR: 1.0
1417-
# results:
1418-
# OUTPUT_LAYER:
1419-
# hash: 7fe0e0174185fd743e23760f33615adf10f771b4275f320db6f7f4f8
1420-
# type: rasterhash
1391+
- algorithm: qgis:relief
1392+
name: Relief (automatic colors generation)
1393+
params:
1394+
AUTO_COLORS: true
1395+
INPUT:
1396+
name: dem.tif
1397+
type: raster
1398+
Z_FACTOR: 1.0
1399+
results:
1400+
OUTPUT:
1401+
hash:
1402+
- 7fe0e0174185fd743e23760f33615adf10f771b4275f320db6f7f4f8
1403+
- 094a2d0dea250690084e0812bf1e8f8666043d17d6a71de278810bb9
1404+
type: rasterhash
1405+
1406+
- algorithm: qgis:relief
1407+
name: Relief (custom colors)
1408+
params:
1409+
AUTO_COLORS: false
1410+
COLORS: 85.000000, 104.436508, 7, 165, 144;104.436508, 104.436508, 12, 221, 162;104.436508,
1411+
104.436508, 33, 252, 183;104.436508, 104.436508, 247, 252, 152;104.436508, 104.436508,
1412+
252, 196, 8;104.436508, 190.333333, 252, 166, 15;190.333333, 226.698413, 175,
1413+
101, 15;226.698413, 226.698413, 255, 133, 92;226.698413, 243.000000, 204, 204,
1414+
204
1415+
INPUT:
1416+
name: dem.tif
1417+
type: raster
1418+
Z_FACTOR: 1.0
1419+
results:
1420+
OUTPUT:
1421+
hash:
1422+
- 7fe0e0174185fd743e23760f33615adf10f771b4275f320db6f7f4f8
1423+
- 094a2d0dea250690084e0812bf1e8f8666043d17d6a71de278810bb9
1424+
type: rasterhash
14211425

14221426
- algorithm: qgis:createconstantrasterlayer
14231427
name: Create constant raster

0 commit comments

Comments
 (0)
Please sign in to comment.