| 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 |
get-rainfall |
| 25 |
|
| 26 |
Environment Variables: |
| 27 |
DOMAIN: The area in which to generate forecasts for in the format |
| 28 |
(lng1, lat1, lng2, lat2). |
| 29 |
RESOLUTION: The length/width of each grid cell in degrees. |
| 30 |
|
| 31 |
""" |
| 32 |
|
| 33 |
from datetime import datetime |
| 34 |
import math |
| 35 |
import os |
| 36 |
import shutil |
| 37 |
|
| 38 |
import h5py |
| 39 |
from pathlib import Path |
| 40 |
import urllib |
| 41 |
import requests # noqa: F401 - required implicitly by urllib. |
| 42 |
|
| 43 |
from mercator import get_scale, pos_to_coord |
| 44 |
import util |
| 45 |
|
| 46 |
S3URL = ( |
| 47 |
'https://met-office-radar-obs-data.s3-eu-west-2.amazonaws.com/radar/' |
| 48 |
'{Y}/{m}/{d}/{YYYYmmddHHMM}_ODIM_ng_radar_rainrate_composite_1km_UK.h5' |
| 49 |
) |
| 50 |
DEBUG=os.environ['CYLC_DEBUG']=='true' |
| 51 |
CYLC_TASK_LOG_DIR=os.environ['CYLC_TASK_LOG_DIR'] |
| 52 |
|
| 53 |
|
| 54 |
class Rainfall(object): |
| 55 |
"""Class for holding rainfall data. |
| 56 |
|
| 57 |
Args: |
| 58 |
domain (dict): Domain as returned by util.parse_domain() |
| 59 |
resolution (float): The length of each grid cell in degrees. |
| 60 |
|
| 61 |
""" |
| 62 |
def __init__(self, domain, resolution): |
| 63 |
self.resolution = resolution |
| 64 |
self.domain = domain |
| 65 |
|
| 66 |
rows = int( |
| 67 |
math.ceil(abs(domain['lat1'] - domain['lat2']) / resolution)) |
| 68 |
cols = int( |
| 69 |
math.ceil(abs(domain['lng1'] - domain['lng2']) / resolution)) |
| 70 |
|
| 71 |
self.data = [] |
| 72 |
for itt_y in range(rows): |
| 73 |
self.data.append([]) |
| 74 |
for _ in range(cols): |
| 75 |
self.data[itt_y].append([]) |
| 76 |
|
| 77 |
def add(self, lng, lat, value): |
| 78 |
"""Add a data point to this data set. |
| 79 |
|
| 80 |
Args: |
| 81 |
lng (float): The longitude for this reading. |
| 82 |
lat (float): The latitude fo this reading. |
| 83 |
value (tuple): The value of the reading. |
| 84 |
|
| 85 |
""" |
| 86 |
itt_x, itt_y = util.get_grid_coordinates(lng, lat, self.domain, |
| 87 |
self.resolution) |
| 88 |
|
| 89 |
self.data[itt_y][itt_x].append(self.value_map(value)) |
| 90 |
|
| 91 |
@staticmethod |
| 92 |
def value_map(v): |
| 93 |
"""Convert rainfall rate values into colour space values. |
| 94 |
|
| 95 |
Checks if rainfall value above each threshold in turn. |
| 96 |
|
| 97 |
TODO: |
| 98 |
- Unit test this |
| 99 |
""" |
| 100 |
thresholds = {32, 16, 8, 4, 2, 1, .5, .2} |
| 101 |
for i, threshold in enumerate(sorted(thresholds, reverse=True)): |
| 102 |
if v > threshold: |
| 103 |
return 8 - i |
| 104 |
return 0 |
| 105 |
|
| 106 |
def compute_bins(self): |
| 107 |
"""Return this dataset as a 2D matrix.""" |
| 108 |
for row in self.data: |
| 109 |
for itt, col in enumerate(row): |
| 110 |
if col: |
| 111 |
row[itt] = sum(col) / float(len(col)) |
| 112 |
else: |
| 113 |
row[itt] = 0 |
| 114 |
return self.data |
| 115 |
|
| 116 |
|
| 117 |
def get_archived_radar_image(filename, time): |
| 118 |
"""Retrieve a png image from the archived data in the workflow directory. |
| 119 |
|
| 120 |
Args: |
| 121 |
filename (str): The path to write the image file to. |
| 122 |
time (str): The datetime of the image to retrieve in ISO8601 format. |
| 123 |
|
| 124 |
""" |
| 125 |
shutil.copyfile( |
| 126 |
os.path.join(os.environ['CYLC_WORKFLOW_RUN_DIR'], 'data', time, |
| 127 |
filename), |
| 128 |
filename) |
| 129 |
|
| 130 |
|
| 131 |
def get_amazon_radar_data(filename, time): |
| 132 |
time = datetime.strptime(time, '%Y%m%dT%H%MZ') |
| 133 |
url = S3URL.format( |
| 134 |
Y=time.strftime('%Y'), |
| 135 |
m=time.strftime('%m'), |
| 136 |
d=time.strftime('%d'), |
| 137 |
YYYYmmddHHMM=time.strftime('%Y%m%d%H%M') |
| 138 |
) |
| 139 |
print(f'[INFO] Getting data from {url=}') |
| 140 |
data = urllib.request.urlopen(url).read() |
| 141 |
with open(filename, 'wb') as fh: |
| 142 |
fh.write(data) |
| 143 |
|
| 144 |
|
| 145 |
# def process_rainfall_data(filename, resolution, domain): |
| 146 |
def process_rainfall_data(filename, resolution, domain): |
| 147 |
"""get_amazon_radar_dataGenerate a 2D matrix of data from the rainfall data in the image. |
| 148 |
|
| 149 |
Args: |
| 150 |
filename (str): Path to the png image to process. |
| 151 |
resolution (float): The length/weight of each grid cell in degrees. |
| 152 |
domain (dict): The bounds of the domain as returned by |
| 153 |
util.parse_domain. |
| 154 |
|
| 155 |
Return: |
| 156 |
list - A 2D matrix of rainfall data. |
| 157 |
|
| 158 |
""" |
| 159 |
print(f'[INFO] Analysing data from {filename}') |
| 160 |
data = h5py.File(filename)['dataset1']['data1']['data'] |
| 161 |
rainfall = Rainfall(domain, resolution) |
| 162 |
|
| 163 |
_height, width = data.shape |
| 164 |
|
| 165 |
scale = get_scale(domain, width) |
| 166 |
offset = (-1100.8461538461539, 1400.6953225710452) |
| 167 |
|
| 168 |
if DEBUG: |
| 169 |
print(f'[INFO] {scale=}, {offset=}') |
| 170 |
from matplotlib import pyplot as plt |
| 171 |
Path(CYLC_TASK_LOG_DIR).mkdir(parents=True, exist_ok=True) |
| 172 |
plt.imshow(data) |
| 173 |
plt.savefig(f'{CYLC_TASK_LOG_DIR}/raw.data.png') |
| 174 |
|
| 175 |
for itt_y, row in enumerate(data): |
| 176 |
for itt_x, col in enumerate(row): |
| 177 |
lng, lat = pos_to_coord( |
| 178 |
itt_x, |
| 179 |
itt_y * (2. / 3.), # Counter aspect ratio. |
| 180 |
offset, |
| 181 |
scale |
| 182 |
) |
| 183 |
val = float(col) |
| 184 |
# Original data uses -1 to indicate radar mask |
| 185 |
val = 0 if val == -1 else val |
| 186 |
rainfall.add(lng, lat, val) |
| 187 |
data = rainfall.compute_bins() |
| 188 |
|
| 189 |
if DEBUG: |
| 190 |
plt.imshow(data) |
| 191 |
plt.savefig(f'{CYLC_TASK_LOG_DIR}/processed.data.png') |
| 192 |
|
| 193 |
return data |
| 194 |
|
| 195 |
def main(): |
| 196 |
time = os.environ['CYLC_TASK_CYCLE_POINT'] |
| 197 |
resolution = float(os.environ['RESOLUTION']) |
| 198 |
domain = util.parse_domain(os.environ['DOMAIN']) |
| 199 |
|
| 200 |
# Acts as a switch - if a file-name is given, use that file-name |
| 201 |
canned_data = os.environ.get('CANNED_DATA', 'fetch') |
| 202 |
|
| 203 |
if canned_data == 'fetch': |
| 204 |
print('[INFO] Attempting to get rainfall data from S3 bucket') |
| 205 |
get_amazon_radar_data('radardata.h5', time) |
| 206 |
canned_data = 'radardata.h5' |
| 207 |
else: |
| 208 |
raise Exception('Not currently provided functionality') |
| 209 |
# Not currently used. |
| 210 |
#print(f'[INFO] Canned data provided: {canned_data}') |
| 211 |
#get_archived_radar_data(canned_data, time) |
| 212 |
|
| 213 |
data = process_rainfall_data(canned_data, resolution, domain) |
| 214 |
|
| 215 |
util.write_csv('rainfall.csv', data) |
| 216 |
|
| 217 |
|
| 218 |
if __name__ == '__main__': |
| 219 |
util.sleep(2) # make the tutorial run a little slower |
| 220 |
main() |