PHYEX 0.9.5
PHYsique EXternalisée
Loading...
Searching...
No Matches
case.py
Go to the documentation of this file.
1"""
2Case classes representing a simulation case
3"""
4
5import argparse
6import glob
7import os
8import re
9import subprocess
10import sys
11import textwrap
12
13import netCDF4
14from scipy.interpolate import RegularGridInterpolator
15
16from . import Phyex1DError
17from . import user_dir, commands_help
18
19# DEPHY-SCM repository (cases in the common format)
20DEPHY_SCM_URL = 'https://github.com/GdR-DEPHY/DEPHY-SCM.git'
21# Driver files of the cases: <CASE>/<SUBCASE>/<CASE>_<SUBCASE>_SCM_driver.nc
22_DRIVER_RE = re.compile(r'^(?P<case>[^/]+)/(?P<subcase>[^/]+)/[^/]+_SCM_driver\.nc$')
23
24
25class Case():
26 """
27 Base class for case implementations
28
29 All subclasses must provide:
30 - description (str property)
31 - duration (float property, seconds)
32 - contains(varname) -> bool
33 - get(varname, slice_idx=None) -> numpy.ndarray
34 - get_interpolator(varname, grid) -> RegularGridInterpolator
35 - context manager support (__enter__ / __exit__)
36 """
37
38 def contains(self, varname):
39 """Check if a variable exists in the case data"""
40 raise NotImplementedError
41
42 def get(self, varname, slice_idx=None):
43 """Read a variable from the case data"""
44 raise NotImplementedError
45
46 @property
47 def duration(self):
48 """Simulation duration in seconds"""
49 raise NotImplementedError
50
51 @property
52 def description(self):
53 """Case description string"""
54 raise NotImplementedError
55
56 def get_interpolator(self, varname, grid):
57 """Get or build an interpolator for a forcing variable"""
58 raise NotImplementedError
59
60 def __enter__(self):
61 return self
62
63 def __exit__(self, *args):
64 self.close()
65
66 def close(self):
67 """Close any open resources. Override in subclasses."""
68
69
70class CaseCommonFormat(Case):
71 """
72 Case backed by a netCDF driver file in the DEPHY common format
73 """
74
75 nc_names = {'Theta': 'theta',
76 'T': 'ta',
77 'Zs': 'orog',
78 'Ps': 'ps',
79 'qv': 'qv',
80 'qc': 'ql',
81 'qi': 'qi',
82 'qr': 'qr',
83 'qs': 'qs',
84 'qg': 'qg',
85 'qh': 'qh',
86 'rv': 'rv',
87 'rc': 'rl',
88 'ri': 'ri',
89 'rr': 'rr',
90 'rs': 'rs',
91 'rg': 'rg',
92 'rh': 'rh',
93 'u': 'ua',
94 'v': 'va',
95 'w': 'wa',
96 'sshf': 'hfss',
97 'slhf': 'hfls',
98 'z0': 'z0',
99 'z0h': 'z0h',
100 'z0q': 'z0q',
101 'tke': 'tke',
102 'Tskin': 'tskin',
103 'ustar': 'ustar',
104 'Ts': 'ts',
105 'SolarIrradiance': 'i0',
106 'albedo': 'alb',
107 'emissivity': 'emis',
108 'sza': 'sza',
109 'o3': 'o3',
110 'lat': 'lat',
111 'lon': 'lon',
112 'u_geo': 'ug',
113 'v_geo': 'vg',
114 'ni': 'ni',
115 'zh': 'zh',
116 'orog': 'orog',
117 'pa': 'pa',
118 'zh_forc': 'zh_forc',
119 'pa_forc': 'pa_forc',
120 'time': 'time',
121 }
122
123 def __init__(self, inputfile, attrs=None):
124 """
125 :param inputfile: path to a netCDF driver file
126 :param attrs: dictionary of attributes to override
127 """
128 self._inputfile = inputfile
129 self._nc = None
131 self.adv_ua = 0
132 self.adv_va = 0
133 with netCDF4.Dataset(inputfile, 'r') as nc:
134 for k in nc.ncattrs():
135 setattr(self, k, getattr(nc, k))
136 if attrs is not None:
137 for k, v in attrs.items():
138 setattr(self, k, v)
139
140 @property
141 def is_open(self):
142 """Whether the netCDF file is currently open"""
143 return self._nc is not None
144
145 def open(self):
146 """
147 Open the netCDF file if not already open
148
149 Returns
150 -------
151 netCDF4.Dataset
152 The opened dataset
153 """
154 if self._nc is None:
155 self._nc = netCDF4.Dataset(self._inputfile, 'r')
156 return self._nc
157
158 def close(self):
159 """Close the netCDF file if open"""
160 if self._nc is not None:
161 self._nc.close()
162 self._nc = None
163
164 def contains(self, varname):
165 """
166 Check if a variable exists in the netCDF file
167
168 Parameters
169 ----------
170 varname : str
171 Variable name (translated via nc_names if present)
172
173 Returns
174 -------
175 bool
176 True if the variable exists
177 """
178 self.open()
179 ncf_name = self.nc_names.get(varname, varname)
180 return ncf_name in self._nc.variables
181
182 def get(self, varname, slice_idx=None):
183 """
184 Read a variable from the netCDF file
185
186 Parameters
187 ----------
188 varname : str
189 Variable name (translated via nc_names if present)
190 slice_idx : int or None, optional
191 Slice index to read. None returns the full array.
192
193 Returns
194 -------
195 numpy.ndarray
196 The data array
197 """
198 self.open()
199 ncf_name = self.nc_names.get(varname, varname)
200 data = self._nc[ncf_name]
201 return data[...] if slice_idx is None else data[slice_idx]
202
203 @property
204 def duration(self):
205 """
206 Simulation duration
207
208 Returns
209 -------
210 float
211 Duration in seconds (time[-1] - time[0])
212 """
213 times = self.get('time')
214 self.close()
215 return times[-1] - times[0]
216
217 def get_interpolator(self, varname, grid):
218 """
219 Get from cache or build an interpolator for a forcing variable
220
221 Parameters
222 ----------
223 varname : str
224 Variable name
225 grid : Grid
226 Grid instance for vertical coordinate
227
228 Returns
229 -------
230 RegularGridInterpolator
231 The interpolator
232 """
233 if varname in self._interpolators:
234 return self._interpolators[varname]
235 input_times = self.get('time')
236 if len(self.get(varname).shape) == 2:
237 if grid.kind in ('H', 'hybridH'):
238 input_coord = self.get('zh_forc', 0)
239 elif grid.kind in ('P', 'hybridP'):
240 input_coord = self.get('pa_forc', 0)
241 else:
242 raise Phyex1DError('Wrong grid kind')
243 interp = RegularGridInterpolator((input_times, input_coord),
244 self.get(varname),
245 bounds_error=False, fill_value=None)
246 else:
247 interp = RegularGridInterpolator((input_times, ),
248 self.get(varname),
249 bounds_error=False, fill_value=None)
250 self._interpolators[varname] = interp
251 return interp
252
253 @property
254 def description(self):
255 """
256 Case description
257
258 Returns
259 -------
260 str
261 Case description string (file path)
262 """
263 return self._inputfile
264
265
267 """
268 Case backed by an in-memory xarray Dataset
269
270 Parameters
271 ----------
272 dataset : xarray.Dataset
273 Dataset containing all case variables. Variable names must match the
274 phyex1d internal names (e.g. 'T', 'qv', 'u', 'zh', 'Ps', 'lat', ...).
275 attrs : dict, optional
276 Additional attributes to set on the case (overrides dataset attrs).
277 """
278
279 def __init__(self, dataset, attrs=None):
280 self._dataset = dataset
282 self.adv_ua = 0
283 self.adv_va = 0
284 for k, v in dataset.attrs.items():
285 setattr(self, k, v)
286 if attrs is not None:
287 for k, v in attrs.items():
288 setattr(self, k, v)
289
290 def contains(self, varname):
291 """
292 Check if a variable exists in the dataset
293
294 Parameters
295 ----------
296 varname : str
297 Variable name
298
299 Returns
300 -------
301 bool
302 True if the variable exists
303 """
304 return varname in self._dataset
305
306 def get(self, varname, slice_idx=None):
307 """
308 Read a variable from the dataset
309
310 Parameters
311 ----------
312 varname : str
313 Variable name
314 slice_idx : int or None, optional
315 Slice index to read. None returns the full array.
316
317 Returns
318 -------
319 numpy.ndarray
320 The data array
321 """
322 data = self._dataset[varname].values
323 return data if slice_idx is None else data[slice_idx]
324
325 @property
326 def duration(self):
327 """
328 Simulation duration
329
330 Returns
331 -------
332 float
333 Duration in seconds (time[-1] - time[0])
334 """
335 times = self._dataset['time'].values
336 return float(times[-1] - times[0])
337
338 @property
339 def description(self):
340 """
341 Case description
342
343 Returns
344 -------
345 str
346 Case description string
347 """
348 return getattr(self, '_description', 'CaseXarray_' + str(id(self._dataset)))
349
350 @description.setter
351 def description(self, value):
352 """Set a custom description string"""
353 self._description = value
354
355 def get_interpolator(self, varname, grid):
356 """
357 Get from cache or build an interpolator for a forcing variable
358
359 Parameters
360 ----------
361 varname : str
362 Variable name
363 grid : Grid
364 Grid instance for vertical coordinate
365
366 Returns
367 -------
368 RegularGridInterpolator
369 The interpolator
370 """
371 if varname in self._interpolators:
372 return self._interpolators[varname]
373 input_times = self.get('time')
374 ndim = len(self.get(varname).shape)
375 if ndim == 2:
376 if grid.kind in ('H', 'hybridH'):
377 input_coord = self.get('zh_forc', 0)
378 elif grid.kind in ('P', 'hybridP'):
379 input_coord = self.get('pa_forc', 0)
380 else:
381 raise Phyex1DError('Wrong grid kind')
382 interp = RegularGridInterpolator((input_times, input_coord),
383 self.get(varname),
384 bounds_error=False, fill_value=None)
385 elif ndim == 1:
386 interp = RegularGridInterpolator((input_times, ),
387 self.get(varname),
388 bounds_error=False, fill_value=None)
389 else:
390 raise Phyex1DError(f'Unexpected variable dimensions: {ndim}')
391 self._interpolators[varname] = interp
392 return interp
393
394
395
398
399def _git(args, directory=None):
400 """Executes a git command (in directory), returns its standard output"""
401 cmd = ['git'] + ([] if directory is None else ['-C', directory]) + args
402 try:
403 return subprocess.run(cmd, check=True, stdout=subprocess.PIPE, text=True).stdout
404 except (OSError, subprocess.CalledProcessError) as err:
405 raise Phyex1DError(f"git command failed: {' '.join(cmd)}") from err
406
407
409 """Directory of the DEPHY-SCM repository: $PHYEXCONF/phyex1d/DEPHY-SCM (PHYEXCONF
410 defaults to ~/.phyex)"""
411 return user_dir('DEPHY-SCM')
412
413
414def install_cases(directory=None):
415 """
416 Installs (clone) or updates (fetch and reset to the remote branch) the DEPHY-SCM
417 repository containing the cases in the common format (the repository is big, about
418 1 GB).
419
420 :param directory: directory of the repository (cases_directory() by default)
421 :return: directory of the repository
422 """
423 directory = cases_directory() if directory is None else directory
424 if os.path.islink(directory):
425 raise Phyex1DError(f"{directory} is a link to {os.readlink(directory)}: the "
426 "repository it points to must be updated by its owner (or the "
427 "link must be removed before downloading)")
428 if os.path.isdir(os.path.join(directory, '.git')):
429 # Update robust to a rewritten history (forced push): the local branch is reset
430 # to the remote one (local modifications of the repository are lost)
431 _git(['fetch', 'origin'], directory)
432 _git(['reset', '--hard', '@{upstream}'], directory)
433 else:
434 os.makedirs(os.path.dirname(os.path.abspath(directory)), exist_ok=True)
435 _git(['clone', DEPHY_SCM_URL, directory])
436 return directory
437
438
439def link_cases(path, directory=None):
440 """
441 Uses an existing DEPHY-SCM repository (or a copy of it): a symbolic link to it is
442 created instead of downloading the repository.
443
444 :param path: path to the existing DEPHY-SCM repository
445 :param directory: path of the link (cases_directory() by default); an existing link
446 is replaced, an existing directory (downloaded repository) is kept
447 and an error is raised
448 :return: path of the link
449 """
450 directory = cases_directory() if directory is None else directory
451 path = os.path.abspath(path)
452 if not os.path.isdir(path):
453 raise Phyex1DError(f"{path} is not a directory")
454 if not glob.glob(os.path.join(path, '*', '*', '*_SCM_driver.nc')):
455 raise Phyex1DError(f"{path} does not contain DEPHY-SCM cases "
456 "(<CASE>/<SUBCASE>/*_SCM_driver.nc files)")
457 if os.path.islink(directory):
458 os.remove(directory)
459 elif os.path.exists(directory):
460 raise Phyex1DError(f"{directory} already exists and is not a link (downloaded "
461 "repository?), remove it before creating the link")
462 os.makedirs(os.path.dirname(os.path.abspath(directory)), exist_ok=True)
463 os.symlink(path, directory)
464 return directory
465
466
467def list_cases(directory=None):
468 """
469 Lists the cases available in the DEPHY-SCM repository.
470
471 :param directory: directory of the repository (cases_directory() by default)
472 :return: list of tuples (case, subcase, path of the driver file)
473 """
474 directory = cases_directory() if directory is None else directory
475 if not os.path.isdir(directory):
476 raise Phyex1DError(f"The DEPHY-SCM repository is not installed in {directory}, "
477 "use phyex1d-cases_install")
478 result = []
479 for path in glob.glob(os.path.join(directory, '*', '*', '*_SCM_driver.nc')):
480 match = _DRIVER_RE.match(os.path.relpath(path, directory))
481 if match:
482 result.append((match.group('case'), match.group('subcase'), path))
483 return sorted(result)
484
485
487 """Entry point of the phyex1d-cases_install command"""
488 parser = argparse.ArgumentParser(
489 description=textwrap.fill(
490 'Installs the DEPHY-SCM cases (in the common format) in '
491 f'{cases_directory()} (the PHYEXCONF environment variable can be used to '
492 'change the root directory, ~/.phyex by default)'),
493 epilog=commands_help(), formatter_class=argparse.RawDescriptionHelpFormatter)
494 subparsers = parser.add_subparsers(dest='command', required=True)
495 subparsers.add_parser('download',
496 help='download (clone) or update the DEPHY-SCM repository (big: '
497 'about 1 GB)')
498 link = subparsers.add_parser('link', help='use an existing DEPHY-SCM repository (a '
499 'symbolic link to it is created)')
500 link.add_argument('path', help='path to the existing DEPHY-SCM repository')
501 args = parser.parse_args()
502 try:
503 if args.command == 'download':
504 directory = install_cases()
505 print(f'DEPHY-SCM cases installed in {directory}')
506 else:
507 directory = link_cases(args.path)
508 print(f'{directory} is a link to {os.path.abspath(args.path)}')
509 except Phyex1DError as err:
510 sys.exit(f'Error: {err}')
511
512
514 """Entry point of the phyex1d-cases_list command"""
515 parser = argparse.ArgumentParser(
516 description=textwrap.fill(
517 'Lists the DEPHY-SCM cases installed in '
518 f'{cases_directory()} (see phyex1d-cases_install) with the path of their '
519 'driver file (the case name or the path can be given to phyex1d-exp_run)'),
520 epilog=commands_help(), formatter_class=argparse.RawDescriptionHelpFormatter)
521 parser.add_argument('-n', '--names', action='store_true',
522 help='list only the case names (CASE/SUBCASE), without the paths')
523 args = parser.parse_args()
524 try:
525 cases = list_cases()
526 except Phyex1DError as err:
527 sys.exit(f'Error: {err}')
528 names = [case + '/' + subcase for case, subcase, _ in cases]
529 width = max((len(name) for name in names), default=0)
530 for name, (_, _, path) in zip(names, cases):
531 print(name if args.names else f'{name:{width}s} {path}')
get(self, varname, slice_idx=None)
Definition case.py:182
__init__(self, inputfile, attrs=None)
Definition case.py:123
get_interpolator(self, varname, grid)
Definition case.py:217
get(self, varname, slice_idx=None)
Definition case.py:306
get_interpolator(self, varname, grid)
Definition case.py:355
__init__(self, dataset, attrs=None)
Definition case.py:279
contains(self, varname)
Definition case.py:290
contains(self, varname)
Definition case.py:38
__exit__(self, *args)
Definition case.py:63
get_interpolator(self, varname, grid)
Definition case.py:56
get(self, varname, slice_idx=None)
Definition case.py:42
list_cases(directory=None)
Definition case.py:467
install_cases(directory=None)
Definition case.py:414
link_cases(path, directory=None)
Definition case.py:439
_git(args, directory=None)
Definition case.py:399
user_dir(subdir)
Definition __init__.py:35