Skip to content

vulcan.agni

agni


Climate hook that couples VULCAN to the AGNI radiative-convective model.

AgniClimate sets up an AGNI atmosphere on VULCAN's pressure range and, at each climate update, hands it VULCAN's mixing ratios, solves for the temperature profile (or, with solve_rce = False, keeps VULCAN's temperature) and returns the temperature and AGNI's eddy diffusion profile as a vulcan.climate.ClimateUpdate. set_composition and climate_update work on any AGNI atmosphere, so a coupled framework that builds its own AGNI atmosphere can use them in its own hook.

AGNI works in SI units and VULCAN in cgs: pressures are converted with PA_TO_DYN and diffusion coefficients with M2_TO_CM2 at this boundary.

Imports

AgniClimate(vulcan_cfg, atm, var)

Climate hook that solves the temperature profile with AGNI (see vulcan.climate).

With solve_rce = True AGNI solves for radiative-convective equilibrium with the surface condition agni_sol_type. With solve_rce = False VULCAN's temperature is returned unchanged, on VULCAN's own grid, and AGNI only computes the convective fluxes and the eddy diffusion profile from it.

vulcan_cfg : Config Run configuration. atm : store.AtmData Atmosphere data, passed to init_agni_atmos. var : store.Variables Model variables, passed to init_agni_atmos.

Source code in src/vulcan/agni.py
365
366
367
368
369
370
371
372
373
374
375
376
377
378
def __init__(self, vulcan_cfg: Config, atm, var):
    """
    Parameters
    ----------
    vulcan_cfg : Config
        Run configuration.
    atm : store.AtmData
        Atmosphere data, passed to `init_agni_atmos`.
    var : store.Variables
        Model variables, passed to `init_agni_atmos`.
    """
    self.cfg = vulcan_cfg
    activate_julia(vulcan_cfg)
    self.atmos = init_agni_atmos(vulcan_cfg, atm, var)

atmos = init_agni_atmos(vulcan_cfg, atm, var) instance-attribute

cfg = vulcan_cfg instance-attribute

close()

Deallocate the AGNI atmosphere.

Source code in src/vulcan/agni.py
424
425
426
def close(self):
    """Deallocate the AGNI atmosphere."""
    deallocate_atmos(self.atmos)

activate_julia(vulcan_cfg)

Load AGNI into Julia, unless a caller (such as PROTEUS) has loaded it already.

When AGNI is already loaded, its Julia environment and logger are left as they are. Otherwise the Julia environment in agni_dir is activated, AGNI is imported and its log goes to agni_recent.log in Config.output_dir.

Parameters:

Name Type Description Default
vulcan_cfg Config

Run configuration; agni_dir and output_dir are used.

required

Returns:

Type Description
juliacall module

The Julia Main module.

Raises:

Type Description
FileNotFoundError

If AGNI is not loaded yet and agni.jl is not in agni_dir.

Source code in src/vulcan/agni.py
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def activate_julia(vulcan_cfg: Config):
    """
    Load AGNI into Julia, unless a caller (such as PROTEUS) has loaded it already.

    When AGNI is already loaded, its Julia environment and logger are left as they are.
    Otherwise the Julia environment in `agni_dir` is activated, AGNI is imported and its
    log goes to `agni_recent.log` in `Config.output_dir`.

    Parameters
    ----------
    vulcan_cfg : Config
        Run configuration; `agni_dir` and `output_dir` are used.

    Returns
    -------
    juliacall module
        The Julia `Main` module.

    Raises
    ------
    FileNotFoundError
        If AGNI is not loaded yet and `agni.jl` is not in `agni_dir`.
    """
    jl = _julia()
    if bool(jl.seval('isdefined(Main, :AGNI)')):
        log.info('AGNI is already loaded; using it as it is')
        return jl

    root = agni_dir(vulcan_cfg)
    if not os.path.isfile(os.path.join(root, 'agni.jl')):
        raise FileNotFoundError(os.path.join(root, 'agni.jl'))

    log.info(f'Activating Julia environment {root}')
    jl.seval('using Pkg')
    jl.Pkg.activate(root)
    jl.seval('ENV["GKSwstype"] = "100"')
    jl.seval('using Plots')
    jl.seval('default(label=nothing, dpi=250)')
    jl.seval('import AGNI')

    # AGNI keeps this log file open for the whole run
    logpath = os.path.join(vulcan_cfg.output_dir, AGNI_LOGFILE_NAME)
    jl.AGNI.setup_logging(logpath, 2)
    log.debug("AGNI will log to '%s'" % logpath)
    return jl

agni_dir(vulcan_cfg)

AGNI folder: agni_dir from the config, or VULCAN/AGNI when that is empty.

Parameters:

Name Type Description Default
vulcan_cfg Config

Run configuration; agni_dir is used.

required

Returns:

Type Description
str

Path to the AGNI folder.

Source code in src/vulcan/agni.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def agni_dir(vulcan_cfg: Config) -> str:
    """
    AGNI folder: `agni_dir` from the config, or `VULCAN/AGNI` when that is empty.

    Parameters
    ----------
    vulcan_cfg : Config
        Run configuration; `agni_dir` is used.

    Returns
    -------
    str
        Path to the AGNI folder.
    """
    return vulcan_cfg.agni_dir or paths.AGNI_DIR

climate_update(atmos)

The temperature and eddy diffusion of an AGNI atmosphere, in VULCAN's cgs units.

Temperature is on AGNI's layer centres and Kzz on its level edges. Pressures are converted from Pa to dyn cm-2 and Kzz from m2 s-1 to cm2 s-1.

Parameters:

Name Type Description Default
atmos Atmos_t

AGNI atmosphere.

required

Returns:

Type Description
ClimateUpdate

p [dyn cm-2] and tmp [K] on the layers, p_kzz [dyn cm-2] and kzz [cm2 s-1] on the levels.

Source code in src/vulcan/agni.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
def climate_update(atmos) -> ClimateUpdate:
    """
    The temperature and eddy diffusion of an AGNI atmosphere, in VULCAN's cgs units.

    Temperature is on AGNI's layer centres and Kzz on its level edges. Pressures are
    converted from Pa to dyn cm-2 and Kzz from m2 s-1 to cm2 s-1.

    Parameters
    ----------
    atmos : AGNI.atmosphere.Atmos_t
        AGNI atmosphere.

    Returns
    -------
    ClimateUpdate
        `p` [dyn cm-2] and `tmp` [K] on the layers, `p_kzz` [dyn cm-2] and `kzz`
        [cm2 s-1] on the levels.
    """
    return ClimateUpdate(
        p=np.asarray(atmos.p, dtype=float) * PA_TO_DYN,
        tmp=np.asarray(atmos.tmp, dtype=float),
        p_kzz=np.asarray(atmos.pl, dtype=float) * PA_TO_DYN,
        kzz=np.asarray(atmos.Kzz, dtype=float) * M2_TO_CM2,
    )

deallocate_atmos(atmos)

Deallocate an AGNI atmosphere.

Parameters:

Name Type Description Default
atmos Atmos_t

The atmosphere to deallocate.

required
Source code in src/vulcan/agni.py
226
227
228
229
230
231
232
233
234
235
def deallocate_atmos(atmos):
    """
    Deallocate an AGNI atmosphere.

    Parameters
    ----------
    atmos : AGNI.atmosphere.Atmos_t
        The atmosphere to deallocate.
    """
    _julia().AGNI.atmosphere.deallocate_b(atmos)

init_agni_atmos(vulcan_cfg, atm, var)

Set up and allocate an AGNI atmosphere on VULCAN's pressure range.

The composition starts from VULCAN's column-median mixing ratios, leaving out species with '_' in their name (condensates and excited states), and the temperature from VULCAN's profile (set_temperature). The instellation comes from _instellation [W m-2]. AGNI gets the boundary pressures atm.pico[0] and atm.pico[-1] in bar, gravity and planet radius in SI, and Config.sl_angle in degrees.

A runtime.sf spectral file in Config.output_dir is used unchanged when it exists; otherwise AGNI makes it from Config.spectral_file in agni_dir and the stellar spectrum. With spectral_file = 'greygas', AGNI uses its grey-gas scheme instead of a spectral file. FastChem files go to agni_fastchem in Config.output_dir.

Parameters:

Name Type Description Default
vulcan_cfg Config

Run configuration.

required
atm AtmData

Atmosphere data; reads pico [dyn cm-2], pco [dyn cm-2] and Tco [K].

required
var Variables

Model variables; reads ymix.

required

Returns:

Type Description
Atmos_t

The allocated AGNI atmosphere.

Raises:

Type Description
ValueError

If spectral_file = 'greygas' is combined with use_rayleigh.

RuntimeError

If AGNI fails to set up or allocate the atmosphere.

Source code in src/vulcan/agni.py
123
124
125
126
127
128
129
130
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
def init_agni_atmos(vulcan_cfg: Config, atm, var):
    """
    Set up and allocate an AGNI atmosphere on VULCAN's pressure range.

    The composition starts from VULCAN's column-median mixing ratios, leaving out species
    with '_' in their name (condensates and excited states), and the temperature from
    VULCAN's profile (`set_temperature`). The instellation comes from `_instellation`
    [W m-2]. AGNI gets the boundary pressures `atm.pico[0]` and `atm.pico[-1]` in bar,
    gravity and planet radius in SI, and `Config.sl_angle` in degrees.

    A `runtime.sf` spectral file in `Config.output_dir` is used unchanged when it exists;
    otherwise AGNI makes it from `Config.spectral_file` in `agni_dir` and the stellar
    spectrum. With `spectral_file = 'greygas'`, AGNI uses its grey-gas scheme instead of
    a spectral file. FastChem files go to `agni_fastchem` in `Config.output_dir`.

    Parameters
    ----------
    vulcan_cfg : Config
        Run configuration.
    atm : store.AtmData
        Atmosphere data; reads `pico` [dyn cm-2], `pco` [dyn cm-2] and `Tco` [K].
    var : store.Variables
        Model variables; reads `ymix`.

    Returns
    -------
    AGNI.atmosphere.Atmos_t
        The allocated AGNI atmosphere.

    Raises
    ------
    ValueError
        If `spectral_file = 'greygas'` is combined with `use_rayleigh`.
    RuntimeError
        If AGNI fails to set up or allocate the atmosphere.
    """
    if vulcan_cfg.spectral_file == 'greygas' and vulcan_cfg.use_rayleigh:
        raise ValueError('AGNI does not support Rayleigh scattering with greygas')
    from .chem_funs import spec_list

    jl = _julia()
    log.debug('New AGNI atmosphere')
    atmos = jl.AGNI.atmosphere.Atmos_t()

    sflux_path = vulcan_cfg.sflux_file
    try_spfile = os.path.join(vulcan_cfg.output_dir, 'runtime.sf')
    if os.path.exists(try_spfile):
        input_sf, input_star = try_spfile, ''  # AGNI made it in an earlier run
    elif vulcan_cfg.spectral_file == 'greygas':
        input_sf, input_star = 'greygas', sflux_path
    else:
        input_sf = os.path.join(agni_dir(vulcan_cfg), vulcan_cfg.spectral_file)
        input_star = sflux_path

    # condensates and excited states carry an underscore
    vol_dict = {
        g: float(np.median(var.ymix[:, i])) for i, g in enumerate(spec_list) if '_' not in g
    }

    fastchem_work = os.path.join(vulcan_cfg.output_dir, 'agni_fastchem')
    os.makedirs(fastchem_work, exist_ok=True)

    succ = jl.AGNI.atmosphere.setup_b(
        atmos,
        agni_dir(vulcan_cfg),
        vulcan_cfg.output_dir,
        input_sf,
        _instellation(vulcan_cfg),
        float(vulcan_cfg.f_diurnal),
        0.0,
        float(vulcan_cfg.sl_angle * 180.0 / np.pi),
        float(vulcan_cfg.Tsurf_guess),
        float(vulcan_cfg.gs * 0.01),  # cm s-2 to m s-2
        float(vulcan_cfg.Rp * 0.01),  # cm to m
        int(vulcan_cfg.agni_nlev),
        float(atm.pico[0] * 1e-6),  # dyn cm-2 to bar
        float(atm.pico[-1] * 1e-6),
        vol_dict,
        '',
        flag_rayleigh=bool(vulcan_cfg.use_rayleigh),
        flag_cloud=False,
        overlap_method='ee',
        albedo_s=float(vulcan_cfg.surf_albedo),
        surface_material='greybody',
        condensates=[],
        use_all_gases=False,
        fastchem_work=fastchem_work,
        real_gas=False,
        skin_d=0.01,
        skin_k=2.0,
        tmp_magma=float(vulcan_cfg.Tsurf_guess),
        tmp_floor=50.0,
        flux_int=float(vulcan_cfg.agni_flux_int),
    )
    if not succ:
        raise RuntimeError('Could not initialise AGNI atmos object')
    if not jl.AGNI.atmosphere.allocate_b(atmos, input_star):
        raise RuntimeError('Could not allocate AGNI atmos object')

    set_temperature(atmos, atm.pco, atm.Tco)
    return atmos

set_composition(atmos, pco, species, ymix)

Give an AGNI atmosphere VULCAN's mixing ratio profiles (see map_composition).

A gas that VULCAN lacks keeps its profile from before condensation (gas_ovmr).

Parameters:

Name Type Description Default
atmos Atmos_t

AGNI atmosphere; gas_vmr and gas_ovmr are updated in place.

required
pco ndarray

VULCAN layer-centre pressures [dyn cm-2].

required
species list of str

VULCAN species names, the columns of ymix.

required
ymix ndarray

VULCAN volume mixing ratios, [dimensionless], shape (nz, ni).

required
Source code in src/vulcan/agni.py
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
def set_composition(atmos, pco, species: list[str], ymix):
    """
    Give an AGNI atmosphere VULCAN's mixing ratio profiles (see `map_composition`).

    A gas that VULCAN lacks keeps its profile from before condensation (`gas_ovmr`).

    Parameters
    ----------
    atmos : AGNI.atmosphere.Atmos_t
        AGNI atmosphere; `gas_vmr` and `gas_ovmr` are updated in place.
    pco : np.ndarray
        VULCAN layer-centre pressures [dyn cm-2].
    species : list of str
        VULCAN species names, the columns of `ymix`.
    ymix : np.ndarray
        VULCAN volume mixing ratios, [dimensionless], shape (nz, ni).
    """
    # gas_ovmr, not the rained-out gas_vmr, so a gas VULCAN lacks keeps its full inventory
    current = {str(g): np.asarray(atmos.gas_ovmr[g], dtype=float) for g in atmos.gas_names}
    p_layers = np.asarray(atmos.p, dtype=float) * PA_TO_DYN
    for gas, prof in map_composition(pco, species, ymix, p_layers, current).items():
        atmos.gas_vmr[gas][:] = prof
        atmos.gas_ovmr[gas][:] = prof

set_temperature(atmos, pco, tco)

Set the AGNI temperature profile from VULCAN's.

The temperature is interpolated in log pressure onto AGNI's layers and levels (see vulcan.climate.interp_logp); the surface temperature is that of the last AGNI level. AGNI's layer properties are then recomputed.

Parameters:

Name Type Description Default
atmos Atmos_t

AGNI atmosphere, updated in place.

required
pco ndarray

VULCAN layer-centre pressures [dyn cm-2].

required
tco ndarray

VULCAN temperatures on pco [K].

required
Source code in src/vulcan/agni.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
def set_temperature(atmos, pco, tco):
    """
    Set the AGNI temperature profile from VULCAN's.

    The temperature is interpolated in log pressure onto AGNI's layers and levels (see
    `vulcan.climate.interp_logp`); the surface temperature is that of the last AGNI
    level. AGNI's layer properties are then recomputed.

    Parameters
    ----------
    atmos : AGNI.atmosphere.Atmos_t
        AGNI atmosphere, updated in place.
    pco : np.ndarray
        VULCAN layer-centre pressures [dyn cm-2].
    tco : np.ndarray
        VULCAN temperatures on `pco` [K].
    """
    p_layers = np.asarray(atmos.p, dtype=float) * PA_TO_DYN
    p_levels = np.asarray(atmos.pl, dtype=float) * PA_TO_DYN
    atmos.tmp[:] = interp_logp(pco, tco, p_layers)
    atmos.tmpl[:] = interp_logp(pco, tco, p_levels)
    atmos.tmp_surf = float(atmos.tmpl[-1])
    _julia().AGNI.atmosphere.calc_layer_props_b(atmos)