PHYEX 0.9.5
PHYsique EXternalisée
Loading...
Searching...
No Matches
grid.py
Go to the documentation of this file.
1"""
2The grib module defines the Grib class that handles the vertical grids:
3- reading
4- conversion between half/full and Height/Pressure
5"""
6
7import argparse
8import os
9import glob
10import json
11import sys
12import textwrap
13import numpy
14from . import Phyex1DError
15from . import Cst
16from . import user_dir
17from . import commands_help
18
19FLUX = ['FLUX', 'HALF', 'INTERFACE']
20MASS = ['MASS', 'FULL']
21
22# Directory of the grids provided with the package
23PACKAGE_GRID_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'grids')
24
25
26def grid_files(name):
27 """
28 Files defining a grid
29 :param name: grid name
30 :return: (user file, package file), each being None if the file does not exist; the user
31 file, if any, is the one used (it overrides the package file)
32 """
33 return tuple(os.path.join(grid_dir, name + '.grid')
34 if os.path.exists(os.path.join(grid_dir, name + '.grid')) else None
35 for grid_dir in (user_dir('grids'), PACKAGE_GRID_DIR))
36
37
39 """
40 List of the available grids (in the user directory and in the package)
41 :return: list of (name, kind, number of levels, location) tuples, sorted by name;
42 location is 'internal' for a grid of the package, the file name for a grid of the
43 user directory and 'internal overridden by <file name>' for a grid of the package
44 replaced by a grid of the user directory; kind and number of levels are None if
45 the grid file cannot be read
46 """
47 names = sorted(set(os.path.basename(filename)[:-len('.grid')]
48 for grid_dir in (user_dir('grids'), PACKAGE_GRID_DIR)
49 for filename in glob.glob(os.path.join(grid_dir, '*.grid'))))
50 result = []
51 for name in names:
52 user_file, package_file = grid_files(name)
53 if user_file is None:
54 location = 'internal'
55 elif package_file is None:
56 location = user_file
57 else:
58 location = 'internal overridden by ' + user_file
59 try:
60 grid = Grid(name)
61 kind, nlev = grid.kind, grid.nlevels
62 except (Phyex1DError, AssertionError, ValueError, KeyError, TypeError, OSError):
63 kind, nlev = None, None
64 result.append((name, kind, nlev, location))
65 return result
66
67
68class Grid():
69 """
70 The Grid class handles vertical grids
71
72 The definition of the vertical grids are stored in files with the '.grid' extension.
73 Theses files contains a dictionary as a json string with the folowing content:
74 - kind: 'hybridP' for an hybrid-pressure coordinate (pressure on level i is P(i)=a(i)+b(i)*Ps)
75 'hybridH' for an hybrid-height coordinate (altitude on level i is Z(i)=a(i)+b(i)*Zs)
76 'P' for a pressure coordinate
77 'H' for a height (above sea level) coordinate
78 - position: 'FLUX' if the grid refers to flux levels
79 'MASS' otherwise
80 - mean: 'linear' or 'quadratic'
81 way to compute flux levels from mass levels if grid is defined on mass levels
82 or the reverse if grid is defined on flux levels
83 - description: a single list of values if kind is 'P' or 'H'
84 a list containing a list for the a(i) coefficients and a list for the b(i)
85 coefficients if kind is 'hybridP' or 'hybridH'.
86 """
87
88 def __init__(self, grid):
89 """
90 Instanciates a Grid object from a file containing a grid description or from an
91 already known grid.
92
93 :param grid: a filename (if ending with the '.grid' extension or a grid name
94 """
95 grid_descr = None
96 if grid.endswith('.grid') and os.path.exists(grid):
97 # grid is a filename provided by the user
98 grid_descr = self._read_gridfile(grid)
99 self.filename = grid
100 else:
101 # look for a grid with the name provided in the user's directory,
102 # then in the package directory
103 for gridfile in grid_files(grid):
104 if gridfile is not None:
105 grid_descr = self._read_gridfile(gridfile)
106 self.filename = gridfile
107 break
108 if grid_descr is None:
109 raise Phyex1DError(f'Grid not found: {grid}')
110 self.position = grid_descr['position']
111 self.mean = grid_descr['mean']
112 self.kind = grid_descr['kind']
113 self.description = grid_descr['description']
114
115 assert self.position in FLUX + MASS, 'grid must be defined on flux or mass points'
116 assert self.mean in ('linear', 'quadratic'), \
117 "grid mean attribute must be 'quadratic' or 'linear'"
118 assert self.kind in ('H', 'P', 'hybridH', 'hybridP'), "grid kind unknown"
119 if self.kind in ('H', 'P'):
120 assert isinstance(self.description, list), 'grid description must be a list'
121 self.len = len(self.description)
122 self.description = numpy.array(self.description)
123 else:
124 assert isinstance(self.description, list) and len(self.description) == 2, \
125 "grid description must be a two-element list"
126 assert isinstance(self.description[0], list) and \
127 isinstance(self.description[1], list), \
128 "Both elements of grid description must be lists"
129 self.len = len(self.description[0])
130 assert self.len == len(self.description[1]), \
131 "Both elements of grid description must have the same length"
132 assert self.len > 0, 'grid must contain at least one level'
133 # Number of model levels (mass levels)
134 self.nlevels = self.len - 1 if self.position in FLUX else self.len
135
136 self.ascending = None
137
138 self.cst = Cst()
139
140 def _read_gridfile(self, gridfile):
141 """
142 Reads a grid
143 """
144 with open(gridfile, 'r', encoding='UTF-8') as f:
145 grid = json.load(f)
146 return grid
147
148 def _mean(self, values, method):
149 """
150 Computes the mean
151 :param method: must be 'linear' or 'quadartic'
152 """
153 if method == 'linear':
154 values = numpy.array([.5 * (values[i] + values[i + 1])
155 for i in range(self.len - 1)])
156 elif method == 'quadratic':
157 if values[0] == 0.:
158 update = (0, values[1] / 2.) # Linear when quadratic is not possible
159 elif values[-1] == 0.:
160 update = (-1, values[-2] / 2.) # Linear when quadratic is not possible
161 else:
162 update = None
163 values = numpy.array([numpy.sqrt(values[i] * values[i + 1])
164 for i in range(self.len - 1)])
165 if update is not None:
166 values[update[0]] = update[1]
167 else:
168 raise Phyex1DError("method must be 'linear' or 'quadartic'")
169 return values
170
171 def get_pressure(self, position, state, pronostic_variables):
172 """
173 Returns the level pressures
174 :param position: must be among grid.MASS + .grid.FLUX
175 :param state: dictionary containing the current state
176 :param pronostic_variables: list of pronostic variables
177 """
178 if self.kind == 'hybridP' and position == self.position:
179 if 'Ps' not in state:
180 raise Phyex1DError("Surface pressure ('Ps') is needed to compute the pressures")
181 pressure = numpy.array([self.description[0][i] + self.description[1][i] * state['Ps']
182 for i in range(self.len)])
183 if self.ascending is None:
184 self.ascending = numpy.all(pressure[1:] < pressure[:-1])
185 elif self.kind == 'P' and position == self.position:
186 pressure = numpy.array(self.description)
187 if self.ascending is None:
188 self.ascending = numpy.all(pressure[1:] < pressure[:-1])
189 elif self.kind in ('P', 'hybridP'):
190 pressure = self._mean(self.get_pressure(self.position, state, pronostic_variables),
191 self.mean)
192 elif self.kind in ('H', 'hybridH'):
193 # We assume hydrostatic equilibrium
194 # leading to dln(P) / dz = -g / (R * T) if T is the prognostic variable
195 # or d[(P / P0) ** (Rd / Cpd)] / dz = -g / (R * Theta) * (Rd / Cpd) with Theta
196 if 'qv' in pronostic_variables:
197 gas_constant = self.cst.Rd + state['qv'] * (self.cst.Rv - self.cst.Rd)
198 for var in ('qc', 'qr', 'qi', 'qs', 'qg', 'qh'):
199 if var in pronostic_variables:
200 gas_constant += - state[var] * self.cst.Rd
201 elif 'rv' in pronostic_variables:
202 div = 1 + state['rv']
203 for var in ('rc', 'rr', 'ri', 'rs', 'rg', 'rh'):
204 if var in pronostic_variables:
205 div += state[var]
206 gas_constant = (self.cst.Rd + state['rv'] * self.cst.Rv) / div
207 z_flux = self.get_altitude('FLUX', state, pronostic_variables)
208 dx = - self.cst.g / gas_constant * numpy.diff(z_flux)
209 if 'T' in pronostic_variables:
210 dx = dx / state['T']
211 elif 'Theta' in pronostic_variables:
212 dx = dx / state['Theta'] * self.cst.Rd / self.cst.Cpd
213 else:
214 raise Phyex1DError("T or Theta must be prognostic")
215 x_flux = numpy.zeros(z_flux.shape)
216 if self.ascending:
217 x_flux[1:] = numpy.cumsum(dx)
218 else:
219 x_flux[:-1] = numpy.cumsum(-dx[::-1])[::-1]
220 if 'T' in pronostic_variables:
221 x_flux += numpy.log(state['Ps'])
222 pressure_flux = numpy.exp(x_flux)
223 else:
224 x_flux += (state['Ps'] / 1.E5) ** (self.cst.Rd / self.cst.Cpd)
225 pressure_flux = x_flux ** (self.cst.Cpd / self.cst.Rd) * 1.E5
226 if position == 'FLUX':
227 pressure = pressure_flux
228 else:
229 # We add the contribution between flux and mass levels assuming constant profiles
230 z_mass = self.get_altitude('MASS', state, pronostic_variables)
231 dx = - self.cst.g / gas_constant
232 if self.ascending:
233 dx = dx * (z_mass - z_flux[:-1])
234 else:
235 dx = dx * (z_mass - z_flux[1:])
236 if self.ascending:
237 temp = pressure_flux[:-1]
238 else:
239 temp = pressure_flux[1:]
240 if 'T' in pronostic_variables:
241 dx = dx / state['T']
242 pressure = numpy.exp(numpy.log(temp) + dx)
243 elif 'Theta' in pronostic_variables:
244 dx = dx / state['Theta'] * self.cst.Rd / self.cst.Cpd
245 pressure = ((temp / 1.E5) ** (self.cst.Rd / self.cst.Cpd) + dx
246 ) ** (self.cst.Cpd / self.cst.Rd) * 1.E5
247 else:
248 raise Phyex1DError("T or Theta must be prognostic")
249 else:
250 raise Phyex1DError("Wrong grid's kind")
251
252 return pressure
253
254 def get_altitude(self, position, state, pronostic_variables):
255 """
256 Returns the level altitudes
257 :param position: must be among grid.MASS + .grid.FLUX
258 :param state: dictionary containing the current state
259 :param pronostic_variables: list of pronostic variables
260 """
261 if self.kind == 'hybridH' and position == self.position:
262 if 'Zs' not in state:
263 raise Phyex1DError("Surface altitude ('Zs') is needed to compute the altitudes")
264 altitude = numpy.array([self.description[0][i] + self.description[1][i] * state['Zs']
265 for i in range(self.len)])
266 if self.ascending is None:
267 self.ascending = numpy.all(altitude[1:] > altitude[:-1])
268 elif self.kind == 'H' and position == self.position:
269 altitude = numpy.array(self.description)
270 if self.ascending is None:
271 self.ascending = numpy.all(altitude[1:] > altitude[:-1])
272 elif self.kind in ('H', 'hybridH'):
273 altitude = self._mean(self.get_altitude(self.position, state, pronostic_variables),
274 self.mean)
275 elif self.kind in ('P', 'hybridP'):
276 # We assume hydrostatic equilibrium
277 # leading to dln(P) / dz = -g / (R*T)
278 pressure_mass = None
279 if 'T' in pronostic_variables:
280 temperature = state['T']
281 elif 'Theta' in pronostic_variables:
282 pressure_mass = self.get_pressure('MASS', state, pronostic_variables)
283 exner = (pressure_mass / 1.E5) ** (self.cst.Rd / self.cst.Cpd)
284 temperature = exner * state['Theta']
285 else:
286 raise Phyex1DError("T or Theta must be prognostic")
287 if 'qv' in pronostic_variables:
288 gas_constant = self.cst.Rd + state['qv'] * (self.cst.Rv - self.cst.Rd)
289 for var in ('qc', 'qr', 'qi', 'qs', 'qg', 'qh'):
290 if var in pronostic_variables:
291 gas_constant += - state[var] * self.cst.Rd
292 elif 'rv' in pronostic_variables:
293 div = 1 + state['rv']
294 for var in ('rc', 'rr', 'ri', 'rs', 'rg', 'rh'):
295 if var in pronostic_variables:
296 div += state[var]
297 gas_constant = (self.cst.Rd + state['rv'] * self.cst.Rv) / div
298 pressure_flux = self.get_pressure('FLUX', state, pronostic_variables)
299 dz = -gas_constant * temperature / self.cst.g * numpy.diff(numpy.log(pressure_flux))
300 z_flux = numpy.zeros(pressure_flux.shape)
301 if self.ascending:
302 z_flux[1:] = numpy.cumsum(dz)
303 else:
304 z_flux[:-1] = numpy.cumsum(-dz[::-1])[::-1]
305 z_flux += state['Zs']
306 if position == 'FLUX':
307 altitude = z_flux
308 else:
309 # We add the contribution between flux and mass levels assuming constant profiles
310 if pressure_mass is None:
311 pressure_mass = self.get_pressure('MASS', state, pronostic_variables)
312 if self.ascending:
313 dlnp = numpy.log(pressure_mass) - numpy.log(pressure_flux[:-1])
314 else:
315 dlnp = numpy.log(pressure_mass) - numpy.log(pressure_flux[1:])
316 dz = -gas_constant * temperature / self.cst.g * dlnp
317 if self.ascending:
318 altitude = z_flux[:-1] + dz
319 else:
320 altitude = z_flux[1:] + dz
321 else:
322 raise Phyex1DError("Wrong grid's kind")
323 return altitude
324
325
327 """Entry point of the phyex1d-grid_list command"""
328 parser = argparse.ArgumentParser(
329 description=textwrap.fill(
330 'Lists the available vertical grids (name, kind, number of levels and location). '
331 f'Grids are searched in {user_dir("grids")}, then in the package; a grid of the '
332 'package can be overridden by a file with the same name in the user directory. '
333 'The grid name can be given to phyex1d-exp_run (grid key).'),
334 epilog=commands_help(), formatter_class=argparse.RawDescriptionHelpFormatter)
335 parser.parse_args()
336 grids = list_grids()
337 lines = [(name, '?' if kind is None else kind, '?' if nlev is None else str(nlev),
338 location + (' (unreadable)' if kind is None else ''))
339 for name, kind, nlev, location in grids]
340 header = ('name', 'kind', 'levels', 'location')
341 widths = [max(len(item) for item in column) for column in zip(header, *lines)]
342 for line in [header] + lines:
343 print(' '.join(f'{item:{width}s}' for item, width in zip(line[:-1], widths)) +
344 ' ' + line[-1])
345
346
348 """Entry point of the phyex1d-grid_show command"""
349 parser = argparse.ArgumentParser(
350 description=textwrap.fill(
351 'Prints the description (content of the .grid file) of a vertical grid. The '
352 'output can be used as a starting point to define a new grid in '
353 f'{user_dir("grids")}. The format of the .grid files is given by the docstring '
354 'of the pyphyex.phyex1d.Grid class.'),
355 epilog=commands_help(), formatter_class=argparse.RawDescriptionHelpFormatter)
356 parser.add_argument('GRID', help='grid name (see phyex1d-grid_list)')
357 args = parser.parse_args()
358 filename = next((gridfile for gridfile in grid_files(args.GRID) if gridfile is not None),
359 None)
360 if filename is None:
361 sys.exit(f'Error: grid {args.GRID} not found (see phyex1d-grid_list)')
362 with open(filename, 'r', encoding='UTF-8') as f:
363 sys.stdout.write(f.read())
get_pressure(self, position, state, pronostic_variables)
Definition grid.py:171
__init__(self, grid)
Definition grid.py:88
_mean(self, values, method)
Definition grid.py:148
_read_gridfile(self, gridfile)
Definition grid.py:140
get_altitude(self, position, state, pronostic_variables)
Definition grid.py:254
user_dir(subdir)
Definition __init__.py:35