PHYEX 0.9.5
PHYsique EXternalisée
Loading...
Searching...
No Matches
cli.py
Go to the documentation of this file.
1"""
2Command line clients: phyex1d-exp_run (execution of experiments), phyex1d-exp_plot (plot of
3the results) and phyex1d-exp_list (list of the existing results)
4"""
5
6import argparse
7import inspect
8import os
9import sys
10import textwrap
11
12from matplotlib import pyplot as plt
13
14from .experiment_runner import (ExperimentRunner, ExistingResults, PHYSICS_CLASSES,
15 DEFAULT_CLASS, physics_options, list_experiments,
16 DEFAULT_COMP_NAME)
17from .case import list_cases
18from .dephycf_export import export
19from . import Phyex1DError, commands_help
20
21
22def convert_option(cls_name, key, value, default):
23 """
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
31 """
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)):
37 try:
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
42 return value
43
44
46 """First line of the docstring of a class"""
47 doc = inspect.getdoc(cls)
48 return doc.splitlines()[0].rstrip('.') if doc else ''
49
50
52 """List of the physics classes (with their description)"""
53 return '\n'.join(textwrap.fill(f" - {cls_name}"
54 f"{' (default)' if cls_name == DEFAULT_CLASS else ''}: "
55 f"{class_description(cls)}",
56 width=90, subsequent_indent=' ', break_on_hyphens=False)
57 for cls_name, cls in PHYSICS_CLASSES.items())
58
59
61 """
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
64 """
65 groups = {}
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)
70 lines = []
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)
78
79
80EXPERIMENTS_HELP = """
81The case is given by the path to a netCDF file in the common format or by the name of
82an installed DEPHY-SCM case (CASE/SUBCASE, e.g. ARMCU/REF, see phyex1d-cases_install and
83phyex1d-cases_list).
84
85Each --exp option is followed by a list of key=value strings (without --exp, one
86experiment is defined with the default values).
87The keys common to all the physics classes are:
88- grid: Grid name or file name containing a grid description
89 (with '.grid' extension).
90- dt: Timestep (s)
91- name: experiment name
92- class: name of the class that implements a timestep among:
93""" + physics_classes_help() + """
94- attr: override an attribute definig the case, eg.: attr=radiation:on
95 (only some of the attributes are implemented)
96
97The other keys are options of the physics class:
98""" + physics_options_help() + """
99
100Results are stored in OUTPUT_DIR/<comparison name>/<experiment name>.hdf5 (OUTPUT_DIR is
101the current directory by default; quotes are removed, spaces and slashes are replaced by
102underscores).
103"""
104
105RUN_EXAMPLES = """Examples:
106- without comparison name (--name) and without experiment name (name key):
107 phyex1d-exp_run ARMCU/REF -o out --exp dt=60
108 results in out/""" + DEFAULT_COMP_NAME + """/Experiment.hdf5
109- with both names, and a case file:
110 phyex1d-exp_run case.nc -o out --name armcu --exp dt=60 name=simple class=SimplePhysicsTQ
111 results in out/armcu/simple.hdf5
112An experiment is not run again if its result file already exists (use --force).
113"""
114
115PLOT_HELP = """
116The results are read in OUTPUT_DIR/<comparison name> (see phyex1d-exp_run); all the
117experiments having results are plotted, unless some are selected with --exp (their list is
118given by phyex1d-exp_list).
119
120Each --plot option is followed by the plot file name, then by options (key=value) and by
121the list of variables to plot. Variable names can contain wildcards (*, ? and [], to be
122quoted to prevent their expansion by the shell), e.g. 'bu_*_RC_*' for all the budgets of rc.
123By default, the time evolution is plotted; with the times option, profiles are plotted at
124the given output times. Options:
125- y_var: variable used for the y-axis (e.g. y_var=P)
126- title, xlabel, ylabel, legend: strings
127- only_param_tag: comma-separated list of experiment names
128- mfactor, linewidth: floats
129- enable_contourf, switch_cls, colorbar, clabel: True or False (time evolution only)
130- times: comma-separated list of output times in seconds (profiles)
131- color_by, style_by: var, scheme or time, dimension distinguished by the color or by the
132 line style (profiles only)
133- ymin, ymax: limits of the y-axis
134- vmin, vmax: limits of the plotted values
135- nonzero: threshold (float) to remove the negligible variables: a variable is not plotted
136 if its maximum absolute value (over the plotted times and experiments) is lower than
137 nonzero times the maximum of all the variables (0 to remove only the null variables)
138Examples:
139 phyex1d-exp_plot -o out --exp simple --plot rc.png y_var=P rc
140 phyex1d-exp_plot -o out --plot rc_prof.png y_var=P times=3600,7200 rc
141 phyex1d-exp_plot -o out --plot rc_bu.png y_var=P times=3600 nonzero=1e-3 'bu_*_RC_*'
142"""
143
144
145def input_file(case):
146 """
147 Path of the netCDF file describing the case
148 :param case: path to a netCDF file or name of an installed DEPHY-SCM case
149 (CASE/SUBCASE)
150 :return: path to the netCDF file
151 """
152 if os.path.isfile(case):
153 return case
154 for case_name, subcase_name, path in list_cases():
155 if case.strip('/') == case_name + '/' + subcase_name:
156 return path
157 raise Phyex1DError(f"{case} is neither a file nor an installed DEPHY-SCM case "
158 "(see phyex1d-cases_list)")
159
160
161def experiments_parser(description, epilog):
162 """Parser with the arguments describing the experiments (common to run and plot)"""
163 parser = argparse.ArgumentParser(description=description,
164 epilog=epilog + '\n' + commands_help(),
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')
177 return parser
178
179
181 """List of experiment descriptions (for ExperimentRunner) from the --exp options"""
182 experiments = []
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])
190 expe_descr = {}
191 attrs = {}
192 for arg in expe:
193 key, val = arg.split('=', 1)
194 if key == 'attr':
195 attr, attrval = val.split(':', 1)
196 if attr in ('radiation', ):
197 attrs[attr] = str(attrval)
198 else:
199 raise Phyex1DError(f"This experiment attribute is not implemented: {attr}")
200 elif key == 'dt':
201 expe_descr[key] = float(val)
202 elif key in ('name', 'grid', 'class'):
203 expe_descr[key] = val
204 elif key in options:
205 expe_descr[key] = convert_option(cls_name, key, val, options[key])
206 else:
207 raise Phyex1DError(f"Option {key} does not exist for {cls_name}, allowed "
208 "options are: dt, name, grid, class, attr, " +
209 ', '.join(options))
210 expe_descr['attrs'] = attrs
211 experiments.append(expe_descr)
212 return experiments
213
214
216 """ExperimentRunner corresponding to the command line arguments"""
217 return ExperimentRunner(input_file(args.CASE), experiments_from_args(args),
218 args.output_dir, args.name)
219
220
221def plot(ph1d, plot_args):
222 """
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)
226 """
227 fig, ax = plt.subplots()
228 filename = plot_args[0]
229 var_names = []
230 options = {}
231 ylim = [None, None] # min max for y-axis
232 vlim = [None, None] # min and max value
233 times = None # output times for profiles
234 nonzero = None # threshold to remove negligible variables
235 for arg in plot_args[1:]:
236 if '=' in arg:
237 key, value = arg.split('=', 1)
238 if key in ('y_var', 'title', 'xlabel', 'ylabel', 'legend',
239 'color_by', 'style_by'):
240 # Strings
241 options[key] = value
242 elif key == 'only_param_tag':
243 # List of strings
244 options[key] = value.split(',')
245 elif key == 'times':
246 # List of floats
247 times = [float(time) for time in value.split(',')]
248 elif key == 'nonzero':
249 nonzero = float(value)
250 elif key in ('mfactor', 'linewidth'):
251 # Floats
252 options[key] = float(value)
253 elif key in ('enable_contourf', 'switch_cls', 'colorbar', 'clabel'):
254 # Booleans
255 options[key] = value == 'True'
256 elif key in ('ymin', 'ymax'):
257 if key == 'ymin':
258 ylim[0] = float(value)
259 else:
260 ylim[1] = float(value)
261 elif key in ('vmin', 'vmax'):
262 if key == 'vmin':
263 vlim[0] = float(value)
264 else:
265 vlim[1] = float(value)
266 else:
267 raise Phyex1DError(f"This plot option does not exist: {key}")
268 else:
269 var_names.append(arg)
270 # Wildcards and removal of the negligible variables
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}")
276 if times is None:
277 for key in ('color_by', 'style_by'):
278 if key in options:
279 raise Phyex1DError(f"The {key} plot option is only valid for profiles (times option)")
280 else:
281 for key in ('enable_contourf', 'switch_cls', 'colorbar', 'clabel'):
282 if key in options:
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':
286 ax.invert_yaxis()
287 ax.set_ylim(ylim)
288 fig.savefig(filename)
289 plt.close(fig)
290 return
291 kwargs_contourf = {}
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':
300 ax.invert_yaxis()
301 ax.set_ylim(ylim)
302 fig.savefig(filename)
303 plt.close(fig)
304
305
307 """Entry point of the phyex1d-exp_run command: execution of experiments"""
308 parser = experiments_parser('Execution of 1D experiments using PHYEX',
309 EXPERIMENTS_HELP + '\n' + RUN_EXAMPLES)
310 parser.add_argument('--force', default=False, action='store_true',
311 help="Force run to be executed even if output already exists")
312 args = parser.parse_args()
313 try:
314 ph1d = runner_from_args(args)
315 except Phyex1DError as err:
316 sys.exit(f'Error: {err}')
317 ph1d.run(force=args.force)
318
319
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)',
324 epilog=PLOT_HELP + '\n' + commands_help(),
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()
338 try:
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}')
344
345
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()
359 try:
360 experiments = list_experiments(args.output_dir, args.name)
361 except Phyex1DError as err:
362 sys.exit(f'Error: {err}')
363 if experiments:
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}')
368
369
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()
392 try:
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]
400 else:
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}')
class_description(cls)
Definition cli.py:45
runner_from_args(args)
Definition cli.py:215
plot(ph1d, plot_args)
Definition cli.py:221
convert_option(cls_name, key, value, default)
Definition cli.py:22
physics_classes_help()
Definition cli.py:51
experiments_parser(description, epilog)
Definition cli.py:161
experiments_from_args(args)
Definition cli.py:180
input_file(case)
Definition cli.py:145
physics_options_help()
Definition cli.py:60