Skip to content

State API ​

For narrative coverage including the dry-basis contract and the tracer accessor surface, see State & basis.

AtmosTransport.State Module
julia
State

Prognostic and diagnostic state containers for the basis-explicit transport architecture.

Provides:

  • CellState — cell-centered air mass + conservative tracer storage

  • AbstractFaceFluxState hierarchy — face mass fluxes

    • AbstractStructuredFaceFluxState → StructuredFaceFluxState (am, bm, cm)

    • AbstractUnstructuredFaceFluxState → FaceIndexedFluxState

  • Tracer allocation and mixing-ratio utilities

source
AtmosTransport.State.AbstractCellState Type

Common basis-tagged prognostic state interface for structured and panel storage.

source
AtmosTransport.State.AbstractFaceFluxState Type
julia
AbstractFaceFluxState

Root type for all face-centered mass flux representations.

The transport operator contract is written in terms of this abstract type. Concrete subtypes differ in storage layout to match the mesh's natural flux_topology, and carry a Basis <: AbstractMassBasis type parameter to enforce moist/dry safety.

source
AtmosTransport.State.AbstractMassBasis Type
julia
AbstractMassBasis

Supertype for mass-basis tags carried by cell and face-flux states.

source
AtmosTransport.State.AbstractStructuredFaceFluxState Type
julia
AbstractStructuredFaceFluxState <: AbstractFaceFluxState

Face fluxes stored as separate directional arrays on a logically rectangular mesh. Concrete subtypes expose am (x-face), bm (y-face), cm (z-face).

Structured cell-loop kernels access these arrays directly for performance.

source
AtmosTransport.State.AbstractSurfacePressureBasis Type

Typed interpretation of a transport binary's stored surface pressure.

source
AtmosTransport.State.AbstractUnstructuredFaceFluxState Type
julia
AbstractUnstructuredFaceFluxState <: AbstractFaceFluxState

Face fluxes stored as a single face-indexed array with explicit connectivity. Natural for reduced Gaussian and other unstructured meshes.

source
AtmosTransport.State.CellState Type
julia
CellState{Basis, A, Raw, Names}

Cell-centered prognostic state for transport.

Fields

  • air_mass :: A — air mass per cell [kg] on the basis carried by Basis. Layout matches grid: (Nx, Ny, Nz) for structured, (ncells, Nz) for unstructured.

  • tracers_raw :: Raw — packed model tracer storage, conventionally dry VMR × dry-air mass (not physical kg species). Shape is (size(air_mass)..., Nt): (Nx, Ny, Nz, Nt) on structured grids, (ncells, Nz, Nt) on face-indexed grids. Kernels dispatch directly on this field; non-kernel code uses the accessor API (ntracers, get_tracer, eachtracer).

  • tracer_names :: Names — NTuple{Nt, Symbol} of tracer names in storage order.

Property access

state.tracers returns a lazy TracerAccessor that forwards state.tracers.CO2 to get_tracer(state, :CO2) (a selectdim view into tracers_raw).

Invariant

After each closed transport step, sum(air_mass) and the per-tracer storage sum sum(view(tracers_raw, ..., t)) must each be conserved (within floating-point tolerance).

source
AtmosTransport.State.CellState Method
julia
CellState(m::AbstractArray; tracers...)

Convenience constructor: CellState(m; CO2=rm_co2, SF6=rm_sf6). Defaults to DryBasis. The input 3D/2D arrays are COPIED into the packed tracers_raw buffer at construction — they are not aliased. Use get_tracer(state, :CO2) (or state.tracers.CO2) to read or mutate the stored tracer after construction.

source
AtmosTransport.State.CellState Method
julia
CellState(::Type{B}, air_mass, tracers_raw, tracer_names)

Direct construction from already-packed storage. Used by adaptation and low-level code that has a 4D buffer in hand.

source
AtmosTransport.State.CubedSphereFaceFluxState Type
julia
CubedSphereFaceFluxState{Basis}(am, bm, cm)

