PHYEX 0.9.5
PHYsique EXternalisée
Loading...
Searching...
No Matches
experiment_runner.py
Go to the documentation of this file.
1"""
2ExperimentRunner is the main object of the phyex1d package; it deals with the execution
3"""
4
5import copy
6import glob
7import inspect
8import os
9
10import h5py
11from pppy import PPPY, PPPYComp
12
13from .phyex import PhysicsAromeTQ, PhysicsAromeThetaR
14from .simple_physics import SimplePhysicsTQ, SimplePhysicsThetaR
15from .case import Case, CaseCommonFormat
16from .grid import Grid
17from . import Phyex1DError
18
19# Default physics class
20DEFAULT_CLASS = 'PhysicsAromeTQ'
21
22# Physics classes that can be designated by their name
23PHYSICS_CLASSES = {'PhysicsAromeTQ': PhysicsAromeTQ,
24 'PhysicsAromeThetaR': PhysicsAromeThetaR,
25 'SimplePhysicsTQ': SimplePhysicsTQ,
26 'SimplePhysicsThetaR': SimplePhysicsThetaR}
27
28# Default comparison name (the results are stored in a subdirectory of the output
29# directory named after the comparison)
30DEFAULT_COMP_NAME = 'phyex1dcomp'
31
32# Arguments of the physics classes that are set by ExperimentRunner
33RUNNER_ARGUMENTS = ('dt', 'method', 'name', 'tag', 'case', 'grid', 'attrs')
34
35# Units of the budgets (bu_<scheme>_<variable>_<process> variables), by variable
36BUDGET_UNITS = {'U': 'm s-2', 'V': 'm s-2', 'W': 'm s-2', 'TH': 'K s-1', 'TKE': 'm2 s-3'}
37
38
39def var_legend(var, mfactor):
40 """
41 String used in the plot legends for a variable (replaces the PPPYComp method to
42 deal with the budget variables)
43 :param var: name of the variable
44 :param mfactor: multiplying factor applied to data
45 """
46 if var.startswith('bu_') and var.count('_') >= 3:
47 _, scheme, variable, process = var.split('_', 3)
48 unit = BUDGET_UNITS.get(variable, 'kg kg-1 s-1')
49 if mfactor != 1.:
50 unit = str(1. / mfactor) + ' ' + unit
51 return f'{process} {variable} budget of {scheme} ({unit})'
52 return PPPYComp._var_legend(var, mfactor) # pylint: disable=protected-access
53
54
55def string2filename(string):
56 """
57 Tag (usable in file names) corresponding to a comparison or an experiment name:
58 quotes are removed, spaces and slashes are replaced by underscores
59 """
60 return string.replace('"', '').replace("'", "").replace(' ', '_').replace('/', '_')
61
62
64 """
65 Options of a physics class: the arguments of its constructor having a default
66 value, except the ones set by ExperimentRunner
67 :param cls: physics class
68 :return: dictionary {option name: default value}
69 """
70 return {name: param.default
71 for name, param in inspect.signature(cls.__init__).parameters.items()
72 if name not in RUNNER_ARGUMENTS and param.default is not inspect.Parameter.empty}
73
74
75class ExperimentRunner(PPPYComp):
76 """
77 Deals with the execution of the 1D model
78 """
79 _var_legend = staticmethod(var_legend)
80
81 def __init__(self, inputfile_or_case, experiments, output_dir, comp_name=DEFAULT_COMP_NAME):
82 """
83 :param inputfile_or_case: path to a netCDF driver file or a Case instance
84 :param experiments: list of dictionaries describing the experiments
85 allowed keys are:
86 - class: name of the class (key of PHYSICS_CLASSES,
87 DEFAULT_CLASS by default) or class implementing
88 the physics
89 - grid: Grid name or file name containing a grid description
90 (with '.grid' extension).
91 - dt: Timestep (s)
92 - name: experiment name
93 - attrs: dictionary of case attributes to override
94 the other keys are options given to the class (see
95 physics_options)
96 :param comp_name: comparison name (DEFAULT_COMP_NAME if empty)
97 The results are stored in <output_dir>/<comparison tag>/<experiment tag>.hdf5, the
98 tags being the comparison and experiment names with quotes removed and spaces and
99 slashes replaced by underscores.
100 """
101 if not comp_name:
102 comp_name = DEFAULT_COMP_NAME
103
104 if isinstance(inputfile_or_case, Case):
105 case = inputfile_or_case
106 else:
107 case = CaseCommonFormat(inputfile_or_case)
108
109 self.case = case
110 schemes = []
111 for exp in experiments:
112 cls = exp.get('class', DEFAULT_CLASS)
113 if isinstance(cls, str):
114 cls = PHYSICS_CLASSES[cls]
115 # The experiment keys are given to the class
116 kw = dict(exp)
117 kw.pop('class', None)
118 kw['dt'] = float(kw.get('dt', 1.)) # pppy needs a float
119 kw['method'] = 'step-by-step'
120 kw['name'] = kw.get('name', 'Experiment')
121 kw['tag'] = string2filename(kw['name'])
122 kw['attrs'] = kw.get('attrs', {})
123 if kw['attrs']:
124 # Case attributes overridden for this experiment only
125 kw['case'] = copy.copy(case)
126 for attr, value in kw['attrs'].items():
127 setattr(kw['case'], attr, value)
128 else:
129 kw['case'] = case
130 kw['grid'] = Grid(kw.get('grid', 'L90arome'))
131 schemes.append(cls(**kw))
132 super().__init__(schemes=schemes,
133 output_dir=output_dir,
134 duration=self.case.duration,
135 init_state={},
136 name=comp_name,
137 tag=string2filename(comp_name))
138
139
140def list_experiments(output_dir='.', comp_name=DEFAULT_COMP_NAME):
141 """
142 Existing results of a comparison
143 :param output_dir: output directory
144 :param comp_name: comparison name
145 :return: list of tuples (experiment name, physics class, result file); the name and
146 class are '?' for results produced by older versions
147 """
148 directory = os.path.join(output_dir, string2filename(comp_name or DEFAULT_COMP_NAME))
149 if not os.path.isdir(directory):
150 raise Phyex1DError(f"No results for the comparison {comp_name} ({directory} does "
151 "not exist)")
152 result = []
153 for filename in sorted(glob.glob(os.path.join(directory, '*.hdf5'))):
154 with h5py.File(filename, 'r') as hdf5:
155 result.append((str(hdf5.attrs.get('experiment_name', '?')),
156 str(hdf5.attrs.get('physics_class', '?')), filename))
157 return result
158
159
160class _ExistingResult(PPPY):
161 """Experiment known only by its result file (it cannot be run)"""
162
163 def __init__(self, name, tag, dt):
164 super().__init__(dt, 'step-by-step', name, tag)
165
166 def step(self, state, timestep, timestep_number):
167 raise Phyex1DError(f"Experiment {self.name} cannot be run, only its results can be used")
168
169
170class ExistingResults(PPPYComp):
171 """
172 Comparison built from the existing result files (for plotting): neither the case nor
173 the description of the experiments are needed
174 """
175 _var_legend = staticmethod(var_legend)
176
177 def __init__(self, output_dir='.', comp_name=DEFAULT_COMP_NAME, experiments=None):
178 """
179 :param output_dir: output directory
180 :param comp_name: comparison name
181 :param experiments: list of the names of the experiments to use (all the experiments
182 having results by default); for results produced by older
183 versions (without stored name), the name is the file name
184 (without .hdf5)
185 """
186 schemes = {}
187 for name, _, filename in list_experiments(output_dir, comp_name):
188 tag = os.path.splitext(os.path.basename(filename))[0]
189 if name == '?':
190 name = tag
191 with h5py.File(filename, 'r') as hdf5:
192 dt = float(hdf5.attrs['dt'])
193 schemes[name] = _ExistingResult(name, tag, dt)
194 if experiments:
195 unknown = [name for name in experiments if name not in schemes]
196 if unknown:
197 raise Phyex1DError(f"No results for the experiment(s) {', '.join(unknown)}, "
198 f"available experiments are: {', '.join(schemes)}")
199 schemes = {name: schemes[name] for name in experiments}
200 if not schemes:
201 raise Phyex1DError(f"No results for the comparison {comp_name}")
202 comp_name = comp_name or DEFAULT_COMP_NAME
203 # The duration is only used to run the experiments
204 super().__init__(schemes=list(schemes.values()), output_dir=output_dir,
205 duration=1., init_state={}, name=comp_name,
206 tag=string2filename(comp_name))
__init__(self, output_dir='.', comp_name=DEFAULT_COMP_NAME, experiments=None)
__init__(self, inputfile_or_case, experiments, output_dir, comp_name=DEFAULT_COMP_NAME)
step(self, state, timestep, timestep_number)
list_experiments(output_dir='.', comp_name=DEFAULT_COMP_NAME)