PHYEX 0.9.5
PHYsique EXternalisée
Loading...
Searching...
No Matches
dephycf_export.py
Go to the documentation of this file.
1"""
2Conversion of the results of an experiment into a netCDF file following the DEPHY common
3format (dephycf) for SCM outputs, as done by EMS (https://github.com/romainroehrig/EMS,
4examples/post.dephycf/variables.py and ems/lfa2nc_dephycf.py):
5- variable names, units and standard_name attributes of the dephycf table of EMS
6- levf (full levels) and levh (half levels) dimensions, time dimension in seconds since the
7 start date of the case
8- NETCDF3_CLASSIC format, float32 values, 1.e20 as missing value
9Variables without dephycf equivalent are written with their phyex1d name, except the ones whose
10information is already in the file (mixing ratios, kinematic surface fluxes...).
11Budgets (bu_<scheme>_<variable>_<process> variables) are summed by scheme and converted into
12the dephycf tendencies.
13"""
14
15import os
16
17import h5py
18import netCDF4
19import numpy
20
21from pppy import VAR_NAME, VAR_UNIT
22
23from . import Phyex1DError
24from . import Cst
25
26MISSING_VALUE = numpy.float32(1.e20)
27
28# dephycf variables used (units and standard_name from EMS examples/post.dephycf/variables.py)
29DEPHYCF_VARIABLES = {
30 # Dynamical and thermodynamical variables
31 'pfull': ('Pa', 'air_pressure_on_model_levels'),
32 'zfull': ('m', 'height_on_model_levels'),
33 'zhalf': ('m', 'height_on_model_half_levels'),
34 'ta': ('K', 'air_temperature'),
35 'theta': ('K', 'air_potential_temperature'),
36 'qv': ('1', 'specific_humidity'),
37 'ql': ('1', 'mass_fraction_of_cloud_liquid_water_in_air'),
38 'qi': ('1', 'mass_fraction_of_cloud_ice_water_in_air'),
39 'qr': ('1', 'mass_fraction_of_rain_water_in_air'),
40 'qsn': ('1', 'mass_fraction_of_snow_water_in_air'),
41 'qt': ('1', 'total_water_content'),
42 'tke': ('m2 s-2', 'specific_turbulent_kinetic_energy'),
43 'ua': ('m s-1', 'eastward_wind'),
44 'va': ('m s-1', 'northward_wind'),
45 'wa': ('m s-1', 'updward_air_velocity'),
46 # Cloud variables
47 'cl': ('-', 'cloud_area_fraction_in_atmospheric_layer'),
48 # Radiation variables
49 'rld': ('W m-2', 'downwelling_longwave_flux_in_air'),
50 'rlu': ('W m-2', 'upwelling_longwave_flux_in_air'),
51 'rsd': ('W m-2', 'downwelling_shortwave_flux_in_air'),
52 'rsu': ('W m-2', 'upwelling_shortwave_flux_in_air'),
53 # Surface turbulent fluxes
54 'hfls': ('W m-2', 'surface_upward_latent_heat_flux'),
55 'hfss': ('W m-2', 'surface_upward_sensible_heat_flux'),
56 'z0': ('m', 'z0'),
57 # Near-surface variables
58 'ps': ('Pa', 'surface_pressure'),
59 'ts': ('K', 'surface_temperature'),
60 'tskin': ('K', 'skin_surface_temperature'),
61 # Turbulence variables
62 'sigs': ('1', 'Subgrid Standard Deviation of s (LNEBECT)'),
63 # Physical tendencies
64 'tnta': ('K s-1', 'tendendy_of_air_temperature'),
65 'tnta_adv': ('K s-1', 'tendendy_of_air_temperature_due_to_advection'),
66 'tnta_advv': ('K s-1', 'tendendy_of_air_temperature_due_to_vertical_advection'),
67 'tnta_nud': ('K s-1', 'tendendy_of_air_temperature_due_to_nudging'),
68 'tnta_conv': ('K s-1', 'tendendy_of_air_temperature_due_to_convection'),
69 'tnta_micro': ('K s-1', 'tendency_of_air_temperarure_due_to_microphysics'),
70 'tnta_turb': ('K s-1', 'tendency_of_air_temperarure_due_to_turbulence'),
71 'tnta_rad': ('K s-1', 'tendency_of_air_temperarure_due_to_radiation'),
72 'tnta_radlw': ('K s-1', 'tendency_of_air_temperarure_due_to_lw_radiation'),
73 'tnta_radsw': ('K s-1', 'tendency_of_air_temperarure_due_to_sw_radiation'),
74 'tnta_other': ('K s-1', 'tendendy_of_air_temperature_due_to_other_processes'),
75 'tnthlscp': ('K s-1', 'Potential Temperature Tendency due to Large-scale Condensation and '
76 'Precipitation'),
77 'tnthpbl': ('K s-1', 'Potential Temperature Tendency due to Turbulence'),
78 'tnthrlw': ('K s-1', 'Potential Temperature Tendency due to LW Radiation'),
79 'tnthrsw': ('K s-1', 'Potential Temperature Tendency due to SW Radiation'),
80 'tnthshc': ('K s-1', 'Potential Temperature Tendency due to Shallow Convection'),
81 'tnqv': ('s-1', 'tendency_of_specific_humidity'),
82 'tnqv_adv': ('s-1', 'tendency_of_specific_humidity_due_to_advection'),
83 'tnqv_advv': ('s-1', 'tendency_of_specific_humidity_due_to_vertical_advection'),
84 'tnqv_nud': ('s-1', 'tendency_of_specific_humidity_due_to_nudging'),
85 'tnqv_micro': ('s-1', 'tendency_of_specific_humidity_due_to_microphysics'),
86 'tnqv_turb': ('s-1', 'tendency_of_specific_humidity_due_to_turbulence'),
87 'tnqv_other': ('s-1', 'tendency_of_specific_humidity_due_to_other_processes'),
88 'tnqt_micro': ('s-1', 'tendency_of_total_water_due_to_microphysics'),
89 'tnqt_turb': ('s-1', 'tendency_of_total_water_due_to_turbulence'),
90 'tnqt_shconv': ('s-1', 'tendency_of_total_water_due_shallow_convection'),
91 'tnql': ('s-1', 'Liquid Water Tendency due to Physics'),
92 'tnqi': ('s-1', 'Ice Water Tendency due to Physics'),
93 'tnqr': ('s-1', 'Rain Tendency due to Physics'),
94 'tnqsn': ('s-1', 'Snow Tendency due to Physics'),
95 'tnua': ('m s-2', 'tendency_of_eastward_wind'),
96 'tnua_adv': ('m s-2', 'tendency_of_eastward_wind_due_to_advection'),
97 'tnua_advv': ('m s-2', 'tendency_of_eastward_wind_due_to_vertical_advection'),
98 'tnua_nud': ('m s-2', 'tendency_of_eastward_wind_due_to_nudging'),
99 'tnua_geo': ('m s-2', 'tendency_of_eastward_wind_due_to_geostrophic_forcing'),
100 'tnua_conv': ('m s-2', 'tendency_of_eastward_wind_due_to_convection'),
101 'tnua_turb': ('m s-2', 'tendency_of_eastward_wind_due_to_turbulence'),
102 'tnva': ('m s-2', 'tendency_of_northward_wind'),
103 'tnva_adv': ('m s-2', 'tendency_of_northward_wind_due_to_advection'),
104 'tnva_advv': ('m s-2', 'tendency_of_northward_wind_due_to_vertical_advection'),
105 'tnva_nud': ('m s-2', 'tendency_of_northward_wind_due_to_nudging'),
106 'tnva_geo': ('m s-2', 'tendency_of_northward_wind_due_to_geostrophic_forcing'),
107 'tnva_conv': ('m s-2', 'tendency_of_northward_wind_due_to_convection'),
108 'tnva_turb': ('m s-2', 'tendency_of_northward_wind_due_to_turbulence'),
109 # TKE budget (dephycf turbulence variables, units not given in the EMS table)
110 'TKEPRDY': ('m2 s-3', 'TKEPRDY'),
111 'TKEPRTH': ('m2 s-3', 'TKEPRTH'),
112 'TKEDIF': ('m2 s-3', 'TKEDIF'),
113 'TKEDISS': ('m2 s-3', 'TKEDISS'),
114}
115
116# Variables without dephycf equivalent, written with names built on the dephycf pattern
117EXTRA_VARIABLES = {
118 'qg': ('1', 'mass_fraction_of_graupel_in_air'),
119 'qh': ('1', 'mass_fraction_of_hail_in_air'),
120 'lat': ('degrees_north', 'latitude'),
121 'lon': ('degrees_east', 'longitude'),
122 'Zs': ('m', 'surface_altitude'),
123 'tnqg': ('s-1', 'Graupel Tendency due to Physics'),
124 'tnqh': ('s-1', 'Hail Tendency due to Physics'),
125 'tnta_res': ('K s-1', 'residual_of_the_air_temperature_budget'),
126 'tnqv_res': ('s-1', 'residual_of_the_specific_humidity_budget'),
127 'tnua_res': ('m s-2', 'residual_of_the_eastward_wind_budget'),
128 'tnva_res': ('m s-2', 'residual_of_the_northward_wind_budget'),
129}
130
131# dephycf name: phyex1d variable
132STATE_VARIABLES = {
133 'pfull': 'P', 'zfull': 'Z_mass', 'zhalf': 'Z_flux',
134 'ta': 'T', 'theta': 'Theta',
135 'qv': 'qv', 'ql': 'qc', 'qi': 'qi', 'qr': 'qr', 'qsn': 'qs', 'qg': 'qg', 'qh': 'qh',
136 'qt': 'qt', 'tke': 'tke', 'ua': 'u', 'va': 'v', 'wa': 'w', 'cl': 'CF',
137 'rld': 'lw_dn', 'rlu': 'lw_up', 'rsd': 'sw_dn', 'rsu': 'sw_up',
138 'hfls': 'slhf', 'hfss': 'sshf', 'z0': 'z0', 'ps': 'Ps', 'ts': 'Ts', 'tskin': 'Tskin',
139 'sigs': 'sigs', 'lat': 'lat', 'lon': 'lon', 'Zs': 'Zs',
140}
141
142# phyex1d variables not written because their information is already in the file
143REDUNDANT_VARIABLES = {
144 't', # time coordinate
145 'rv', 'rc', 'rr', 'ri', 'rs', 'rg', 'rh', 'rt', # mixing ratios (specific contents written)
146 'sfth', 'sfrv', 'swf', # surface fluxes in other units (hfss, hfls written)
147 'dt_rad_lw', 'dt_rad_sw', # temperature tendencies (tnta_radlw, tnta_radsw written)
148}
149
150# Budgets: (phyex1d scheme, processes or None for all) -> dephycf name for each budget variable
151# (TH budgets are potential temperature tendencies, converted into temperature tendencies
152# for the tnta_* variables; mixing ratio budgets are converted into specific content
153# tendencies)
154BUDGET_GROUPS = [
155 # (dephycf name, phyex1d variable, schemes, processes (None for all), conversion)
156 ('tnta_turb', 'TH', ('turb', ), None, 'exner'),
157 ('tnthpbl', 'TH', ('turb', ), None, None),
158 ('tnqv_turb', 'RV', ('turb', ), None, 'q'),
159 ('tnqt_turb', 'RT', ('turb', ), None, 'qt'),
160 ('tnua_turb', 'U', ('turb', ), None, None),
161 ('tnva_turb', 'V', ('turb', ), None, None),
162 ('TKEPRDY', 'TKE', ('turb', ), ('DP', ), None),
163 ('TKEPRTH', 'TKE', ('turb', ), ('TP', ), None),
164 ('TKEDIF', 'TKE', ('turb', ), ('TR', ), None),
165 ('TKEDISS', 'TKE', ('turb', ), ('DISS', ), None),
166 ('tnta_conv', 'TH', ('shallow', ), None, 'exner'),
167 ('tnthshc', 'TH', ('shallow', ), None, None),
168 ('tnqt_shconv', 'RV', ('shallow', ), None, 'qt'), # shallow RV budget is the rt tendency
169 ('tnua_conv', 'U', ('shallow', ), None, None),
170 ('tnva_conv', 'V', ('shallow', ), None, None),
171 ('tnta_micro', 'TH', ('adjust', 'micro'), None, 'exner'),
172 ('tnthlscp', 'TH', ('adjust', 'micro'), None, None),
173 ('tnqv_micro', 'RV', ('adjust', 'micro'), None, 'q'),
174 ('tnqt_micro', 'RT', ('adjust', 'micro'), None, 'qt'),
175 ('tnta_radlw', 'TH', ('rad', ), ('LW', ), 'exner'),
176 ('tnta_radsw', 'TH', ('rad', ), ('SW', ), 'exner'),
177 ('tnthrlw', 'TH', ('rad', ), ('LW', ), None),
178 ('tnthrsw', 'TH', ('rad', ), ('SW', ), None),
179 ('tnta_adv', 'TH', ('forc', ), ('ADV', ), 'exner'),
180 ('tnqv_adv', 'RV', ('forc', ), ('ADV', ), 'q'),
181 ('tnua_adv', 'U', ('forc', ), ('ADV', ), None),
182 ('tnva_adv', 'V', ('forc', ), ('ADV', ), None),
183 ('tnta_advv', 'TH', ('forc', ), ('SUBS', ), 'exner'),
184 ('tnqv_advv', 'RV', ('forc', ), ('SUBS', ), 'q'),
185 ('tnua_advv', 'U', ('forc', ), ('SUBS', ), None),
186 ('tnva_advv', 'V', ('forc', ), ('SUBS', ), None),
187 ('tnta_rad', 'TH', ('forc', ), ('RAD', ), 'exner'),
188 ('tnta_nud', 'TH', ('forc', ), ('NUD', ), 'exner'),
189 ('tnqv_nud', 'RV', ('forc', ), ('NUD', ), 'q'),
190 ('tnua_nud', 'U', ('forc', ), ('NUD', ), None),
191 ('tnva_nud', 'V', ('forc', ), ('NUD', ), None),
192 ('tnua_geo', 'U', ('forc', ), ('GEO', ), None),
193 ('tnva_geo', 'V', ('forc', ), ('GEO', ), None),
194 ('tnta_other', 'TH', ('driver', ), None, 'exner'),
195 ('tnqv_other', 'RV', ('driver', ), None, 'q'),
196 ('tnta', 'TH', ('all', ), ('TOT', ), 'exner'),
197 ('tnqv', 'RV', ('all', ), ('TOT', ), 'q'),
198 ('tnua', 'U', ('all', ), ('TOT', ), None),
199 ('tnva', 'V', ('all', ), ('TOT', ), None),
200 ('tnta_res', 'TH', ('all', ), ('RES', ), 'exner'),
201 ('tnqv_res', 'RV', ('all', ), ('RES', ), 'q'),
202 ('tnua_res', 'U', ('all', ), ('RES', ), None),
203 ('tnva_res', 'V', ('all', ), ('RES', ), None),
204]
205# Tendencies of the hydrometeors due to the physics (all schemes except forcings, driver and all)
206PHYSICS_SCHEMES = ('adjust', 'micro', 'turb', 'shallow', 'rad')
207HYDROMETEOR_TENDENCIES = {'tnql': 'RC', 'tnqi': 'RI', 'tnqr': 'RR', 'tnqsn': 'RS',
208 'tnqg': 'RG', 'tnqh': 'RH'}
209WATER_VARIABLES = ('RV', 'RC', 'RR', 'RI', 'RS', 'RG', 'RH')
210
211
212def _budget_sum(hdf5, variables, schemes, processes):
213 """
214 Sum of the budgets
215 :param hdf5: result file
216 :param variables: budget variables (TH, RV...)
217 :param schemes: list of schemes
218 :param processes: list of processes, None for all
219 :return: sum (None if no budget variable is found)
220 """
221 result = None
222 for key in hdf5:
223 if key.startswith('bu_') and key.count('_') >= 3:
224 _, scheme, var, process = key.split('_', 3)
225 if var in variables and scheme in schemes and \
226 (processes is None or process in processes):
227 result = hdf5[key][...] if result is None else result + hdf5[key][...]
228 return result
229
230
231def budgets(hdf5):
232 """
233 dephycf tendencies computed from the budgets of a result file
234 :param hdf5: result file (h5py File)
235 :return: dictionary {dephycf name: values}
236 """
237 if not any(key.startswith('bu_') for key in hdf5):
238 return {}
239 cst = Cst()
240 exner = (hdf5['P'][...] / 1.E5) ** (cst.Rd / cst.Cpd)
241 qt = sum(hdf5[var][...] for var in ('qv', 'qc', 'qr', 'qi', 'qs', 'qg', 'qh') if var in hdf5)
242 conversion = {None: 1., 'exner': exner,
243 'q': 1. - qt, # dq = dr / (1 + rt), neglecting the change of rt
244 'qt': (1. - qt) ** 2} # dqt = drt / (1 + rt)**2
245 result = {}
246 for name, var, schemes, processes, conv in BUDGET_GROUPS:
247 variables = WATER_VARIABLES if var == 'RT' else (var, )
248 values = _budget_sum(hdf5, variables, schemes, processes)
249 if values is not None:
250 result[name] = values * conversion[conv]
251 for name, var in HYDROMETEOR_TENDENCIES.items():
252 values = _budget_sum(hdf5, (var, ), PHYSICS_SCHEMES, None)
253 if values is not None:
254 result[name] = values * conversion['q']
255 return result
256
257
258def start_date(hdf5):
259 """
260 Start date of the case
261 :param hdf5: result file (h5py File)
262 :return: start date as a string, None if unknown
263 """
264 inputfile = str(hdf5.attrs.get('inputfile', ''))
265 if os.path.exists(inputfile):
266 try:
267 with netCDF4.Dataset(inputfile) as case:
268 if 'start_date' in case.ncattrs():
269 return str(case.getncattr('start_date'))
270 except OSError:
271 pass
272 return None
273
274
275def export(hdf5file, ncfile):
276 """
277 Converts a result file into a netCDF file following the DEPHY common format
278 :param hdf5file: result file of an experiment
279 :param ncfile: netCDF file to produce
280 """
281 with h5py.File(hdf5file, 'r') as hdf5:
282 time = hdf5['t'][...]
283 nlev = hdf5['P'].shape[1]
284
285 # Variables to write: {name: (values, units, standard_name, original name)}
286 variables = {}
287 for name, var in STATE_VARIABLES.items():
288 if var in hdf5:
289 units, std_name = {**DEPHYCF_VARIABLES, **EXTRA_VARIABLES}[name]
290 variables[name] = (hdf5[var][...], units, std_name, var)
291 for name, values in budgets(hdf5).items():
292 units, std_name = {**DEPHYCF_VARIABLES, **EXTRA_VARIABLES}[name]
293 variables[name] = (values, units, std_name, 'budgets')
294 # Variables without dephycf equivalent
295 for var in hdf5:
296 if var not in STATE_VARIABLES.values() and var not in REDUNDANT_VARIABLES and \
297 not var.startswith('bu_'):
298 if var in variables:
299 raise Phyex1DError(f'Name conflict for variable {var}')
300 variables[var] = (hdf5[var][...], VAR_UNIT.get(var, None) or '-',
301 VAR_NAME.get(var, '') or var, var)
302
303 date = start_date(hdf5)
304 attrs = {key: str(value) for key, value in hdf5.attrs.items()}
305
306 with netCDF4.Dataset(ncfile, 'w', format='NETCDF3_CLASSIC') as nc:
307 for key, value in attrs.items():
308 nc.setncattr(key, value)
309 nc.createDimension('levf', nlev)
310 levf = nc.createVariable('levf', 'i4', ('levf', ))
311 levf.standard_name = 'full_level_number'
312 levf.units = '-'
313 levf.axis = 'Z'
314 levf[:] = range(0, nlev)
315 nc.createDimension('levh', nlev + 1)
316 levh = nc.createVariable('levh', 'i4', ('levh', ))
317 levh.standard_name = 'half_level_number'
318 levh.units = '-'
319 levh.axis = 'Z'
320 levh[:] = range(0, nlev + 1)
321 nc.createDimension('time', None)
322 times = nc.createVariable('time', 'f4', ('time', ))
323 times.calendar = 'gregorian'
324 times.axis = 'T'
325 times.units = 'seconds' if date is None else f'seconds since {date}'
326 times[:] = time
327
328 for name, (values, units, std_name, original) in variables.items():
329 values = numpy.asarray(values, dtype=numpy.float64)
330 values = values.reshape((values.shape[0], -1)) # (time, ) or (time, 1) -> (time, 1)
331 if values.shape[1] == nlev:
332 dims, coordinates = ('time', 'levf'), 'time zfull'
333 elif values.shape[1] == nlev + 1:
334 dims, coordinates = ('time', 'levh'), 'time zhalf'
335 elif values.shape[1] == 1:
336 dims, coordinates = ('time', ), 'time'
337 values = values[:, 0]
338 else:
339 raise Phyex1DError(f'Unexpected shape for variable {original}: {values.shape}')
340 ncvar = nc.createVariable(name, 'f4', dims, fill_value=MISSING_VALUE)
341 ncvar.missing_value = MISSING_VALUE
342 ncvar.standard_name = std_name
343 ncvar.units = units
344 ncvar.coordinates = coordinates
345 ncvar.original_name = original
346 ncvar[...] = numpy.ma.masked_invalid(values).astype(numpy.float32)
_budget_sum(hdf5, variables, schemes, processes)