Debian Codegraph @

cylc/flow/etc/tutorial/cylc-forecasting-workflow/bin/consolidate-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.
22 """
23 Usage:
24 consolidate-observations
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 glob import glob
34 import math
35 import os
36 import sys
37
38 import util
39
40
41 def plot_wind_data(wind_x, wind_y, x_range, y_range, x_coords, y_coords,
42 z_coords):
43 """Generate a 2D vector plot of the wind data if matplotlib is installed"""
44 try:
45 import matplotlib
46 matplotlib.use('Agg')
47 import matplotlib.pyplot as plt
48 except ModuleNotFoundError:
49 print('matplotlib not installed: plotting disabled.', file=sys.stderr)
50 return
51
52 plt.figure()
53 x_points = [point[0] for point in util.permutations(x_range, y_range)]
54 y_points = [point[1] for point in util.permutations(x_range, y_range)]
55 plt.quiver(x_points,
56 y_points,
57 [wind_x(x, y) for x, y in zip(x_points, y_points)],
58 [wind_y(x, y) for x, y in zip(x_points, y_points)])
59 plt.quiver(x_coords,
60 y_coords,
61 [x[0] for x in z_coords],
62 [y[1] for y in z_coords],
63 color='red')
64 plt.savefig(f'{os.environ["CYLC_TASK_LOG_DIR"]}/wind.png')
65
66
67 def get_wind_fields():
68 """Read in wind.csv files, interpolate and return the wind fields."""
69 # Filename glob for observation files.
70 files = glob(os.path.join(
71 os.environ['CYLC_WORKFLOW_WORK_DIR'],
72 os.environ['CYLC_TASK_CYCLE_POINT'],
73 'get_observations*',
74 'wind.csv'))
75
76 # Extract observation data.
77 data = []
78 for filename in files:
79 with open(filename, 'r') as datafile:
80 data.append(list(map(float, datafile.read().split(', '))))
81 data.sort(key=lambda x: x[1])
82
83 # Convert data into (lat, lng, (wind_x, wind_y)) components.
84 x_coords = [datum[1] for datum in data]
85 y_coords = [datum[0] for datum in data]
86 z_coords = [(datum[3] * math.sin(math.radians(datum[2])),
87 datum[3] * math.cos(math.radians(datum[2])))
88 for datum in data]
89
90 # Interpolate this data to generate wind "fields".
91 wind_x = util.SurfaceFitter(x_coords, y_coords, [x[0] for x in z_coords])
92 wind_y = util.SurfaceFitter(x_coords, y_coords, [y[1] for y in z_coords])
93
94 return wind_x, wind_y, (x_coords, y_coords, z_coords)
95
96
97 def main():
98 domain = util.parse_domain(os.environ['DOMAIN'])
99 resolution = float(os.environ['RESOLUTION'])
100
101 # Interpolate fields for the longitudinal (x) and latitudinal (y)
102 # components of wind.
103 wind_x, wind_y, data_points = get_wind_fields()
104
105 # The coordinates of the domain.
106 x_range = list(util.frange(domain['lng1'], domain['lng2'], resolution))
107 y_range = list(util.frange(domain['lat1'], domain['lat2'], resolution))
108
109 # Plot wind fields for reference.
110 plot_wind_data(wind_x, wind_y, x_range, y_range, *data_points)
111
112 # Write wind data to csv.
113 util.field_to_csv(wind_x, x_range, y_range, 'wind_x.csv')
114 util.field_to_csv(wind_y, x_range, y_range, 'wind_y.csv')
115
116
117 if __name__ == '__main__':
118 util.sleep()
119 main()