PHYEX 0.9.5
PHYsique EXternalisée
Loading...
Searching...
No Matches
case_xarray_demo.py
Go to the documentation of this file.
1"""
2Demonstration of CaseXarray with idealised profiles
3
4This example shows how to create a CaseXarray from scratch using xarray,
5run a simple experiment, and produce plots. It requires the pyphyex package
6(see docs/phyex1d.md for installation).
7
8Usage:
9 python case_xarray_demo.py
10"""
11
12import logging
13import os
14import sys # noqa: F401
15
16import numpy as np
17import xarray as xr
18from matplotlib import pyplot as plt
19
20from pyphyex.phyex1d import CaseXarray, ExperimentRunner
21
22logging.basicConfig(level=logging.INFO)
23
24
26 """
27 Create an xarray Dataset with idealised atmospheric profiles
28 on a 90-level height grid up to 20 km.
29 """
30 nz = 90
31 z = np.linspace(0, 20000, nz) # height above ground (m)
32 time = np.array([0., 3600.]) # start and end times (s)
33
34 # Lapse-rate temperature profile
35 T = np.broadcast_to(290. - z * 0.0065, (2, nz))
36 # Exponentially decreasing moisture
37 qv = np.broadcast_to(0.01 * np.exp(-z / 3000.), (2, nz))
38 # Hydrostatic pressure profile (needed by pressure-based grids), from the surface pressure
39 # and the virtual temperature (trapezoidal integration of dln(p)/dz = -g / (Rd Tv))
40 ps = 101325.
41 tv = T[0] * (1. + 0.608 * qv[0])
42 dlnp = -9.80665 / 287.0597 * np.diff(z) * 0.5 * (1. / tv[1:] + 1. / tv[:-1])
43 pa = np.broadcast_to(ps * np.exp(np.concatenate(([0.], np.cumsum(dlnp)))), (2, nz))
44 # Zero wind
45 u = np.zeros((2, nz))
46 v = np.zeros((2, nz))
47 w = np.zeros((2, nz))
48 tke = np.zeros((2, nz))
49
50 ds = xr.Dataset(
51 {
52 'Zs': ('time', np.array([0., 0.])),
53 'zh': (('time', 'z'), np.broadcast_to(z, (2, nz))),
54 'orog': ('time', np.array([0., 0.])),
55 'Ps': ('time', np.array([ps, ps])),
56 'Ts': ('time', np.array([290., 290.])),
57 'T': (('time', 'z'), T),
58 'qv': (('time', 'z'), qv),
59 'u': (('time', 'z'), u),
60 'v': (('time', 'z'), v),
61 'w': (('time', 'z'), w),
62 'tke': (('time', 'z'), tke),
63 'lat': ('time', np.array([0., 0.])),
64 'lon': ('time', np.array([0., 0.])),
65 'ts_forc': ('time', np.array([290., 290.])),
66 'ps_forc': ('time', np.array([ps, ps])),
67 'zh_forc': (('time', 'z'), np.broadcast_to(z, (2, nz))),
68 'pa': (('time', 'z'), pa),
69 'pa_forc': (('time', 'z'), pa),
70 },
71 coords={'time': time, 'z': z},
72 attrs={
73 'adv_theta': 0,
74 'adv_ta': 0,
75 'adv_rv': 0,
76 'adv_qv': 0,
77 'adv_ua': 0,
78 'adv_va': 0,
79 'nudging_theta': 0,
80 'nudging_ta': 0,
81 'nudging_rv': 0,
82 'nudging_qv': 0,
83 'nudging_ua': 0,
84 'nudging_va': 0,
85 'forc_wa': 0,
86 'forc_geo': 0,
87 'radiation': 'none',
88 'surface_forcing_temp': 'ts',
89 'surface_forcing_moisture': 'none',
90 'surface_forcing_wind': 'none',
91 'surface_type': 'ocean',
92 'start_date': '2000-01-01T00:00:00',
93 },
94 )
95 return ds
96
97
98def make_plots(runner, output_dir):
99 """Create plots similar to the easy_install script."""
100 plots = [
101 ('T.png', ['T'], {'y_var': 'P'}),
102 ('qv.png', ['qv'], {'y_var': 'P'}),
103 ('qc.png', ['qc'], {'y_var': 'P', 'vmin': 0., 'vmax': 5.e-5}),
104 ('Theta.png', ['Theta'], {'y_var': 'P'}),
105 ]
106 for filename, var_names, options in plots:
107 fig, ax = plt.subplots()
108 kwargs_contourf = {}
109 vmin = options.pop('vmin', None)
110 vmax = options.pop('vmax', None)
111 if vmin is not None:
112 kwargs_contourf['vmin'] = vmin
113 if vmax is not None:
114 kwargs_contourf['vmax'] = vmax
115 if kwargs_contourf:
116 options['kwargs_contourf'] = kwargs_contourf
117 runner.plot_evol(ax, var_names, **options)
118 if options.get('y_var', 'X') == 'P':
119 ax.invert_yaxis()
120 filepath = os.path.join(output_dir, filename)
121 fig.savefig(filepath)
122 plt.close(fig)
123 print(f' Saved {filepath}')
124
125
126def main():
128 case = CaseXarray(ds)
129
130 print(f'Created CaseXarray (duration: {case.duration} s)')
131 print(f'Variables: {list(ds.data_vars)}')
132
133 output_dir = './output_casexarray_demo'
134 os.makedirs(output_dir, exist_ok=True)
135
136 runner = ExperimentRunner(
137 case,
138 [
139 {
140 'dt': 60,
141 'grid': 'L90mesonh',
142 'name': 'idealised_demo',
143 'class': 'PhysicsAromeTQ',
144 },
145 ],
146 output_dir=output_dir,
147 comp_name='demo',
148 )
149
150 print('\nRunning experiment...')
151 runner.run()
152 print('Done!')
153
154 print('\nCreating plots...')
155 make_plots(runner, output_dir)
156 print('\nAll plots saved in', output_dir)
157
158
159if __name__ == '__main__':
160 main()
make_plots(runner, output_dir)