Debian Codegraph @

cylc/flow/etc/tutorial/cylc-forecasting-workflow/bin/get-observations

raw
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.s
22 """
23 Usage:
24 get-observations
25
26 Environment Variables:
27 SITE_ID: The four digit WMO (World Meteorological Organization)
28 site code identifying the weather station we are to fetch results for.
29
30 """
31
32 from pathlib import Path
33 from datetime import datetime
34 import json
35 import os
36 import re
37
38 import requests
39
40 import util
41
42
43 # Compass bearings for ordinate directions.
44 # NOTE: We measure direction by where the winds have come from!
45 ORDINATES = {
46 'N': '180',
47 'NNE': '202.5',
48 'NE': '225',
49 'ENE': '247.5',
50 'E': '270',
51 'ESE': '292.9',
52 'SE': '315',
53 'SSE': '337.5',
54 'S': '0',
55 'SSW': '22.5',
56 'SW': '45',
57 'WSW': '67.5',
58 'W': '90',
59 'WNW': '112.5',
60 'NW': '135',
61 'NNW': '157.5'
62 }
63
64 class Meteorology:
65 """
66 Surface winds tend to be 20-30 degrees backed (vector anticlockwise)
67 from the winds which steer weather systems:
68 Friction with the ground surface tends to mean that land surface winds
69 are as slow as half the speed of the wind at 2000ft. This fudge factor is
70 a more conservative 1.5:
71
72 .. seealso::
73
74 [Source Book to the Forecaster's Reference Book](https://digital.nmla
75 .metoffice.gov.uk/IO_011f7cd4-50fc-4903-b556-d24480ea883d/), section
76 1.2
77 """
78 SURFACE_BACKING = 2
79 SURFACE_FRICTION = .66
80 KT_TO_MPH = 1.15078
81
82 @staticmethod
83 def process_direction(direction: str) -> str:
84 """Process raw wind direction:
85
86 * Convert direction from 10s of degrees to degrees.
87 * Convert from Oceanographic (wind to) to Meteorological (wind from)
88 convention.
89 * Surface Friction Correction
90 """
91 return str(
92 ((int(direction) + 18 - Meteorology.SURFACE_BACKING) % 36) * 10)
93
94 @staticmethod
95 def process_speed(speed: str) -> str:
96 """Process Raw wind speed
97
98 * Convert to KT to MPH
99 * Surface Friction Correction
100 """
101 return str(
102 (
103 int(speed) * Meteorology.KT_TO_MPH
104 ) / Meteorology.SURFACE_FRICTION
105 )
106
107
108 class NoDataException(Exception):
109 ...
110
111
112 def get_archived_data(site_id, time):
113 """Return archived weather data from the workflow directory."""
114 print(
115 [os.environ['CYLC_WORKFLOW_RUN_DIR'], 'data', time, site_id + '.json']
116 )
117 path = os.path.join(
118 os.environ['CYLC_WORKFLOW_RUN_DIR'], 'data', time, site_id + '.json')
119 print('Opening File: %s' % path)
120 return json.load(open(path, 'r'))['SiteRep']['DV']['Location']
121
122
123 def extract_observations(data):
124 """Extract the relevant observations from the weather data."""
125 return [data['lon'],
126 data['lat'],
127 ORDINATES[data['Period']['Rep']['D']],
128 data['Period']['Rep']['S']]
129
130
131 def reference_lat_long(site_id):
132 """Extract lat-long from a reference file."""
133 src = Path(os.environ['CYLC_WORKFLOW_RUN_DIR'], 'etc/met-office-sites.dat')
134 info = Path(src).read_text()
135 siteinfo = re.findall(f'^{int(site_id):05d}.*', info, re.MULTILINE)
136 if not siteinfo:
137 raise NoDataException(
138 f'Cannot find site with ID {site_id} in reference file {src}'
139 )
140 siteinfo = siteinfo[0].split()
141 lat = siteinfo[-4]
142 lon = siteinfo[-3]
143 return lat, lon
144
145
146 def synop_grab(site_id, time):
147 """Get obs data from a resonably reliable 3rd Party source.
148
149 n.b. In theory the remote site has some limits on how many requests
150 you throw at it, but this is in the tens of thousands of lines, and
151 this request should get just 1.
152 """
153 # Construct a Request:
154 time = datetime.strptime(time, '%Y%m%dT%H%MZ').strftime('%Y%m%d%H%M')
155 url = (
156 f'https://www.ogimet.com/cgi-bin/getsynop?block={int(site_id):05d}'
157 f'&begin={time}&end={time}'
158 )
159 req = requests.get(url)
160 print(f'Requests Returned: {req.text}')
161
162 if req.status_code != 200:
163 # If request has failed return False.
164 raise NoDataException(f'Request for data Failed for {url}')
165
166 # See https://allaboutweather.tripod.com/synopcode.htm for an explanation
167 # of what this regex is looking for: Synopcode dd and ff
168 regex_wind = re.compile(
169 r'AAXX [\d\/]{5} [\d\/]{5} [\d\/]{5} [\d\/]'
170 r'(?P<direction>\d\d)(?P<speed>\d\d) 1'
171 )
172 try:
173 data = regex_wind.search(req.text).groupdict()
174 except AttributeError:
175 raise NoDataException(
176 f'Request for data failed, raw request was {req.text}')
177
178 # * Parse the direction from 10's of degrees to degrees
179 # * Convert direction from to direction it's blowing to
180 data['direction'] = Meteorology.process_direction(data['direction'])
181
182 # Convert data in KT to MPH:
183 data['speed'] = Meteorology.process_speed(data['speed'])
184
185 # Get lat and long from MO Data:
186 lat, lon = reference_lat_long(site_id)
187
188 return [lat, lon, data['direction'], data['speed']]
189
190
191 def get_nearby_site(site_id, badsites):
192 """Use Pythagoras to find the next nearest site."""
193 lat, lon = reference_lat_long(site_id)
194 src = Path(os.environ['CYLC_WORKFLOW_RUN_DIR'], 'etc/met-office-sites.dat')
195 info = Path(src).read_text()
196 dist = 100
197 result = 0
198 for site in info.split('\n')[6:]:
199 site = site.split()
200 slat = site[-4]
201 slon = site[-3]
202 x = float(slat) - float(lat)
203 y = float(slon) - float(lon)
204 ndist = (x ** 2 + y ** 2) ** 0.5
205 if ndist < dist and site[0] not in badsites:
206 dist = ndist
207 result = site
208 print('using {} (dist {})'.format(" ".join(result[1:][:-5]), dist))
209 return int(result[0]), dist
210
211
212 def main(site_id):
213 cycle_point = os.environ['CYLC_TASK_CYCLE_POINT']
214
215 # Try to get the information from SYNOPS.
216 dist = 0.0
217 badsites = []
218 fails = True
219 obs = None
220 while dist < 1 and fails:
221 try:
222 obs = synop_grab(site_id, cycle_point)
223 fails = False
224 except NoDataException:
225 badsites.append(f'{int(site_id):05d}')
226 site_id, dist = get_nearby_site(site_id, badsites)
227
228 if obs is None:
229 print('Obs unavailable, falling back to archived data')
230 data = get_archived_data(site_id, cycle_point)
231 obs = extract_observations(data)
232
233 # Write observations.
234 with open('wind.csv', 'w+') as data_file:
235 data_file.write(', '.join(obs))
236
237
238 if __name__ == '__main__':
239 util.sleep()
240 main(os.environ['SITE_ID'])