PHYEX 0.9.5
PHYsique EXternalisée
Loading...
Searching...
No Matches
physics_base.py
Go to the documentation of this file.
1"""
2Minimal base class for physics schemes
3"""
4
5import logging
6
7import numpy
8from pppy import PPPY
9from scipy.interpolate import RegularGridInterpolator
10
11from . import Cst
12from . import Phyex1DError
13
14
15# Surface temperatures, and the forcing variables to use (in order of preference)
16SURFACE_TEMPERATURES = {'Ts': ('ts_forc', 'tskin'), 'Tskin': ('tskin', 'ts_forc')}
17
18
19class PhysicsBase(PPPY):
20 """
21 Base class for 1D model physics schemes
22
23 This class is not intended to be used directly.
24
25 The first line of the docstring of the classes is used to describe them in the help
26 message of phyex1d-exp_run.
27 """
28
29 # Description of the options of the constructor (arguments with a default value, except
30 # those set by ExperimentRunner), used in the help message of phyex1d-exp_run
31 OPTIONS_HELP = {}
32
33 # Budget variables, in the order of the NBUDGET_* indexes of MODD_BUDGET (PHYEX),
34 # and corresponding state variables
35 BUDGET_VARIABLES = ('U', 'V', 'W', 'TH', 'TKE', 'RV', 'RC', 'RR', 'RI', 'RS', 'RG', 'RH')
36 BUDGET_STATE_NAMES = {'U': 'u', 'V': 'v', 'W': 'w', 'TH': 'Theta', 'TKE': 'tke',
37 'RV': 'rv', 'RC': 'rc', 'RR': 'rr', 'RI': 'ri', 'RS': 'rs',
38 'RG': 'rg', 'RH': 'rh'}
39
40 def __init__(self, dt, method, name, tag, case, grid, prognostic_variables):
41 # The keyword arguments are stored as attributes of the result files
42 super().__init__(dt, method, name, tag, inputfile=case.description,
43 grid=grid.filename, experiment_name=name,
44 physics_class=type(self).__name__)
45 self.case = case
46 self.grid = grid
47 self.prognostic_variables = prognostic_variables
48 self.cst = Cst()
49 # minimum TKE (overridden by the PHYEX namelist value, None for no minimum value)
50 self.tkemin = 1e-6
51 # Scalar variables of the state (e.g. LIMA concentrations), transported by the
52 # vertical advection of the forcing
54 # Budgets: bu_<scheme>_<variable>_<process> variables of the state, tendencies of
55 # the potential temperature (TH), mixing ratios (RV...), wind (U, V, W) and TKE
56 self.budgets = False # budgets activation
57 self._budget_keys = None # list of the budget variables (known after a first step)
58 self._budget_active = list(self.BUDGET_VARIABLES) # budget variables computed
59
60 # Budgets
61
62 def budget_add(self, state, key, value):
63 """
64 Add a contribution to a budget variable of the state
65 :param state: state dictionary
66 :param key: name of the budget variable (bu_<scheme>_<variable>_<process>)
67 :param value: contribution (tendency)
68 """
69 if self._budget_keys is not None and key not in self._budget_keys:
70 logging.warning('Budget %s was not found during the first step, it is ignored', key)
71 else:
72 state[key] = state.get(key, 0.) + value
73
74 def budget_fields(self, state):
75 """
76 Values of the budget variables
77 :param state: state dictionary
78 :return: None if budgets are not activated, a dictionary {budget variable: field} otherwise
79 """
80 if not self.budgets:
81 return None
82 tmp = dict(state)
83 self.add_conversions(tmp)
84 return {var: numpy.array(tmp[self.BUDGET_STATE_NAMES[var]], copy=True)
85 for var in self._budget_active}
86
87 def budget_record(self, state, before, scheme, process, variables, timestep):
88 """
89 Record the contribution of an operation done on the state
90 :param state: state dictionary, after the operation
91 :param before: output of budget_fields called before the operation
92 :param scheme: name of the scheme (forc for forcings, driver for operations done by the
93 driver...)
94 :param process: name of the process
95 :param variables: list of the state variables modified by the operation
96 :param timestep: timestep (s)
97 """
98 if before is None:
99 return
100 after = self.budget_fields(state)
101 budget_vars = set()
102 for var in variables:
103 if var in ('T', 'Theta'):
104 budget_vars.add('TH')
105 elif var.startswith('q') and var != 'qt':
106 # A specific content modifies all the mixing ratios
107 budget_vars.update(['RV', 'RC', 'RR', 'RI', 'RS', 'RG', 'RH'])
108 else:
109 budget_vars.update([bvar for bvar, name in self.BUDGET_STATE_NAMES.items()
110 if name == var])
111 for var in self._budget_active:
112 if var in budget_vars:
113 self.budget_add(state, f'bu_{scheme}_{var}_{process}',
114 (after[var] - before[var]) / timestep)
115
116 def setup(self, init_state, duration):
117 """Set up the scheme. Override in subclasses."""
118
119 def finalize(self):
120 """Tear down the scheme. Override in subclasses."""
121
122 def execute(self, previous_state, timestep, timestep_number):
123 """
124 Advance the state by one timestep
125
126 Parameters
127 ----------
128 previous_state : dict
129 Dictionary holding all the variables.
130 timestep : float
131 Timestep (s)
132 timestep_number : int
133 Current time step number
134
135 Returns
136 -------
137 dict
138 State after time integration
139 """
140 if self.budgets:
141 # Budgets of the previous step are reset
142 for key in [key for key in previous_state if key.startswith('bu_')]:
143 del previous_state[key]
144 begin = self.budget_fields(previous_state)
145 new_state = self.step(previous_state, timestep, timestep_number)
146 new_state = self.forcing(new_state, timestep, timestep_number)
147 self.add_vertical_coordinate(new_state)
148 self.add_conversions(new_state)
149 if self.budgets:
150 # Total tendency over the step, and part not explained by the budgets
151 end = self.budget_fields(new_state)
152 for var in self._budget_active:
153 total = (end[var] - begin[var]) / timestep
154 explained = sum(value for key, value in new_state.items()
155 if key.startswith('bu_') and key.split('_')[2] == var)
156 self.budget_add(new_state, f'bu_all_{var}_TOT', total)
157 self.budget_add(new_state, f'bu_all_{var}_RES', total - explained)
158 if self._budget_keys is not None:
159 # Budgets not computed during this step
160 for key in self._budget_keys:
161 if key not in new_state:
162 new_state[key] = numpy.zeros(new_state['P'].shape)
163 return new_state
164
165 def step(self, state, timestep, timestep_number):
166 """
167 Physics step. Override in subclasses.
168
169 Returns the state unchanged by default.
170 """
171 return state
172
173 def add_vertical_coordinate(self, state):
174 """
175 Add vertical coordinate to the state
176
177 Parameters
178 ----------
179 state : dict
180 Current state
181 """
182 state['Z_mass'] = self.grid.get_altitude('MASS', state, self.prognostic_variables)
183 state['P'] = self.grid.get_pressure('MASS', state, self.prognostic_variables)
184 state['Z_flux'] = self.grid.get_altitude('FLUX', state, self.prognostic_variables)
185 top = -1 if self.grid.ascending else 0
186 if numpy.all(state['Z_flux'][top] == numpy.inf):
187 state['Z_flux'][top] = state['Z_flux'][-2 if self.grid.ascending else 1]
188
189 def add_conversions(self, state):
190 """
191 Add derived variables to the state
192
193 Parameters
194 ----------
195 state : dict
196 Current state
197 """
198 pressure_mass = self.grid.get_pressure('MASS', state, self.prognostic_variables)
199 exner = (pressure_mass / 1.E5) ** (self.cst.Rd / self.cst.Cpd)
200 if 'T' in self.prognostic_variables:
201 state['Theta'] = state['T'] / exner
202 elif 'Theta' in self.prognostic_variables:
203 state['T'] = state['Theta'] * exner
204
205 if 'qv' in self.prognostic_variables:
206 qt = state['qv'].copy()
207 for var in ('qc', 'qi', 'qr', 'qs', 'qg', 'qh'):
208 if var in state:
209 qt += state[var]
210 state['qt'] = qt
211 for v in ('v', 'c', 'i', 'r', 's', 'g', 'h'):
212 if 'q' + v in state:
213 state['r' + v] = state['q' + v] / (1. - qt)
214 elif 'rv' in self.prognostic_variables:
215 rt = state['rv'].copy()
216 for var in ('rc', 'ri', 'rr', 'rs', 'rg', 'rh'):
217 if var in state:
218 rt += state[var]
219 state['rt'] = rt
220 for v in ('v', 'c', 'i', 'r', 's', 'g', 'h'):
221 if 'r' + v in state:
222 state['q' + v] = state['r' + v] / (1. + rt)
223
224 def build_init_state(self, init_state):
225 """
226 Build the initial state
227
228 Parameters
229 ----------
230 init_state : dict
231 Initial state dictionary to populate
232
233 Returns
234 -------
235 dict
236 Populated initial state
237 """
238 init_state = super().build_init_state(init_state)
239
240 with self.case:
241 # Surface fields
242 for var in ('Zs', 'Ps', 'sshf', 'slhf', 'z0', 'z0h', 'z0q', 'Tskin', 'Ts', 'ustar',
243 'SolarIrradiance', 'albedo', 'emissivity', 'sza', 'lat', 'lon'):
244 if self.case.contains(var):
245 init_state[var] = self.case.get(var, 0)
246 elif var not in SURFACE_TEMPERATURES:
247 logging.warning('%s not found in the case description!', var)
248 # Surface temperatures not found: forcing values (the variable corresponding the
249 # best is used first)
250 for var, names in SURFACE_TEMPERATURES.items():
251 if var not in init_state:
252 name = next((name for name in names if self.case.contains(name)), None)
253 if name is None:
254 logging.warning('%s not found in the case description!', var)
255 else:
256 init_state[var] = self.case.get(name, 0)
257
258 # We perform the interpolation on the natural vertical coordinate
259 if self.grid.kind in ('H', 'hybridH'):
260 input_coord = self.case.get('zh', 0) + self.case.get('orog', 0)
261 output_coord = self.grid.get_altitude('MASS', init_state, self.prognostic_variables)
262 elif self.grid.kind in ('P', 'hybridP'):
263 input_coord = self.case.get('pa', 0)
264 output_coord = self.grid.get_pressure('MASS', init_state, self.prognostic_variables)
265 else:
266 raise Phyex1DError('Wrong grid kind')
267
268 # Interpolation of initial profiles
269 for var in self.prognostic_variables:
270 if var in ('qc', 'qi', 'qr', 'qs', 'qg', 'qh',
271 'rc', 'ri', 'rr', 'rs', 'rg', 'rh',
272 'w') and not self.case.contains(var):
273 init_state[var] = numpy.zeros(output_coord.shape)
274 logging.warning('%s not found in the case description!', var)
275 else:
276 interp = RegularGridInterpolator((input_coord, ), self.case.get(var, 0),
277 bounds_error=False, fill_value=None)
278 init_state[var] = interp(output_coord)
279 if self.tkemin is not None:
280 init_state['tke'] = numpy.maximum(self.tkemin, init_state['tke'])
281
282 # Vertical coordinates
283 self.add_vertical_coordinate(init_state)
284
285 # Conversions
286 self.add_conversions(init_state)
287
288 # Arrays needed to keep memory from one timestep to the other
289 for var in ('ni', 'sigs', 'WEIGHT_MF_CLOUD', 'CF_MF', 'rc_MF', 'ri_MF',
290 'HLC_HRC_MF', 'HLC_HCF_MF', 'HLI_HRI_MF', 'HLI_HCF_MF'):
291 init_state[var] = numpy.zeros(init_state['P'].shape)
292
293 # Initial value
294 for var in ('CF', 'dt_rad_lw', 'dt_rad_sw'):
295 init_state[var] = numpy.zeros(init_state['P'].shape)
296 for var in ('lw_up', 'lw_dn', 'sw_up', 'sw_dn'):
297 init_state[var] = numpy.zeros((init_state['P'].shape[0] + 1, ))
298 for var in ('sfrv', 'swf', 'sfth', 'sshf', 'slhf'):
299 if var not in init_state:
300 init_state[var] = numpy.zeros((1, ))
301
302 return init_state
303
304 def forcing(self, state, timestep, timestep_number):
305 """
306 Apply large-scale forcings to the state
307
308 Parameters
309 ----------
310 state : dict
311 Dictionary holding all the variables.
312 timestep : float
313 Timestep (s)
314 timestep_number : int
315 Current time step number
316
317 Returns
318 -------
319 dict
320 Updated state after forcing
321 """
322 time = timestep * timestep_number
323 # All forcing variable are taken on mass levels
324 if self.grid.kind in ('H', 'hybridH'):
325 output_coord = self.grid.get_altitude('MASS', state, self.prognostic_variables)
326 elif self.grid.kind in ('P', 'hybridP'):
327 output_coord = self.grid.get_pressure('MASS', state, self.prognostic_variables)
328 else:
329 raise Phyex1DError('Wrong grid kind')
330
331 with self.case:
332
333 def profile(name):
334 """Forcing profile at the current time"""
335 interp = self.case.get_interpolator(name, self.grid)
336 return interp(numpy.column_stack(([time] * len(output_coord), output_coord)))
337
338 def nudging(var, suffix):
339 """
340 Nudging of a state variable towards the <suffix>_nud profile, following the
341 DEPHY common format. The nudging_<suffix> attribute is:
342 - 0: no nudging
343 - a positive value: the nudging timescale (s); nudging is then applied above
344 the zh_nudging_<suffix> height (m, above the surface) for a height-based
345 grid, or above the pa_nudging_<suffix> pressure level (Pa) for a
346 pressure-based grid, if defined
347 - -1: the inverse of the nudging timescale (s-1) is given by the
348 nudging_constant_<suffix> profile (nudging_coefficient_<suffix> in the
349 files produced by EMS)
350 """
351 timescale = getattr(self.case, 'nudging_' + suffix, 0)
352 if timescale == 0:
353 return
354 active = numpy.ones(state[var].shape, dtype=bool)
355 if timescale > 0:
356 coefficient = 1. / timescale
357 if self.grid.kind in ('H', 'hybridH'):
358 zh_nudging = getattr(self.case, 'zh_nudging_' + suffix, None)
359 if zh_nudging is not None:
360 height = self.grid.get_altitude('MASS', state,
361 self.prognostic_variables) - \
362 state.get('Zs', 0.)
363 active &= height >= zh_nudging
364 else:
365 pa_nudging = getattr(self.case, 'pa_nudging_' + suffix, None)
366 if pa_nudging is not None:
367 active &= self.grid.get_pressure('MASS', state,
368 self.prognostic_variables) <= \
369 pa_nudging
370 elif timescale == -1:
371 name = 'nudging_constant_' + suffix
372 if not self.case.contains(name) and \
373 self.case.contains('nudging_coefficient_' + suffix):
374 name = 'nudging_coefficient_' + suffix
375 coefficient = profile(name)
376 else:
377 raise Phyex1DError(f'Wrong value for nudging_{suffix}: {timescale}')
378 before = self.budget_fields(state)
379 state[var] += numpy.where(active,
380 coefficient * (profile(suffix + '_nud') - state[var]),
381 0.) * timestep
382 self.budget_record(state, before, 'forc', 'NUD', [var], timestep)
383
384 # Temperature advection and nudging, radiative tendency
385 if 'Theta' in self.prognostic_variables or 'T' in self.prognostic_variables:
386 var = 'Theta' if 'Theta' in self.prognostic_variables else 'T'
387 suffix = 'theta' if var == 'Theta' else 'ta'
388 if getattr(self.case, 'adv_' + suffix) == 1:
389 before = self.budget_fields(state)
390 state[var] += profile(f'tn{suffix}_adv') * timestep
391 self.budget_record(state, before, 'forc', 'ADV', [var], timestep)
392 nudging(var, suffix)
393 if self.case.radiation == 'tend':
394 before = self.budget_fields(state)
395 state[var] += profile(f'tn{suffix}_rad') * timestep
396 self.budget_record(state, before, 'forc', 'RAD', [var], timestep)
397
398 # Hydrometeors advection and nudging
399 if 'rv' in self.prognostic_variables or 'qv' in self.prognostic_variables:
400 var = 'rv' if 'rv' in self.prognostic_variables else 'qv'
401 if getattr(self.case, 'adv_' + var) == 1:
402 before = self.budget_fields(state)
403 state[var] += profile(f'tn{var}_adv') * timestep
404 self.budget_record(state, before, 'forc', 'ADV', [var], timestep)
405 nudging(var, var)
406
407 # Wind advection and nudging
408 for var, suffix in (('u', 'ua'), ('v', 'va')):
409 if getattr(self.case, 'adv_' + suffix) == 1:
410 before = self.budget_fields(state)
411 state[var] += profile(f'tn{suffix}_adv') * timestep
412 self.budget_record(state, before, 'forc', 'ADV', [var], timestep)
413 nudging(var, suffix)
414
415 # Vertical advection (subsidence)
416 if self.case.forc_wa == 1:
417 w = profile('wa')
418 z_mass = self.grid.get_altitude('MASS', state, self.prognostic_variables)
419 variables = [var for var in self.prognostic_variables if var != 'w'] + \
421 before = self.budget_fields(state)
422 for var in variables:
423 grad = numpy.gradient(state[var], z_mass)
424 state[var] += - grad * w * timestep
425 self.budget_record(state, before, 'forc', 'SUBS', variables, timestep)
426 # Negative values (done by the driver)
427 variables = [var for var in variables
428 if var in ('qv', 'qc', 'qr', 'qi', 'qs', 'qg', 'qh',
429 'rv', 'rc', 'rr', 'ri', 'rs', 'rg', 'rh', 'tke') or
430 var in self.scalar_variables]
431 before = self.budget_fields(state)
432 for var in variables:
433 state[var] = numpy.maximum(state[var], 0.)
434 self.budget_record(state, before, 'driver', 'NEGA', variables, timestep)
435
436 # Geostrophic wind (Coriolis force)
437 if self.case.forc_geo == 1:
438 before = self.budget_fields(state)
439 f = 2. * self.cst.omega * numpy.sin(numpy.radians(state['lat']))
440 state['u'] += +f * (state['v'] - profile('vg')) * timestep
441 state['v'] += -f * (state['u'] - profile('ug')) * timestep
442 self.budget_record(state, before, 'forc', 'GEO', ['u', 'v'], timestep)
443
444 # Surface
445 for surf_var, names in list(SURFACE_TEMPERATURES.items()) + [('Ps', ('ps_forc', ))]:
446 if surf_var in state:
447 # The variable corresponding the best is used first
448 name = next((name for name in names if self.case.contains(name)), names[0])
449 interp = self.case.get_interpolator(name, self.grid)
450 state[surf_var] = interp([time])[0]
451 if self.case.surface_forcing_temp == 'surface_flux':
452 interp = self.case.get_interpolator('hfss', self.grid)
453 state['sshf'] = interp([time])[0]
454 if self.case.surface_forcing_moisture == 'surface_flux':
455 interp = self.case.get_interpolator('hfls', self.grid)
456 state['slhf'] = interp([time])[0]
457 for var in ('z0', 'z0h', 'z0q'):
458 if var in state:
459 interp = self.case.get_interpolator(var, self.grid)
460 state[var] = interp([time])[0]
461
462 # Other fields
463 interp = self.case.get_interpolator('lat', self.grid)
464 state['lat'] = interp([time])[0]
465 interp = self.case.get_interpolator('lon', self.grid)
466 state['lon'] = interp([time])[0]
467
468 return state
setup(self, init_state, duration)
forcing(self, state, timestep, timestep_number)
budget_add(self, state, key, value)
budget_record(self, state, before, scheme, process, variables, timestep)
__init__(self, dt, method, name, tag, case, grid, prognostic_variables)
step(self, state, timestep, timestep_number)
execute(self, previous_state, timestep, timestep_number)