Skip to content

vulcan.netcdf

netcdf

Write VULCAN results to a self-describing NetCDF file.

All quantities are stored in the CGS units used internally by VULCAN. Index 0 along the layer and level dimensions is the bottom of the atmosphere (highest pressure).

write_netcdf(fpath, var, atm, para, cfg, species, nr, re_wM_dict, compress=True)

Write the final state of a VULCAN run to a NetCDF4 file.

Parameters:

Name Type Description Default
fpath str

Path of the file to write. It is overwritten if it exists.

required
var (Variables, AtmData, Parameters)

Model state containers at the end of the run.

required
atm (Variables, AtmData, Parameters)

Model state containers at the end of the run.

required
para (Variables, AtmData, Parameters)

Model state containers at the end of the run.

required
cfg Config

Configuration used for the run.

required
species list

Species names (chem_funs.spec_list).

required
nr int

Number of reactions (chem_funs.nr).

required
re_wM_dict dict

Reactants and products of each reaction, including 'M' (chem_funs.re_wM_dict).

required
compress bool

Apply zlib compression to the large 2D arrays.

True
Source code in src/vulcan/netcdf.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
def write_netcdf(fpath, var, atm, para, cfg, species, nr, re_wM_dict, compress=True):
    """
    Write the final state of a VULCAN run to a NetCDF4 file.

    Parameters
    ----------
    fpath : str
        Path of the file to write. It is overwritten if it exists.
    var, atm, para : store.Variables, store.AtmData, store.Parameters
        Model state containers at the end of the run.
    cfg : Config
        Configuration used for the run.
    species : list
        Species names (chem_funs.spec_list).
    nr : int
        Number of reactions (chem_funs.nr).
    re_wM_dict : dict
        Reactants and products of each reaction, including 'M' (chem_funs.re_wM_dict).
    compress : bool
        Apply zlib compression to the large 2D arrays.
    """
    from vulcan import __version__

    nz = cfg.nz
    ni = len(species)
    atoms = list(cfg.atom_list)

    log.info(f'Writing NetCDF output to {fpath}')
    with nc.Dataset(fpath, 'w', format='NETCDF4') as ds:
        # ---------------- Metadata ----------------
        ds.title = 'VULCAN photochemical kinetics output (CGS units)'
        ds.vulcan_version = __version__
        ds.date_created = str(datetime.now(timezone.utc).isoformat(timespec='seconds'))
        ds.hostname = str(os.uname()[1])
        ds.username = str(getpass.getuser())
        ds.network = str(cfg.network)
        ds.atom_list = ','.join(atoms)

        end_case = int(getattr(para, 'end_case', 0))
        ds.end_case = end_case
        ds.termination = END_CASES.get(end_case, 'unknown')
        ds.steps = int(para.count)
        ds.model_time_s = float(var.t)
        ds.dt_s = float(var.dt)
        ds.longdy = float(var.longdy)
        ds.longdydt = float(var.longdydt)
        if getattr(para, 'start_time', None) is not None:
            ds.wall_time_s = time.time() - para.start_time
        climate_dT = list(getattr(para, 'climate_dT', []))
        ds.climate_updates = len(climate_dT)
        if climate_dT:
            ds.climate_max_rel_dT = np.asarray(climate_dT, dtype=float)

        for key in (
            'Rp',
            'gs',
            'r_star',
            'orbit_radius',
            'sl_angle',
            'f_diurnal',
            'rocky',
            'use_photo',
            'use_ion',
            'use_condense',
            'use_moldiff',
            'nz',
            'P_b',
            'P_t',
        ):
            if hasattr(cfg, key):
                setattr(ds, key, _attr(getattr(cfg, key)))

        # ---------------- Dimensions ----------------
        ds.createDimension('layer', nz)
        ds.createDimension('level', nz + 1)
        ds.createDimension('species', ni)
        ds.createDimension('reaction', nr)
        ds.createDimension('atom', len(atoms))

        # ---------------- Atmospheric structure ----------------
        _put(ds, 'p', ('layer',), atm.pco, 'dyn cm-2', 'pressure at layer centres')
        _put(ds, 'pl', ('level',), atm.pico, 'dyn cm-2', 'pressure at interfaces')
        _put(ds, 'tmp', ('layer',), atm.Tco, 'K', 'temperature at layer centres')
        _put(ds, 'z', ('layer',), atm.zmco, 'cm', 'altitude at layer centres')
        _put(ds, 'zl', ('level',), atm.zco, 'cm', 'altitude at interfaces')
        _put(
            ds,
            'Kzz',
            ('level',),
            _on_levels(atm.Kzz, nz),
            'cm2 s-1',
            'eddy diffusion coefficient',
        )
        _put(
            ds,
            'vz',
            ('level',),
            _on_levels(atm.vz, nz),
            'cm s-1',
            'vertical advection velocity',
        )
        _put(
            ds, 'mean_molecular_weight', ('layer',), atm.mu, 'g mol-1', 'mean molecular weight'
        )
        _put(ds, 'number_density_total', ('layer',), atm.n_0, 'cm-3', 'total number density')
        _put(
            ds,
            'third_body_density',
            ('layer',),
            atm.M,
            'cm-3',
            'third-body (M) number density used in the rate equations',
        )

        # ---------------- Species ----------------
        _put_str(ds, 'species', ('species',), species, 'species name')
        _put(ds, 'molecular_mass', ('species',), atm.ms, 'g mol-1', 'molar mass of species')
        _put(
            ds,
            'N_gas',
            ('layer', 'species'),
            var.y,
            'cm-3',
            'number density',
            compress=compress,
        )
        _put(
            ds,
            'x_gas',
            ('layer', 'species'),
            var.ymix,
            '1',
            'volume mixing ratio',
            compress=compress,
        )
        _put(
            ds,
            'N_gas_ini',
            ('layer', 'species'),
            var.y_ini,
            'cm-3',
            'initial number density',
            compress=compress,
        )

        # ---------------- Reactions ----------------
        ids = np.arange(1, nr + 1)
        v = ds.createVariable('reaction_id', 'i4', ('reaction',))
        v.long_name = 'reaction index (odd = forward, even = reverse of the preceding one)'
        v[:] = ids

        equations = [
            ' + '.join(re_wM_dict[i][0]) + ' -> ' + ' + '.join(re_wM_dict[i][1]) for i in ids
        ]
        _put_str(ds, 'reaction_equation', ('reaction',), equations, 'reaction equation')
        _put_str(ds, 'reaction_type', ('reaction',), _reaction_types(var, nr), 'reaction type')

        v = ds.createVariable('reaction_is_reverse', 'S1', ('reaction',))
        v.long_name = "'y' if this is the reverse of reaction_id - 1, else 'n'"
        v[:] = np.array([_yn(i % 2 == 0) for i in ids], dtype='S1')

        v = ds.createVariable('reaction_order', 'i4', ('reaction',))
        v.long_name = 'number of reactants including M; sets the units of rate_coefficient'
        v[:] = [len(re_wM_dict[i][0]) for i in ids]

        k_arr = np.stack([np.asarray(var.k[i], dtype=float) for i in ids], axis=1)
        _put(
            ds,
            'rate_coefficient',
            ('layer', 'reaction'),
            k_arr,
            'cm^(3*(reaction_order-1)) s-1',
            'rate coefficient (s-1, cm3 s-1 or cm6 s-1 for reaction_order 1, 2 or 3)',
            compress=compress,
        )
        _put(
            ds,
            'reaction_rate',
            ('layer', 'reaction'),
            compute_reaction_rates(var.k, var.y, atm.M, re_wM_dict, species, nr),
            'cm-3 s-1',
            'reaction rate, k times the product of reactant number densities',
            compress=compress,
        )

        # ---------------- Element conservation ----------------
        _put_str(ds, 'atom', ('atom',), atoms, 'element')
        _put(
            ds,
            'atom_initial',
            ('atom',),
            [var.atom_ini[a] for a in atoms],
            'cm-3',
            'initial number density of the element, summed over layers',
        )
        _put(
            ds,
            'atom_sum',
            ('atom',),
            [var.atom_sum.get(a, FILL) for a in atoms],
            'cm-3',
            'final number density of the element, summed over layers',
        )
        _put(
            ds,
            'atom_loss',
            ('atom',),
            [var.atom_loss[a] for a in atoms],
            '1',
            'fractional change (atom_sum - atom_initial) / atom_initial',
        )
        if getattr(var, 'atom_conden', None):
            _put(
                ds,
                'atom_conden',
                ('atom',),
                [var.atom_conden.get(a, FILL) for a in atoms],
                'cm-3',
                'number density of the element in condensates, summed over layers',
            )

        # ---------------- Radiation ----------------
        if cfg.use_photo:
            ds.createDimension('wavelength', len(var.bins))
            _put(ds, 'wavelength', ('wavelength',), var.bins, 'nm', 'wavelength')
            _put(
                ds,
                'ba_ACTINIC',
                ('layer', 'wavelength'),
                var.aflux,
                'photons cm-2 s-1 nm-1',
                'actinic flux at layer centres',
                compress=compress,
            )
            _put(
                ds,
                'ba_D_DIRECT',
                ('level', 'wavelength'),
                var.sflux,
                'erg cm-2 s-1 nm-1',
                'direct stellar beam at interfaces, not multiplied by cos(zenith angle)',
                compress=compress,
            )
            _put(
                ds,
                'ba_U_DIFFUSE',
                ('level', 'wavelength'),
                var.dflux_u,
                'erg cm-2 s-1 nm-1',
                'upward diffuse flux at interfaces',
                compress=compress,
            )
            _put(
                ds,
                'ba_D_DIFFUSE',
                ('level', 'wavelength'),
                var.dflux_d,
                'erg cm-2 s-1 nm-1',
                'downward diffuse flux at interfaces',
                compress=compress,
            )
            _put(
                ds,
                'optdepth',
                ('level', 'wavelength'),
                var.tau,
                '1',
                'vertical optical depth at interfaces, measured from the top',
                compress=compress,
            )