Six-panel, halo-padded directional mass-flux storage for cubed-sphere transport. Each tuple contains one structured directional array per panel and uses the same mass basis as CubedSphereState.

source
AtmosTransport.State.CubedSphereState Type
julia
CubedSphereState{Basis, A3, Raw4, Names}
CubedSphereState(Basis, mesh, air_mass; tracers...)
CubedSphereState(Basis, air_mass; halo_width, tracers...)

Panel-native prognostic state. Air mass is stored as six halo-padded three-dimensional panels. Tracers are packed into one trailing tracer axis on each panel, with names retained in storage order. Diagnostics and global sums exclude halos.

Fields

  • air_mass :: NTuple{CS_PANEL_COUNT, A3} — halo-padded panel air mass arrays with shape (Nc + 2Hp, Nc + 2Hp, Nz).

  • tracers_raw :: NTuple{CS_PANEL_COUNT, Raw4} — packed per-panel model tracer storage (conventionally dry VMR × dry-air mass, not physical kg species) with shape (Nc + 2Hp, Nc + 2Hp, Nz, Nt).

  • tracer_names :: Names — names of the tracer axis in storage order.

  • halo_width :: Int — halo width Hp needed to recover the physical interior.

source
AtmosTransport.State.DryBasis Type
julia
DryBasis <: AbstractMassBasis

Tag for dry-air mass.

source
AtmosTransport.State.DrySurfacePressure Type

Stored ps is the column dry-air pressure implied by the dry air mass.

source
AtmosTransport.State.FaceIndexedFluxState Type
julia
FaceIndexedFluxState{Basis}(horizontal_flux, cm)

Prepared substep mass transport for a connected-face mesh. Horizontal storage has shape (nfaces, Nz), while vertical storage has shape (ncells, Nz+1). Positive horizontal flux follows the mesh face orientation.

source
AtmosTransport.State.MoistBasis Type
julia
MoistBasis <: AbstractMassBasis

Tag for total-air / moist mass.

source
AtmosTransport.State.StructuredFaceFluxState Type
julia
StructuredFaceFluxState{Basis}(am, bm, cm)

Prepared substep mass transport on a logically rectangular grid. Arrays use shapes (Nx+1, Ny, Nz), (Nx, Ny+1, Nz), and (Nx, Ny, Nz+1). Positive horizontal fluxes point east/north; positive vertical flux points toward increasing level index. Basis must match the prognostic state.

source
AtmosTransport.State.TotalSurfacePressure Type

Stored ps is the total (moist-air) pressure used by the hybrid coordinate.

source
AtmosTransport.State.TracerAccessor Type
julia
TracerAccessor{S}

Lazy, allocation-free wrapper that forwards property-style tracer access (state.tracers.CO2) to get_tracer(state, :CO2). Returned by getproperty(::CellState, :tracers). Reading a tracer that does not exist throws KeyError.

state.tracers[:CO2] is also supported and forwards to get_tracer(state, :CO2) for code that prefers index syntax.

source
AtmosTransport.State.allocate_face_fluxes Method
julia
allocate_face_fluxes(::FaceIndexedFluxTopology, nfaces, ncells, Nz;
                     FT=Float64, ArrayType=Array,
                     basis::Type{<:AbstractMassBasis}=DryBasis)

Allocate zeroed face-indexed flux arrays for a connected-face mesh.

source
AtmosTransport.State.allocate_face_fluxes Method
julia
allocate_face_fluxes(::StructuredFluxTopology, Nx, Ny, Nz;
                     FT=Float64, ArrayType=Array,
                     basis::Type{<:AbstractMassBasis}=DryBasis)

Allocate zeroed face flux arrays for a structured mesh. The returned StructuredFaceFluxState is tagged with the specified basis.

source
AtmosTransport.State.allocate_face_fluxes Method
julia
allocate_face_fluxes(mesh::AbstractHorizontalMesh, Nz; kwargs...)

Allocate a flux container using the mesh's natural face-connected topology.

source
AtmosTransport.State.allocate_face_fluxes Method
julia
allocate_face_fluxes(mesh::AbstractStructuredMesh, Nz; kwargs...)

