Debian Codegraph @

cylc/flow/etc/tutorial/cylc-forecasting-workflow/lib/python/util.py

raw
1 # -*- coding: utf-8 -*-
2 # -----------------------------------------------------------------------------
3 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
4 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 # -----------------------------------------------------------------------------
19 # This is illustrative code developed for tutorial purposes, it is not
20 # intended for scientific use and is not guarantied to be accurate or correct.
21 from copy import copy
22 from contextlib import suppress
23 import math
24 import os
25 import sys
26 import time
27
28 import jinja2
29
30 R_0 = 6371. # Radius of the Earth (km).
31
32
33 def frange(start, stop, step):
34 """Implementation of python's xrange which works with floats."""
35 while start < stop:
36 yield start
37 start += step
38
39
40 def read_csv(filename, cast=float):
41 """Reads in data from a 2D csv file.
42
43 Args:
44 filename (str): The path to the file to read.
45 cast (function): A function to call on each value to convert the data
46 into the desired format.
47
48 """
49 data = []
50 with open(filename, 'r') as datafile:
51 line = datafile.readline()
52 while line:
53 data.append(list(map(cast, line.split(','))))
54 line = datafile.readline()
55 return data
56
57
58 def write_csv(filename, matrix, fmt='%.2f'):
59 """Write data from a 2D array to a csv format file."""
60 with open(filename, 'w+') as datafile:
61 for row in matrix:
62 datafile.write(', '.join(fmt % x for x in row) + '\n')
63
64
65 def field_to_csv(field, x_range, y_range, filename):
66 """Extrapolate values from the field and write them to a csv file.
67
68 Args:
69 filename (str): The path of the csv file to write to.
70 field (function): A function of the form f(x, y) -> z.
71 x_range (list): List of the x coordinates of the extrapolated grid.
72 These are the extrapolation coordinates, the length of this list
73 defines the size of the grid.
74 y_range (list): List of the y coordinates of the extrapolated grid.
75 These are the extrapolation coordinates, the length of this list
76 defines the size of the grid.
77
78 """
79 with open(filename, 'w+') as csv_file:
80 for itt_y in y_range:
81 csv_file.write(', '.join('%.2f' % field(x, itt_y) for
82 x in x_range) + '\n')
83
84
85 def generate_matrix(dim_x, dim_y, value=0.):
86 """Generates a 2D list with the desired dimensions.
87
88 Args:
89 dim_x (int): The x-dimension of the matrix.
90 dim_y (int): The y-dimension of the matrix.
91 value: The default value for each cell of the matrix.
92
93 """
94 matrix = []
95 for _ in range(dim_y):
96 matrix.append([copy(value)] * dim_x)
97 return matrix
98
99
100 def permutations(collection_1, collection_2):
101 """Yield all permutations of two collections."""
102 for val_1 in collection_1:
103 for val_2 in collection_2:
104 yield val_1, val_2
105
106
107 def great_arc_distance(coordinate_1, coordinate_2):
108 """Compute the distance between two (lng, lat) coordinates in km.
109
110 Uses the Haversine formula.
111
112 Args:
113 coordinate_1 (tuple): A 2-tuple (lng, lat) of the first coordinate.
114 coordinate_2 (tuple): A 2-tuple (lng, lat) of the second coordinate.
115
116 """
117 (lng_1, lat_1) = coordinate_1
118 (lng_2, lat_2) = coordinate_2
119 lng_1 = math.radians(lng_1)
120 lat_1 = math.radians(lat_1)
121 lng_2 = math.radians(lng_2)
122 lat_2 = math.radians(lat_2)
123 return (
124 2 * R_0 * math.asin(
125 math.sqrt(
126 (math.sin((lat_2 - lat_1) / 2.) ** 2) + (
127 math.cos(lat_1) *
128 math.cos(lat_2) *
129 (math.sin((lng_2 - lng_1) / 2.) ** 2)
130 )
131 )
132 )
133 )
134
135
136 def interpolate_grid(points, dim_x, dim_y, d_x, d_y, spline_order=0):
137 """Interpolate 2D data onto a grid.
138
139 Args:
140 points (list): The points to interpolate as a list of 3-tuples
141 (x, y, z).
142 dim_x (int): The size of the grid in the x-dimension.
143 dim_y (int): The size of the grid in the y-dimension.
144 d_x (float): The grid spacing in the x-dimension.
145 d_y (float): The grid spacing in the y-dimension.
146 spline_order (int): The order of the beta-spline to use for
147 interpolation (0 = nearset).
148
149 Return:
150 list - 2D matrix of dimensions dim_x, dim_y containing the interpolated
151 data.
152
153 """
154 def spline_0(pos_x, pos_y, z_val):
155 """Zeroth order beta spline (i.e. nearest point)."""
156 return [(int(round(pos_x)), int(round(pos_y)), z_val)] # [(x, y, z)]
157
158 def spline_1(pos_x, pos_y, z_val):
159 """First order beta spline (weight spread about four nearest
160 points)."""
161 x_0 = int(math.floor(pos_x))
162 y_0 = int(math.floor(pos_y))
163 x_1 = x_0 + 1
164 y_1 = y_0 + 1
165 return [
166 # (x, y, z), ...
167 (x_0, y_0, (x_0 + d_x - pos_x) * (y_0 + d_y - pos_y) * z_val),
168 (x_1, y_0, (pos_x - x_0) * (y_0 + d_y - pos_y) * z_val),
169 (x_0, y_1, (x_0 + d_x - pos_x) * (pos_y - y_0) * z_val),
170 (x_1, y_1, (pos_x - x_0) * (pos_y - y_0) * z_val)
171 ]
172
173 if spline_order == 0:
174 spline = spline_0
175 elif spline_order == 1: # noqa: SIM106 (case type matching)
176 spline = spline_1
177 else:
178 raise ValueError('Invalid spline order "%d" must be in (0, 1).' %
179 spline_order)
180
181 grid = generate_matrix(dim_x, dim_y, 0.)
182
183 for x_val, y_val, z_val in points:
184 x_coord = x_val / d_x
185 y_coord = y_val / d_y
186 for grid_x, grid_y, grid_z in spline(x_coord, y_coord, z_val):
187 with suppress(IndexError):
188 grid[grid_y][grid_x] += grid_z
189 # skip grid point out of bounds
190
191 return grid
192
193
194 def plot_vector_grid(filename, x_grid, y_grid):
195 try:
196 import matplotlib
197 matplotlib.use('Agg')
198 import matplotlib.pyplot as plt
199 except ImportError:
200 print('Plotting disabled', file=sys.stderr)
201 return
202
203 fig = plt.figure()
204 x_coords = []
205 y_coords = []
206 z_coords = []
207 for itt_x in range(len(x_grid[0])):
208 for itt_y in range(len(x_grid)):
209 x_coords.append(itt_x)
210 y_coords.append(itt_y)
211 z_coords.append((
212 x_grid[itt_y][itt_x],
213 y_grid[itt_y][itt_x]
214 ))
215
216 plt.quiver(x_coords,
217 y_coords,
218 [x[0] for x in z_coords],
219 [y[1] for y in z_coords])
220 fig.savefig(filename)
221
222
223 def get_grid_coordinates(lng, lat, domain, resolution):
224 """Return the grid coordinates for a lat, long coordinate pair."""
225 # NOTE: Grid coordinates run from *top* left to bottom right.
226 length_y = int(abs(domain['lat2'] - domain['lat1']) // resolution)
227 return (
228 int((abs(lng - domain['lng1'])) // resolution),
229 length_y - int((abs(lat - domain['lat1'])) // resolution))
230
231
232 class SurfaceFitter:
233 """A 2D interpolation for random points.
234
235 A standin for scipy.interpolate.interp2d
236
237 Args:
238 x_points (list): A list of the x coordinates of the points to
239 interpolate.
240 y_points (list): A list of the y coordinates of the points.
241 z_points (list): A list of the z coordinates of the points.
242 kind (str): String representing the order of the interpolation to
243 perform (either linear, quadratic or cubic).
244
245 Returns:
246 function: fcn(x, y) -> z
247
248 """
249
250 def __init__(self, x_points, y_points, z_points, kind='linear'):
251 self.points = list(zip(x_points, y_points, z_points))
252
253 if kind == 'linear':
254 self.power = 1.
255 elif kind == 'quadratic':
256 self.power = 2.
257 elif kind == 'cubic': # noqa: SIM106 (case type matching)
258 self.power = 3.
259 else:
260 raise ValueError('"%s" is not a valid interpolation method' % kind)
261
262 def __call__(self, grid_x, grid_y):
263 sum_value = 0.0
264 sum_weight = 0.0
265 z_val = None
266 for x_point, y_point, z_point in self.points:
267 d_x = grid_x - x_point
268 d_y = grid_y - y_point
269 if d_x == 0 and d_y == 0:
270 # This point is exactly at the grid location we are
271 # interpolating for, return this value.
272 z_val = z_point
273 break
274 else:
275 weight = 1. / ((math.sqrt(d_x ** 2 + d_y ** 2)) ** self.power)
276 sum_weight += weight
277 sum_value += weight * z_point
278
279 if z_val is None:
280 z_val = sum_value / sum_weight
281
282 return z_val
283
284
285 def parse_domain(domain: str):
286 lng1, lat1, lng2, lat2 = list(map(float, domain.split(',')))
287 msg = "Invalid domain '{}' ({} {} >= {})"
288 if lng1 >= lng2:
289 raise ValueError(msg.format(domain, 'longitude', lng1, lng2))
290 if lat1 >= lat2:
291 raise ValueError(msg.format(domain, 'latitude', lat1, lat2))
292 return {
293 'lng1': lng1,
294 'lat1': lat1,
295 'lng2': lng2,
296 'lat2': lat2,
297 }
298
299
300 def generate_html_map(filename, template_file, data, domain, resolution):
301 with open(template_file, 'r') as template: # noqa: SIM117
302 with open(filename, 'w+') as html_file:
303 html_file.write(jinja2.Template(template.read()).render(
304 resolution=resolution,
305 lng1=domain['lng1'],
306 lng2=domain['lng2'],
307 lat1=domain['lat1'],
308 lat2=domain['lat2'],
309 data=data
310 ))
311
312
313 def sleep(secs=4):
314 """Make the tutorials run a little slower so users can follow along.
315
316 (Only if not running in CI).
317 """
318 if 'CI' not in os.environ:
319 time.sleep(secs)