-
Notifications
You must be signed in to change notification settings - Fork 1
/
ltop_precipitation.py
368 lines (304 loc) · 12.3 KB
/
ltop_precipitation.py
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# -*- coding: utf-8 -*-
"""
/***************************************************************************
LTOrographicPrecipitation
A QGIS plugin
Implements the Smith & Barstad (2004) LT model
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2018-05-02
copyright : (C) 2018-2020 by Andy Aschwanden and Constantine Khrulev
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* 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__ = "Andy Aschwanden and Constantine Khrulev"
__date__ = "2018-05-02"
__copyright__ = "(C) 2018-2020 by Andy Aschwanden and Constantine Khrulev"
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = "$Format:%H$"
import os
from PyQt5.QtCore import QCoreApplication
from qgis.core import (
Qgis,
QgsProcessingAlgorithm,
QgsProcessingParameterBand,
QgsProcessingParameterBoolean,
QgsProcessingParameterNumber,
QgsProcessingParameterRasterDestination,
QgsProcessingParameterRasterLayer,
QgsRasterFileWriter,
)
try:
import numpy
from .linear_orog_precip import LTOP
has_numpy = True
except:
has_numpy = False
def raster_to_array(layer, band=1):
"Convert a raster layer to a NumPy array."
provider = layer.dataProvider()
width, height = layer.width(), layer.height()
block = provider.block(band, provider.extent(), width, height)
# supported types
types = {
Qgis.Byte: numpy.byte,
Qgis.UInt16: numpy.uint16,
Qgis.Int16: numpy.int16,
Qgis.UInt32: numpy.uint32,
Qgis.Int32: numpy.int32,
Qgis.Float32: numpy.float32,
Qgis.Float64: numpy.float64,
}
try:
T = types[block.dataType()]
except KeyError:
raise NotImplementedError(
"raster type {} is not supported".format(block.dataType())
)
return numpy.ndarray((height, width), dtype=T, buffer=block.data().data())
def grid(layer):
"Build x and y coordinates of a raster layer."
# physical extent of the layer
extent = layer.extent()
# size of the raster
Mx = layer.width()
My = layer.height()
# grid spacing
dx = extent.width() / float(Mx)
dy = extent.height() / float(My)
x_min, x_max = extent.xMinimum(), extent.xMaximum()
y_min, y_max = extent.yMinimum(), extent.yMaximum()
# assume that raster cells are centered at corresponding x and y
x = numpy.linspace(x_min + 0.5 * dx, x_max - 0.5 * dy, Mx)
y = numpy.linspace(y_min + 0.5 * dy, y_max - 0.5 * dy, My)[::-1]
return x, y
class LTOrographicPrecipitationAlgorithm(QgsProcessingAlgorithm):
# Constants used to refer to parameters and outputs. They will be
# used when calling the algorithm from another algorithm, or when
# calling from the QGIS console.
OUTPUT = "OUTPUT"
INPUT_RASTER = "INPUT_RASTER"
RASTER_BAND = "RASTER_BAND"
TAU_C = "TAU_C"
TAU_F = "TAU_F"
P0 = "P0"
P_SCALE = "P_SCALE"
NM = "NM"
HW = "HW"
LATITUDE = "LATITUDE"
WIND_DIRECTION = "WIND_DIRECTION"
WIND_SPEED = "WIND_SPEED"
TRUNCATE = "TRUNCATE"
def initAlgorithm(self, config):
"""
Define inputs and output of the algorithm.
"""
self.addParameter(
QgsProcessingParameterRasterLayer(
self.INPUT_RASTER, self.tr("Input DEM (meters above sea level)")
)
)
self.addParameter(
QgsProcessingParameterBand(
self.RASTER_BAND, self.tr("Band number"), 1, self.INPUT_RASTER
)
)
model = LTOP()
self.addParameter(
QgsProcessingParameterNumber(
self.TAU_C,
self.tr("Conversion time (seconds)"),
QgsProcessingParameterNumber.Double,
defaultValue=model.tau_c,
minValue=0.0,
)
)
self.addParameter(
QgsProcessingParameterNumber(
self.TAU_F,
self.tr("Fallout time (seconds)"),
QgsProcessingParameterNumber.Double,
defaultValue=model.tau_f,
minValue=0.0,
)
)
self.addParameter(
QgsProcessingParameterNumber(
self.P0,
self.tr("Background precipitation rate (mm/hour)"),
QgsProcessingParameterNumber.Double,
defaultValue=model.P0,
minValue=0.0,
)
)
self.addParameter(
QgsProcessingParameterNumber(
self.P_SCALE,
self.tr("Precipitation scale factor"),
QgsProcessingParameterNumber.Double,
defaultValue=1.0,
minValue=0.0,
)
)
self.addParameter(
QgsProcessingParameterNumber(
self.NM,
self.tr("Moist stability frequency (1/second)"),
QgsProcessingParameterNumber.Double,
defaultValue=model.Nm,
minValue=0.0,
)
)
self.addParameter(
QgsProcessingParameterNumber(
self.HW,
self.tr("Water vapor scale height (meters)"),
QgsProcessingParameterNumber.Double,
defaultValue=model.Hw,
minValue=0.0,
)
)
self.addParameter(
QgsProcessingParameterNumber(
self.LATITUDE,
self.tr("Latitude used to compute the Coriolis force"),
QgsProcessingParameterNumber.Double,
defaultValue=model.latitude,
minValue=-90.0,
maxValue=90.0,
)
)
self.addParameter(
QgsProcessingParameterNumber(
self.WIND_DIRECTION,
self.tr(
"The direction the wind is coming from (0 is north, 270 is west)"
),
QgsProcessingParameterNumber.Double,
defaultValue=model.direction,
minValue=0.0,
maxValue=360.0,
)
)
self.addParameter(
QgsProcessingParameterNumber(
self.WIND_SPEED,
self.tr("Wind speed (m/second)"),
QgsProcessingParameterNumber.Double,
defaultValue=model.speed,
minValue=0.0,
)
)
self.addParameter(
QgsProcessingParameterBoolean(
self.TRUNCATE,
self.tr("Truncate negative precipitation"),
defaultValue=True,
)
)
self.addParameter(
QgsProcessingParameterRasterDestination(
self.OUTPUT, self.tr("Precipitation")
)
)
def prepareAlgorithm(self, parameters, context, feedback):
"Process inputs and update derived contants."
self.orography = self.parameterAsRasterLayer(
parameters, self.INPUT_RASTER, context
)
self.bandNumber = self.parameterAsInt(parameters, self.RASTER_BAND, context)
self.truncate = self.parameterAsBool(parameters, self.TRUNCATE, context)
m = LTOP()
m.tau_c = self.parameterAsDouble(parameters, self.TAU_C, context)
m.tau_f = self.parameterAsDouble(parameters, self.TAU_F, context)
m.P0 = self.parameterAsDouble(parameters, self.P0, context)
m.P_scale = self.parameterAsDouble(parameters, self.P_SCALE, context)
m.Nm = self.parameterAsDouble(parameters, self.NM, context)
m.Hw = self.parameterAsDouble(parameters, self.HW, context)
m.latitude = self.parameterAsDouble(parameters, self.LATITUDE, context)
m.direction = self.parameterAsDouble(parameters, self.WIND_DIRECTION, context)
m.speed = self.parameterAsDouble(parameters, self.WIND_SPEED, context)
m.update()
self.model = m
self.outputFile = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
return True
def processAlgorithm(self, parameters, context, feedback):
"Compute orographic precipitation."
dem = raster_to_array(self.orography, self.bandNumber)
x, y = grid(self.orography)
dx = x[1] - x[0]
dy = y[0] - y[1] # note: y is decreasing
assert dx > 0
assert dy > 0
P = self.model.run(dem, dx, dy, self.truncate)
outputFormat = QgsRasterFileWriter.driverForExtension(
os.path.splitext(self.outputFile)[1]
)
writer = QgsRasterFileWriter(self.outputFile)
writer.setOutputProviderKey("gdal")
writer.setOutputFormat(outputFormat)
provider = writer.createOneBandRaster(
Qgis.Float64, x.size, y.size, self.orography.extent(), self.orography.crs()
)
provider.setNoDataValue(1, -9999)
provider.write(
bytes(P.data), 1, x.size, y.size, 0, 0 # band # width # height
) # offset
provider.setEditable(False)
return {self.OUTPUT: self.outputFile}
def name(self):
"""
Returns the algorithm name, used for identifying the algorithm. This
string should be fixed for the algorithm, and must not be localised.
The name should be unique within each provider. Names should contain
lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return "precipitation"
def displayName(self):
"""
Returns the translated algorithm name, which should be used for any
user-visible display of the algorithm name.
"""
return self.tr("Compute orographic precipitation")
def group(self):
"""
Returns the name of the group this algorithm belongs to. This string
should be localised.
"""
return self.tr("Model")
def groupId(self):
"""
Returns the unique ID of the group this algorithm belongs to. This
string should be fixed for the algorithm, and must not be localised.
The group id should be unique within each provider. Group id should
contain lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return "model"
def tr(self, string):
return QCoreApplication.translate("Processing", string)
def createInstance(self):
return LTOrographicPrecipitationAlgorithm()
def shortHelpString(self):
return """
This plugin implements the Linear Theory of Orographic Precipitation model by Smith and Barstad (2004).
The model includes airflow dynamics, condensed water advection, and downslope evaporation. Vertically integrated steady-state governing equations for condensed water are solved using Fourier transform techniques. The precipitation field is computed quickly by multiplying the terrain transform by a wavenumber-dependent transfer function.
This method is fast even for larger rasters if sufficient RAM is available. However, processing large rasters with insuffiecient RAM is very slow.
Before using this plugin, please read the original manuscript of Smith and Barstad (2004) to understand the model physics and its limitations.
To reproduce the figure 4c from Smith and Barstad, generate a DEM using the "Gaussian bump" tool with default parameter values.
Click on the "Help" button below for more information.
"""
def helpUrl(self):
path = os.path.dirname(__file__)
return "file://" + os.path.join(path, "help", "help.html")
def canExecute(self):
return has_numpy, "NumPy is not installed"