Allocate a flux container using the mesh's natural structured topology.

source
AtmosTransport.State.allocate_tracers Method
julia
allocate_tracers(names::NTuple{N, Symbol}, Nx, Ny, Nz;
                 FT=Float64, ArrayType=Array, fill_value=zero(FT))

Allocate a NamedTuple of 3D model tracer-storage arrays. Still useful for test fixtures that want to pre-build per-tracer 3D arrays for a CellState(m; tracers...) keyword-form constructor call.

source
AtmosTransport.State.basis_symbol Method

Return the canonical :dry or :moist tag for a mass basis.

source
AtmosTransport.State.eachtracer Method
julia
eachtracer(state::AbstractCellState)

Iterate name => tracer_slice pairs for every tracer in state, in storage order. The yielded shape matches the previous pairs(::NamedTuple) contract so callers that destructure for (name, rm) in eachtracer(state) continue to work.

source
AtmosTransport.State.get_tracer Method
julia
get_tracer(state::AbstractCellState, name::Symbol)
get_tracer(state::CellState, idx::Integer)

Return a view of the model tracer-storage slice. For a structured grid with state.tracers_raw :: Array{FT, 4}, this is selectdim(state.tracers_raw, 4, idx), a contiguous SubArray{FT, 3} (because Julia is column-major and the tracer axis is the slowest-varying). Mutations through the returned view are reflected in state.tracers_raw.

Throws KeyError(name) if name is not a tracer in state.

source
AtmosTransport.State.mass_basis Method
julia
mass_basis(value::Union{Symbol, AbstractString})

Parse a dry/moist tag (case insensitive). Unknown values raise ArgumentError. State and flux accessors return these same basis instances.

source
AtmosTransport.State.mass_basis Method
julia
mass_basis(state) → AbstractMassBasis

Return the mass flux basis tag for the given flux state.

source
AtmosTransport.State.mixing_ratio Method
julia
mixing_ratio(state::CellState, name::Symbol)

Compute mixing ratio q = tracer_storage / air_mass for the named tracer.

source
AtmosTransport.State.ntracers Method
julia
ntracers(state::CellState) -> Int

Number of tracers carried by state.

source
AtmosTransport.State.panel_interior Method

Physical interior of a three-dimensional panel, with halos excluded.

source
AtmosTransport.State.panel_interior Method

Physical panel interior, excluding Hp halo cells along each horizontal axis.

source
AtmosTransport.State.set_uniform_mixing_ratio! Method
julia
set_uniform_mixing_ratio!(state::CellState, name::Symbol, χ)

Set tracer name to uniform mixing ratio χ: tracer_mass = χ × air_mass.

source
AtmosTransport.State.total_air_mass Method
julia
total_air_mass(state::CellState) -> Float64

Sum of air mass across all cells and levels (in Float64).

source
AtmosTransport.State.total_mass Method
julia
total_mass(state::CellState, name::Symbol) -> Float64

Sum the named tracer's conservative model storage across all cells and levels (in Float64, whatever the storage precision). For dry VMR tracers this is sum(χ_dry × dry_air_mass), not physical kg species unless an explicit molecular-weight conversion is applied.

source
AtmosTransport.State.tracer_index Method
julia
tracer_index(state::AbstractCellState, name::Symbol) -> Union{Int, Nothing}

Index of the tracer named name in state.tracer_names, or nothing if absent.

source
AtmosTransport.State.tracer_name Method
julia
tracer_name(state::CellState, idx::Integer) -> Symbol

Name of the tracer at index idx. Throws BoundsError if out of range.

source
AtmosTransport.State.tracer_names Method
julia
tracer_names(state::AbstractCellState) -> NTuple{Nt, Symbol}

Names of all tracers in state, in stored order.

source

Fields ​

Time-varying and panel-wise field types used by State (Kz caches, profile fields, PBL parameters, …).

AtmosTransport.State.Fields Module
julia
Fields

Time-varying field abstraction.

