-
Notifications
You must be signed in to change notification settings - Fork 1
/
processing_algorithm.py
270 lines (234 loc) · 11.9 KB
/
processing_algorithm.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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Prepare CoolParksTool
A QGIS plugin
This plugin prepare data for the CoolParksTool
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2023-07-06
copyright : (C) 2023 by Jérémy Bernard
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__ = 'Jérémy Bernard'
__date__ = '2023-07-06'
__copyright__ = '(C) 2023 by Jérémy Bernard'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
from qgis.PyQt.QtCore import QCoreApplication, QVariant
from qgis.core import (QgsProcessing,
QgsProcessingAlgorithm,
QgsProcessingParameterField,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterNumber,
QgsProcessingParameterMatrix,
QgsProcessingParameterFolderDestination,
QgsProcessingParameterString,
QgsProcessingParameterRasterLayer,
QgsProcessingParameterBoolean,
QgsRasterLayer,
QgsVectorLayer,
QgsProject,
QgsProcessingContext,
QgsProcessingParameterEnum,
QgsProcessingParameterFile,
QgsProcessingException,
QgsLayerTreeGroup)
# qgis.utils import iface
from pathlib import Path
from qgis.PyQt.QtGui import QIcon
import inspect
import unidecode
import geopandas as gpd
from .functions import mainCalculations
from .functions.globalVariables import *
from .functions import WriteMetadata
from .functions.DataUtil import trunc_to, round_to
from .functions.coolparks_postprocess import loadCoolParksRaster, loadCoolParksVector, Renamer
class CoolParksProcessorAlgorithm(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.
# Input variables
SCENARIO_DIRECTORY = "SCENARIO_DIRECTORY"
WEATHER_FILE = "WEATHER_FILE"
WEATHER_SCENARIO = "WEATHER_SCENARIO"
OUTPUT_DIRECTORY = "OUTPUT_DIRECTORY"
def initAlgorithm(self, config):
"""
Here we define the inputs and output of the algorithm, along
with some other properties.
"""
# We add the input parameters
self.addParameter(
QgsProcessingParameterString(
self.WEATHER_SCENARIO,
self.tr('Meteorological scenario name'),
defaultValue = DEFAULT_WEATHER,
optional = False))
self.addParameter(
QgsProcessingParameterFile(
self.SCENARIO_DIRECTORY,
self.tr(f'Directory of the scenario of interest (should contain two folders called "{OUTPUT_PREPROCESSOR_FOLDER}" and "{OUTPUT_PROCESSOR_FOLDER})"'),
behavior=QgsProcessingParameterFile.Folder))
self.addParameter(
QgsProcessingParameterFile(
self.WEATHER_FILE,
self.tr('Input meteorological file (.txt or .csv)')))
def processAlgorithm(self, parameters, context, feedback):
"""
Here is where the processing itself takes place.
"""
# try:
# import jaydebeapi
# except:
# raise QgsProcessingException("'jaydebeapi' Python package is missing.")
scenarioDirectory = self.parameterAsString(parameters, self.SCENARIO_DIRECTORY, context)
weatherFile = self.parameterAsString(parameters, self.WEATHER_FILE, context)
weatherScenario = self.parameterAsString(parameters, self.WEATHER_SCENARIO, context)
prefix = unidecode.unidecode(weatherScenario).replace(" ", "_")
# Creates the output folder if it does not exist
if os.path.exists(scenarioDirectory + os.sep + OUTPUT_PROCESSOR_FOLDER):
if os.path.exists(scenarioDirectory + os.sep + OUTPUT_PROCESSOR_FOLDER + os.sep + prefix):
raise QgsProcessingException(f'"{prefix}" folder already exists in "{scenarioDirectory + os.sep + OUTPUT_PROCESSOR_FOLDER}"')
else:
os.mkdir(scenarioDirectory + os.sep + OUTPUT_PROCESSOR_FOLDER + os.sep + prefix)
else:
raise QgsProcessingException(f'"{scenarioDirectory}" should contain a folder called "{OUTPUT_PROCESSOR_FOLDER}". It is not the directory of a preprocessed scenario.')
# if feedback:
# feedback.setProgressText("Writing settings for this model run to specified output folder (Filename: RunInfoURock_YYYY_DOY_HHMM.txt)")
# WriteMetadataURock.writeRunInfo(outputDirectory, build_file, heightBuild,
# veg_file, attenuationVeg, baseHeightVeg, topHeightVeg,
# z_ref, v_ref, windDirection, profileType,
# profileFile,
# meshSize, dz)
if feedback:
feedback.setProgressText("Calculate park effect on air temperature")
if feedback.isCanceled():
feedback.setProgressText("Calculation cancelled by user")
return {}
# Calculates the effect of the park on its surrounding
output_t_path, output_dt_path, deltaT_min_value, deltaT_max_value = \
mainCalculations.calcParkInfluence(weatherFilePath = weatherFile,
preprocessOutputPath = scenarioDirectory,
prefix = prefix,
feedback = feedback)
if feedback:
feedback.setProgressText("Calculate park effect on building energy and thermal comfort")
if feedback.isCanceled():
feedback.setProgressText("Calculation cancelled by user")
return {}
# Calculates the impact of the cooling on the buildings
gdf_build, output_build_path = \
mainCalculations.calcBuildingImpact(preprocessOutputPath = scenarioDirectory,
prefix = prefix)
######################################################################
######################## LOAD DATA INTO QGIS #########################
######################################################################
# Calculates the number of significant digits
if NB_ISOVALUES < 10:
sign_digits = 1
else:
sign_digits = 2
# Load data into QGIS
global layernames
layernames = {}
i = 0
for tp in [DAY_TIME, NIGHT_TIME]:
layernames[i] = Renamer(f"{scenarioDirectory.split(os.sep)[-1]} and {weatherScenario}: Park impact on air temperature at {tp}:00 (°C)")
# Load the vector layer with a given style
loadCoolParksVector(filepath = output_dt_path[tp] + ".geojson",
layername = layernames[i],
variable = None,
subgroup = QgsLayerTreeGroup("parameter not used..."),
vector_min = deltaT_min_value,
vector_max = deltaT_max_value,
feedback = feedback,
context = context,
valueZero = 0,
opacity = DEFAULT_OPACITY)
i += 1
# Load building results into QGIS
for var in BUILDING_LEGEND_PROCESS.index:
layernames[i] = Renamer(f"{scenarioDirectory.split(os.sep)[-1]} and {weatherScenario}: {BUILDING_LEGEND_PROCESS[var]}")
loadCoolParksVector(filepath = output_build_path,
layername = layernames[i],
variable = var,
subgroup = QgsLayerTreeGroup("parameter not used..."),
vector_min = gdf_build[var].min(),
vector_max = gdf_build[var].max(),
feedback = feedback,
context = context,
valueZero = 0,
opacity = 1)
i += 1
# Return the output file names
return {self.OUTPUT_DIRECTORY: scenarioDirectory + os.sep + OUTPUT_PROCESSOR_FOLDER + os.sep + prefix}
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 'coolparkstool_process'
def displayName(self):
"""
Returns the translated algorithm name, which should be used for any
user-visible display of the algorithm name.
"""
return self.tr('2. Calculate park effects')
def group(self):
"""
Returns the name of the group this algorithm belongs to. This string
should be localised.
"""
return self.tr(self.groupId())
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 ''
def tr(self, string):
return QCoreApplication.translate('Processing', string)
def shortHelpString(self):
return self.tr('The CoolParksTool "2. Calculate park effects" module is used '+
'to calculate:\n'+
' - the effect of the park composition on the cooling,\n'+
' - the effect of the urban morphology on the transport of cool air,\n'+
' - the effect of the cool air on building energy and building '+
' thermal comfort\n'
'\n'
'\n'
"""You need to first use the '1. Prepare data' for each new scenario you
want to simulate."""
'\n'
'\n'
'---------------\n'
'Full manual available via the <b>Help</b>-button.')
def helpUrl(self):
url = "https://github.com/j3r3m1/coolparkstool"
return url
def icon(self):
cmd_folder = Path(os.path.split(inspect.getfile(inspect.currentframe()))[0]).parent
icon = QIcon(str(cmd_folder) + "/icons/urock.png")
return icon
def createInstance(self):
return CoolParksProcessorAlgorithm()