File: contour.py

package info (click to toggle)
qgis 3.40.11%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,183,800 kB
  • sloc: cpp: 1,595,841; python: 372,637; xml: 23,474; sh: 3,761; perl: 3,664; ansic: 2,257; sql: 2,137; yacc: 1,068; lex: 577; javascript: 540; lisp: 411; makefile: 154
file content (310 lines) | stat: -rw-r--r-- 10,632 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
"""
***************************************************************************
    contour.py
    ---------------------
    Date                 : September 2013
    Copyright            : (C) 2013 by Alexander Bruy
    Email                : alexander bruy at gmail dot com
***************************************************************************
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
***************************************************************************
"""

__author__ = "Alexander Bruy"
__date__ = "September 2013"
__copyright__ = "(C) 2013, Alexander Bruy"

import os

from qgis.PyQt.QtGui import QIcon

from qgis.core import (
    QgsProcessing,
    QgsProcessingException,
    QgsProcessingParameterDefinition,
    QgsProcessingParameterRasterLayer,
    QgsProcessingParameterBand,
    QgsProcessingParameterString,
    QgsProcessingParameterNumber,
    QgsProcessingParameterBoolean,
    QgsProcessingParameterVectorDestination,
)
from processing.algs.gdal.GdalAlgorithm import GdalAlgorithm
from processing.algs.gdal.GdalUtils import GdalUtils

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


class contour(GdalAlgorithm):
    INPUT = "INPUT"
    BAND = "BAND"
    INTERVAL = "INTERVAL"
    FIELD_NAME = "FIELD_NAME"
    CREATE_3D = "CREATE_3D"
    IGNORE_NODATA = "IGNORE_NODATA"
    NODATA = "NODATA"
    OFFSET = "OFFSET"
    EXTRA = "EXTRA"
    OPTIONS = "OPTIONS"
    OUTPUT = "OUTPUT"

    def __init__(self):
        super().__init__()

    def initAlgorithm(self, config=None):
        self.addParameter(
            QgsProcessingParameterRasterLayer(self.INPUT, self.tr("Input layer"))
        )
        self.addParameter(
            QgsProcessingParameterBand(
                self.BAND,
                self.tr("Band number"),
                1,
                parentLayerParameterName=self.INPUT,
            )
        )
        self.addParameter(
            QgsProcessingParameterNumber(
                self.INTERVAL,
                self.tr("Interval between contour lines"),
                type=QgsProcessingParameterNumber.Type.Double,
                minValue=0.0,
                defaultValue=10.0,
            )
        )
        self.addParameter(
            QgsProcessingParameterString(
                self.FIELD_NAME,
                self.tr(
                    "Attribute name (if not set, no elevation attribute is attached)"
                ),
                defaultValue="ELEV",
                optional=True,
            )
        )

        create_3d_param = QgsProcessingParameterBoolean(
            self.CREATE_3D, self.tr("Produce 3D vector"), defaultValue=False
        )
        create_3d_param.setFlags(
            create_3d_param.flags() | QgsProcessingParameterDefinition.Flag.FlagAdvanced
        )
        self.addParameter(create_3d_param)

        ignore_nodata_param = QgsProcessingParameterBoolean(
            self.IGNORE_NODATA,
            self.tr("Treat all raster values as valid"),
            defaultValue=False,
        )
        ignore_nodata_param.setFlags(
            ignore_nodata_param.flags()
            | QgsProcessingParameterDefinition.Flag.FlagAdvanced
        )
        self.addParameter(ignore_nodata_param)

        nodata_param = QgsProcessingParameterNumber(
            self.NODATA,
            self.tr("Input pixel value to treat as NoData"),
            type=QgsProcessingParameterNumber.Type.Double,
            defaultValue=None,
            optional=True,
        )
        nodata_param.setFlags(
            nodata_param.flags() | QgsProcessingParameterDefinition.Flag.FlagAdvanced
        )
        self.addParameter(nodata_param)

        offset_param = QgsProcessingParameterNumber(
            self.OFFSET,
            self.tr("Offset from zero relative to which to interpret intervals"),
            type=QgsProcessingParameterNumber.Type.Double,
            defaultValue=0.0,
            optional=True,
        )
        nodata_param.setFlags(
            offset_param.flags() | QgsProcessingParameterDefinition.Flag.FlagAdvanced
        )
        self.addParameter(offset_param)

        extra_param = QgsProcessingParameterString(
            self.EXTRA,
            self.tr("Additional command-line parameters"),
            defaultValue=None,
            optional=True,
        )
        extra_param.setFlags(
            extra_param.flags() | QgsProcessingParameterDefinition.Flag.FlagAdvanced
        )
        self.addParameter(extra_param)

        # TODO: remove in QGIS 4
        options_param = QgsProcessingParameterString(
            self.OPTIONS,
            self.tr("Additional creation options"),
            defaultValue="",
            optional=True,
        )
        options_param.setFlags(
            options_param.flags() | QgsProcessingParameterDefinition.Flag.FlagHidden
        )
        self.addParameter(options_param)

        self.addParameter(
            QgsProcessingParameterVectorDestination(
                self.OUTPUT,
                self.tr("Contours"),
                QgsProcessing.SourceType.TypeVectorLine,
            )
        )

    def name(self):
        return "contour"

    def displayName(self):
        return self.tr("Contour")

    def icon(self):
        return QIcon(os.path.join(pluginPath, "images", "gdaltools", "contour.png"))

    def group(self):
        return self.tr("Raster extraction")

    def groupId(self):
        return "rasterextraction"

    def commandName(self):
        return "gdal_contour"

    def _buildArgsList(self, parameters, context, feedback, executing):
        inLayer = self.parameterAsRasterLayer(parameters, self.INPUT, context)
        if inLayer is None:
            raise QgsProcessingException(
                self.invalidRasterError(parameters, self.INPUT)
            )
        input_details = GdalUtils.gdal_connection_details_from_layer(inLayer)

        fieldName = self.parameterAsString(parameters, self.FIELD_NAME, context)
        if self.NODATA in parameters and parameters[self.NODATA] is not None:
            nodata = self.parameterAsDouble(parameters, self.NODATA, context)
        else:
            nodata = None
        offset = self.parameterAsDouble(parameters, self.OFFSET, context)

        outFile = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
        self.setOutputValue(self.OUTPUT, outFile)
        output_details = GdalUtils.gdal_connection_details_from_uri(outFile, context)

        arguments = ["-b", str(self.parameterAsInt(parameters, self.BAND, context))]
        if fieldName:
            arguments.append("-a")
            arguments.append(fieldName)

        arguments.append("-i")
        arguments.append(
            str(self.parameterAsDouble(parameters, self.INTERVAL, context))
        )

        if self.parameterAsBoolean(parameters, self.CREATE_3D, context):
            arguments.append("-3d")

        if self.parameterAsBoolean(parameters, self.IGNORE_NODATA, context):
            arguments.append("-inodata")

        if nodata is not None:
            arguments.append(f"-snodata {nodata}")

        if offset:
            arguments.append(f"-off {offset}")

        if output_details.format:
            arguments.append(f"-f {output_details.format}")

        if input_details.credential_options:
            arguments.extend(input_details.credential_options_as_arguments())

        if self.EXTRA in parameters and parameters[self.EXTRA] not in (None, ""):
            extra = self.parameterAsString(parameters, self.EXTRA, context)
            arguments.append(extra)

        # TODO: remove in QGIS 4
        options = self.parameterAsString(parameters, self.OPTIONS, context)
        if options:
            arguments.append(options)

        arguments.append(input_details.connection_string)
        arguments.append(output_details.connection_string)
        return arguments

    def getConsoleCommands(self, parameters, context, feedback, executing=True):
        arguments = self._buildArgsList(parameters, context, feedback, executing)
        return [self.commandName(), GdalUtils.escapeAndJoin(arguments)]