AbstractTimeVaryingField{FT, N} is the common interface presented to physics operators for rate-like and field-like inputs (chemistry decay rates, Kz diffusion fields, ...). Concrete types back different sources — constant, stepwise from file, derived from meteorology — with the same kernel code downstream.

Required interface (every concrete type):

  • field_value(f, idx::NTuple{N, Int}) -> FT — kernel-safe read

  • update_field!(f, t::Real) -> f — refresh caches for time t

Concrete types:

  • ConstantField{FT, N} — one scalar presented as a rank-N field.

  • PreComputedKzField{FT, A} — rank-2/3 wrapper over a spatial array.

  • GCHPNonlocalPBLField{FT, ...} — cubed-sphere GEOS-Chem non-local PBL exchange.

  • StepwiseField{FT, N, A, B, W} — piecewise-constant in time at any rank.

source
AtmosTransport.State.Fields.AbstractCSDkgField Type
julia
AbstractCSDkgField{FT}

Cubed-sphere diffusion fields that supply interface air-mass exchange dkg [kg s⁻¹] directly to the conservative implicit solver (panel_field(f, p) returns a rank-3 (Nc, Nc, Nz) field; the last level is the zero-flux surface).

source
AtmosTransport.State.Fields.AbstractCubedSphereField Type
julia
AbstractCubedSphereField{FT}

Panel-native field contract for cubed-sphere operators.

Unlike AbstractTimeVaryingField, which describes a single rank-N spatial field, cubed-sphere runtime paths keep the panel boundary explicit. A concrete cubed-sphere field therefore owns one structured rank-3 field per panel and exposes them through panel_field.

source
AtmosTransport.State.Fields.AbstractTimeVaryingField Type
julia
AbstractTimeVaryingField{FT, N}

Common interface for rate-like / field-like inputs to physics operators. FT <: AbstractFloat is the element type; N :: Int is the spatial rank (0 = scalar, 2 = surface, 3 = volume).

See field_value and update_field! for the required methods.

source
AtmosTransport.State.Fields.ConstantField Type
julia
ConstantField{FT, N}(value)

A scalar value presented as an AbstractTimeVaryingField{FT, N}. field_value ignores its index and returns value. update_field! is a no-op. Storage is one scalar; backend-agnostic by construction.

Examples

julia
rate    = ConstantField{Float64, 0}(2.098e-6)   # chemistry decay rate
kz_test = ConstantField{Float32, 3}(1.0f0)      # idealized diffusion Kz
source
AtmosTransport.State.Fields.CubedSphereField Type
julia
CubedSphereField{FT, F}(panels::NTuple{6, F})

Panel-native cubed-sphere field wrapper.

Each panel field must satisfy the standard structured field contract:

  • panel_field(f, p) isa AbstractTimeVaryingField{FT, 3}

  • field_value(panel_field(f, p), (i, j, k)) -> FT

  • update_field!(panel_field(f, p), t)

This keeps the cubed-sphere operator boundary honest without forcing a fake global 4D/5D field abstraction onto code that already runs panel by panel.

source
AtmosTransport.State.Fields.GCHPNonlocalPBLField Type
julia
GCHPNonlocalPBLField(Nc, Nz, FT; params = GCHPVdiffParameters{FT}())

GEOS-Chem's non-local PBL mixing on the cubed sphere, refreshed every met window from the archived PBL height, surface fluxes (hflux, eflux, ustar) and the VDIFF profiles (u, v, t, qv):

  • dkg — dry-air exchange A ρ K / Δz [kg s⁻¹] between top-down layers k and k+1 (TM5 convention; zero at the surface), solved by the conservative implicit :dkg diffusion. K is GEOS-Chem's: a Richardson-number closure in the free troposphere and the Holtslag–Boville profile inside the PBL.

  • emission_profile — the fraction of a column's fresh surface emission that each layer receives: GEOS-Chem's counter-gradient term ∂(ρ K γ)/∂z, with γ = cgs · F/ρ_sfc, is linear in the surface flux F, so it moves the fraction w = ρ K cgs / ρ_sfc of each step's emission upward through every interface. Layer k keeps w_below − w_above; the fractions sum to one.

