File: buildvrt.py

package info (click to toggle)
qgis 3.40.6%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 1,181,336 kB
  • sloc: cpp: 1,593,302; python: 370,494; xml: 23,474; perl: 3,664; sh: 3,482; ansic: 2,257; sql: 2,133; yacc: 1,068; lex: 577; javascript: 540; lisp: 411; makefile: 157
file content (285 lines) | stat: -rw-r--r-- 10,206 bytes parent folder | download | duplicates (6)
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
"""
***************************************************************************
    merge.py
    ---------------------
    Date                 : October 2014
    Copyright            : (C) 2014 by Radoslaw Guzinski
    Email                : rmgu at dhi-gras 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__ = "Radoslaw Guzinski"
__date__ = "October 2014"
__copyright__ = "(C) 2014, Radoslaw Guzinski"

import os
import pathlib

from qgis.PyQt.QtCore import QCoreApplication
from qgis.PyQt.QtGui import QIcon

from qgis.core import (
    QgsProcessingAlgorithm,
    QgsProcessing,
    QgsProcessingParameterDefinition,
    QgsProperty,
    QgsProcessingParameters,
    QgsProcessingParameterMultipleLayers,
    QgsProcessingParameterEnum,
    QgsProcessingParameterBoolean,
    QgsProcessingParameterRasterDestination,
    QgsProcessingParameterCrs,
    QgsProcessingParameterString,
    QgsProcessingOutputLayerDefinition,
    QgsProcessingUtils,
)
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 buildvrt(GdalAlgorithm):
    INPUT = "INPUT"
    OUTPUT = "OUTPUT"
    RESOLUTION = "RESOLUTION"
    SEPARATE = "SEPARATE"
    PROJ_DIFFERENCE = "PROJ_DIFFERENCE"
    ADD_ALPHA = "ADD_ALPHA"
    ASSIGN_CRS = "ASSIGN_CRS"
    RESAMPLING = "RESAMPLING"
    SRC_NODATA = "SRC_NODATA"
    EXTRA = "EXTRA"

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

    def initAlgorithm(self, config=None):

        class ParameterVrtDestination(QgsProcessingParameterRasterDestination):

            def __init__(self, name, description):
                super().__init__(name, description)

            def clone(self):
                copy = ParameterVrtDestination(self.name(), self.description())
                return copy

            def defaultFileExtension(self):
                return "vrt"

            def createFileFilter(self):
                return "{} (*.vrt *.VRT)".format(
                    QCoreApplication.translate("GdalAlgorithm", "VRT files")
                )

            def supportedOutputRasterLayerExtensions(self):
                return ["vrt"]

            def parameterAsOutputLayer(self, definition, value, context):
                return super(
                    QgsProcessingParameterRasterDestination, self
                ).parameterAsOutputLayer(definition, value, context)

            def isSupportedOutputValue(self, value, context):
                output_path = QgsProcessingParameters.parameterAsOutputLayer(
                    self, value, context, testOnly=True
                )
                if pathlib.Path(output_path).suffix.lower() != ".vrt":
                    return False, QCoreApplication.translate(
                        "GdalAlgorithm", "Output filename must use a .vrt extension"
                    )
                return True, ""

        self.RESAMPLING_OPTIONS = (
            (self.tr("Nearest Neighbour"), "nearest"),
            (self.tr("Bilinear (2x2 Kernel)"), "bilinear"),
            (self.tr("Cubic (4x4 Kernel)"), "cubic"),
            (self.tr("Cubic B-Spline (4x4 Kernel)"), "cubicspline"),
            (self.tr("Lanczos (6x6 Kernel)"), "lanczos"),
            (self.tr("Average"), "average"),
            (self.tr("Mode"), "mode"),
        )

        self.RESOLUTION_OPTIONS = (
            (self.tr("Average"), "average"),
            (self.tr("Highest"), "highest"),
            (self.tr("Lowest"), "lowest"),
        )

        self.addParameter(
            QgsProcessingParameterMultipleLayers(
                self.INPUT, self.tr("Input layers"), QgsProcessing.SourceType.TypeRaster
            )
        )
        self.addParameter(
            QgsProcessingParameterEnum(
                self.RESOLUTION,
                self.tr("Resolution"),
                options=[i[0] for i in self.RESOLUTION_OPTIONS],
                defaultValue=0,
            )
        )

        separate_param = QgsProcessingParameterBoolean(
            self.SEPARATE,
            self.tr("Place each input file into a separate band"),
            defaultValue=True,
        )
        # default to not using separate bands is a friendlier option, but we can't change the parameter's actual
        # defaultValue without breaking API!
        separate_param.setGuiDefaultValueOverride(False)
        self.addParameter(separate_param)

        self.addParameter(
            QgsProcessingParameterBoolean(
                self.PROJ_DIFFERENCE,
                self.tr("Allow projection difference"),
                defaultValue=False,
            )
        )

        add_alpha_param = QgsProcessingParameterBoolean(
            self.ADD_ALPHA,
            self.tr("Add alpha mask band to VRT when source raster has none"),
            defaultValue=False,
        )
        add_alpha_param.setFlags(
            add_alpha_param.flags() | QgsProcessingParameterDefinition.Flag.FlagAdvanced
        )
        self.addParameter(add_alpha_param)

        assign_crs = QgsProcessingParameterCrs(
            self.ASSIGN_CRS,
            self.tr("Override projection for the output file"),
            defaultValue=None,
            optional=True,
        )
        assign_crs.setFlags(
            assign_crs.flags() | QgsProcessingParameterDefinition.Flag.FlagAdvanced
        )
        self.addParameter(assign_crs)

        resampling = QgsProcessingParameterEnum(
            self.RESAMPLING,
            self.tr("Resampling algorithm"),
            options=[i[0] for i in self.RESAMPLING_OPTIONS],
            defaultValue=0,
        )
        resampling.setFlags(
            resampling.flags() | QgsProcessingParameterDefinition.Flag.FlagAdvanced
        )
        self.addParameter(resampling)

        src_nodata_param = QgsProcessingParameterString(
            self.SRC_NODATA,
            self.tr("Nodata value(s) for input bands (space separated)"),
            defaultValue=None,
            optional=True,
        )
        src_nodata_param.setFlags(
            src_nodata_param.flags()
            | QgsProcessingParameterDefinition.Flag.FlagAdvanced
        )
        self.addParameter(src_nodata_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)

        self.addParameter(
            ParameterVrtDestination(
                self.OUTPUT,
                QCoreApplication.translate("ParameterVrtDestination", "Virtual"),
            )
        )

    def name(self):
        return "buildvirtualraster"

    def displayName(self):
        return QCoreApplication.translate("buildvrt", "Build virtual raster")

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

    def group(self):
        return QCoreApplication.translate("buildvrt", "Raster miscellaneous")

    def groupId(self):
        return "rastermiscellaneous"

    def commandName(self):
        return "gdalbuildvrt"

    def getConsoleCommands(self, parameters, context, feedback, executing=True):
        arguments = [
            "-overwrite",
            "-resolution",
            self.RESOLUTION_OPTIONS[
                self.parameterAsEnum(parameters, self.RESOLUTION, context)
            ][1],
        ]

        if self.parameterAsBoolean(parameters, buildvrt.SEPARATE, context):
            arguments.append("-separate")
        if self.parameterAsBoolean(parameters, buildvrt.PROJ_DIFFERENCE, context):
            arguments.append("-allow_projection_difference")
        if self.parameterAsBoolean(parameters, buildvrt.ADD_ALPHA, context):
            arguments.append("-addalpha")
        crs = self.parameterAsCrs(parameters, self.ASSIGN_CRS, context)
        if crs.isValid():
            arguments.append("-a_srs")
            arguments.append(GdalUtils.gdal_crs_string(crs))
        arguments.append("-r")
        arguments.append(
            self.RESAMPLING_OPTIONS[
                self.parameterAsEnum(parameters, self.RESAMPLING, context)
            ][1]
        )

        if self.SRC_NODATA in parameters and parameters[self.SRC_NODATA] not in (
            None,
            "",
        ):
            nodata = self.parameterAsString(parameters, self.SRC_NODATA, context)
            arguments.append("-srcnodata")
            arguments.append(nodata)

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

        # Always write input files to a text file in case there are many of them and the
        # length of the command will be longer then allowed in command prompt
        list_file = GdalUtils.writeLayerParameterToTextFile(
            filename="buildvrtInputFiles.txt",
            alg=self,
            parameters=parameters,
            parameter_name=self.INPUT,
            context=context,
            executing=executing,
            quote=False,
        )
        arguments.append("-input_file_list")
        arguments.append(list_file)

        out = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
        self.setOutputValue(self.OUTPUT, out)
        arguments.append(out)

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