class contour_polygon(contour):
    FIELD_NAME_MIN = "FIELD_NAME_MIN"
    FIELD_NAME_MAX = "FIELD_NAME_MAX"

    def __init__(self):
        super().__init__()

    def initAlgorithm(self, config=None):
        super().initAlgorithm(config)
        # FIELD_NAME isn't used in polygon mode
        self.removeParameter(contour.FIELD_NAME)

        self.addParameter(
            QgsProcessingParameterString(
                self.FIELD_NAME_MIN,
                self.tr("Attribute name for minimum elevation of contour polygon"),
                defaultValue="ELEV_MIN",
                optional=True,
            )
        )

        self.addParameter(
            QgsProcessingParameterString(
                self.FIELD_NAME_MAX,
                self.tr("Attribute name for maximum elevation of contour polygon"),
                defaultValue="ELEV_MAX",
                optional=True,
            )
        )

        # Need to replace the output parameter, as we are producing a different type of output
        self.removeParameter(contour.OUTPUT)
        self.addParameter(
            QgsProcessingParameterVectorDestination(
                contour.OUTPUT,
                self.tr("Contours"),
                QgsProcessing.SourceType.TypeVectorPolygon,
            )
        )

    def name(self):
        return "contour_polygon"

    def displayName(self):
        return self.tr("Contour Polygons")

    def getConsoleCommands(self, parameters, context, feedback, executing=True):
        arguments = self._buildArgsList(parameters, context, feedback, executing)

        fieldNameMin = self.parameterAsString(parameters, self.FIELD_NAME_MIN, context)
        fieldNameMax = self.parameterAsString(parameters, self.FIELD_NAME_MAX, context)

        if fieldNameMin:
            arguments.insert(0, fieldNameMin)
            arguments.insert(0, "-amin")

        if fieldNameMax:
            arguments.insert(0, fieldNameMax)
            arguments.insert(0, "-amax")

        arguments.insert(0, "-p")

        return [self.commandName(), GdalUtils.escapeAndJoin(arguments)]