GEOS-Chem mixes on moist air and closes the column with a mass fix; here the exchange uses the dry density, so the implicit solve is conservative by construction.

source
AtmosTransport.State.Fields.GCHPVdiffParameters Type
julia
GCHPVdiffParameters{FT}()

Constants of GEOS-Chem's non-local boundary-layer scheme (vdiff_mod.F90, after Holtslag & Boville 1993, J. Climate 6, 1825), with GEOS-Chem's physical constants (physconstants.F90).

source
AtmosTransport.State.Fields.PreComputedKzField Type
julia
PreComputedKzField{FT, N, A}(data::AbstractArray{FT, N})

A rank-2/3 AbstractTimeVaryingField{FT, N} backed directly by a spatial array. field_value(f, idx) returns f.data[idx...] — the no-abstraction path for Kz profiles read from a pre-computed source (met binary snapshot, GCHP-style 3D diffusivity export, etc.).

Time variation, if any, is handled by the caller: mutate f.data in place when the current met window advances, then call (or skip) update_field! — this method is a no-op and does not own the storage. A more structured stepwise-in-time backing (e.g. a 4D buffer with an internal window index) can be added later as a separate concrete type; keeping this one minimal makes the contract transparent.

Backend

A <: AbstractArray{FT, N} is parametric: Array{FT, N} for CPU, CuArray{FT, N} / MtlArray{FT, N} for GPU runs. field_value indexes the array element-wise, which is kernel-safe on all three backends.

Examples

julia
# CPU: static 3D Kz snapshot
Kz = fill(1.0, 144, 72, 34)
f  = PreComputedKzField(Kz)

field_value(f, (1, 1, 1))      # 1.0
field_value(f, (144, 72, 34))  # 1.0

# Updating the snapshot between met windows (caller-owned)
Kz .= 2.0
field_value(f, (1, 1, 1))      # 2.0  — same f, updated data
source
AtmosTransport.State.Fields.PrecomputedCSDkgField Type
julia
PrecomputedCSDkgField(host_cache)

Cubed-sphere interface air-mass exchange field loaded from a binary :dkg payload. dkg[i,j,k] is the TM5 vertical-diffusion exchange rate [kg s⁻¹] between top-down layers k and k+1; the final level is the zero-flux surface boundary.

Unlike a Kz field, this payload already includes the preprocessing-time layer mass and virtual-temperature geometry. The runtime must therefore consume it directly rather than reconstructing an interface coefficient from layer-centre Kz and a second, potentially inconsistent, dz profile.

source
AtmosTransport.State.Fields.StepwiseField Type
julia
StepwiseField{FT, N, A, B, W}(samples, boundaries, current_window)

A rank-N AbstractTimeVaryingField{FT, N} that is piecewise-constant in time. Stores a sequence of N_win spatial snapshots plus N_win + 1 window boundaries. field_value reads from the snapshot for the window containing the current time; update_field!(f, t) binary- searches the boundaries and caches the index of the current window.

Designed for CATRINE-style emission inventories that arrive as window- averaged values (monthly, annual, weekly). The sample for window n is the average value over [boundaries[n], boundaries[n+1]).

Layout

julia
samples     :: AbstractArray{FT, N + 1}   # rank N + 1
                                          # last dim iterates over windows
                                          # size(samples)[1:N] = spatial shape
                                          # size(samples, N+1) = N_win
boundaries  :: AbstractVector{<:Real}     # length N_win + 1, sorted
                                          # boundaries[n], boundaries[n+1]
                                          # bound window n
current_window :: AbstractVector{Int}     # length 1, holds the index that
                                          # `field_value` reads

The spatial prefix of samples matches the field's rank: rank-2 field → samples::AbstractArray{FT, 3} with shape (Nx, Ny, N_win). Rank-3 field → samples::AbstractArray{FT, 4} with (Nx, Ny, Nz, N_win).

