| 1 |
#!/usr/bin/env python3 |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
# ----------------------------------------------------------------------------- |
| 4 |
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. |
| 5 |
# Copyright (C) NIWA & British Crown (Met Office) & Contributors. |
| 6 |
# |
| 7 |
# This program is free software: you can redistribute it and/or modify |
| 8 |
# it under the terms of the GNU General Public License as published by |
| 9 |
# the Free Software Foundation, either version 3 of the License, or |
| 10 |
# (at your option) any later version. |
| 11 |
# |
| 12 |
# This program is distributed in the hope that it will be useful, |
| 13 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 14 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 15 |
# GNU General Public License for more details. |
| 16 |
# |
| 17 |
# You should have received a copy of the GNU General Public License |
| 18 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 19 |
# ----------------------------------------------------------------------------- |
| 20 |
# This is illustrative code developed for tutorial purposes, it is not |
| 21 |
# intended for scientific use and is not guarantied to be accurate or correct. |
| 22 |
""" |
| 23 |
Usage: |
| 24 |
forecast INTERVAL ITERATIONS |
| 25 |
|
| 26 |
Arguments: |
| 27 |
INTERVAL: The period between forecasts in minutes. |
| 28 |
ITERATIONS: The number of forecasts to produce. |
| 29 |
|
| 30 |
Example: |
| 31 |
forecast 60 5 # Produce 5 forecasts at one hour intervals |
| 32 |
# i.e. T+1, T+2, T+3, T+4, T+5 |
| 33 |
|
| 34 |
Environment Variables: |
| 35 |
PT3H: The cycle point 3 hours prior. |
| 36 |
PT6H: The cycle point 6 hours prior. |
| 37 |
SPLINE_LEVEL (int): The beta-spline level to use for interpolating |
| 38 |
rainfall data onto the grid (either 0 or 1). |
| 39 |
WEIGHTING (list): The weighting to give to each observation set. |
| 40 |
|
| 41 |
""" |
| 42 |
|
| 43 |
import os |
| 44 |
from subprocess import Popen, PIPE |
| 45 |
import sys |
| 46 |
|
| 47 |
import util |
| 48 |
|
| 49 |
|
| 50 |
MI2KM = 1.609344001 # Conversion between miles and kilometers. |
| 51 |
|
| 52 |
|
| 53 |
def get_wind_data(wind_file_path, wind_cycles): |
| 54 |
"""Return wind field data for the provided cycle points. |
| 55 |
|
| 56 |
Args: |
| 57 |
wind_file_path (str): Template for the path to a wind data file. |
| 58 |
The template should contain substitutions for `{cycles}` |
| 59 |
(i.e. the cycle point) and `{xy}` (i.e. the value 'x' or 'y'). |
| 60 |
wind_cycles (list): List of cycle points to get wind data for |
| 61 |
as strings. |
| 62 |
|
| 63 |
Return: |
| 64 |
list - A list 2-tuples containing wind field matrices i.e. |
| 65 |
[(wind_x, wind_y), ...] |
| 66 |
|
| 67 |
""" |
| 68 |
wind_fields = [] |
| 69 |
for cycle in wind_cycles: |
| 70 |
wind_x = util.read_csv(wind_file_path.format(cycle=cycle, xy='x')) |
| 71 |
wind_y = util.read_csv(wind_file_path.format(cycle=cycle, xy='y')) |
| 72 |
wind_fields.append((wind_x, wind_y)) |
| 73 |
return wind_fields |
| 74 |
|
| 75 |
|
| 76 |
def apply_weighting(wind_fields, weightings): |
| 77 |
"""Return a single wind field averaged from the provided fields using the |
| 78 |
provided weightings. |
| 79 |
|
| 80 |
Args: |
| 81 |
wind_fields (list): List of wind field data as returned by |
| 82 |
get_wind_data(). |
| 83 |
weightings (list): List of the weighting to apply to each field in the |
| 84 |
generated result (e.g. [1] would just use the first field and |
| 85 |
[0.5, 0.5] would average the first two. |
| 86 |
|
| 87 |
Return: |
| 88 |
tuple - (weighted_wind_x, weighted_wind_y) |
| 89 |
|
| 90 |
""" |
| 91 |
# Get dimensions (in degrees lng/lat). |
| 92 |
dim_y = len(wind_fields[0][0]) |
| 93 |
dim_x = len(wind_fields[0][0][0]) |
| 94 |
|
| 95 |
# Generate matrices for the x and y components of the weighted wind. |
| 96 |
weighted_x = util.generate_matrix(dim_x, dim_y, 0.) |
| 97 |
weighted_y = util.generate_matrix(dim_x, dim_y, 0.) |
| 98 |
|
| 99 |
# Iterate over wind data from this and previous cycles. |
| 100 |
for ind, (wind_x, wind_y) in enumerate(wind_fields): |
| 101 |
for itt_y in range(dim_y): |
| 102 |
for itt_x in range(dim_x): |
| 103 |
# Acquire weighting for the cycle #ind. |
| 104 |
try: |
| 105 |
weighting = weightings[ind] |
| 106 |
except IndexError: |
| 107 |
continue |
| 108 |
weighted_x[itt_y][itt_x] += weighting * wind_x[itt_y][itt_x] |
| 109 |
weighted_y[itt_y][itt_x] += weighting * wind_y[itt_y][itt_x] |
| 110 |
|
| 111 |
util.plot_vector_grid('weighted-wind-data.png', weighted_x, weighted_y) |
| 112 |
|
| 113 |
return weighted_x, weighted_y |
| 114 |
|
| 115 |
|
| 116 |
def push_rainfall(rainfall, wind_data, step, resolution, spline_level): |
| 117 |
"""Generate forecasts using rainfall and wind data. |
| 118 |
|
| 119 |
A simple system which "pushes" the rainfall by the wind i.e. if there is a |
| 120 |
10km/h wind blowing from the west assume that the rain would move 10km to |
| 121 |
the east every hour. |
| 122 |
|
| 123 |
Args: |
| 124 |
rainfall (list): A 2D list of rainfall data. |
| 125 |
wind_data (tuple): A 2-tuple containing the x and y components of the |
| 126 |
wind each as a 2D list. |
| 127 |
step (int): The number of minutes between each forecast. |
| 128 |
resolution (float): The size of each grid cell in degrees. |
| 129 |
spline_level (int): The order of beta-spline to use for the |
| 130 |
interpolation. |
| 131 |
|
| 132 |
Yields: |
| 133 |
list - A 2D list of predicted rainfall data |
| 134 |
|
| 135 |
""" |
| 136 |
dim_y = len(rainfall) |
| 137 |
dim_x = len(rainfall[0]) |
| 138 |
|
| 139 |
x_values = [] |
| 140 |
y_values = [] |
| 141 |
z_values = [] |
| 142 |
|
| 143 |
for itt_y in range(dim_y): |
| 144 |
for itt_x in range(dim_x): |
| 145 |
x_values.append(itt_x * resolution) |
| 146 |
y_values.append((dim_y - itt_y) * resolution) # y-axis is flipped. |
| 147 |
z_values.append(rainfall[itt_y][itt_x]) |
| 148 |
|
| 149 |
yield util.interpolate_grid(list(zip(x_values, y_values, z_values)), |
| 150 |
dim_x, dim_y, resolution, resolution, |
| 151 |
spline_level) |
| 152 |
|
| 153 |
domain = util.parse_domain(os.environ['DOMAIN']) |
| 154 |
|
| 155 |
while True: |
| 156 |
out_of_bounds = [] |
| 157 |
for itt in range(len(x_values)): |
| 158 |
try: |
| 159 |
lng = domain['lng1'] + x_values[itt] |
| 160 |
lat = domain['lat1'] + y_values[itt] |
| 161 |
|
| 162 |
width = util.great_arc_distance( |
| 163 |
(lng - (resolution / 2.), lat), |
| 164 |
(lng + (resolution / 2.), lat)) |
| 165 |
height = util.great_arc_distance( |
| 166 |
(lng, lat - (resolution / 2.)), |
| 167 |
(lng, lat + (resolution / 2.))) |
| 168 |
|
| 169 |
x_values[itt] += ( |
| 170 |
(wind_data[0][int(y_values[itt])][int(x_values[itt])] * |
| 171 |
MI2KM * (step / 60.)) * (resolution / width)) |
| 172 |
y_values[itt] -= ( |
| 173 |
(wind_data[1][int(y_values[itt])][int(x_values[itt])] * |
| 174 |
MI2KM * (step / 60.)) * (resolution / height)) |
| 175 |
except IndexError: |
| 176 |
out_of_bounds.append(itt) |
| 177 |
for itt in reversed(sorted(out_of_bounds)): |
| 178 |
del x_values[itt] |
| 179 |
del y_values[itt] |
| 180 |
del z_values[itt] |
| 181 |
|
| 182 |
yield util.interpolate_grid(list(zip(x_values, y_values, z_values)), |
| 183 |
dim_x, dim_y, resolution, resolution, |
| 184 |
spline_level) |
| 185 |
|
| 186 |
|
| 187 |
def get_cyclepoint(offset_hours): |
| 188 |
"""Calculate a cyclepoint from a relative offset. |
| 189 |
|
| 190 |
Run the system call `cylc cyclepoint --offset-hours <offset_hours>` |
| 191 |
""" |
| 192 |
return Popen( |
| 193 |
['cylc', 'cyclepoint', '--offset-hours', str(int(offset_hours))], |
| 194 |
stdout=PIPE |
| 195 |
).communicate()[0].strip().decode() |
| 196 |
|
| 197 |
|
| 198 |
def main(forecast_interval, forecast_iterations): |
| 199 |
# Get workflow settings. |
| 200 |
domain = util.parse_domain(os.environ['DOMAIN']) |
| 201 |
resolution = float(os.environ['RESOLUTION']) |
| 202 |
|
| 203 |
# Get science settings. |
| 204 |
spline_level = int(os.environ.get('SPLINE_LEVEL', 0)) |
| 205 |
weighting = list(map(float, os.environ.get('WEIGHTING', '1').split(','))) |
| 206 |
|
| 207 |
# Get file paths. |
| 208 |
rainfall_file = os.environ['RAINFALL_FILE'] |
| 209 |
wind_cycles = [get_cyclepoint(offset) for offset in |
| 210 |
os.environ['WIND_CYCLES'].split(',')] |
| 211 |
wind_file_template = os.environ['WIND_FILE_TEMPLATE'] |
| 212 |
map_file = os.environ['MAP_FILE'] |
| 213 |
map_template = os.environ['MAP_TEMPLATE'] |
| 214 |
|
| 215 |
# Get wind data from specified cycles. |
| 216 |
wind_data = get_wind_data(wind_file_template, wind_cycles) |
| 217 |
|
| 218 |
# Convert these into a single data grid using the specified weighting. |
| 219 |
weighted_wind_data = apply_weighting(wind_data, weighting) |
| 220 |
|
| 221 |
# Get rainfall data. |
| 222 |
rainfall = util.read_csv(rainfall_file) |
| 223 |
|
| 224 |
# Initiate the forecaster. |
| 225 |
generator = push_rainfall(rainfall, weighted_wind_data, forecast_interval, |
| 226 |
resolution, spline_level) |
| 227 |
|
| 228 |
# Generate forecasts. |
| 229 |
forecasts = {} |
| 230 |
for lead_minutes in range(0, forecast_interval * (forecast_iterations + 1), |
| 231 |
forecast_interval): |
| 232 |
forecast_name = '+PT%02dH%02dM' % (lead_minutes // 60, |
| 233 |
lead_minutes % 60) |
| 234 |
# Generate forecast. |
| 235 |
forecast = next(generator) |
| 236 |
forecasts[forecast_name] = forecast |
| 237 |
# Output forecast data. |
| 238 |
util.write_csv(forecast_name + '.csv', forecast) |
| 239 |
|
| 240 |
# Generate html page from forecast data. |
| 241 |
util.generate_html_map(map_file, map_template, forecasts, domain, |
| 242 |
resolution) |
| 243 |
|
| 244 |
|
| 245 |
if __name__ == '__main__': |
| 246 |
util.sleep() |
| 247 |
try: |
| 248 |
args = [int(sys.argv[1]), int(sys.argv[2])] |
| 249 |
except IndexError: |
| 250 |
print(__doc__) |
| 251 |
sys.exit(1) |
| 252 |
|
| 253 |
main(*args) |