14from .experiment_runner
import (ExperimentRunner, ExistingResults, PHYSICS_CLASSES,
15 DEFAULT_CLASS, physics_options, list_experiments,
24 Conversion of a command line value, according to the type of the default value
25 of the option in the physics class
26 :param cls_name: name of the physics class (for error messages)
27 :param key: option name
28 :param value: string to convert
29 :param default: default value of the option
30 :return: converted value
32 if isinstance(default, bool):
33 if value
not in (
'True',
'False'):
34 raise Phyex1DError(f
"Option {key} of {cls_name} must be True or False")
35 return value ==
'True'
36 if isinstance(default, (int, float)):
38 return type(default)(value)
39 except ValueError
as err:
40 raise Phyex1DError(f
"Option {key} of {cls_name} must be a "
41 f
"{type(default).__name__}")
from err
62 Description of the options of the physics classes (OPTIONS_HELP class attribute) with
63 their default values; classes having the same options are grouped
66 for cls_name, cls
in PHYSICS_CLASSES.items():
67 options = tuple((key, repr(default), cls.OPTIONS_HELP.get(key,
''))
68 for key, default
in physics_options(cls).items())
69 groups.setdefault(options, []).append(cls_name)
71 for options, cls_names
in groups.items():
72 lines.append(f
"- for {', '.join(cls_names)}:")
73 for key, default, description
in options:
74 lines.append(textwrap.fill(f
' - {key} (default: {default}): {description}',
75 width=90, subsequent_indent=
' ',
76 break_on_hyphens=
False))
77 return '\n'.join(lines)
162 """Parser with the arguments describing the experiments (common to run and plot)"""
163 parser = argparse.ArgumentParser(description=description,
165 formatter_class=argparse.RawDescriptionHelpFormatter)
166 parser.add_argument(
'CASE',
167 help=
'Netcdf file describing the case or name of an installed '
168 'DEPHY-SCM case (CASE/SUBCASE)')
169 parser.add_argument(
'--exp', nargs=
'*', action=
'append', dest=
'experiments',
170 help=
"List of key=value strings defining an experiment. " +
171 "The list of keys is provided at the end of the help message.")
172 parser.add_argument(
'-o', dest=
'output_dir', type=str, default=
'.',
173 help=
"Output directory (default: current directory); it must exist")
174 parser.add_argument(
'--name', default=DEFAULT_COMP_NAME, type=str,
175 help=
'Name of the comparison (default: %(default)s); results are '
176 'stored in OUTPUT_DIR/NAME/<experiment name>.hdf5')
181 """List of experiment descriptions (for ExperimentRunner) from the --exp options"""
183 for expe
in args.experiments
or [[]]:
184 values = dict(arg.split(
'=', 1)
for arg
in expe
if not arg.startswith(
'attr='))
185 cls_name = values.get(
'class', DEFAULT_CLASS)
186 if cls_name
not in PHYSICS_CLASSES:
187 raise Phyex1DError(f
"Unknown physics class {cls_name}, allowed classes are: " +
188 ', '.join(PHYSICS_CLASSES))
189 options = physics_options(PHYSICS_CLASSES[cls_name])
193 key, val = arg.split(
'=', 1)
195 attr, attrval = val.split(
':', 1)
196 if attr
in (
'radiation', ):
197 attrs[attr] = str(attrval)
199 raise Phyex1DError(f
"This experiment attribute is not implemented: {attr}")
201 expe_descr[key] = float(val)
202 elif key
in (
'name',
'grid',
'class'):
203 expe_descr[key] = val
205 expe_descr[key] =
convert_option(cls_name, key, val, options[key])
207 raise Phyex1DError(f
"Option {key} does not exist for {cls_name}, allowed "
208 "options are: dt, name, grid, class, attr, " +
210 expe_descr[
'attrs'] = attrs
211 experiments.append(expe_descr)
223 Plots the evolution of variables, or their profiles at given times
224 :param ph1d: ExperimentRunner instance
225 :param plot_args: arguments of a --plot option (file name, options and variables)
227 fig, ax = plt.subplots()
228 filename = plot_args[0]
235 for arg
in plot_args[1:]:
237 key, value = arg.split(
'=', 1)
238 if key
in (
'y_var',
'title',
'xlabel',
'ylabel',
'legend',
239 'color_by',
'style_by'):
242 elif key ==
'only_param_tag':
244 options[key] = value.split(
',')
247 times = [float(time)
for time
in value.split(
',')]
248 elif key ==
'nonzero':
249 nonzero = float(value)
250 elif key
in (
'mfactor',
'linewidth'):
252 options[key] = float(value)
253 elif key
in (
'enable_contourf',
'switch_cls',
'colorbar',
'clabel'):
255 options[key] = value ==
'True'
256 elif key
in (
'ymin',
'ymax'):
258 ylim[0] = float(value)
260 ylim[1] = float(value)
261 elif key
in (
'vmin',
'vmax'):
263 vlim[0] = float(value)
265 vlim[1] = float(value)
267 raise Phyex1DError(f
"This plot option does not exist: {key}")
269 var_names.append(arg)
271 if nonzero
is not None or any(char
in var
for var
in var_names
for char
in '*?['):
272 var_names = ph1d.expand_var_names(var_names, only_param_tag=options.get(
'only_param_tag'),
273 only_times=times, threshold=nonzero)
274 if len(var_names) == 0:
275 raise Phyex1DError(f
"No variable to plot in {filename}")
277 for key
in (
'color_by',
'style_by'):
279 raise Phyex1DError(f
"The {key} plot option is only valid for profiles (times option)")
281 for key
in (
'enable_contourf',
'switch_cls',
'colorbar',
'clabel'):
283 raise Phyex1DError(f
"The {key} plot option is not valid for profiles (times option)")
284 ph1d.plot_profile(ax, var_names, times, xlim=vlim, **options)
285 if options.get(
'y_var',
'X') ==
'P':
288 fig.savefig(filename)
292 if vlim[0]
is not None:
293 kwargs_contourf[
'vmin'] = vlim[0]
294 if vlim[1]
is not None:
295 kwargs_contourf[
'vmax'] = vlim[1]
296 if len(kwargs_contourf) != 0:
297 options[
'kwargs_contourf'] = kwargs_contourf
298 ph1d.plot_evol(ax, var_names, **options)
299 if options.get(
'y_var',
'X') ==
'P':
302 fig.savefig(filename)
321 """Entry point of the phyex1d-exp_plot command: plot of the results of experiments"""
322 parser = argparse.ArgumentParser(
323 description=
'Plot of the results of 1D experiments (run with phyex1d-exp_run)',
325 formatter_class=argparse.RawDescriptionHelpFormatter)
326 parser.add_argument(
'-o', dest=
'output_dir', type=str, default=
'.',
327 help=
"Output directory (default: current directory)")
328 parser.add_argument(
'--name', default=DEFAULT_COMP_NAME, type=str,
329 help=
'Name of the comparison (default: %(default)s)')
330 parser.add_argument(
'--exp', action=
'append', dest=
'experiments', metavar=
'EXP_NAME',
331 help=
'name of an experiment to plot (option can be repeated), all '
332 'the experiments by default')
333 parser.add_argument(
'--plot', nargs=
'+', action=
'append', dest=
'plots', required=
True,
334 help=
"plot file name followed by options and then the list of "
335 "variables to plot (one plot by --plot usage). " +
336 "example: --plot theta.png y_var=P Theta")
337 args = parser.parse_args()
339 results =
ExistingResults(args.output_dir, args.name, args.experiments)
340 for plot_args
in args.plots:
341 plot(results, plot_args)
342 except Phyex1DError
as err:
343 sys.exit(f
'Error: {err}')
347 """Entry point of the phyex1d-exp_list command: list of the existing results"""
348 parser = argparse.ArgumentParser(
349 description=textwrap.fill(
350 'List of the experiments (name and physics class) having results in '
351 'OUTPUT_DIR/<comparison name> (see phyex1d-exp_run); they can be plotted '
352 'with phyex1d-exp_plot'),
353 epilog=
commands_help(), formatter_class=argparse.RawDescriptionHelpFormatter)
354 parser.add_argument(
'-o', dest=
'output_dir', type=str, default=
'.',
355 help=
"Output directory (default: current directory)")
356 parser.add_argument(
'--name', default=DEFAULT_COMP_NAME, type=str,
357 help=
'Name of the comparison (default: %(default)s)')
358 args = parser.parse_args()
360 experiments = list_experiments(args.output_dir, args.name)
361 except Phyex1DError
as err:
362 sys.exit(f
'Error: {err}')
364 width_name = max(len(name)
for name, _, _
in experiments)
365 width_cls = max(len(cls)
for _, cls, _
in experiments)
366 for name, cls, filename
in experiments:
367 print(f
'{name:{width_name}s} {cls:{width_cls}s} {filename}')
371 """Entry point of the phyex1d-exp_2nc command: conversion of a result into netCDF"""
372 parser = argparse.ArgumentParser(
373 description=textwrap.fill(
374 'Conversion of the results of an experiment (run with phyex1d-exp_run) into a '
375 'netCDF file following the DEPHY common format for SCM outputs (dephycf: '
376 'variable names, units and attributes as in '
377 'https://github.com/romainroehrig/EMS, examples/post.dephycf/variables.py). '
378 'Budgets (budgets=True option of phyex1d-exp_run) are summed by scheme and '
379 'converted into the dephycf tendencies.'),
380 epilog=
commands_help(), formatter_class=argparse.RawDescriptionHelpFormatter)
381 parser.add_argument(
'NCFILE', help=
'netCDF file to produce')
382 parser.add_argument(
'-o', dest=
'output_dir', type=str, default=
'.',
383 help=
"Output directory of phyex1d-exp_run (default: current directory)")
384 parser.add_argument(
'--name', default=DEFAULT_COMP_NAME, type=str,
385 help=
'Name of the comparison (default: %(default)s)')
386 parser.add_argument(
'--exp', dest=
'experiment', metavar=
'EXP_NAME',
387 help=
'name of the experiment to convert (can be omitted if the '
388 'comparison contains only one experiment)')
389 parser.add_argument(
'--force', action=
'store_true',
390 help=
'overwrite NCFILE if it exists')
391 args = parser.parse_args()
393 experiments = list_experiments(args.output_dir, args.name)
394 if args.experiment
is None:
395 if len(experiments) != 1:
396 raise Phyex1DError(
'The comparison contains several experiments, one must be '
397 'chosen with --exp among: ' +
398 ', '.join(name
for name, _, _
in experiments))
399 filename = experiments[0][2]
401 filenames = [filename
for name, _, filename
in experiments
402 if name == args.experiment]
403 if len(filenames) == 0:
404 raise Phyex1DError(f
'Unknown experiment {args.experiment}, available '
405 'experiments are: ' +
406 ', '.join(name
for name, _, _
in experiments))
407 filename = filenames[0]
408 if os.path.exists(args.NCFILE)
and not args.force:
409 raise Phyex1DError(f
'{args.NCFILE} already exists (use --force)')
410 export(filename, args.NCFILE)
411 except Phyex1DError
as err:
412 sys.exit(f
'Error: {err}')