2Case classes representing a simulation case
14from scipy.interpolate
import RegularGridInterpolator
16from .
import Phyex1DError
17from .
import user_dir, commands_help
20DEPHY_SCM_URL =
'https://github.com/GdR-DEPHY/DEPHY-SCM.git'
22_DRIVER_RE = re.compile(
r'^(?P<case>[^/]+)/(?P<subcase>[^/]+)/[^/]+_SCM_driver\.nc$')
27 Base class for case implementations
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__)
39 """Check if a variable exists in the case data"""
40 raise NotImplementedError
42 def get(self, varname, slice_idx=None):
43 """Read a variable from the case data"""
44 raise NotImplementedError
48 """Simulation duration in seconds"""
49 raise NotImplementedError
53 """Case description string"""
54 raise NotImplementedError
57 """Get or build an interpolator for a forcing variable"""
58 raise NotImplementedError
67 """Close any open resources. Override in subclasses."""
70class CaseCommonFormat(Case):
72 Case backed by a netCDF driver file in the DEPHY common format
75 nc_names = {
'Theta':
'theta',
105 'SolarIrradiance':
'i0',
107 'emissivity':
'emis',
118 'zh_forc':
'zh_forc',
119 'pa_forc':
'pa_forc',
125 :param inputfile: path to a netCDF driver file
126 :param attrs: dictionary of attributes to override
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():
142 """Whether the netCDF file is currently open"""
143 return self.
_nc is not None
147 Open the netCDF file if not already open
159 """Close the netCDF file if open"""
160 if self.
_nc is not None:
166 Check if a variable exists in the netCDF file
171 Variable name (translated via nc_names if present)
176 True if the variable exists
180 return ncf_name
in self.
_nc.variables
182 def get(self, varname, slice_idx=None):
184 Read a variable from the netCDF file
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.
200 data = self.
_nc[ncf_name]
201 return data[...]
if slice_idx
is None else data[slice_idx]
211 Duration in seconds (time[-1] - time[0])
213 times = self.
get(
'time')
215 return times[-1] - times[0]
219 Get from cache or build an interpolator for a forcing variable
226 Grid instance for vertical coordinate
230 RegularGridInterpolator
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)
243 interp = RegularGridInterpolator((input_times, input_coord),
245 bounds_error=
False, fill_value=
None)
247 interp = RegularGridInterpolator((input_times, ),
249 bounds_error=
False, fill_value=
None)
261 Case description string (file path)
268 Case backed by an in-memory xarray Dataset
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).
284 for k, v
in dataset.attrs.items():
286 if attrs
is not None:
287 for k, v
in attrs.items():
292 Check if a variable exists in the dataset
302 True if the variable exists
306 def get(self, varname, slice_idx=None):
308 Read a variable from the dataset
314 slice_idx : int or None, optional
315 Slice index to read. None returns the full array.
322 data = self.
_dataset[varname].values
323 return data
if slice_idx
is None else data[slice_idx]
333 Duration in seconds (time[-1] - time[0])
335 times = self.
_dataset[
'time'].values
336 return float(times[-1] - times[0])
346 Case description string
348 return getattr(self,
'_description',
'CaseXarray_' + str(id(self.
_dataset)))
352 """Set a custom description string"""
357 Get from cache or build an interpolator for a forcing variable
364 Grid instance for vertical coordinate
368 RegularGridInterpolator
373 input_times = self.
get(
'time')
374 ndim = len(self.
get(varname).shape)
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)
382 interp = RegularGridInterpolator((input_times, input_coord),
384 bounds_error=
False, fill_value=
None)
386 interp = RegularGridInterpolator((input_times, ),
388 bounds_error=
False, fill_value=
None)
390 raise Phyex1DError(f
'Unexpected variable dimensions: {ndim}')
400 """Executes a git command (in directory), returns its standard output"""
401 cmd = [
'git'] + ([]
if directory
is None else [
'-C', directory]) + args
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
409 """Directory of the DEPHY-SCM repository: $PHYEXCONF/phyex1d/DEPHY-SCM (PHYEXCONF
410 defaults to ~/.phyex)"""
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
420 :param directory: directory of the repository (cases_directory() by default)
421 :return: directory of the repository
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')):
431 _git([
'fetch',
'origin'], directory)
432 _git([
'reset',
'--hard',
'@{upstream}'], directory)
434 os.makedirs(os.path.dirname(os.path.abspath(directory)), exist_ok=
True)
435 _git([
'clone', DEPHY_SCM_URL, directory])
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.
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
451 path = os.path.abspath(path)
452 if not os.path.isdir(path):
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):
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)
469 Lists the cases available in the DEPHY-SCM repository.
471 :param directory: directory of the repository (cases_directory() by default)
472 :return: list of tuples (case, subcase, path of the driver file)
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")
479 for path
in glob.glob(os.path.join(directory,
'*',
'*',
'*_SCM_driver.nc')):
480 match = _DRIVER_RE.match(os.path.relpath(path, directory))
482 result.append((match.group(
'case'), match.group(
'subcase'), path))
483 return sorted(result)
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: '
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()
503 if args.command ==
'download':
505 print(f
'DEPHY-SCM cases installed in {directory}')
508 print(f
'{directory} is a link to {os.path.abspath(args.path)}')
509 except Phyex1DError
as err:
510 sys.exit(f
'Error: {err}')
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()
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)
get_interpolator(self, varname, grid)
__init__(self, dataset, attrs=None)
get_interpolator(self, varname, grid)
get(self, varname, slice_idx=None)
list_cases(directory=None)
install_cases(directory=None)
link_cases(path, directory=None)
_git(args, directory=None)