-
Notifications
You must be signed in to change notification settings - Fork 1
/
wind_forecast_routing_launch.py
395 lines (353 loc) · 15.7 KB
/
wind_forecast_routing_launch.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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# -*- coding: utf-8 -*-
"""
/***************************************************************************
windForecastRouting
A QGIS plugin
sailing routing by wind forecast
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2021-03-30
copyright : (C) 2021 by enrico ferreguti
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__ = 'enrico ferreguti'
__date__ = '2021-03-30'
__copyright__ = '(C) 2021 by enrico ferreguti'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
from qgis.PyQt.QtCore import QCoreApplication, QVariant
from PyQt5 import QtGui, QtWidgets, uic
from PyQt5.QtCore import QUrl, QJsonDocument
from PyQt5.QtNetwork import QNetworkRequest
from qgis.core import (QgsProcessing,
QgsCoordinateTransform,
QgsCoordinateReferenceSystem,
QgsFeatureSink,
QgsMeshLayer,
QgsMeshDatasetIndex,
QgsProject,
QgsNetworkAccessManager,
QgsVectorLayer,
QgsField,
QgsFields,
QgsRectangle,
QgsFeature,
QgsGeometry,
QgsWkbTypes,
QgsInterval,
QgsPointXY,
QgsProcessingAlgorithm,
QgsProcessingParameterPoint,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterMeshLayer,
QgsProcessingParameterNumber,
QgsProcessingParameterVectorLayer,
QgsProcessingParameterFileDestination,
QgsProcessingParameterEnum,
QgsProcessingParameterDateTime,
QgsProcessingParameterBoolean,
QgsProcessingParameterVectorDestination)
import processing
import math
import os
from datetime import datetime, timedelta
import dateutil
import requests
wind_models = [
{
"service": 'icon_p25_',
"context": "Global - ICON",
"interval": '3',
"days": '5',
"limits": None,
"resolution": 0.25
},
{
"service": 'gfs_p25_',
"context": "Global - GFS",
"interval": '3',
"days": '5',
"limits": None,
"resolution": 0.25
},
{
"service": 'arpege_p50_',
"context": "Global - ARPEGE",
"interval": '3',
"days": '4',
"limits": None,
"resolution": 0.5
},
{
"service": 'arpege_eu_p10_',
"context": "Europe - ARPEGE_EU",
"interval": '1',
"days": '3',
"limits": [-32.0, 20.0, 42.0, 72.0],
"resolution": 0.1
},
{
"service": 'icon_eu_p06_',
"context": "Europe - ICON_EU",
"interval": '1',
"days": '5',
"limits": [-23.5, 29.5, 45.0, 70.5],
"resolution": 0.06
},
{
"service": 'nam_conus_12km_',
"context": "North America - NAM_CONUS",
"interval": '1',
"days": '4',
"limits": [-152.879, 12.220, -49.416, 61.310],
"resolution": 0.1
},
{
"service": 'nam_cacbn_12km_',
"context": "Caribbean sea - NAM_CACBN",
"interval": '1',
"days": '4',
"limits": [-100.0, 0.138, -60.148, 30.054],
"resolution": 0.1
},
{
"service": 'nam_pacific_12km_',
"context": "Pacific ocean - NAM_PACIFIC",
"interval": '1',
"days": '4',
"limits": [-170.0, 8.133, -140.084, 32.973],
"resolution": 0.1
},
]
class windForecastLaunchAlgorithm(QgsProcessingAlgorithm):
"""
This is an example algorithm that takes a vector layer and
creates a new identical one.
It is meant to be used as an example of how to create your own
algorithms and explain methods and variables used to do it. An
algorithm like this will be available in all elements, and there
is not need for additional work.
All Processing algorithms should extend the QgsProcessingAlgorithm
class.
"""
# 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.
START_POINT = 'START_POINT'
END_POINT = 'END_POINT'
POLAR = 'POLAR'
START_TIME = 'START_TIME'
GRIB_OUTPUT = 'GRIB_OUTPUT'
OUTPUT_WAYPOINTS = 'OUTPUT_WAYPOINTS'
OUTPUT_ROUTE = 'OUTPUT_ROUTE'
OUTPUT_CONTEXT = 'OUTPUT_CONTEXT'
MODEL = 'MODEL'
FORCE_LOAD_RESULTS = 'FORCE_LOAD_RESULTS'
ANIMATION = 'ANIMATION'
def initAlgorithm(self, config):
"""
Here we define the inputs and output of the algorithm, along
with some other properties.
"""
if "nooutput" in config:
self.allow_output = False
else:
self.allow_output = True
#http://jieter.github.io/orc-data/site/
self.polars_dir = os.path.join(os.path.dirname(__file__),"polar_files")
self.polars = {}
for polar_file in os.listdir(self.polars_dir):
polar_name, ext = os.path.splitext(polar_file)
if ext == '.pol':
self.polars[polar_name] = polar_file
self.polar_names = list(self.polars.keys())
self.polar_names.sort()
wind_models_labels = ["Auto"]
for wm in wind_models:
wind_models_labels.append(wm["context"])
# We add the input vector features source. It can have any kind of
# geometry.
self.addParameter(QgsProcessingParameterEnum(self.MODEL, 'Wind Model', options=wind_models_labels, defaultValue=0, allowMultiple=False))
self.addParameter(QgsProcessingParameterEnum(self.POLAR, 'Polar (Courtesy of seapilot.com)', options=self.polar_names, defaultValue=None, allowMultiple=False))
self.addParameter(QgsProcessingParameterPoint(self.START_POINT, self.tr('Start point')))
self.addParameter(QgsProcessingParameterPoint(self.END_POINT, self.tr('End point')))
self.addParameter(QgsProcessingParameterDateTime(self.START_TIME, self.tr('Time of departure')))
self.addParameter(QgsProcessingParameterBoolean(self.ANIMATION, self.tr('Animate route with temporal controller at the end of algorithm processing'), defaultValue=False))
self.addParameter(QgsProcessingParameterFileDestination(self.GRIB_OUTPUT, self.tr('Grib Output file'), fileFilter="*.grb"))
# We add a feature sink in which to store our processed features (this
# usually takes the form of a newly created vector layer when the
# algorithm is run in QGIS).
if self.allow_output:
self.addParameter(
QgsProcessingParameterVectorDestination(
self.OUTPUT_WAYPOINTS,
self.tr('Waypoints Output layer'),
createByDefault=True
)
)
self.addParameter(
QgsProcessingParameterVectorDestination(
self.OUTPUT_ROUTE,
self.tr('Route Output layer'),
createByDefault=True
)
)
else:
self.addParameter(
QgsProcessingParameterFileDestination(
self.OUTPUT_WAYPOINTS,
self.tr('Waypoints Output vector file'),
createByDefault=True
)
)
self.addParameter(
QgsProcessingParameterFileDestination(
self.OUTPUT_ROUTE,
self.tr('Route Output vector file'),
createByDefault=True
)
)
self.addParameter(
QgsProcessingParameterFileDestination(
self.OUTPUT_CONTEXT,
self.tr('Context output file'),
createByDefault=True
)
)
def processAlgorithm(self, parameters, context, feedback):
"""
Here is where the processing itself takes place.
"""
polar = self.parameterAsEnum(parameters, self.POLAR, context)
start_time = self.parameterAsDateTime(parameters, self.START_TIME, context)
grib_crs = QgsCoordinateReferenceSystem("EPSG:4326")
start_point = self.parameterAsPoint(parameters, self.START_POINT, context, crs=grib_crs)
end_point = self.parameterAsPoint(parameters, self.END_POINT, context, crs=grib_crs)
grib_output = self.parameterAsFile(parameters, self.GRIB_OUTPUT, context)
animation = self.parameterAsBool(parameters, self.ANIMATION, context)
track = ((start_point.y(), start_point.x()), (end_point.y(), end_point.x()))
geo_context = QgsRectangle(start_point.x(),start_point.y(), end_point.x(),end_point.y())
track_dist = start_point.distance(end_point)
if track_dist < 0.25:
feedback.reportError("Error: Track path length too short, must be almost 15 Nautical miles to obtain significant results", fatalError=True)
return {"ERROR": "Track path too short"}
grow = 0.5 if track_dist < 0.5 else track_dist
grow = 1 if grow > 1 else grow
geo_context.grow( track_dist/2 ) #limit grow to 0.5 degree
output_context = self.parameterAsFileOutput(parameters, self.OUTPUT_CONTEXT, context)
if self.allow_output:
output_route = self.parameterAsOutputLayer(parameters, self.OUTPUT_ROUTE, context)
output_waypoints = self.parameterAsOutputLayer(parameters, self.OUTPUT_WAYPOINTS, context)
else:
output_route = self.parameterAsFileOutput(parameters, self.OUTPUT_ROUTE, context)
output_waypoints = self.parameterAsFileOutput(parameters, self.OUTPUT_WAYPOINTS, context)
#self.force_load_on_map = self.parameterAsBoolean(parameters, self.FORCE_LOAD_RESULTS, context)
model = self.parameterAsEnum(parameters, self.MODEL, context)
wind_model_def = None
if model == 0:
for wm in wind_models:
if wm["limits"]:
wm_extent = QgsRectangle(*wm["limits"])
if wm_extent.contains(geo_context):
wind_model_def = wm
break
if not wind_model_def:
wind_model_def = wind_models[0]
else:
wind_model_def = wind_models[model-1]
if not wind_model_def["limits"]:
geo_context.grow( 1 ) #if the wind model is global a bigger extent is appropriate
wind_model_def["bottom"] = geo_context.yMinimum()
wind_model_def["top"] = geo_context.yMaximum()
wind_model_def["left"] = geo_context.xMinimum()
wind_model_def["right"] =geo_context.xMaximum()
#url = 'http://grbsrv.opengribs.org/getmygribs2.php/?osys=Unknown&ver=1.2.4&la1={bottom}&la2={top}&lo1={left}&lo2={right}&model=icon_eu_p06_&wmdl=none&intv=1&days=5&cyc=last&par=W%3B&wpar='.format(**params)
url = 'http://grbsrv.opengribs.org/getmygribs2.php/?osys=Unknown&ver=1.2.4&la1={bottom}&la2={top}&lo1={left}&lo2={right}&model={service}&wmdl=none&intv={interval}&days={days}&cyc=last&par=W%3B&wpar='.format(**wind_model_def)
print (url)
manager = QgsNetworkAccessManager.instance()
request = QNetworkRequest()
request.setUrl(QUrl(url))
rawReplyObject = manager.blockingGet(request)
j = QJsonDocument.fromJson(rawReplyObject.content())
replyObject = j.toVariant()
if replyObject["status"]:
download_params = {
'URL': replyObject["message"]["url"],
'OUTPUT': grib_output
}
output_download = processing.run('native:filedownloader', download_params, context=context, feedback=feedback, is_child_algorithm=True)
else:
print ("ERROR", replyObject)
return replyObject
routing_params = {
'START_POINT': start_point,
'END_POINT': end_point,
'POLAR': polar,
'GRIB': output_download['OUTPUT'],
'WIND_DATASET_INDEX': 0,
'START_TIME': start_time,
'OUTPUT_WAYPOINTS': output_waypoints, #QgsProcessing.TEMPORARY_OUTPUT,
'OUTPUT_ROUTE': output_route #QgsProcessing.TEMPORARY_OUTPUT,
}
self.output_routing = processing.run('sailtools:windrouting', routing_params, context=context, feedback=feedback, is_child_algorithm=True)
self.output_routing[self.GRIB_OUTPUT] = output_download['OUTPUT']
self.output_routing[self.ANIMATION] = animation
global_oceans_layer = QgsVectorLayer(os.path.join(os.path.dirname(__file__),"ne_10m_ocean.zip"), "context", "ogr")
context_land_params = {
"sourcelayer": os.path.join(os.path.dirname(__file__),"ne_10m_ocean.zip"),
"extent": QgsMeshLayer(output_download['OUTPUT'],"grib","mdal").extent(),
"Inverted_clip": output_context
}
context_land_results = processing.run('sailtools:inverted_clip', context_land_params, context=context, feedback=feedback, is_child_algorithm=True)
self.output_routing[self.OUTPUT_CONTEXT] = context_land_results['OUTPUT']
self.output_routing["elab_name"] = "wind routing %s %s %s %.2f,%.1f,%.1f,%.1f" % (
self.polar_names[polar],
wind_model_def["context"],
start_time.toString("yyyyMMdd_hh:mm"),
start_point.x(),start_point.y(),
end_point.x(),end_point.y(),
)
return self.output_routing
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 'windroutinglaunch'
def displayName(self):
"""
Returns the translated algorithm name, which should be used for any
user-visible display of the algorithm name.
"""
return 'windrouting launch'
def group(self):
"""
Returns the name of the group this algorithm belongs to. This string
should be localised.
"""
return self.tr('Sail tools')
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 'sailtools'
def tr(self, string):
return QCoreApplication.translate('Processing', string)
def createInstance(self):
return windForecastLaunchAlgorithm()