compute_reaction_rates(k, y, M, re_wM_dict, species, nr)

Compute the rate of every reaction at every layer.

The rate of reaction i is R_i = k_i * prod(n_s) over its reactants, where the third body 'M' contributes the total number density M. A species appearing n times in the reactant list contributes n_s**n. This mirrors the rate expressions generated by make_chem_funs.make_chemdf, so that the net change from all reactions equals chemdf.

Parameters:

Name Type Description Default
k dict

Rate coefficients, k[i] has shape (nz,).

required
y ndarray

Number densities, shape (nz, ni) [cm-3].

required
M ndarray

Third-body number density, shape (nz,) [cm-3].

required
re_wM_dict dict

re_wM_dict[i] = [[reactants], [products]], including 'M'.

required
species list

Species names, ordered as the columns of y.

required
nr int

Number of reactions; reactions are numbered 1..nr.

required

Returns:

Type Description
ndarray

Reaction rates, shape (nz, nr) [cm-3 s-1].

Source code in src/vulcan/netcdf.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def compute_reaction_rates(k, y, M, re_wM_dict, species, nr):
    """
    Compute the rate of every reaction at every layer.

    The rate of reaction i is R_i = k_i * prod(n_s) over its reactants, where the third
    body 'M' contributes the total number density M. A species appearing n times in the
    reactant list contributes n_s**n. This mirrors the rate expressions generated by
    `make_chem_funs.make_chemdf`, so that the net change from all reactions equals `chemdf`.

    Parameters
    ----------
    k : dict
        Rate coefficients, k[i] has shape (nz,).
    y : np.ndarray
        Number densities, shape (nz, ni) [cm-3].
    M : np.ndarray
        Third-body number density, shape (nz,) [cm-3].
    re_wM_dict : dict
        re_wM_dict[i] = [[reactants], [products]], including 'M'.
    species : list
        Species names, ordered as the columns of y.
    nr : int
        Number of reactions; reactions are numbered 1..nr.

    Returns
    -------
    np.ndarray
        Reaction rates, shape (nz, nr) [cm-3 s-1].
    """
    sp_indx = {sp: i for i, sp in enumerate(species)}
    rates = np.zeros((y.shape[0], nr))
    for i in range(1, nr + 1):
        rate = np.array(k[i], dtype=float, copy=True)
        for sp in re_wM_dict[i][0]:
            rate *= M if sp == 'M' else y[:, sp_indx[sp]]
        rates[:, i - 1] = rate
    return rates