Why current_window is a 1-element array

Base.RefValue{Int} would be the idiomatic mutable Int cache, but it is not kernel-safe on GPU — a Ref dereference inside a KA kernel pulls from host memory. Storing the index in a 1-element array lets Adapt.adapt convert it to device storage alongside samples, so the kernel reads current_window[1] as a device-local memory access. Overhead: one extra device load per field_value call, broadcast across all kernel threads (same value for every thread), effectively free.

Kernel-safety

After update_field!(f, t) has been called by the operator, the kernel can call field_value(f, idx) freely. The call is allocation-free and type-stable. The operator is responsible for calling update_field! on the host before launching the kernel.

Out-of-bounds time

update_field!(f, t) with t < boundaries[1] or t >= boundaries[end] throws an ArgumentError. This is stricter than clamping but avoids silently extrapolating the first/last window — which would bias emission totals. Callers that need cyclic coverage can wrap in a CyclicField (future plan) or extend boundaries explicitly.

Examples

julia
# Rank-2 (surface) StepwiseField: monthly CO2 emission inventory
# over 12 months, Nx × Ny = 144 × 72.
samples    = rand(144, 72, 12)                        # kg/s per cell
boundaries = [FT(m * 30 * 86400) for m in 0:12]       # month starts, seconds
f          = StepwiseField(samples, boundaries)

update_field!(f, 15.0 * 86400)   # day 15 → window 1
field_value(f, (10, 20))         # = samples[10, 20, 1]

update_field!(f, 65.0 * 86400)   # day 65 → window 3
field_value(f, (10, 20))         # = samples[10, 20, 3]

Adapt / GPU

julia
using CUDA, Adapt
f_gpu = Adapt.adapt(CuArray, f)
# f_gpu.samples isa CuArray{FT, 3}
# f_gpu.current_window isa CuArray{Int, 1}
# field_value(f_gpu, (i, j)) now kernel-safe on GPU
source
AtmosTransport.State.Fields.StepwiseField Method
julia
StepwiseField(samples, boundaries, current_window)

Three-argument form that preserves an explicit current_window buffer. Primarily used by Adapt.adapt_structure to carry the cached window index across a host → device conversion without losing state.

source
AtmosTransport.State.Fields.StepwiseField Method
julia
StepwiseField(samples, boundaries)

Outer convenience constructor. Infers FT from eltype(samples) and N from ndims(samples) - 1. Initializes current_window = [1]; the first call to update_field!(f, t) sets the real index.

source
AtmosTransport.State.Fields.field_value Function
julia
field_value(f::AbstractTimeVaryingField{FT, N}, idx::NTuple{N, Int}) -> FT

Return the field's current value at spatial index idx.

Contract (kernel-safe): allocation-free, type-stable, pure with respect to f. Called from inside KernelAbstractions kernels. For N = 0, idx is the empty tuple ().

Every concrete subtype of AbstractTimeVaryingField must implement a method of field_value.

source
AtmosTransport.State.Fields.panel_field Function
julia
panel_field(f, p) -> AbstractTimeVaryingField

Return the per-panel field stored at panel index p (1..6) inside an AbstractCubedSphereField. Subtypes implement this to expose their panel storage.

source
AtmosTransport.State.Fields.update_field! Function
julia
update_field!(f::AbstractTimeVaryingField, t::Real) -> f

Refresh any caches so that subsequent field_value calls return the field's value at simulation time t. Runs on the host (not kernel- safe itself); may be expensive for derived fields. Called once per apply! by an operator, before any kernel launch that reads the field.

For time-independent fields (e.g. ConstantField), this is a no-op. Returns f for chaining.

source
AtmosTransport.State.Fields.update_field! Method
julia
update_field!(f::StepwiseField, t::Real) -> f

Binary-search f.boundaries for the window n such that f.boundaries[n] <= t < f.boundaries[n+1] and cache n into f.current_window[1]. Host-side; not kernel-safe itself.

Throws ArgumentError if t is outside [f.boundaries[1], f.boundaries[end]).

source