-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmannings_roughness_algorithm.py
More file actions
339 lines (281 loc) · 14.3 KB
/
mannings_roughness_algorithm.py
File metadata and controls
339 lines (281 loc) · 14.3 KB
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
# -*- coding: utf-8 -*-
"""
Manning's Roughness Generator - A QGIS Plugin
Generates Manning's roughness coefficient layers for hydrological modeling.
Created on: 2025-02-08
Copyright: (C) 2025 by Abdullah Azzam
Email: mabdazzam@outlook.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 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
__author__ = "Abdullah Azzam"
__date__ = "2025-02-08"
__copyright__ = "(C) 2025 by Abdullah Azzam"
import os
import sys
import inspect
import processing
from qgis.core import (
QgsProcessing,
QgsProcessingAlgorithm,
QgsProcessingException,
QgsProcessingMultiStepFeedback,
QgsProcessingUtils,
QgsVectorLayer,
QgsApplication,
QgsRasterLayer,
QgsProject,
QgsCoordinateReferenceSystem,
QgsProcessingOutputLayerDefinition,
QgsProcessingParameterVectorLayer,
QgsProcessingParameterEnum,
QgsProcessingParameterRasterDestination,
QgsProcessingParameterDefinition,
QgsProcessingOutputLayerDefinition,
)
from qgis.PyQt.QtCore import QCoreApplication
#from .mannings_roughness_calculator import ManningsRoughnessCalculator
class ManningsRoughnessAlgorithm(QgsProcessingAlgorithm):
"""QGIS Processing Algorithm for Manning's Roughness"""
def name(self):
return "manningsroughness"
def displayName(self):
return "Manning's Roughness Generator"
def shortHelpString(self):
return QCoreApplication.translate(
"Processing",
"""<html><body>
<h2>Algorithm description</h2>
<p>This algorithm generates a <b>Manning’s roughness coefficient layer</b> for the given Area of Interest (AOI).
It derives roughness values from the <b>ESA WorldCover 2021</b> dataset using predefined lookup tables corresponding to different hydrological surface types.</p>
<p>Users can select from three predefined roughness classes: <b>Low, Medium, and High</b>,
each representing a different hydrological scenario. The roughness values are applied based on ESA Land Cover classification.</p>
<h2>Input parameters</h2>
<h3>Area of Interest</h3>
<p>Polygon layer representing an area of interest.</p>
<h3>Roughness Class</h3>
<p>Selects the Manning's roughness classification scheme to be applied. Options include:</p>
<ul>
<li><b>Low</b> - Represents minimal surface resistance (e.g., paved surfaces, short grass).</li>
<li><b>Medium</b> - Represents moderate roughness (e.g., agricultural fields, shrublands).</li>
<li><b>High</b> - Represents maximum roughness (e.g., dense forests, wetlands).</li>
</ul>
<h3>Lookup Table (default)</h3>
<p>The algorithm uses predefined lookup tables that assign Manning’s n-values to ESA WorldCover land cover classes.
These tables are stored in the plugin directory under <code>lookups/</code> and include:</p>
<ul>
<li><b>low_n.csv</b> - Lookup table for the Low roughness category.</li>
<li><b>med_n.csv</b> - Lookup table for the Medium roughness category.</li>
<li><b>high_n.csv</b> - Lookup table for the High roughness category.</li>
</ul>
<p>Each file contains two columns: <code>grid_code</code> (ESA Land Cover class) and <code>n</code> (Manning's roughness coefficient).</p>
<h2>Outputs</h2>
<h3>ESA WorldCover 2021</h3>
<p>Clipped ESA Land Cover raster for the specified AOI.</p>
<h3>Manning's Roughness</h3>
<p>Generated raster layer with Manning’s roughness coefficients derived from the selected lookup table.</p>
<br>
<p align="right">Author: Abdullah Azzam</p>
<p align="right">Algorithm version: 1.0.0</p>
<p align="right">Contact email: mabdazzam@outlook.com</p>
<p>Disclaimer: The roughness values generated by this algorithm are approximations and should be reviewed before use in detailed hydrological modeling.</p>
</body></html>"""
)
def createInstance(self):
return ManningsRoughnessAlgorithm()
def initAlgorithm(self, config=None):
self.roughness_classes = ["Low", "Medium", "High"]
self.lc_pixel_size = 0.000083333333333
# add aoi parameter
self.addParameter(
QgsProcessingParameterVectorLayer(
"aoi",
"Area of Interest",
types=[QgsProcessing.TypeVectorPolygon],
defaultValue=None,
)
)
# add roughness class selection
param = QgsProcessingParameterEnum(
"ROUGHNESS_CLASS",
"Roughness Class",
options=self.roughness_classes,
allowMultiple=False,
defaultValue=1,
)
param.setFlags(param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
self.addParameter(param)
# add esa worldcover output
self.addParameter(
QgsProcessingParameterRasterDestination(
"EsaWorldcoverAOI",
"ESA WorldCover 2021",
optional=True,
createByDefault=False,
defaultValue=None,
)
)
# add mannings roughness output
self.addParameter(
QgsProcessingParameterRasterDestination(
"ManningsRoughness",
"Manning's Roughness",
optional=True,
createByDefault=True,
defaultValue=None,
)
)
def processAlgorithm(self, parameters, context, model_feedback):
feedback = QgsProcessingMultiStepFeedback(3, model_feedback)
# load aoi
aoi_layer = QgsProcessingUtils.mapLayerFromString(parameters["aoi"], context)
if aoi_layer is None or not isinstance(aoi_layer, QgsVectorLayer):
raise QgsProcessingException("invalid aoi vector layer.")
feedback.pushInfo(f"aoi original crs: {aoi_layer.crs().authid()}")
# reproject aoi to epsg:4326
target_crs = QgsCoordinateReferenceSystem("EPSG:4326")
transformed_layer = processing.run(
"native:reprojectlayer",
{
"INPUT": aoi_layer,
"TARGET_CRS": target_crs,
"OUTPUT": "memory:"
},
context=context,
feedback=feedback
)["OUTPUT"]
if transformed_layer is None:
raise QgsProcessingException("failed to reproject aoi to epsg:4326.")
# extract extent
reprojected_extent = transformed_layer.extent()
feedback.pushInfo(f"aoi reprojected extent (epsg:4326): {reprojected_extent.toString()}")
if not hasattr(self, "lc_pixel_size") or self.lc_pixel_size is None:
raise QgsProcessingException("lc_pixel_size is not defined!")
extent_esa = (
reprojected_extent.xMinimum() - 2 * self.lc_pixel_size,
reprojected_extent.yMinimum() - 2 * self.lc_pixel_size,
reprojected_extent.xMaximum() + 2 * self.lc_pixel_size,
reprojected_extent.yMaximum() + 2 * self.lc_pixel_size,
)
feedback.pushInfo(f"buffered esa extent: {extent_esa}")
# clip esa worldcover and rename temp layer
#esa_output = parameters.get("EsaWorldcoverAOI", QgsProcessing.TEMPORARY_OUTPUT)
if parameters.get("EsaWorldcoverAOI", None):
try:
parameters["EsaWorldcoverAOI"].destinationName = "ESA WorldCover 2021"
except AttributeError:
pass
esa_output = parameters["EsaWorldcoverAOI"]
else:
esa_output = QgsProcessing.TEMPORARY_OUTPUT
gdal_output = processing.run(
"gdal:cliprasterbyextent",
{
"INPUT": os.path.normpath(os.path.join(os.path.dirname(__file__), "esa_worldcover_2021.vrt")),
"PROJWIN": f"{extent_esa[0]},{extent_esa[2]},{extent_esa[1]},{extent_esa[3]} [EPSG:4326]",
"OUTPUT": esa_output,
},
context=context, feedback=feedback,
is_child_algorithm=True
)
if "OUTPUT" not in gdal_output or not os.path.exists(gdal_output["OUTPUT"]):
raise QgsProcessingException("esa raster processing failed.")
esa_raster = gdal_output["OUTPUT"]
feedback.pushInfo(f"esa worldcover raster processed at: {esa_raster}")
feedback.pushInfo("starting Manning's roughness calculation...")
roughness_lookup = ["low_n.csv", "med_n.csv", "high_n.csv"]
selected_lookup = roughness_lookup[parameters["ROUGHNESS_CLASS"]]
lookup_file = os.path.normpath(os.path.join(os.path.dirname(__file__), "lookups", selected_lookup))
feedback.pushInfo(f"loading Manning's roughness lookup table from: {lookup_file}")
if not os.path.exists(lookup_file):
raise QgsProcessingException(f"lookup table not found: {lookup_file}")
lookup_values = []
with open(lookup_file, "r", encoding="utf-8") as file:
lines = file.readlines()
for line in lines[1:]:
parts = line.strip().split(",")
if len(parts) == 2:
try:
lc_value = int(parts[0])
n_value = float(parts[1])
lookup_values.append((lc_value, n_value))
except ValueError:
feedback.pushWarning(f"skipping invalid row in lookup file: {line.strip()}")
if not lookup_values:
raise QgsProcessingException(f"lookup table {selected_lookup} is empty or malformed.")
feedback.pushInfo(f"loaded {len(lookup_values)} land cover to roughness mappings.")
exprs = " + ".join([f"(A == {lc}) * {n}" for lc, n in lookup_values])
feedback.pushInfo(f"generated raster math expression: {exprs}")
input_dict = {"input_a": esa_raster, "band_a": 1}
# rename temp roughness output
#roughness_output = parameters.get("ManningsRoughness", QgsProcessing.TEMPORARY_OUTPUT)
if parameters.get("ManningsRoughness", None):
try:
parameters["ManningsRoughness"].destinationName = "Manning's n"
except AttributeError:
pass
roughness_output = parameters["ManningsRoughness"]
else:
roughness_output = QgsProcessing.TEMPORARY_OUTPUT
gdal_result = processing.run(
"gdal:rastercalculator",
{
"FORMULA": exprs,
"INPUT_A": input_dict["input_a"],
"BAND_A": input_dict["band_a"],
"NO_DATA": -9999,
"RTYPE": 5,
"OUTPUT": roughness_output,
},
context=context, feedback=feedback,
is_child_algorithm=True
)
if "OUTPUT" not in gdal_result or not os.path.exists(gdal_result["OUTPUT"]):
raise QgsProcessingException("manning's roughness raster was not created!")
mannings_raster = gdal_result["OUTPUT"]
feedback.pushInfo(f"Manning's roughness raster saved at: {mannings_raster}")
feedback.pushInfo("applying styling...")
esa_style_path = os.path.normpath(os.path.join(os.path.dirname(__file__), "esa_worldcover_2021.qml"))
roughness_style_path = os.path.normpath(os.path.join(os.path.dirname(__file__), "mannings_n.qml"))
## renaming and styling
# check if esa output is defined to avoid keyerror
esa_output_selected = "EsaWorldcoverAOI" in parameters and parameters["EsaWorldcoverAOI"] not in [None, ""]
# normalize raster paths to avoid OS issues
esa_raster = os.path.normpath(esa_raster) if esa_output_selected else None
mannings_raster = os.path.normpath(mannings_raster) if "ManningsRoughness" in parameters and parameters["ManningsRoughness"] not in [None, ""] else None
# only apply esa styling if the user selected an output
if esa_output_selected:
if os.path.exists(esa_raster):
esa_layer = QgsRasterLayer(esa_raster, "", "gdal")
if esa_layer.isValid():
esa_layer.setName("ESA WorldCover 2021")
esa_style_path = os.path.normpath(os.path.join(os.path.dirname(__file__), "esa_worldcover_2021.qml"))
if os.path.exists(esa_style_path):
esa_layer.loadNamedStyle(esa_style_path)
esa_layer.triggerRepaint()
QgsProject.instance().addMapLayer(esa_layer)
# apply styling to mannings n (independent of esa)
if mannings_raster:
if os.path.exists(mannings_raster):
roughness_layer = QgsRasterLayer(mannings_raster, "", "gdal")
if roughness_layer.isValid():
roughness_layer.setName("Manning's n")
roughness_style_path = os.path.normpath(os.path.join(os.path.dirname(__file__), "mannings_n.qml"))
if os.path.exists(roughness_style_path):
roughness_layer.loadNamedStyle(roughness_style_path)
roughness_layer.triggerRepaint()
QgsProject.instance().addMapLayer(roughness_layer)
feedback.pushInfo("styling applied. returning results.")
# return only the outputs that were selected
return {
"EsaWorldcoverAOI": esa_raster,
"ManningsRoughness": mannings_raster
}