Preprocessing API
For narrative coverage of the source × target dispatch model and per-source pipelines, see Preprocessing overview and the per-source pages ERA5 spectral path and GEOS native cubed-sphere.
AtmosTransport.Preprocessing Module
PreprocessingTransport binary generation from meteorological input.
Converts raw meteorology into mass-balanced transport binaries ready for the runtime TransportBinaryDriver. Supported sources and targets:
ERA5 spectral GRIB (VO, D, LNSP) → lat-lon, reduced-Gaussian, or cubed sphere
GEOS native cubed-sphere NetCDF (GEOS-IT, GEOS-FP) → cubed sphere (same resolution or nested block coarsening)
ERA5 N320 native GRIB → cubed sphere (conservative regrid)
MERRA-2 lat-lon NetCDF → cubed sphere (conservative regrid)
an existing lat-lon transport binary → cubed sphere (
regrid_transport_binary)
Architecture
The pipeline dispatches on AbstractTargetGeometry subtypes:
AbstractTargetGeometry
├── LatLonTargetGeometry — regular lat-lon (any Nx × Ny)
├── ReducedGaussianTargetGeometry — native ERA5 RG (O90, O160, N320, …)
└── CubedSphereTargetGeometry — convention-aware CS (C24, C90, C180, …)and on the source settings type. Each supported pair has a process_day method:
process_day(date, grid::LatLonTargetGeometry, settings::ERA5SpectralSettings, vertical; …)
process_day(date, grid::ReducedGaussianTargetGeometry, settings::ERA5SpectralSettings, vertical; …)
process_day(date, grid::CubedSphereTargetGeometry, settings::ERA5SpectralSettings, vertical; …)
process_day(date, grid::CubedSphereTargetGeometry, settings::AbstractGEOSSettings, vertical; …)
process_day(date, grid::CubedSphereTargetGeometry, settings::AbstractERA5GRIBSettings, vertical; …)
process_day(date, grid::CubedSphereTargetGeometry, settings::MERRA2Settings, vertical; …)ERA5 spectral pipeline (per day)
Read ERA5 spectral GRIB (VO, D, LNSP) —
spectral_io.jlSpectral synthesis (Legendre + FFT → gridpoint) —
spectral_synthesis.jlMerge native 137L → transport levels —
vertical_coordinates.jlPin global mean ps (mass fix) —
pin_global_mean_ps!/pin_global_mean_ps_using_qv!inmass_support.jlColumn Poisson balance of the horizontal mass fluxes (header key
horizontal_balance = "column"): one Poisson solve for the column-integrated divergence against the column mass tendency, each face's correction spread over the layers by the column weights (spread_column_correction!; air mass in hybrid layers by default), socmkeeps the vertical motion:
LL: FFT Poisson solve —
balance_column_mass_fluxes!,mass_support.jlRG: compressed-Laplacian CG —
balance_compressed_column_fluxes!,ring_poisson_balance.jlCS: global 6-panel graph-Laplacian CG —
balance_cs_column_mass_fluxes!,cs_poisson_balance.jl
Diagnose
cmfrom explicit endpoint mass targets — replay continuityWrite transport binary with declared payload semantics and replay checks
The GEOS, ERA5 N320, MERRA-2, and binary-regrid paths implement their own mass construction or regridding, flux balancing, and cm diagnosis (with an optional dry-mass pin where the source has one); every path ends in the same write-time replay and positivity gates.
Target workflows are the submodules LatLonTarget, ReducedGaussianTarget and CubedSphereTarget (folders Targets/LatLon, Targets/ReducedGaussian, Targets/CubedSphere); shared binary APIs live in TransportBinary. Native readers and day drivers live in the independent GEOS, ERA5 and MERRA2 submodules under Sources/. The parent owns only entrypoint dispatch.
Usage
julia --project=. scripts/preprocessing/preprocess_transport_binary.jl config.toml --day 2021-12-01Advanced users can call process_day directly from Julia.
AtmosTransport.Preprocessing.TransportBinary.process_day Method
process_day(cfg::Dict; day_override=nothing, start_date=nothing, end_date=nothing)Top-level TOML-driven preprocessor entry. Detects source type from cfg:
[source].toml = "config/met_sources/<source>.toml"→ typedAbstractMetSettingspath, supports cross-day state carry (e.g. GEOS pressure-fixer chained mass).otherwise → typed ERA5 spectral config path (
[input].spectral_dir).
Both paths accept a single day_override or a start_date/end_date range.
Both paths converge on process_day(date, grid::AbstractTargetGeometry, settings, vertical; ...) for the per-day work. There is no parallel GEOS-only or per-source CLI — new sources plug in via AbstractMetSettings + load_met_settings.
AtmosTransport.Preprocessing.Common.AbstractChainPolicy Type
Type tag for cross-day seed policy.
sourceAtmosTransport.Preprocessing.Common.AbstractColumnWeights Type
How a column mass-budget correction is spread over the levels of a column.
MassWeightedColumn(): in proportion to layer air mass (default).HybridBWeightedColumn(B): in proportion toΔB_k, the layer's share of a surface-pressure change, as in TM5. Pure-pressure layers (ΔB = 0, the stratosphere) receive none of it, so a column mismatch cannot appear in their vertical mass flux as a coherent mode proportional to pressure.HybridMassWeightedColumn(B): in proportion to layer air mass, but only in hybrid layers,ΔB_k ≥ HYBRID_LAYER_MIN_DB(1e-6); pure-pressure layers, including near-pure-pressure ones such as GEOS L72 layer 41 (ΔB = 8.2e-9), receive none of it.
AtmosTransport.Preprocessing.Common.AbstractERA5GRIBSettings Type
Abstract settings for ERA5 native GRIB meteorology.
sourceAtmosTransport.Preprocessing.Common.AbstractGEOSSettings Type
Abstract settings for GEOS native meteorology.
sourceAtmosTransport.Preprocessing.Common.AbstractMetReader Type
AbstractMetReader{FT, S, CP}Typed met-reader nominal. Bundles a met-source's settings, per-day handle context, and chained-mass-policy carry into one struct that the unified preprocessor driver dispatches on. Type parameters:
FT <: AbstractFloat— preprocessing float type (Float32for GPU,Float64for diagnostic runs).S <: AbstractMetSettings— concrete settings type (GEOSITSettings,GEOSFPSettings,ERA5SpectralSettings, …).CP <: AbstractChainPolicy—NoChainorChainedMass{T}for some seed array typeT.
Concrete readers implement open, close, and per-window access.
sourceAtmosTransport.Preprocessing.Common.AbstractMetSettings Type
AbstractMetSettingsTop-level supertype for typed met-data source descriptors used by the preprocessor. Concrete subtypes (GEOSITSettings, GEOSFPSettings, ERA5N320Settings, MERRA2Settings, ERA5SpectralSettings) carry source-specific paths and parameters and implement the parts of the read_window! / windows_per_day interface that their process_day path uses.
process_day(date, grid::AbstractTargetGeometry, settings::AbstractMetSettings, vertical; ...) dispatches on settings to pick the reader.
AtmosTransport.Preprocessing.Common.ChainedMass Type
ChainedMass{T} <: AbstractChainPolicyThe reader carries an end-of-day mass field of shape T into the next day's open. The shape T is the seed array type (e.g. NTuple{6, Array{Float32, 3}}); the actual seed VALUE lives in the reader struct, but its STATIC type is encoded here so seed access has a known type.
AtmosTransport.Preprocessing.Common.CubedSphereTargetGeometry Type
CubedSphereTargetGeometryTarget geometry for spectral→CS transport binary preprocessing. The CS mesh stores cell areas, metric terms, panel convention, and connectivity; the face table and Poisson scratch are pre-built at construction time for efficient per-window balance.
The staging_nlon × staging_nlat fields define an internal LL grid used for spectral synthesis before conservative regridding to CS panels.
AtmosTransport.Preprocessing.Common.ERA5SpectralSettings Type
ERA5SpectralSettings <: AbstractMetSettingsTyped wrapper for the historical ERA5 spectral settings NamedTuple. The spectral preprocessor still performs spectral synthesis inside the topology workspaces, but the source axis is now explicit: TOML parsing constructs this settings type and topology methods dispatch on it.
AtmosTransport.Preprocessing.Common.FlushingLogger Type
Forward log messages and flush standard output/error for redirected CLI logs.
sourceAtmosTransport.Preprocessing.Common.LatLonTargetGeometry Type
LatLonTargetGeometryStructured target geometry used by the current spectral preprocessor. Stores the LatLonMesh plus cached coordinate and metric arrays needed by the spectral-synthesis and mass-flux routines.
AtmosTransport.Preprocessing.Common.MassWeightedColumn Type
Spread a column correction in proportion to nonnegative air mass.
sourceAtmosTransport.Preprocessing.Common.NoChain Type
NoChain <: AbstractChainPolicyThe reader does not carry mass state across days. Day N starts from the raw source endpoint. The seed slot is nothing.
AtmosTransport.Preprocessing.Common.RawWindow Type
RawWindow{FT, A2, A3}Per-window source-grid intermediate carrying both window endpoints (t_n and t_{n+1}) and the window-integrated horizontal mass fluxes between them.
The right endpoint of window n is the left endpoint of window n+1, so the reader caches it across calls. For the last window of the day, the right endpoint comes from the next day's first instantaneous file (the existing next_day_hour0 plumbing in the orchestrator).
Cell-center winds u, v (geographic frame) are filled only when the target grid differs from the source grid and fluxes must be reconstructed downstream. For native passthrough (source mesh == target mesh) u/v stay nothing and am/bm are written through directly after vertical merging.
cmfmc/dtrain are filled only when the source supports convection and the user has enabled it via settings.include_convection. vdiff carries optional Holtslag-Boville VDIFF source fields (u, v, t, qv) when the source can archive them into the transport binary for runtime diffusion.
AtmosTransport.Preprocessing.Common.ReducedGaussianTargetGeometry Type
ReducedGaussianTargetGeometryGeometry descriptor for native ERA5 reduced-Gaussian grids. Target of the ERA5 spectral preprocessing path in reduced_spectral_day.jl, which writes face-indexed reduced-Gaussian transport binaries.
AtmosTransport.MetDrivers.BinaryReaders.has_pbl_eflux Method
has_pbl_eflux(settings) -> Bool
has_cmfmc_cloud_base(settings) -> BoolWhether this source writes the surface latent heat flux (GCHP non-local PBL scheme) or the convective cloud-base layer (GCHP cloud convection).
sourceAtmosTransport.MetDrivers.BinaryReaders.has_surface Method
has_surface(settings::AbstractMetSettings) -> BoolWhether this source can populate raw PBL surface fields in RawWindow.surface. Sources gate actual reads behind their settings flags.
AtmosTransport.MetDrivers.BinaryReaders.has_vdiff_fields Method
has_vdiff_fields(settings::AbstractMetSettings) -> BoolWhether this source can populate RawWindow.vdiff with layer-center fields needed by the GCHP Holtslag-Boville vertical-diffusion data contract.
AtmosTransport.Preprocessing.Common.allocate_raw_window Function
allocate_raw_window(settings::AbstractMetSettings;
FT::Type, Nc=nothing, Nz=nothing) -> RawWindowAllocate a pre-zeroed RawWindow sized for one window of settings's source data. The orchestrator calls this once before the per-window loop and reuses the same buffer across all windows in a day. The shape parameters (Nc, Nz, …) are source-specific — concrete subtypes pick the keys they need.
AtmosTransport.Preprocessing.Common.build_target_geometry Method
build_target_geometry(cfg_grid, FT=Float64) -> AbstractTargetGeometryDispatch configuration-driven target-geometry construction from the user-facing grid.type string.
AtmosTransport.Preprocessing.Common.build_target_geometry Method
build_target_geometry(::Val{:cubed_sphere}, cfg_grid, FT)Build a cubed-sphere target geometry from the [grid] config section.
Required keys:
Nc :: Int— cells per panel edge
Optional keys:
definition—"equiangular_gnomonic"(synthetic) or"gmao_equal_distance"(GEOS-IT/GEOS-FP equal-distance gnomonic)panel_convention—"gnomonic"(default) or"geos_native". Ifdefinitionis omitted,"geos_native"selects"gmao_equal_distance"and"gnomonic"selects"equiangular_gnomonic".regridder_cache_dir— directory for CR.jl weight cache (defaultRegridding.default_regrid_cache_dir(), the cache the runtime uses too)staging_nlon,staging_nlat— override the internal LL staging grid size (defaults:max(4Nc, 360)×max(2Nc+1, 181))
AtmosTransport.Preprocessing.Common.build_target_geometry Method
build_target_geometry(::Val{:era5_native_reduced_gaussian}, cfg_grid, FT)Build the reduced-Gaussian geometry metadata from a native ERA5 GRIB file. This is currently intended for geometry discovery and future native-grid preprocessing work rather than the active lat-lon synthesis path.
sourceAtmosTransport.Preprocessing.Common.build_target_geometry Method
build_target_geometry(::Val{:latlon}, cfg_grid, FT) -> LatLonTargetGeometryBuild the regular lat-lon target geometry used by the current v4 spectral preprocessor.
sourceAtmosTransport.Preprocessing.Common.build_target_geometry Method
build_target_geometry(::Val{:synthetic_reduced_gaussian}, cfg_grid, FT)Build a reduced-Gaussian target geometry from scratch without needing a source GRIB file. cfg_grid["gaussian_number"] controls the truncation N so the mesh has 2N Gauss-Legendre latitude rings. cfg_grid["nlon_mode"] selects the longitude layout:
"regular"(default): every ring has4Ncells — the classical "regular reduced" Gaussian grid used e.g. in the TL159/N80 family."octahedral": ECMWF octahedral layoutnlon = 4k + 16per hemisphere, mirrored between the two hemispheres withk = 1at the pole-adjacent ring.
Mesh latitudes are produced from FastGaussQuadrature.gausslegendre(2N), which returns ascending Gauss-Legendre nodes on (-1, 1). geometry_source_grib is left as an empty string to mark the grid as synthetic.
AtmosTransport.Preprocessing.Common.check_column_weight_levels Function
Validate that column weights match the number of layers.
sourceAtmosTransport.Preprocessing.Common.check_fixed_global_mass Method
check_fixed_global_mass(m, endpoint_or_tendency; applications=nothing, mass_type)Reject a fixed global dry-mass budget if abs(Σ(m_next-m))/Σm exceeds GLOBAL_DRY_MASS_BUDGET_RTOL. With applications, the second argument is a per-application tendency and the numerator is abs(applications * Σdm). Both reductions are compensated Float64 sums of stored values (including CS panel tuples). Expected global change is zero. Call only for a fixed dry target; moist and unpinned windows retain their physical global tendency. Stored lower precision endpoints allow 2eps(mass_type) for their independent rounding.
AtmosTransport.Preprocessing.Common.checked_mass_fix_config Method
resolve_mass_fix_settings(cfg) -> NamedTupleParse the optional global dry-surface-pressure mass-fix settings.
sourceAtmosTransport.Preprocessing.Common.close_day! Function
close_day!(ctx)Close all resources held by a day context. Must be idempotent; safe to call from a finally block.
AtmosTransport.Preprocessing.Common.close_reader! Function
close_reader!(reader::AbstractMetReader) → nothingClose all per-day file handles and release scratch held by the reader. Idempotent — safe to call from a finally block. Concrete readers implement.
AtmosTransport.Preprocessing.Common.column_weights Function
Construct configured column weights for hybrid interfaces B.
AtmosTransport.Preprocessing.Common.ensure_supported_target Method
ensure_supported_target(grid)Fail fast when the selected target geometry is known to the configuration layer but does not yet have a spectral mass-flux implementation.
sourceAtmosTransport.Preprocessing.Common.grid_kind Method
Return a symbol identifying the grid type (:latlon or :era5_native_reduced_gaussian).
AtmosTransport.Preprocessing.Common.has_convection Method
has_convection(settings::AbstractMetSettings) -> BoolWhether this source can populate RawWindow.cmfmc and RawWindow.dtrain. Defaults to false; sources that support convection override and gate the actual output behind a user flag (e.g. settings.include_convection).
AtmosTransport.Preprocessing.Common.load_met_settings Method
load_met_settings(toml_path::String; root_dir, kwargs...) -> AbstractMetSettingsConstruct a typed met-source descriptor from toml_path. The TOML's [source].name key picks the concrete settings type, and per-type build_met_settings methods consume the source-specific TOML tables.
root_dir is the on-disk directory holding the source's daily files. Additional kwargs are forwarded to the constructor and override any values supplied by the TOML.
AtmosTransport.Preprocessing.Common.log_preprocessor_configuration Method
log_preprocessor_configuration(settings, grid, vertical)Emit the human-readable startup summary for the current preprocessing run.
sourceAtmosTransport.Preprocessing.Common.native_output_filename Method
native_output_filename(settings, date, FT) -> StringOutput filename for native-source preprocessing: <prefix>transport_YYYYMMDD_float32.bin (or float64). Concrete sources extend native_output_prefix (geos_, era5_n320_, merra2_); the default prefix is empty.
AtmosTransport.Preprocessing.Common.native_output_prefix Method
Prefix used by the common native-source output filename formatter.
sourceAtmosTransport.Preprocessing.Common.open_day Function
open_day(settings::AbstractMetSettings, date::Date; ...) -> ctxOpen per-day source-specific context (file handles, caches, vertical coefficients, …). The orchestrator calls this once per day at the start of process_day, threads ctx through every read_window! call, and calls close_day!(ctx) in a finally block.
ctx is opaque to the orchestrator — only the source knows its layout.
AtmosTransport.Preprocessing.Common.open_preprocessing_staging Method
Reserve a unique staging path for a preprocessor writer.
sourceAtmosTransport.Preprocessing.Common.open_reader Function
open_reader(settings::AbstractMetSettings, date::Date, ::Type{FT};
seed = nothing, next_day_handle::Bool = true)
→ reader::AbstractMetReader{FT, typeof(settings), CP}Construct a typed met-reader for one calendar day. The reader owns the underlying day-handle context (file handles, vertical coefficients, chained-mass seed) and exposes the per-window trait surface.
seed carries cross-day mass state for chained-mass readers; pass the previous day workflow’s final_m result. For NoChain readers, seed must be nothing.
next_day_handle controls whether the reader opens a handle into the next day's first-hour instantaneous file. Required when the day produces endpoint mass for the last window (the standard case for hourly sources).
Dispatch by settings type to select the concrete reader; concrete readers register their own method.
AtmosTransport.Preprocessing.Common.read_era5_reduced_gaussian_geometry Function
Read native ERA5 reduced-Gaussian geometry from GRIB.
sourceAtmosTransport.Preprocessing.Common.read_era5_reduced_gaussian_mesh Function
Read a native ERA5 reduced-Gaussian mesh from GRIB.
sourceAtmosTransport.Preprocessing.Common.read_window! Function
read_window!(raw::RawWindow, settings::AbstractMetSettings, ctx,
date::Date, win_idx::Int) -> rawFill raw in place with one window of source data on the source's native grid. ctx is the day context returned by open_day. Implementations must NOT allocate per call beyond bounded scratch — raw is a pre-allocated workspace owned by the orchestrator — and should be idempotent in (date, win_idx).
AtmosTransport.Preprocessing.Common.reject_removed_balance_mode Method
reject_removed_balance_mode(numerics)Throw if a preprocessing [numerics] table sets balance_mode (or its older name geos_balance_mode): the per-layer balance it selected was removed, and every path that applies a Poisson balance uses the column balance (HORIZONTAL_BALANCE_TAG). GEOS pressure_fixer keeps its native horizontal fluxes and records horizontal_balance = "none".
AtmosTransport.Preprocessing.Common.reject_removed_horizontal_balance_keyword Method
reject_removed_horizontal_balance_keyword(kwargs)Reject the removed writer keyword when a source-specific process_day adapter otherwise absorbs unified-driver keywords through kwargs....
AtmosTransport.Preprocessing.Common.reject_removed_tm5_convection_route Method
reject_removed_tm5_convection_route(cfg)Reject a preprocessing config that still has a [tm5_convection] table. That table selected the lat-lon ERA5 physics-file route (ERA5 convection NetCDF converted to flat physics files, then to TM5 fields on the lat-lon grid). The route placed the fields 180° off in longitude and one hour early (issue #55) and was removed. TM5 convection comes from the ERA5 N320 → cubed-sphere preprocessor (include_convection = true in the met source's [preprocessing] table) or from the TM5-converted CATRINE archive attached with scripts/preprocessing/attach_catrine_tm5_convection_cs.jl.
AtmosTransport.Preprocessing.Common.resolve_balance_settings Method
resolve_balance_settings(cfg) -> NamedTupleParse optional solver controls for topology-specific mass-flux balancing.
cs_balance_tol keeps the historical strict default, DEFAULT_POISSON_BALANCE_TOL. cs_balance_project_every (default DEFAULT_POISSON_PROJECT_EVERY) controls how often the CS PCG solver reprojects residuals to the mean-zero subspace after the initial exact projection; the graph Laplacian preserves that subspace, so periodic projection removes redundant global reductions while keeping roundoff bounded. Set it to 1 for the legacy every-iteration path.
AtmosTransport.Preprocessing.Common.resolve_column_balance_weights Method
resolve_column_balance_weights(numerics) -> Symbol[numerics] column_balance_weights of an ERA5 spectral preprocessing config: how the column balance spreads its correction over the levels, :hybrid_mass (default, on every target: lat-lon, reduced Gaussian and cubed sphere), :hybrid_b or :mass (see AbstractColumnWeights). Native sources set it in their met-source [preprocessing] table instead.
AtmosTransport.Preprocessing.Common.resolve_mass_basis Method
resolve_mass_basis(cfg) -> (thermo_dir, include_qv, mass_basis)Parse humidity-related runtime choices from the TOML configuration.
thermo_diris the directory containing daily ERA5 thermo NetCDF files.include_qvcontrols whether pairedqv_start/qv_endendpoint fields are written into the output payload.mass_basisis:moistor:dryand determines whether native fields are converted to dry basis before vertical merging.
Dry basis is the default runtime contract. All transport binaries should use dry basis so that Poisson balance and cm diagnosis operate on dry mass. Moist basis is available as an explicit opt-out for diagnostic purposes only.
Dry-basis preprocessing requires a humidity source (input.thermo_dir).
AtmosTransport.Preprocessing.Common.resolve_output_float_type Method
resolve_output_float_type(cfg) -> TypeReturn the on-disk floating-point type requested by [numerics] float_type (default Float32 on this spectral path). Unknown values throw.
AtmosTransport.Preprocessing.Common.resolve_preprocessing_cache_settings Method
resolve_preprocessing_cache_settings(cfg) -> NamedTupleParse optional cache and preload controls.
Persistent spectral caching is disabled unless [cache] provides spectral_coefficients_dir or ATMOSTR_SPECTRAL_CACHE_DIR is set. Daily QV preload is an in-memory optimization and is enabled by default, bounded by qv_preload_max_gb.
AtmosTransport.Preprocessing.Common.resolve_runtime_settings Method
resolve_runtime_settings(cfg) -> NamedTupleResolve the script configuration into a compact runtime settings bundle used by the day-processing pipeline.
sourceAtmosTransport.Preprocessing.Common.resolve_spectral_flux_settings Method
resolve_spectral_flux_settings(cfg) -> NamedTupleResolve the ERA5 spectral-to-cubed-sphere flux construction selected in [numerics]. The defaults are the GCHP-matched path: regrid winds as Cartesian vectors, interpolate them to true cube edges with FV3's fourth-order filtered stencil, and average independently constructed start/end face fluxes over the meteorological window. face_fluxes = "line_integral" instead evaluates
directly on the spectral staging grid.
sourceAtmosTransport.Preprocessing.Common.resolve_surface_settings Method
resolve_surface_settings(cfg) -> NamedTupleParse optional ERA5 single-level surface input for raw PBL diffusion fields. The daily LL writer stores the raw pblh/t2m/ustar/pbl_hflux payload; CS regridding preserves it and runtime [diffusion] kind="tm5_beljaars_viterbo_local_kz" derives Kz.
AtmosTransport.Preprocessing.Common.source_grid Function
Return the native source mesh for a meteorological settings type.
sourceAtmosTransport.Preprocessing.Common.spread_column_correction! Function
Spread one face's column correction over its layers.
sourceAtmosTransport.Preprocessing.Common.supports_day_threading Method
supports_day_threading(settings) -> BoolTrue when process_day(date, grid, settings, ...) is genuinely day-local and the unified driver may launch Threads.@threads over a date range. Sources that maintain cross-day state (e.g. GEOS pressure-flux endpoint chaining) must keep the serial default. The driver still respects chain_mass=true — threading is enabled only when this trait AND !chain_mass both hold.
AtmosTransport.Preprocessing.Common.supports_initial_endpoint_mass_pin Method
supports_initial_endpoint_mass_pin(settings) -> BoolTrue when the source's process_day implements [mass_fix] mode = "initial_endpoint": the dry mass at the start of the first window becomes the pin target of every later window, carried across the days of one run. Only the GEOS native path does; the other native sources pin to an explicit target.
AtmosTransport.Preprocessing.Common.supports_spectral_massflux_preprocessing Method
Whether this target geometry supports spectral mass-flux preprocessing.
sourceAtmosTransport.Preprocessing.Common.target_balance_geometry Function
Allocate target cell degrees and balance scratch from a face table.
sourceAtmosTransport.Preprocessing.Common.target_spectral_truncation Method
target_spectral_truncation(grid) -> IntSpectral truncation T for the target grid: the highest zonal wavenumber its widest latitude ring resolves, nlon ÷ 2 − 1 (the term m = nlon/2 is never synthesised; see ring_max_wavenumber). For a reduced Gaussian grid this is set by the widest ring; each narrower ring drops its wavenumbers above ring_max_wavenumber(T, nlon_j).
AtmosTransport.Preprocessing.Common.target_summary Method
target_summary(grid) -> StringReturn a short human-readable summary of the configured target grid.
sourceAtmosTransport.Preprocessing.Common.target_surface_means Method
target_surface_means(source_mesh, grid, fields; regridder=nothing)Remap intensive surface primitives to LL/RG target cell-area means using the shared conservative Regridding API. Return (fields, regridder) so day drivers reuse the weights. The default three-argument application has IntensiveCellField semantics, including the shared spherical-polygon geometry on RG targets.
AtmosTransport.Preprocessing.Common.validate_tm5_pbl_target Function
Validate the topology and hourly input contract of optional live-Calc_Kzz preprocessing.
sourceAtmosTransport.Preprocessing.Common.windows_per_day Function
windows_per_day(settings::AbstractMetSettings, date::Date) -> IntNumber of preprocessing windows per UTC day for this source on date. For most sources this is constant (24 for hourly), but date-dependent sources (e.g. a leap-second day) may override.
AtmosTransport.Preprocessing.Vertical.AbstractFieldKind Type
AbstractFieldKindSingleton-type tag selecting the vertical-reduction rule apply_vertical! uses for one payload field. Concrete subtypes (all zero-size singletons) below.
AtmosTransport.Preprocessing.Vertical.AbstractVerticalTransform Type
AbstractVerticalTransformTyped nominal selecting how native source levels are mapped to output levels. Concrete subtypes:
IdentityVertical— no merge.MergeLayersThinnerThan— automatic local coarsening.MergeAbovePressure— upper-atmosphere coarsening.LevelSelection— echlevs-style level selection.
A concrete transform T is consumed by plan_vertical(transform, native_vc) to produce a VerticalPlan{FT, T}. apply_vertical! dispatches on (plan, ::FieldKind) to select the right per-field rule.
AtmosTransport.Preprocessing.Vertical.ConvectionInterfaceFlux Type
Convective interface flux (e.g. cmfmc). Select the kept interfaces.
AtmosTransport.Preprocessing.Vertical.ConvectionTendencyField Type
Convective center tendency (e.g. dtrain). Extensive at the layer; sum within merged group.
AtmosTransport.Preprocessing.Vertical.IdentityVertical Type
No-op identity vertical transform. Nz_output = Nz_native, merge_map[k] = k.
AtmosTransport.Preprocessing.Vertical.IntensiveCenterField Type
Center-level intensive field (e.g. T, Q). Mass-weighted mean within merged group; weights provided positionally.
AtmosTransport.Preprocessing.Vertical.InterfaceMassFluxField Type
Non-convective interface mass flux (kg/s); select retained interfaces.
sourceAtmosTransport.Preprocessing.Vertical.LevelSelection Type
LevelSelection(echlevs)Typed wrapper for the existing select_levels_echlevs algorithm. echlevs is a vector of native level INTERFACE indices (0-based, numbered from the model top as in TM5); levels between selected interfaces are summed. See vertical_coordinates.jl:64 and the ECHLEVS_ML137_* constants.
AtmosTransport.Preprocessing.Vertical.MassField Type
Center-level extensive mass (e.g. delp, m). Sum native layers within each merged group.
AtmosTransport.Preprocessing.Vertical.MassFluxField Type
Horizontal face mass flux (e.g. am, bm). Already integrated over the layer thickness; sum within merged group.
AtmosTransport.Preprocessing.Vertical.MergeAbovePressure Type
MergeAbovePressure(pressure_Pa; target_min_thickness_Pa = Inf,
reference_surface_pressure_Pa = STANDARD_PRESSURE)Upper-atmosphere coarsening: native layers whose midpoint pressure is LOWER than pressure_Pa (physically ABOVE the cutoff altitude) get greedily merged until each merged layer exceeds target_min_thickness_Pa. Below the cutoff, the native grid is preserved verbatim.
target_min_thickness_Pa = Inf merges every above-cutoff native layer into one top cap. The GEOS-IT L72 use case is pressure_Pa = 100.0 + target_min_thickness_Pa = 50.0 — merges the ~14 Pa mesospheric layers into ~50 Pa output layers while keeping the troposphere and stratosphere at native resolution. target_min_thickness_Pa must be positive (Inf allowed): the greedy merge never advances past a zero, negative or NaN threshold.
AtmosTransport.Preprocessing.Vertical.MergeLayersThinnerThan Type
MergeLayersThinnerThan(min_thickness_Pa; reference_surface_pressure_Pa = STANDARD_PRESSURE)Typed wrapper for the merge_thin_levels algorithm: merge adjacent native layers from the surface up, closing each group as soon as its thickness at the reference surface pressure reaches min_thickness_Pa. The native layers left above the last group become the top output layer, which can be thinner than min_thickness_Pa (ERA5 L137 at 100 Pa: 117 layers, top layer 6.8 Pa from native layers 1–4); every other output layer is at least that thick.
AtmosTransport.Preprocessing.Vertical.VerticalPlan Type
VerticalPlan{FT, T <: AbstractVerticalTransform}Result of plan_vertical. Type-parameterized by the originating transform so the apply_vertical! dispatch is statically resolved.
Fields:
transform: the originatingAbstractVerticalTransformvalue.native_vc: the input native hybrid coordinate.merged_vc: the output hybrid coordinate.merge_map:Vector{Int}such thatmerge_map[k_native]is the output-level index for merge-map flavors.groups:Vector{UnitRange{Int}}of native center-level ranges that map to each output level (derived frommerge_mapfor the merge-map flavors).Nz_output: the output level count.Nz_native: the input level count (cached for cheap access).
AtmosTransport.Preprocessing.Vertical.apply_vertical! Function
apply_vertical!(buf_out, buf_in, plan::VerticalPlan, kind::AbstractFieldKind, args...)Apply the vertical transform to one window of buf_in, writing the result into buf_out. Dispatches on the (plan.transform, kind) combination:
Extensive center fields (
MassField,MassFluxField,ConvectionTendencyField) sum native layers within each output group.Interface fields (
ConvectionInterfaceFlux) select the kept half-level interfaces.IntensiveCenterFieldtakes an additional positionalweightsargument (native mass-per-layer); produces the mass-weighted mean within each output group.
buf_out and buf_in must be 3D arrays with the vertical axis on dim 3.
AtmosTransport.Preprocessing.Vertical.build_vertical_setup Method
build_vertical_setup(coeff_path, level_range, min_dp, cfg_grid) -> NamedTupleConstruct the native and output vertical-coordinate metadata for the current run.
Two vertical mapping modes are supported:
:merge_mapcollapses native ERA5 layers onto selected/native-derived output layers using a native-levelmerge_map.:pressure_overlapremaps native ERA5 layer integrals onto an independent target hybrid coordinate, e.g. GEOS-IT L72, by pressure-thickness overlap:where
p = A + B p_s. For face-centered fluxes the same formula is applied with the face surface pressure used by the spectral flux construction.
AtmosTransport.Preprocessing.Vertical.echlevs_preset Method
echlevs_preset(name) -> Vector{Int}Resolve a named ERA5 L137 interface-selection preset. The returned vector is copied from the immutable process-wide preset library. An unknown name is an error that lists the available presets.
The two 34-layer TM5 selections are "ml137_tropo34" (TM5-MP r1112 levels/ml137/tropo34) and "ml137_tropo34a" (TM5 cy3-4dvar levels/ml137/tropo34a, the CAMS73 selection); both store TM5's lists verbatim. The AtmosTransport-native presets store TM5-numbered indices chosen to retain their grids from before the selector's TM5-numbering correction.
AtmosTransport.Preprocessing.Vertical.load_hybrid_coefficients Method
Load all hybrid sigma-pressure interface coefficients from TOML.
sourceAtmosTransport.Preprocessing.Vertical.merge_thin_levels Method
merge_thin_levels(vc; min_thickness_Pa=1000, p_surface=STANDARD_PRESSURE)Merge adjacent native layers into output layers, from the surface up: a group closes as soon as its summed thickness at the reference surface pressure p_surface reaches min_thickness_Pa. The native layers left above the last closed group (their summed thickness is below the minimum) form the top output layer, so the top layer can be thinner than min_thickness_Pa; every other output layer is at least that thick. For ERA5 L137 at 101 325 Pa, 100 Pa gives 117 layers with a 6.8 Pa top layer (native layers 1–4) and 1000 Pa gives 68 layers with a 33 Pa top layer (native layers 1–9).
Returns (merged_vc, merge_map) where merge_map[k] maps native layer k to its output layer. The kept interfaces keep their native A and B. The level sets are bit-identical to those of the top-down pass removed on 2026-10-14 for every level set without a zero-thickness layer (all ERA5 sets); only a degenerate set with a zero-thickness layer can round differently.
AtmosTransport.Preprocessing.Vertical.plan_vertical Function
plan_vertical(transform::AbstractVerticalTransform,
native_vc::HybridSigmaPressure{FT}) → VerticalPlan{FT, typeof(transform)}Materialize the planned vertical-coordinate mapping for one day's run. Called once per day (or once per run if native_vc is invariant); the returned plan is reused across all windows.
AtmosTransport.Preprocessing.Vertical.resolve_coefficients_path Method
resolve_coefficients_path(path) -> StringLocate a hybrid-coefficient table. path is expanded with expand_data_path; an absolute path must exist as given. A relative path is looked up in the working directory first and then in the package root, where the shipped tables live (config/era5_L137_coefficients.toml, config/geos_L72_coefficients.toml), so a shipped config works from any working directory (Pkg.test runs in test/). A working-directory table that differs from the shipped table of the same relative path is used, with a warning naming both files. A table found in neither place is an error naming both locations.
AtmosTransport.Preprocessing.Vertical.select_levels_echlevs Method
select_levels_echlevs(vc_native, echlevs)TM5-style level selection (TM5's echlevs): keep a subset of the native interfaces. The selected interfaces keep their native A and B coefficients. The native layers between two selected interfaces become one output layer, and the preprocessor sums their layer quantities (air mass, horizontal mass fluxes) through the returned merge_map, as TM5 does.
echlevs uses TM5/ECMWF half-level numbering: e = 0 is the model top and e = 137 is the surface for ERA5 L137. Following TM5 geometry.F90, which assigns at(l) = a_ec(echlevs(l-1)), an entry e selects Julia coefficient index e + 1. Thus each retained interface obeys
and an output-layer extensive quantity is
TM5 files conventionally list interfaces from surface to top, e.g. [137, 134, 129, ..., 7, 0] for "ml137_tropo34"; order does not matter to this function because it sorts the indices into the model's top-to-surface array order.
Returns (selected_vc, merge_map), where merge_map[k] is the output layer that contains native layer k (both counted from the top).
AtmosTransport.Preprocessing.Vertical.sum_merged_layers! Method
Sum native layers in ascending order using a native-to-output layer map.
The vertical axis is last. Each input element is converted to the output eltype before addition, matching apply_vertical! for mixed precision.
AtmosTransport.Preprocessing.Spectral.LLPoissonWorkspace Type
LLPoissonWorkspacePre-allocated scratch and cached FFT plans for the LL Poisson mass-flux balance. Construct once per grid size and reuse across all windows and levels.
sourceAtmosTransport.Preprocessing.Spectral.ReducedSpectralSynthesis Type
ReducedSpectralSynthesis(grid, T, Nf)Precomputed Legendre tables, FFT plans and buffers for synthesising Nf columns (model levels) of a spectral field with truncation T on the cell centres of the reduced Gaussian grid. Calls to synthesize_reduced! reuse the buffers, so one object serves any number of fields, but not two calls at once. The Legendre table holds n_rings × (T + 1)(T + 2)/2 values (1.1 GB for N320 at T639) and the half-spectrum buffer Nf × Σ_j (nlon_j ÷ 2 + 1) complex values (0.6 GB for 137 levels).
AtmosTransport.Preprocessing.Spectral.apply_dry_basis_native! Method
apply_dry_basis_native!(m, am, bm, qv)Convert native-level moist mass and horizontal fluxes to dry basis before level merging. Face humidity is reconstructed by simple two-point averaging.
sourceAtmosTransport.Preprocessing.Spectral.available_spectral_dates Method
available_spectral_dates(spectral_dir) -> Vector{Date}Discover all processing dates available in the spectral-input directory by scanning for era5_spectral_YYYYMMDD_lnsp.gb.
AtmosTransport.Preprocessing.Spectral.balance_column_mass_fluxes! Method
balance_column_mass_fluxes!(am, bm, m, dm_dt, ws::LLPoissonWorkspace;
weights = MassWeightedColumn())Column Poisson balance of a lat-lon window: one FFT Poisson solve (balance_mass_fluxes!) makes the convergence of the column-integrated fluxes Σ_k am, Σ_k bm equal the column mass tendency Σ_k dm_dt in every cell, and each face's column correction δ is spread over the layers by spread_column_correction! with the column weights (AbstractColumnWeights; production passes the configured column_balance_weights, hybrid_mass by default, built from the output coordinate's B). The layer winds keep their vertical structure, and cm diagnosed afterwards from the explicit tendency carries the vertical motion and closes at the top and the surface. The unsatisfiable global residual is left in proportion to current column mass, via a shift of the solver-only column target by R̄ * (M_c / mean(M) - 1) only with fixed_global_mass=true, after the independent global budget guard (using steps_per_window). Otherwise the uniform mode remains. dm_dt is not modified.
AtmosTransport.Preprocessing.Spectral.balance_mass_fluxes! Method
balance_mass_fluxes!(am, bm, dm_dt, ws::LLPoissonWorkspace)FFT Poisson solve of the lat-lon balance (the solver of TM5 r1112 BalanceMassFluxes_m, grid_type_ll.F90:2536-2653), applied to every level k of the arrays it is given.
Adjusts am and bm in-place so that the discrete horizontal convergence at each cell (i, j) matches the prescribed mass tendency dm_dt:
(am[i] − am[i+1]) + (bm[j] − bm[j+1]) = dm_dt[i, j] ∀ (i, j)The correction is a streamfunction ψ found by solving ∇²ψ = residual on the periodic lat-lon grid via FFT division by the discrete Laplacian eigenvalues. The ws::LLPoissonWorkspace provides pre-computed eigenvalues, scratch arrays, and cached in-place FFT plans for zero-allocation operation.
Preprocessing calls it on the column-integrated fluxes only (one level, from balance_column_mass_fluxes!). Balancing every model level to its own mass change would leave nothing for the vertical mass flux cm: TM5's per-level balance keeps vertical motion only because its target includes the IFS vertical flux, which our preprocessing does not have.
AtmosTransport.Preprocessing.Spectral.balance_mass_fluxes! Method
balance_mass_fluxes!(am, bm, dm_dt)Convenience overload that allocates a temporary workspace. Prefer the LLPoissonWorkspace overload when calling in a loop (e.g., per window).
AtmosTransport.Preprocessing.Spectral.compute_air_mass! Method
compute_air_mass!(m_arr, dp, area, Nlon, Nlat, Nz)Convert pressure thickness to air mass per cell [kg]:
m[i, j, k] = dp[i, j, k] × area[i, j] / gwhere area[i, j] is the horizontal cell area [m²] and g is the gravitational acceleration [m/s²].
AtmosTransport.Preprocessing.Spectral.compute_dp! Method
compute_dp!(dp, ps, dA, dB, Nlon, Nlat, Nz)Compute native-layer pressure thickness [Pa] from hybrid A/B coefficients and surface pressure. Uses |dA[k] + dB[k] × ps| (absolute value handles either level-ordering convention).
Vertical convention: k=1 is TOA, k=Nz is the surface-adjacent level. dA[k] = A_ifc[k+1] - A_ifc[k] and dB[k] = B_ifc[k+1] - B_ifc[k] where A_ifc [Pa] and B_ifc [dimensionless] define the half-level pressures: p_half[k] = A_ifc[k] + B_ifc[k] × ps.
AtmosTransport.Preprocessing.Spectral.compute_legendre_column! Method
compute_legendre_column!(P, T, sin_lat)Fill the fully-normalised associated Legendre polynomial table P[n+1, m+1] for spectral truncation T at latitude φ (given as sin_lat = sin(φ)).
Uses the standard three-term recurrence (Belousov 1962):
P_m^m = √((2m+1)/(2m)) · cos(φ) · P_{m-1}^{m-1} (sectoral)
P_{m+1}^m = √(2m+3) · sin(φ) · P_m^m (semi-sectoral)
P_n^m = a · sin(φ) · P_{n-1}^m − b · P_{n-2}^m (general)where a, b include the normalisation factors for the fully-normalised convention used by ECMWF spectral fields (IFS Doc Part III, Eq. 2.3).
Output: P is (T+1) × (T+1), 1-indexed, with P[n+1, m+1] = P̃_n^m(sin φ).
AtmosTransport.Preprocessing.Spectral.compute_mass_fluxes! Method
compute_mass_fluxes!(am, bm, u_stag, v_stag, ps, dA, dB, grid, half_dt, Nz)Compute the native-level horizontal mass fluxes am and bm.
Horizontal fluxes
Zonal mass flux through the west face of cell (i, j):
am[i, j, k] = (u / cos φ) × Δp_face × (R / g) × Δφ × Δt/2 [kg]where u is the spectral pseudo-wind U·cos(φ), so u / cos φ recovers the physical zonal wind. Δp_face is the Jensen-corrected face-level pressure thickness |dA + dB × exp((ln(ps_L) + ln(ps_R)) / 2)|, and Δt/2 = half_dt is the v4 binary's per-substep flux convention (Strang splitting applies fluxes twice per full step: forward + reverse).
Meridional mass flux through the south face of cell (i, j):
bm[i, j, k] = v × Δp_face × (R / g) × Δλ × Δt/2 [kg]where v is the spectral pseudo-wind V·cos(φ). The east-west face length's cos(φ) factor is therefore already present in v, so there is no additional explicit latitude-cosine multiplier in the bm formula.
Sign convention: positive am = eastward mass flux; positive bm = northward.
The pole rows j = 1 and j = Nlat are ordinary cells, centred at ±(90° − Δφ/2): their zonal faces carry the synthesized flux like every other row. Only the meridional faces on the poles (bm[:, 1, :], bm[:, Nlat+1, :], at φ = ±90°) have zero length and carry no flux. Closing the pole-row zonal faces would leave a flow that crosses the pole no path through the polar cap; the column balance would then re-route bm at every latitude (issue #58; the same zeroing was removed once before, see docs/resources/bug_archive/SESSION1_GRID_CM_FIX_2026-04-03.md, section 3).
The stored vertical flux is diagnosed after column balance from the explicit forward mass endpoint; no native vertical staging estimate is needed.
sourceAtmosTransport.Preprocessing.Spectral.era5_spectral_paths Method
Paths of the daily ERA5 spectral vorticity/divergence and log-pressure files.
sourceAtmosTransport.Preprocessing.Spectral.era5_thermo_path Method
Daily ERA5 thermodynamic NetCDF path shared by source-independent workflows.
sourceAtmosTransport.Preprocessing.Spectral.fill_ring_spectrum! Method
fill_ring_spectrum!(buf, spec, P, T, lon_shift_rad) -> bufFill buf (length N, the ring's number of points) with the zonal Fourier coefficients of one latitude ring, in the layout of an unnormalised inverse FFT (FFTW bfft):
G_m = e^{i m λ_0} Σ_{n=m}^{T} f̂_n^m P̃_n^m(sin φ), 0 ≤ m ≤ M,
buf[1] = G_0,
buf[m + 1] = G_m, buf[N − m + 1] = conj(G_m) (1 ≤ m ≤ M),and zero in every other bin, with M = ring_max_wavenumber(T, N). Then bfft(buf)[k + 1] = G_0 + 2 Re Σ_{m=1}^{M} G_m e^{2πimk/N} = f(λ_0 + 2πk/N, φ). spec[n + 1, m + 1] = f̂_n^m are the spectral coefficients, P[n + 1, m + 1] the Legendre column P̃_n^m(sin φ) of the ring's latitude (compute_legendre_column!) and λ_0 = lon_shift_rad the longitude of the first point (radians), applied in its own precision.
AtmosTransport.Preprocessing.Spectral.fill_xface_surface_pressure! Method
fill_xface_surface_pressure!(ps_xface, ps_cell)Fill west/east face surface pressures with the same Jensen/geometric mean used by compute_mass_fluxes! for the native zonal mass flux thickness.
AtmosTransport.Preprocessing.Spectral.fill_yface_surface_pressure! Method
fill_yface_surface_pressure!(ps_yface, ps_cell)Fill south/north face surface pressures with the same Jensen/geometric mean used by compute_mass_fluxes! for native meridional mass flux thickness. Polar boundary values are copied from the adjacent pole row; the corresponding mass fluxes are zeroed separately by close_pole_faces!.
AtmosTransport.Preprocessing.Spectral.foreach_thermo_record Method
foreach_thermo_record(f, ds, records, Ny; FT=Float64, variable="q")Read a bounded block of consecutive thermo records once, calling f(field, record) with each normalized (longitude, south_to_north_latitude, level) field. Temporal chunk alignment avoids decompressing the same NetCDF chunks for each hour. Conversion and orientation match the scalar reader, one record at a time. The callback can retain only interpolated target values rather than a native day.
AtmosTransport.Preprocessing.Spectral.mass_fix_target_ps_dry_record Method
mass_fix_target_ps_dry_record(target_ps_dry_pa, target_kg, total_area_m2, g) -> Float64Header value mass_fix_target_ps_dry_pa of a native-source dry-mass pin. A configured target ([mass_fix] mode = "target_ps_dry", target_ps_dry_pa finite) is recorded exactly: recomputing it from the pinned air mass rounds (98325.00000000001 Pa) or, with a Float32 g, is off by 1.6e-3 Pa. Without one (GEOS mode = "initial_endpoint", or a caller that passes only a kg target, target_ps_dry_pa = NaN) the record is the mean dry surface pressure of the pinned mass, target_kg g / A.
AtmosTransport.Preprocessing.Spectral.mass_target_offset Method
mass_target_offset(target, current, sensitivity) -> Float64Solve the linear dry-mass pin shared by the spectral and native paths,
The inputs may be pressure or mass so long as target and current share units and sensitivity is their change per pascal. For a hybrid layer, \partial \Delta p_{dry,k}/\partial p_s = \Delta B_k(1-q_k). Keeping this algebra in one function ensures the spectral surface-pressure pin and every native mass pin solve the same physical correction.
AtmosTransport.Preprocessing.Spectral.maybe_preload_qv_day Method
maybe_preload_qv_day(thermo_path, Nx, Ny, Nz, settings)Return a daily in-memory QV cache when enabled and within the configured memory cap. The empty 0×0×0×0 array means the caller should use the historical hourly NetCDF read path.
AtmosTransport.Preprocessing.Spectral.merge_cell_field! Method
merge_cell_field!(merged, native, mm)Accumulate a native-level cell field onto merged output levels using the native-to-merged level map mm.
AtmosTransport.Preprocessing.Spectral.merge_qv! Method
merge_qv!(qv_merged, qv_native, m_native, mm)Merge native-level specific humidity to the output vertical grid using native air mass as the averaging weight.
sourceAtmosTransport.Preprocessing.Spectral.next_day_hour0 Method
next_day_hour0(date, dates, spectral_dir, T_target)Load the next day's hour-0 spectral fields when available so the final window of the current day can form forward differences for dam, dbm, and dm. Returns nothing when no next-day file is available.
AtmosTransport.Preprocessing.Spectral.normalize_lon_to_centered Method
normalize_lon_to_centered(field, lons) -> fieldRoll a 3D (Nx, Ny, Nz) field along the longitude axis into the [-180, 180) order. Detects the source longitude convention from the NetCDF longitude variable: when source longitudes start at or near 0° (i.e. 0..360-Δ convention), rolls by Nx ÷ 2 columns; when source already starts near -180°, no-op. The roll reorders values; it does not change where they sit: point values at 0, Δ, … land at -180, -180 + Δ, … (see read_thermo_coordinates).
Returns field unchanged when length(lons) ≠ size(field, 1) (mismatch that the caller will catch downstream) or when the source is already in the staging convention.
AtmosTransport.Preprocessing.Spectral.pin_global_mean_ps! Method
pin_global_mean_ps!(sp, area; target_ps_dry_pa, qv_global) -> Float64Apply a uniform additive offset to sp so that ⟨sp⟩_area corresponds to a prescribed dry-air mass target inferred from a global humidity climatology. sp and area hold one value per column: lat-lon (Nx, Ny) or reduced-Gaussian (ncell,). The defaults are GLOBAL_MEAN_DRY_SURFACE_PRESSURE(98325 Pa) andGLOBAL_MEAN_SPECIFIC_HUMIDITY (0.00247 kg kg⁻¹).
AtmosTransport.Preprocessing.Spectral.pin_global_mean_ps_using_qv! Method
pin_global_mean_ps_using_qv!(sp, area, dA, dB, qv; target_ps_dry_pa) -> Float64Apply a uniform additive offset to sp so that the area-weighted global mean dry surface pressure implied by the native-layer hourly humidity field matches the prescribed target.
The correction is still spatially uniform in ps; only the global dry-mass targeting uses the instantaneous humidity pattern. sp and area hold one value per column and qv adds the level dimension last: lat-lon (Nx, Ny) and (Nx, Ny, Nz), or reduced-Gaussian (ncell,) and (ncell, Nz). The default target is GLOBAL_MEAN_DRY_SURFACE_PRESSURE (98325 Pa). All native and global sums are compensated Float64 reductions; the small target difference retains the low parts. Accumulators are local and no scratch is allocated.
AtmosTransport.Preprocessing.Spectral.read_daily_qv_from_thermo Method
read_daily_qv_from_thermo(thermo_path, Nx, Ny, Nz; FT=Float64, time_block=3)Read a complete daily ERA5 thermo NetCDF q field into (longitude, south_to_north_latitude, level, time).
ERA5 thermo files are usually deflated and chunked across multiple times. The reader therefore pulls chunk-aligned time blocks instead of 24 independent hour slices, avoiding repeated decompression of the same HDF5 chunks while keeping the result in the exact orientation expected by the dry-basis preprocessing paths.
sourceAtmosTransport.Preprocessing.Spectral.read_day_spectral Method
read_day_spectral(vo_d_path, lnsp_path; T_target=0, cache_dir="")Read one ERA5 spectral day, optionally using a persistent decoded-coefficient cache. Empty cache_dir disables disk caching and preserves the historical direct-GRIB path. Cache writes are best-effort: a failed write logs a warning but never invalidates the decoded in-memory result.
AtmosTransport.Preprocessing.Spectral.read_day_spectral_streaming Method
Whole-day spectral reader: decodes all hours into memory (legacy point sampling). Returns a NamedTuple with hours, lnsp_all, vo_by_hour, d_by_hour, T, n_times.
sourceAtmosTransport.Preprocessing.Spectral.read_qv_from_thermo Method
read_qv_from_thermo(thermo_path, hour_idx, Nx, Ny, Nz; FT=Float32)Read hourly ERA5 model-level specific humidity from the thermo NetCDF sidecar as (longitude, south_to_north_latitude, level).
Two reorderings relative to the raw NetCDF data, both decided from the file's coordinate variables (found as GriddedIO.find_coordinate finds them):
Latitude orientation. ERA5 latitudes run north to south (
latitude[1] = +90); the array is then reversed along latitude soj = 1is the southernmost row.Longitude order. A
0 … 360 − Δlongitude axis is rolled byNx ÷ 2columns, so the column of longitude 180° comes first.
The values stay where the file put them. ERA5 thermo fields are point values at longitudes 0, Δ, …, 360 − Δ and latitudes 90, 90 − Δ, …, −90 (scripts/downloads/download_era5_physics.py checks this layout), so after the reordering index (i, j) holds the value at (−180 + (i − 1)Δ, −90 + (j − 1)Δ). These are not the cell centres of a lat-lon staging mesh (−180 + (i − ½)Δ); read_thermo_coordinates returns the coordinates of the reordered array, and the lat-lon workspaces interpolate with them.
AtmosTransport.Preprocessing.Spectral.read_spectral_coeffs! Method
Read spectral coefficients from a GRIB message into a complex matrix using vals as scratch. Returns spec[n+1, m+1] for m=0..T, n=m..T.
AtmosTransport.Preprocessing.Spectral.read_thermo_coordinates Method
read_thermo_coordinates(thermo_path) -> (lon, lat)Longitudes and latitudes [degrees] of the humidity values in the arrays read_qv_from_thermo and read_daily_qv_from_thermo return: the file's coordinate variables (found by name through GriddedIO.find_coordinate), reordered as the data are (latitude south to north; a 0 … 360 longitude axis rolled by Nx ÷ 2) and written in [−180°, 180°). For the ERA5 thermo archive this is lon[i] = −180 + (i − 1)Δ and lat[j] = −90 + (j − 1)Δ.
AtmosTransport.Preprocessing.Spectral.recompute_cm_from_divergence! Method
recompute_cm_from_divergence!(cm, am, bm, m; B_ifc)Recompute merged-level vertical mass flux from merged horizontal divergence. Uses the TM5/ERA5 hybrid-coordinate Δb × pit closure. B_ifc must contain exactly Nz + 1 interface coefficients.
For the post-Poisson-balance correctness-critical path, prefer recompute_cm_from_dm_target! which uses an explicit dm target and is basis-agnostic. This legacy function is retained for the pre-Poisson staging / on-the-fly synthesis code paths that only seed merged.cm_merged for the unused :window_constant delta payload.
AtmosTransport.Preprocessing.Spectral.recompute_native_mass_fields! Method
recompute_native_mass_fields!(transform, ab, grid, half_dt)Recompute native dp, moist cell mass, and mass fluxes after a uniform surface-pressure adjustment has been applied to transform.sp.
AtmosTransport.Preprocessing.Spectral.remap_extensive_field_pressure_overlap! Method
remap_extensive_field_pressure_overlap!(dst, src, ps, src_vc, dst_vc)Conservatively remap a layer-integrated field from one hybrid coordinate to another using pressure-thickness overlap in each column.
For a source layer s and target layer k, interface pressures are evaluated with the column surface pressure,
and the target layer integral is
src and dst are extensive in the vertical direction: air mass and half-step horizontal mass fluxes are both valid inputs. For horizontal fluxes, pass the face surface pressure field used to construct the flux thickness.
AtmosTransport.Preprocessing.Spectral.remap_qv_pressure_overlap! Method
remap_qv_pressure_overlap!(qv_dst, qv_src, m_src, ps, src_vc, dst_vc)Mass-weighted vertical remap of specific humidity onto an independent target hybrid coordinate. The same pressure-overlap fractions used for extensive mass fields are applied to the source dry-air mass, then qv is averaged over each target layer:
This is only for optional diagnostic humidity output. Transport masses and fluxes are remapped by remap_extensive_field_pressure_overlap!.
AtmosTransport.Preprocessing.Spectral.ring_max_wavenumber Method
ring_max_wavenumber(T, nlon) -> IntHighest zonal wavenumber synthesised on a latitude ring of nlon equally spaced points from a field of triangular truncation T:
M = min(T, ⌊(nlon − 1) / 2⌋).Every spectral synthesizer uses this limit (spectral_to_grid!, spectral_to_ring! and synthesize_reduced!, through fill_ring_spectrum! for the first two).
On a ring of N points λ_k = λ_0 + 2πk/N (k = 0, …, N − 1) the real field
f(λ_k) = G_0 + 2 Re Σ_{m=1}^{M} G_m e^{i m λ_k}is the unnormalised inverse DFT of bins m and N − m holding G_m e^{i m λ_0} and its conjugate, which are distinct bins for every m < N/2. For m = N/2 on an even ring they are one bin: the samples are e^{i N λ_k / 2} = e^{i N λ_0 / 2} (−1)^k, so the term 2 Re(G e^{i m λ_k}) samples as 2 Re(G e^{i N λ_0 / 2}) (−1)^k. That depends on the ring's origin: 2 Re G at the faces (λ_0 = 0) and −2 Im G at the cell centres (λ_0 = π/N), so one coefficient cannot be represented consistently on the staggered points of a ring. The term is dropped, and every 1 ≤ m ≤ M enters with its mirror (weight 2).
This matches ECMWF ecTrans's rule for linear reduced grids, NMEN = MIN(NSMAX, (NLOEN − 1)/2) (src/trans/common/internal/setup_geom_mod.F90:48, ecTrans aff81b9), including ERA5's linear N320 grid at T639. On lat-lon and cubed-sphere staging targets target_spectral_truncation sets T = nlon ÷ 2 − 1, so M = T there. On a reduced Gaussian target T is set by the widest ring, and each narrower ring drops its wavenumbers above M.
AtmosTransport.Preprocessing.Spectral.spectral_day_cache_path Method
spectral_day_cache_path(cache_dir, vo_d_path, lnsp_path; T_target=0)Return the deterministic on-disk cache path for one decoded spectral day.
The key includes absolute input paths plus file sizes and mtimes, so replacing either GRIB file automatically invalidates stale coefficient caches. The cache stores only the truncated coefficient tensors consumed by the transport preprocessor, not the original GRIB payload.
sourceAtmosTransport.Preprocessing.Spectral.spectral_to_grid! Method
spectral_to_grid!(field, spec, T, lats, Nlon, P_buf, fft_buf; lon_shift_rad=0.0, ...)Synthesize a single 2D spectral field onto a regular lat-lon grid.
For each latitude φ ∈ lats:
Build the associated Legendre column
P̃_n^m(sin φ).Sum over
nfor eachmto get the zonal harmonic coefficientG_m(φ) = Σ_n spec[n+1, m+1] · P̃_n^m(sin φ).Apply longitude phase shift:
G_m *= exp(i · m · lon_shift_rad). This shifts the output so index 1 represents the field at physical longitudelon_shift_rad(radians). Uselon_shift_rad = deg2rad(λᶜ[1])to align with a mesh whose first cell center is atλᶜ[1].Fill negative-frequency bins via conjugate symmetry (real-valued output).
Inverse FFT → gridpoint values along the longitude ring.
Steps 2–4 are fill_ring_spectrum!, shared with the reduced Gaussian ring synthesis spectral_to_ring!.
Longitude convention: the FFT's natural origin is lon=0°. Without a shift, field[1, j] is at lon=0°. With lon_shift_rad = deg2rad(-178.125), field[1, j] is at lon=-178.125° (first cell center of a [-180, 180) mesh).
Truncation: wavenumbers 0 ≤ m ≤ ring_max_wavenumber(T, Nlon) = min(T, (Nlon − 1) ÷ 2) are synthesised, each m > 0 with full weight; the term m = Nlon/2 of an even Nlon is dropped (see ring_max_wavenumber). Lat-lon targets use T = Nlon ÷ 2 − 1, so nothing is dropped there.
AtmosTransport.Preprocessing.Spectral.spectral_to_native_fields! Method
spectral_to_native_fields!(...)Transform one analysis hour of ERA5 spectral lnsp, vo, and d into native gridpoint mass/flux fields on the configured target geometry.
This routine builds only the moist native fields. Dry-basis conversion and any humidity-aware mass fix are applied later once the matching hourly q field is available.
AtmosTransport.Preprocessing.Spectral.stagger_winds! Method
stagger_winds!(u_stag, v_stag, u_cc, v_cc, Nlon, Nlat, Nz)Map spectral-synthesised winds onto the Arakawa C-grid staggered positions:
u_stag[i, j, k]: zonal wind at the west face of cell(i, j). For i=1..Nlon, copied fromu_cc(which is synthesised at west-edge longitudes viaspectral_to_grid!with the face shift). IndexNlon+1wraps periodically tou_cc[1, j, k].v_stag[i, j, k]: meridional wind at the south face of cell(i, j). Averaged fromv_ccat cell centers j-1 and j. Pole boundaries (j=1, j=Nlat+1) are zeroed (no meridional mass flux through the poles).
Stagger convention: am[i, j, k] = u_stag[i, j, k] × dp_face × ... is the eastward mass flux through the west face of cell (i, j). Positive flux = mass moving eastward.
AtmosTransport.Preprocessing.Spectral.synthesize_reduced! Method
synthesize_reduced!(out, spec, s::ReducedSpectralSynthesis) -> outSynthesise the spectral coefficients spec[n + 1, m + 1, k] of s.Nf levels k onto the reduced Gaussian cell centres: out[c, k] for cell c. Ring j carries the wavenumbers m ≤ ring_max_wavenumber(s.T, nlon_j), as in spectral_to_ring!.
AtmosTransport.Preprocessing.Spectral.vod2uv! Method
vod2uv!(u_spec, v_spec, vo_spec, d_spec, T)Convert one level of spectral relative vorticity (VO) and divergence (D) into spectral zonal (U) and meridional (V) wind coefficients using the IFS/TM5 reconstruction formula (IFS Doc Part III, Eq. 2.14-2.15):
Û_n^m = R_E · [ δ(m,n)·VO_{n-1}^m + i·σ(m,n)·D_n^m − δ(m,n+1)·VO_{n+1}^m ]
V̂_n^m = R_E · [−δ(m,n)·D_{n-1}^m + i·σ(m,n)·VO_n^m + δ(m,n+1)·D_{n+1}^m ]where R_E is the Earth radius [m], δ(m,n) = −√((n²−m²)/(4n²−1)) / n is the coupling coefficient, and σ(m,n) = −m / (n(n+1)) is the asymmetric rotation coefficient. i is the imaginary unit.
The output u_spec, v_spec are the spectral coefficients of U·cos(φ) and V·cos(φ) respectively (the scaled pseudo-winds used by ECMWF), so the gridpoint synthesis via spectral_to_grid! produces the cos-scaled wind. Division by cos(φ) to obtain the physical wind is done later in compute_mass_fluxes!.
Input arrays are (T+1) × (T+1) 1-indexed: spec[n+1, m+1] = Ŝ_n^m.
AtmosTransport.Preprocessing.MassClosure.COLUMN_WEIGHT_KINDS Constant
COLUMN_WEIGHT_KINDSTOML names of the column-balance weightings: mass, hybrid_b, hybrid_mass.
AtmosTransport.Preprocessing.MassClosure.AbstractWindRegrid Type
AbstractWindRegridHow the east/north winds are regridded from the source grid to the cube: ScalarWindRegrid or CartesianWindRegrid ([preprocessing] wind_regrid).
AtmosTransport.Preprocessing.MassClosure.AlongFaceFilter Type
AlongFaceFilterThe filter that GCHP's restaggering of A-grid winds applies along each face (A2D2C in GEOS_FV3_Utilities.F90, then d2a2c_vect in sw_core.F90). The D-grid wind is the two-cell average; the fourth-order D → A step then returns the A-grid wind smoothed along the face direction, (−1, 8, 18, 8, −1)/32 in the panel interior and (1, 2, 1)/4 within three cells of a panel edge. It removes the 2Δ wave along the face and keeps 62% of the 4Δ wave.
It acts here on the face-normal winds of the faces on the same grid line of the face's panel: face f becomes Σₘ w[f][m] uₙ(face[f][m]). Two approximations of FV3: the stencil is chosen per face rather than per contributing cell, and the faces in the first and last row of a panel, whose stencil would leave the panel, are not filtered.
AtmosTransport.Preprocessing.MassClosure.CSPoissonScratch Type
CSPoissonScratchPre-allocated work buffers for the CS global Poisson balance. tol holds the per-cell closure tolerance of the last column balance (balance_cs_column_mass_fluxes!), which the cm diagnosis that follows it checks the column residuals against.
AtmosTransport.Preprocessing.MassClosure.CSVectorFaceGeometry Type
CSVectorFaceGeometry(mesh, face_table; order = 2, along_face_filter = false)Geometry for building face fluxes from cell-centre winds as vectors, for every unique face of face_table (interior and panel-seam faces):
len: the face's great-circle length;cell: its two cells(pl, il, jl, pr, ir, jr), lower-index cell first;coef: the face-normal components of the two cells' east and north unit vectors, times the weights that interpolate to the face midpoint (inverse great-circle distance from the two cell centres). The face-normal wind iscoef[1] u_l + coef[2] v_l + coef[3] u_r + coef[4] v_rwithueast andvnorth, and the layer thicknessdpw[1] dp_l + dpw[2] dp_r.
At a panel seam the grid lines kink and the cells on both sides are skewed along the edge, so the point between the two cell centres lies up to a quarter of a face length along the edge from the face midpoint (2e-4 in the panel interior). As in FV3's cube-edge treatment, a seam face also takes the value of the neighbouring seam face on the side of its midpoint, projected on its own normal, and interpolates along the edge with weight w_partner. These partner data are stored for the seam faces only; slot[f] indexes them (0 for interior faces and for a seam face whose midpoint needs no correction).
With order = 4 the wind at interior faces with two cells on each side in the same panel row is interpolated with FV3's interior fourth-order stencil (−1, 9, 9, −1)/16 (outer, a OuterCellPair); the layer thickness stays linear. The faces next to a seam (index 2 and Nc) and the seam faces stay second order. The cells between a second- and a fourth-order face keep an O(h²) divergence error, 1e-5 of U Δx for a solid-body rotation at C90 (the linear construction leaves 1e-7). FV3 avoids it with one-sided stencils next to the seams and fourth-order interpolation across them (edge_interpolate4). along_face_filter = true adds GCHP's filter along the faces (filter, an AlongFaceFilter). Either is nothing when off.
AtmosTransport.Preprocessing.MassClosure.CartesianWindRegrid Type
CartesianWindRegrid(source_mesh, target_mesh, Nz, FT)Remap the wind as a vector, as GCHP's MAPL does for UA;VA (MAPL_EsmfRegridder.F90). The source winds are written in fixed Cartesian components
X = −sin λ u − sin φ cos λ v, Y = cos λ u − sin φ sin λ v, Z = cos φ v,the three components are remapped conservatively, and the result is projected on the east and north unit vectors at each cube-cell centre. The remapped vector is the area mean of the source vectors, so it is not exactly tangent to the sphere at the cell centre; the projection drops the small radial part.
source_mesh is a LatLonMesh (MERRA-2) or a ReducedGaussianMesh (ERA5 N320); the source cells are taken in the regridder's order (longitude fastest, or ring by ring). Owns the three source component buffers (per source cell and level; 3 × 60 MB for MERRA-2 L72 and 3 × 300 MB for N320 L137 in Float32), the remapped Z panels, and the basis trigonometry of both grids. The buffers are only used inside one regrid_winds! call, so one instance can serve several pipelines.
AtmosTransport.Preprocessing.MassClosure.CompressedLaplacian Type
CompressedLaplacianSparse cell-to-cell adjacency with multiplicity weights, equivalent to the graph Laplacian on the face-indexed mesh but stored in CSR-like format with O(ncells) entries instead of O(nfaces).
For octahedral reduced-Gaussian grids, adjacent rings differ by only 4 cells, so each cell has at most ~6 unique neighbors (2 zonal + 2-4 meridional). The LCM boundary segmentation creates up to ~100 faces per cell for the same neighbors — the compressed form collapses these into weighted edges.
sourceAtmosTransport.Preprocessing.MassClosure.DirectCSPoisson Type
Pinned principal-minor CS graph Cholesky, reused across layers and windows.
sourceAtmosTransport.Preprocessing.MassClosure.HybridBWeightedColumn Type
HybridBWeightedColumn(B) -> weightsΔB_k weights from hybrid B at the Nz + 1 interfaces, top first.
AtmosTransport.Preprocessing.MassClosure.HybridMassWeightedColumn Type
HybridMassWeightedColumn(B) -> weightsAir-mass weights restricted to the hybrid layers of interface B (top first): layer k is hybrid when ΔB_k = B_{k+1} − B_k ≥ HYBRID_LAYER_MIN_DB (1e-6), i.e. when a 1000 hPa change of surface pressure changes its thickness by at least 0.1 Pa. Smaller positive increments are rounding residues of a pure-pressure layer (GEOS/MERRA-2 L72 layer 41, 150–177 hPa: ΔB = 8.2e-9, 8.2e-4 Pa per 1000 hPa, 3e-7 of its thickness); the smallest genuine increment of the shipped tables is ERA5 L137 layer 55 (ΔB = 7e-6, 0.7 Pa per 1000 hPa). A coordinate with no hybrid layer is an error.
AtmosTransport.Preprocessing.MassClosure.LineIntegralFaceFluxes Type
LineIntegralFaceFluxes(source_mesh, target_mesh, face_table; samples_per_face = 16)Face mass fluxes integrated along each cube face from the source-grid winds,
F_f = (Δt / g) ∫_f (V · N_f) Δp dl ≈ (Δt / g) (ℓ_f / n) Σ_q N_f · (V Δp)(x_q).A cube face is a great-circle arc, so its unit normal N_f (oriented from the face's left to its right cell, as in CSVectorFaceGeometry) is the same 3-vector at every point of the arc. The integrand is sampled at n = samples_per_face equally spaced midpoints x_q of the arc of length ℓ_f, where the Cartesian components of V Δp are interpolated bilinearly from the source cells. The integral is therefore a fixed linear map of the source fields, stored as one sparse matrix L = [L_X L_Y L_Z] (faces × 3 source cells),
F = (Δt / g) L [X Δp; Y Δp; Z Δp],with X = −sin λ u − sin φ cos λ v, Y = cos λ u − sin φ sin λ v, Z = cos φ v the Cartesian wind components of each source cell. Cartesian components are smooth across the poles, unlike u and v.
source_mesh may be a ReducedGaussianMesh (ERA5 N320) or a regular LatLonMesh (the spectral-to-cube staging grid). With 16 samples a C90 face (≤ 1.2°) is sampled every ≤ 0.08°, about four times per N320 cell.
AtmosTransport.Preprocessing.MassClosure.OuterCellPair Type
OuterCellPairThe outer cells of FV3's fourth-order stencil (−1, 9, 9, −1)/16 across a face (see CSVectorFaceGeometry): for face f with slot[f] ≠ 0, the cells cell[slot[f]] two rows from the face and their weighted face-normal coefficients coef[slot[f]] (the -1/16 terms).
AtmosTransport.Preprocessing.MassClosure.ScalarWindRegrid Type
ScalarWindRegrid()Remap u and v as two independent scalars (historical default). Their basis vectors turn with longitude, so near a pole a cube cell averages components that point in different directions. A C90 cell touching the pole spans 90° of longitude, and its remapped wind is off by about 5% for a flow across the pole; the resulting spurious divergence poleward of 88° is several times the global RMS divergence (docs/src/theory/vertical_transport.md).
AtmosTransport.Preprocessing.Common.column_weights Method
column_weights(kind::Symbol, B) -> AbstractColumnWeightsWeights named kind (a key of COLUMN_WEIGHT_KINDS) for hybrid interfaces B, top first.
AtmosTransport.Preprocessing.Common.spread_column_correction! Method
spread_column_correction!(flux, delta, weights, m_a, m_b)Add the column correction delta (kg per flux application) of one face to the face's layer fluxes flux[k], k = 1 … Nz (top first), with m_a[k] and m_b[k] the air masses of the two cells that share the face:
where the finite, non-negative layer weight w_k comes from weights (see AbstractColumnWeights): w_k = max(m_{a,k},0) + max(m_{b,k},0) for MassWeightedColumn(). Each increment is rounded to the flux type. The last level with positive weight receives δ minus the realized changes of the other levels, so a hybrid mask can never leak a correction into an excluded level. A non-finite weight or Σ_j w_j = 0 is an error: no physically defined vertical distribution exists in that case.
This is the vertical distribution step of every column Poisson balance (the lat-lon balance_column_mass_fluxes!, the reduced-Gaussian balance_compressed_column_fluxes! and the cubed-sphere balance_cs_column_mass_fluxes!).
AtmosTransport.Preprocessing.MassClosure.apply_cs_flux_correction! Method
apply_cs_flux_correction!(panels_am, panels_bm, psi, ft, k)Apply the Poisson correction to per-panel am and bm arrays at level k.
For each face, the correction is δflux = psi[face_right] - psi[face_left]. Cross-panel mirror entries are set equal to the corrected canonical value (same sign — both entries describe "mass flows from p to q" as positive).
AtmosTransport.Preprocessing.MassClosure.balance_compressed_column_fluxes! Method
balance_compressed_column_fluxes!(hflux, m_cur, m_next, face_left, face_right,
L::CompressedLaplacian, steps_per_window, scratch;
weights = MassWeightedColumn(),
tol = DEFAULT_POISSON_BALANCE_TOL,
max_iter = DEFAULT_POISSON_BALANCE_MAX_ITER)Column Poisson balance of the face-indexed horizontal fluxes hflux[f, k] of a reduced-Gaussian window (kg per application, twice per substep; m_cur and m_next are the window's endpoint air masses, (ncells, Nz), top first).
One window of n = steps_per_window substeps, whose palindrome applies each window flux twice, must take m_cur to m_next:
with the vertical mass flux C (cm) zero at the top and at the surface. Summed over a column the C terms cancel, so the horizontal fluxes must satisfy the column budget
One Jacobi-preconditioned CG solve of L ψ = D(Σ_k F_k) − T (L the graph Laplacian with face multiplicities, CompressedLaplacian; the right-hand side removes the global mode in proportion to current column mass only with fixed_global_mass=true, after checking the independent fixed-target global budget; otherwise it retains the uniform mode. It is then accurately projected to zero mean) gives every interior face the column correction δ_f = ψ_{right(f)} − ψ_{left(f)}, which changes the column divergence by −Lψ. Each δ_f is spread over the layers by spread_column_correction! (air mass of the two cells for MassWeightedColumn()). The vertical mass flux then follows from the explicit tendency, recompute_cm_from_dm_target!, and carries the vertical motion. The lat-lon (balance_column_mass_fluxes!) and cubed-sphere (balance_cs_column_mass_fluxes!) paths balance the same way.
Balancing every level to its own tendency instead, D_c(F_k) = T_{c,k}, leaves cm only the column residual: about 1e-4 of the vertical mass flux on the O24 test day (issue #11). The CG works on the compressed Laplacian; the corrections go to every face-indexed flux, LCM duplicates included, which is equivalent because ψ is cell-valued.
Returns the column residuals before and after (max_pre_raw_residual, max_post_raw_residual, kg per application), the residual mean the solve cannot remove (max_rhs_mean), the projected residuals (max_pre_projected, max_post_projected, the latter |Lψ − rhs| of the solve), the CG iterations and the largest face correction (max_face_delta).
AtmosTransport.Preprocessing.MassClosure.balance_cs_column_mass_fluxes! Method
balance_cs_column_mass_fluxes!(panels_am, panels_bm, panels_m, panels_m_next,
ft, degree, steps_per_window, scratch; ...)Apply vertically integrated CS Poisson corrections, then distribute every physical face correction over levels with weights (MassWeightedColumn(), local air mass, by default; HybridBWeightedColumn follows TM5). Seam faces use the two cells in ft.face_left/right, independent of which panel owns the canonical stored face.
With fixed_global_mass=true, the independent global dry-mass budget guard runs before any flux correction. The projected column equation is
For moist or unpinned windows, leave fixed_global_mass=false (the default): q_c = 1, with no mass-proportional shift or zero-global-change assertion.
Corrections repeat until every cell has |r_c^⊥| ≤ τ_c or closure_passes is exhausted, in which case this function raises. The typed tolerance is per cell,
the requested absolute tolerance (COLUMN_CLOSURE_TOL_KG, 10 kg, by default) for Float64 and a conservative representability bound of the cell's own stored faces for Float32 redistribution (a global maximum over cells would let a small-flux cell keep a residual set by the largest-flux cell). The returned final_column_residual_ratio = max_c |r_c^⊥|/τ_c must still be checked by production callers with require_cs_column_balance; τ_c stays in scratch.tol (final_column_tolerance_by_cell) for the cm diagnosis.
This is the ERA CS default. It enforces the column mass budget required by zero top/bottom cm while avoiding the legacy per-layer correction that can rewrite real vertical wind shear.
AtmosTransport.Preprocessing.MassClosure.balance_cs_global_mass_fluxes! Method
balance_cs_global_mass_fluxes!(panels_am, panels_bm, panels_m, panels_m_next,
ft, degree, steps_per_window, scratch;
tol=DEFAULT_POISSON_BALANCE_TOL,
max_iter=DEFAULT_POISSON_BALANCE_MAX_ITER)TM5-style global Poisson mass-flux balance for a 6-panel cubed sphere.
Corrects panels_am[p] and panels_bm[p] so that horizontal flux convergence at every cell matches the prescribed mass tendency:
dm_dt[c, k] = (m_next[c, k] - m_cur[c, k]) / (2 × steps_per_window)Returns a diagnostic NamedTuple with pre/post residuals and CG iteration counts. mass_weighted_global_mode=true is used on the single-level column buffers by balance_cs_column_mass_fluxes!; the standalone per-level balance defaults to its original uniform global mode.
AtmosTransport.Preprocessing.MassClosure.balance_cs_level! Method
Balance a CS layer against explicit outward divergence, keeping seam mirrors.
sourceAtmosTransport.Preprocessing.MassClosure.build_compressed_laplacian Method
build_compressed_laplacian(face_left, face_right, nc) -> CompressedLaplacianCompress the face-indexed graph Laplacian into cell-to-cell adjacency. Iterates over faces once to build the compressed representation.
sourceAtmosTransport.Preprocessing.MassClosure.compute_cs_cm_pressure_fixer! Method
compute_cs_cm_pressure_fixer!(cm_panels, am_v4, bm_v4, ΔB, Nc, Nz)Diagnose the vertical mass flux cm from the column horizontal flux convergence using FV3's pressure-fixer rule:
pit[i,j] = Σ_k (am[i,j,k] − am[i+1,j,k] + bm[i,j,k] − bm[i,j+1,k])
cm[i,j,1] = 0
cm[i,j,k+1] = cm[i,j,k] + (am[i,j,k] − am[i+1,j,k] + bm[i,j,k] − bm[i,j+1,k])
− ΔB[k] · pit[i,j]Σ ΔB[k] = 1 by construction of a hybrid sigma-pressure coordinate, so cm[Nz+1] = 0 exactly: the surface no-flux boundary condition is enforced without any per-cell residual redistribution. This is the same formulation used by the historical GEOS-FP CS forward runner (commit 76fa489, compute_cm_panel_cpu!) and matches GFDL FV3's discrete continuity.
Use this on native-source paths (GEOS-IT, GEOS-FP) where dry-mass horizontal flux divergence is NOT closed by m_next − m_cur per cell (vertical moisture transport contributes). For sources where the closure DOES hold by construction (Poisson-balanced spectral → CS), use diagnose_cs_cm! instead — it derives cm from (am, bm, dm) directly.
AtmosTransport.Preprocessing.MassClosure.cs_cell_face_degree Method
cs_cell_face_degree(ft::CSGlobalFaceTable) -> Vector{Int}Compute face degree for each global cell. On a closed CS, every cell has degree 4.
sourceAtmosTransport.Preprocessing.MassClosure.cs_column_convergence Method
Sum native horizontal convergence in ascending level order and the flux element type.
sourceAtmosTransport.Preprocessing.MassClosure.cs_face_fluxes! Method
cs_face_fluxes!(am_panels, bm_panels, u_cs, v_cs, dp_panels, face_lengths,
gravity, dt_factor, Nc, Nz)Face mass fluxes from cell-center face-normal winds and layer thicknesses: the two adjacent cells are averaged and multiplied by the face length,
am[i,j,k] = ū × d̄p × L_x[i,j] / g × dt_factor
bm[i,j,k] = v̄ × d̄p × L_y[i,j] / g × dt_factorPanel-edge faces use the adjacent cell's values; CS edge mirrors are synchronized before the binary is written.
sourceAtmosTransport.Preprocessing.MassClosure.cs_graph_laplacian_mul! Method
cs_graph_laplacian_mul!(out, psi, ft, degree)Compute out = L · psi for the global CS graph Laplacian.
AtmosTransport.Preprocessing.MassClosure.cs_level_scratches Method
Allocate independent per-thread CS solve scratch, reusing the supplied first slot.
sourceAtmosTransport.Preprocessing.MassClosure.cs_vector_face_fluxes! Method
cs_vector_face_fluxes!(am_panels, bm_panels, u_east, v_north, dp_panels,
geom, face_table, gravity, dt_factor, Nc, Nz)Face mass fluxes from cell-centre east/north winds, treated as vectors (see CSVectorFaceGeometry): the two cells' winds, interpolated to the face midpoint and projected onto the face normal, times the interpolated layer thickness and the face's great-circle length,
F = u_n × dp × L / g × dt_factor,with the along-edge interpolation at panel seams. Mirror entries of the seam faces are written from the canonical ones with their signs (sync_cs_mirrors!).
AtmosTransport.Preprocessing.MassClosure.diagnose_balanced_cs_cm! Method
diagnose_balanced_cs_cm!(..., balance_diag, context[, weights])Production bridge between column balance and vertical-flux diagnosis. It explicitly checks balance_diag.final_column_residual_ratio ≤ 1 (every cell's projected residual within its own closure tolerance), then passes the same per-cell tolerances (final_column_tolerance_by_cell) to diagnose_cs_cm!, whose returned diagnostic books any residual folded into cm.
AtmosTransport.Preprocessing.MassClosure.diagnose_cs_cm! Method
diagnose_cs_cm!(panels_cm, panels_am, panels_bm, panels_dm, panels_m, Nc, Nz[, weights];
residual_tol=COLUMN_CLOSURE_TOL_KG, context="cm diagnosis")Diagnose vertical mass flux cm from column-balanced horizontal flux divergence and mass tendency for all 6 panels:
The raw surface residual R_c = C_{N_z+1} of column c is never folded silently. It must satisfy
where τ_c is residual_tol (a number, or a vector over the 6 N_c^2 cells in face-table order) and the sum bounds the rounding of the recursion above in the storage type FT; otherwise this function raises before redistribution, naming [mass_fix] when the global-mean residual (a change of the global air mass that no horizontal flux can remove) dominates. Accepted residuals are booked in the returned diagnostics and folded back as
Weights must be finite and have a positive sum. Production callers pass the per-cell closure tolerance of balance_cs_column_mass_fluxes! (diagnose_balanced_cs_cm!).
AtmosTransport.Preprocessing.MassClosure.fill_cs_layer_thickness! Method
fill_cs_layer_thickness!(dp_panels, ps_panels, A_ifc, B_ifc, Nc, Nz)Layer pressure thickness |A_k − A_{k+1} + (B_k − B_{k+1}) ps| of every cell.
AtmosTransport.Preprocessing.MassClosure.geos_native_to_face_flux! Method
geos_native_to_face_flux!(am_v4, bm_v4, am_native, bm_native, conn, Nc, Nz, scale)Convert GCHP-convention cell-centered mass fluxes to v4 face-staggered arrays.
GCHP semantic: MFXC[i, j, k] is the eastward mass flux at the east face of cell (i, j, k). The v4 convention has am[i, j, k] as the flux through face index i (where i=1 is the west boundary, i=Nc+1 is the east boundary, and i=2..Nc are interior faces between cells i-1 and i). The mapping is therefore:
am_v4[i+1, j, k] = MFXC[i, j, k] * scale for i = 1..NcLikewise for MFYC → bm. The west halo am_v4[1, :, :] and south halo bm_v4[:, 1, :] come from the corresponding neighbor panel's NORTH or EAST canonical (the same physical face), with a sign flip when both edges sit at outflow. This is a one-way propagation: we never overwrite a canonical (Nc+1) face. (sync_all_cs_boundary_mirrors! is bidirectional and would clobber correctly-filled canonicals when paired with a zero-initialized halo on the partner panel.)
scale is multiplied into every face value (typically dt_factor / g for unit conversion to the v4 binary's kg per substep).
AtmosTransport.Preprocessing.MassClosure.line_integral_face_fluxes! Method
line_integral_face_fluxes!(am, bm, method, u, v, dp, gravity, dt_factor, Nz)Line-integral face fluxes with explicitly supplied pressure thickness dp[source_cell, level]. The dry-air path supplies dp selected by the caller's existing dry-thickness policy.
AtmosTransport.Preprocessing.MassClosure.line_integral_face_fluxes! Method
line_integral_face_fluxes!(am, bm, m::LineIntegralFaceFluxes, u, v, ps, A, B,
gravity, dt_factor, Nz)Fill the face mass fluxes am, bm (per panel, levels 1:Nz) with the line integrals of LineIntegralFaceFluxes, from the source east/north winds u, v (source cell × level) and surface pressure ps (Pa). The layer thickness of source cell c is Δp = |ΔA_k + ΔB_k ps_c| from the hybrid interfaces A, B, as for the cell-centre flux methods. Mirror entries of the panel-seam faces are written from the canonical ones.
AtmosTransport.Preprocessing.MassClosure.point_weights Method
point_weights(mesh::LatLonMesh, x) -> NTuple{4, Tuple{Int, Float64}}Bilinear interpolation weights at the unit vector x from a regular latitude-longitude mesh. Longitude is periodic and is bracketed relative to the mesh's actual first centre (so meshes centred on 0° and meshes centred on ±180° both work). Latitude is linear between adjacent centres; poleward of the outermost centres the nearest row is used. Flat indices use the mesh's longitude-fast storage order, c = i + (j - 1) Nx.
AtmosTransport.Preprocessing.MassClosure.point_weights Method
point_weights(mesh::ReducedGaussianMesh, x) -> NTuple{4, Tuple{Int, Float64}}Bilinear interpolation weights at the unit vector x from the cell centres of a reduced Gaussian mesh: linear in longitude along the two rings that bracket the latitude (cell centres at (i − ½) Δλ), then linear in latitude between them. Poleward of the outermost ring the outermost ring is used alone.
AtmosTransport.Preprocessing.MassClosure.project_mean_zero! Method
Compensated nullspace projection selected only by column solves.
sourceAtmosTransport.Preprocessing.MassClosure.project_mean_zero! Method
project_mean_zero!(v)Subtract the mean of v in-place. Used to keep Conjugate-Gradient iterates in the range of the singular graph Laplacian (which has a 1-dimensional constant null space on the CS and reduced-Gaussian graphs).
AtmosTransport.Preprocessing.MassClosure.recheck_cs_column_closure Method
recheck_cs_column_closure(panels_am, panels_bm, panels_m, panels_m_next, ft,
steps_per_window, scratch, balance_diag;
closure_tol = COLUMN_CLOSURE_TOL_KG,
flux_scale = 1.0) -> balance_diag′Recompute the column-closure statistics and per-cell tolerances of balance_cs_column_mass_fluxes! for fluxes changed after the balance (the GEOS OMEGA reconstruction moves flux between levels of a column; GEOS stores full-window amounts), so the cm diagnosis and the recorded closure describe the fluxes that are stored. flux_scale converts the given amounts to amounts per flux application before the check (1/(2 steps_per_window) for full-window amounts); residuals and tolerances are per application. Returns balance_diag with its final_column_* fields replaced.
AtmosTransport.Preprocessing.MassClosure.reconstruct_cs_fluxes! Method
reconstruct_cs_fluxes!(am_panels, bm_panels, u_cs, v_cs, dp_panels,
ps_panels, A_ifc, B_ifc, Δx, Δy,
gravity, dt_factor, Nc, Nz;
face_lengths = CellCenterlineLengths(Δx, Δy))Reconstruct per-panel horizontal mass fluxes from regridded cell-center winds, with the layer thickness dp = A_{k+1} − A_k + (B_{k+1} − B_k) ps of each cell (see cs_face_fluxes!).
AtmosTransport.Preprocessing.MassClosure.recover_ll_cell_center_winds! Method
recover_ll_cell_center_winds!(u_cc, v_cc, am_ll, bm_ll, ps_ll,
A_ifc, B_ifc, lats_deg,
Δy_ll, Δlon_ll, radius, gravity, dt_factor)Recover cell-center u,v wind components from LL mass fluxes by dividing by the cross-sectional area factor: am / (Δy × dp/g × dt_factor).
dt_factor = dt_met / (2 × steps_per_window) is the flux scaling used in the binary.
AtmosTransport.Preprocessing.MassClosure.regrid_winds! Method
regrid_winds!(method, u_cs, v_cs, regrid!, u, v)Regrid the source east/north winds u, v to the east/north cube panels u_cs, v_cs with method, an AbstractWindRegrid. regrid!(panels, field) remaps one source field, in the layout of u (lon × lat × level, or cell × level, level last), to cube panels; it must not keep field, which may be a reshaped internal buffer.
AtmosTransport.Preprocessing.MassClosure.rotate_winds_to_panel_local! Method
rotate_winds_to_panel_local!(u_panel, v_panel, u_east, v_north,
mesh, Nz)Rotate geographic (east, north) wind components to cubed-sphere face-normal components for all 6 panels.
u_panel is the wind normal to local-x faces, scaled with Δy when reconstructing am; v_panel is the wind normal to local-y faces, scaled with Δx when reconstructing bm. The panel tangent directions on the gnomonic cubed sphere are not generally orthogonal, so these are not simple dot products onto the local x/y tangents. The routine derives the two face normals from the convention-aware tangent basis and projects onto those normals.
AtmosTransport.Preprocessing.MassClosure.solve_compressed_poisson_pcg! Method
solve_compressed_poisson_pcg!(psi, rhs, L::CompressedLaplacian, scratch;
tol=DEFAULT_POISSON_BALANCE_TOL,
max_iter=DEFAULT_POISSON_BALANCE_MAX_ITER)Solve the singular system L · psi = rhs via Jacobi-Preconditioned CG using the compressed Laplacian. Mathematically identical to the face-indexed graph-Laplacian solver but ~16-27× faster due to compressed MatVec.
The compressed Laplacian has the same 1-D constant null space as the face-indexed version, so the same mean-zero projection is applied.
sourceAtmosTransport.Preprocessing.MassClosure.solve_cs_poisson_pcg! Method
solve_cs_poisson_pcg!(psi, rhs, ft, degree, scratch; tol=DEFAULT_POISSON_BALANCE_TOL,
max_iter=DEFAULT_POISSON_BALANCE_MAX_ITER,
project_every=DEFAULT_POISSON_PROJECT_EVERY)Jacobi-Preconditioned CG for the global CS graph Laplacian L · psi = rhs.
L has a 1-D constant null space (closed surface), so we project rhs and iterates to mean-zero. The graph Laplacian preserves the mean-zero subspace, so the residual/preconditioned residual projection is applied periodically rather than every iteration by default; set project_every=1 to recover the fully projected legacy path. Returns (residual_linfty, iterations).
AtmosTransport.Preprocessing.MassClosure.sync_all_cs_boundary_mirrors! Method
sync_all_cs_boundary_mirrors!(panels_am, panels_bm, conn, Nc, Nz)Comprehensive boundary flux mirror sync using panel connectivity directly.
Iterates all 12 physical edges of the cubed sphere (all 4 directions per panel, de-duplicated by p < q). For each edge, copy the lower-numbered canonical panel's boundary flux to its neighbor's mirror slot.
Sign convention: when canonical and mirror are both at inflow positions (i=1 or j=1) or both at outflow positions (i=Nc+1 or j=Nc+1), negate so that per-panel flux telescoping conserves mass.
Call after modifying canonical boundary fluxes to propagate them to all mirror positions. Column balance already synchronizes through its face table.
sourceAtmosTransport.Preprocessing.MassClosure.sync_cs_mirrors! Method
sync_cs_mirrors!(panels_am, panels_bm, ft, Nz)Copy canonical boundary flux values to their cross-panel mirror entries for all levels.
sourceAtmosTransport.Preprocessing.PhysicsInputs.BLDiffColumnScratch Type
BLDiffColumnScratch{FT}(Nz)Per-column work buffers for [tm5_bldiff_center_kz_column!]. Allocate once per thread and reuse across the millions of columns in a global preprocess to avoid per-column allocation.
AtmosTransport.Preprocessing.PhysicsInputs.BLDiffConstants Type
BLDiffConstants{FT}Physical constants for the TM5 boundary-layer diffusion scheme. Defaults reproduce TM5's binas module and the hard-coded bldiff parameters; they are exposed as a struct so tests can probe sensitivities without editing the kernel.
Thermodynamic constants
grav— gravitational acceleration (m s⁻²)cp_air— specific heat of dry air at constant pressure (J kg⁻¹ K⁻¹)r_air— specific gas constant for dry air (J kg⁻¹ K⁻¹)r_vap— specific gas constant for water vapour (J kg⁻¹ K⁻¹)l_vap— latent heat of vaporisation (J kg⁻¹)vkarman— von Kármán constantp_ref— reference pressure for potential temperature (Pa)
Derived: kappa = r_air / cp_air, vt_coef = r_vap/r_air - 1 (the 0.61 in the virtual-temperature correction).
Scheme parameters (Holtslag & Boville constants)
ri_crit— critical bulk Richardson number defining the PBL topsf_frac— surface-layer fraction of the PBL depthbeta_m/_h— stability-function slopes for momentum/heatfak,fakn— convective excess factor and counter-gradient factorustar_shear— coefficient of the ustar shear term in the bulk Richardson number (zacbin TM5)kvh_min— floor on the in-PBL diffusivity (m² s⁻¹)kv_free_min— floor on the free-troposphere diffusivity (m² s⁻¹)pblh_min— floor on the diagnosed PBL height (m)ustar_min— floor on the friction velocity u* entering the Obukhov length and the velocity scales (m s⁻¹)
AtmosTransport.Preprocessing.PhysicsInputs.BLDiffDiag Type
BLDiffDiag{FT}()Per-thread counters for the boundary-layer diffusion fallbacks, accumulated by [tm5_bldiff_kvh_column!] over the columns of one window so the preprocessor can log how often (and how hard) the entrainment override was skipped or the output guard fired — a few stray cells is expected; widespread fallback means a met problem to investigate, not silently fill.
AtmosTransport.Preprocessing.PhysicsInputs.TM5ConvectionColumnScratch Type
TM5ConvectionColumnScratch{FT}Per-column storage for converting ECMWF convection diagnostics to TM5 entrainment and detrainment on the target grid. One instance is allocated per Julia thread and reused across panels, cells, and windows.
sourceAtmosTransport.Preprocessing.PhysicsInputs.TM5CleanupStats Method
TM5CleanupStats() -> NamedTuple of Ref{Int} countersDiagnostic counters bumped by ec2tm_from_rates!. Nothing-overhead when the function runs without stats (pass nothing); when stats are passed, each counter increments once per level/column that hit the corresponding cleanup branch.
columns_processed— total columns the function was called on.no_updraft— columns with no level satisfyingudmf > 0(after small-value clipping). entu/detu zeroed out.no_downdraft— columns with no level satisfyingddmf < 0.levels_udmf_clipped,levels_ddmf_clipped— levels where half-level mass flux magnitude was below 1e-6 kg/m²/s and got zeroed.levels_udrf_clipped,levels_ddrf_clipped— full-level detrainment rates zeroed (|rate| < 1e-10 kg/m³/s).levels_entu_neg,levels_detu_neg,levels_entd_neg,levels_detd_neg— levels where the indicated output went negative and got fixed via symmetric redistribution with its complementary rate.columns_closure_entu,columns_closure_entd— columns where the column closure moved a non-zero residualΣdet − Σent. For ERA5 input that residual is rounding (or a flux through the model top); seeec2tm_from_rates!.
Interpretation
On clean data we expect ~0% clipped levels and ~0 no-updraft columns (outside pure stratospheric columns). O(1%) redistribution firings are normal TM5 behaviour. O(50%) firings indicate a data pathology (wrong param IDs, wrong stream, bad units).
sourceAtmosTransport.Preprocessing.PhysicsInputs.dz_hydrostatic_virtual! Method
dz_hydrostatic_virtual!(dz, T_col, Q_col, ps, ak, bk, Nz) -> dzCompute layer thickness dz[1:Nz] (m) at layer centers from a single column's temperature T_col[1:Nz] (K) and specific humidity Q_col[1:Nz] (kg/kg), plus surface pressure ps (Pa) and the hybrid-sigma coefficients ak, bk (length Nz+1).
Uses the hydrostatic approximation with virtual temperature:
p_top[k] = ak[k] + bk[k] * ps (Pa, higher-altitude side)
p_bot[k] = ak[k+1] + bk[k+1] * ps (Pa, lower-altitude side)
dp[k] = p_bot[k] - p_top[k] (> 0 in AtmosTransport orientation)
p_mid[k] = 0.5 · (p_top[k] + p_bot[k])
T_v[k] = T_col[k] · (1 + 0.61 · Q_col[k])
dz[k] = R · T_v[k] / g · dp[k] / p_mid[k]Orientation: AtmosTransport (k=1=TOA, k=Nz=surface). ak/bk are the full (Nz+1)-length ERA5 L137 hybrid coefficients.
For the TOA half-level we fall back to an ordinary scale-height estimate (T_v=T_top, p_mid=p_bot) when p_top → 0. In practice the top-level dz is never in the convection window so the approximation is irrelevant; it's a guard against divide-by-zero.
AtmosTransport.Preprocessing.PhysicsInputs.ec2tm_from_rates! Method
ec2tm_from_rates!(entu, detu, entd, detd,
udmf, ddmf, udrf_rate, ddrf_rate,
dz, Nz; stats=nothing, ddrf_layer_above=true) -> nothingColumn-level port of TM5's ECconv_to_TMconv (see deps/tm5/base/src/phys_convec_ec2tm.F90:87-237). Fills the output arrays entu, detu, entd, detd (kg/m²/s at layer centers) in place from raw ERA5 physics inputs. All arrays use AtmosTransport orientation (k=1=TOA, k=Nz=surface).
Inputs
udmf::AbstractVector{FT}, lengthNz+1— updraft mass flux at half levels (kg/m²/s). Half levelkis the interface at the TOP of layerk;udmf[Nz+1]is the ground and must be zero (after clipping; anArgumentErrorotherwise). ERA5 archives UDMF levelk(1 = model top) as the flux through the top of layerk, so callers pass[GRIB levels 1..Nz; 0], as TM5'stmm.F90does (udmf_gg(:,0:nlev-1) = buf; udmf_gg(:,nlev) = 0). Must be ≥ 0.ddmf::AbstractVector{FT}, lengthNz+1— downdraft mass flux at half levels, ECMWF convention (≤ 0), packed likeudmf.udrf_rate::AbstractVector{FT}, lengthNz— updraft detrainment RATE at layer centers (kg/m³/s).ddrf_rate::AbstractVector{FT}, lengthNz— downdraft detrainment RATE as archived on GRIB levelk(kg/m³/s). The IFS steps its downdraft from the layer above, so the rate it archives on levelkis the detrainment of layerk - 1(seeddrf_layer_above).dz::AbstractVector{FT}, lengthNz— layer thickness (m), positive. Compute fromdz_hydrostatic_virtual!.Nz::Int— number of full levels.stats::Union{Nothing, NamedTuple}— cleanup-stats counters fromTM5CleanupStats(). Whennothing, no counter work.ddrf_layer_above::Bool = true— read the downdraft detrainment archived on levelkas that of layerk - 1:detd[k] = ddrf_rate[k + 1] * dz[k + 1],detd[Nz] = 0(step 5 then gives the lowest layer the flux that reaches the ground), and level 1 has no layer above it and is dropped. The IFS steps the downdraft from the layer above, closing-pmfd(jk) + pmfd(jk-1) + pmfdde_rate(jk)(ECMWFCUCTRACER; ICON's public IFS port,mo_cudescn.f90:651,mo_cumaster.f90:1778/1784/2326), so the detrainment archived on levelkbelongs to the layer above levelk.falsereads it on its own layer, as TM5'sECconv_to_TMconvdoes; on ERA5 that same-layer reading turns about a quarter of the downdraft detrainment into negative entrainment, which step 5 then moves. The updraft detrainment is always read on its own layer.
Algorithm (line-for-line match to F90 lines 132-236)
Copy-with-clipping (F90 L132-144).
|udmf| < 1e-6 → 0,|ddmf| < 1e-6 → 0(applied asddmf > -1e-6 → 0),udrf_rate < 1e-10 → 0,ddrf_rate < 1e-10 → 0.dz integration (F90 L146-151):
detu = udrf × dz(kg/m³/s → kg/m²/s). Same for detd, on the level it was archived on, then moved up one layer unlessddrf_layer_above = false.Cloud-top search (F90 L153-173,
do l = 1, lm; if (mflu(l) > 0)): the cloud-top layeruptopis the highest layer whose BOTTOM interface carries updraft, i.e.uptop = k - 1for the first interfacek ∈ 2:Nz+1withudmf[k] > 0;dotoplikewise withddmf[k] < 0. The model-top interface 1 is not searched, as in TM5. If none, zero out everything in that direction.Layer budgets (F90 L175-212): for each active direction,
entu[k] = udmf[k] - udmf[k+1] + detu[k](out through the top, minus in through the bottom, plus detrainment) fork = uptop:Nz; layers aboveuptopstay zero.Symmetric negative redistribution (F90 L214-232): if
entu[k] < 0, add-entu[k]todetu[k]and zeroentu[k]. Same fordetu<0(adds to entu), and the same two for downdraft.Column closure (TM5
meteo.F90:2023-2052): the residualΣdetu − Σentuis added to the layer of largest entrainment (on the detrainment side when it is negative, so nothing turns negative).
Mass conservation
In every layer entu[k] - detu[k] = udmf[k] - udmf[k+1], the flux convergence (step 4; the redistribution of step 5 keeps entu - detu). Summed over the column this telescopes to udmf[uptop] - udmf[Nz+1] = 0: no flux crosses the top of the cloud-top layer or the ground, so the TM5 fields reproduce the input fluxes at every interface and the closure of step 6 moves only rounding (or a flux through the model top, which TM5 does not exclude either).
AtmosTransport.Preprocessing.PhysicsInputs.ecmwf_convection_to_basis! Method
ecmwf_convection_to_basis!(basis, udmf, ddmf, udrf, ddrf, q) -> nothingPut one column of ECMWF convective fields (top-first, Nz = length(q) layers) on the air-mass basis of the transport binary before ec2tm_from_rates! turns them into TM5 entrainment and detrainment.
udmf,ddmf(lengthNz + 1): updraft and downdraft mass fluxes at the interfaces, kg m⁻² s⁻¹; interfacekis the top of layerk.udrf,ddrf(lengthNz): updraft and downdraft detrainment rates at the layer centres, kg m⁻³ s⁻¹.q(lengthNz): specific humidity at the layer centres, kg kg⁻¹.
ECMWF fluxes are per unit of total (moist) air. For DryBasis() they become dry-air fluxes,
for the interface fluxes M (udmf, ddmf) and the centre rates D (udrf, ddrf), with the interface humidity q̂_k of interface_specific_humidity, so the TM5 rates entu / m_dry equal TM5's own entu / m_moist. Converting the inputs keeps the ec2tm budget entu − detu = udmf[k] − udmf[k+1] exact. MoistBasis() leaves the fields unchanged. ec2tm's noise thresholds then act on the converted values.
AtmosTransport.Preprocessing.PhysicsInputs.era5_surface_source_mesh Method
era5_surface_source_mesh(reader, radius) -> LatLonMeshBuild the ERA5 single-level source mesh from the coordinates stored in the open file. SnappedFaces preserves the point-registered 0.25° grid: the longitude points remain cell centres and the latitude rows at ±90° become half-width polar caps. The returned coordinate order matches the normalized surface arrays produced by load_era5_surface_window.
AtmosTransport.Preprocessing.PhysicsInputs.era5_tm5_convection_header Method
era5_tm5_convection_header(include_convection::Bool) -> Dict{String, Any}Header record of TM5 convection sections that a writer derived from ERA5 with ec2tm_from_rates!: their source (TM5_CONVECTION_SOURCE_KEY => "ec2tm_from_rates(udmf,ddmf,udrf,ddrf)") and the index convention (TM5_EC2TM_CONVENTION_KEY => TM5_EC2TM_CONVENTION), which readers require of ERA5-derived sections. Without convection the record is only the source "none".
AtmosTransport.Preprocessing.PhysicsInputs.interface_specific_humidity Method
interface_specific_humidity(k, Nz, q...) -> q̂_k
interface_specific_humidity(k, Nz, i, j, q...) -> q̂_kSpecific humidity at interface k of a top-first column of Nz layers (interface k is the top of layer k; k = 1 is the model top and k = Nz + 1 the surface), the mean of the adjacent layer centres:
where q_k is the value at the centre of layer k and q̂_k the value at interface k.
Each q is a column of layer-centre values indexed by level; with several columns (time samples, e.g. the start and end of a window) the result is also averaged over them, in the order q[1][k-1], q[1][k], q[2][k-1], ..., which is the four-corner mean of GEOS CMFMC (moist_to_dry_cmfmc!).
The (i, j, q...) method applies the identical rule directly to columns of three-dimensional arrays without constructing a view in the GEOS grid loop.
AtmosTransport.Preprocessing.PhysicsInputs.load_era5_surface_window Method
load_era5_surface_window(reader, win_idx, FT; with_latent = false) -> NamedTupleRead one time window of ERA5 surface fields, normalised to the lat-lon transport-binary convention (longitude on [-180, 180), latitude south→north). Instantaneous fields use the start of the window. Hourly heat accumulations use its end (the next day's 00 UTC record for the last window of the day); the source archive must include that record.
Returns (pblh, t2m, ustar, hflux):
pblh— boundary-layer height (m),t2m— 2 m temperature (K),ustar— friction velocity (m s⁻¹), read directly when ERA5zustis present, otherwise estimated from the 10 m wind via a constant drag coefficient (warns once per source path),hflux— surface sensible heat flux, upward-positive (W m⁻²).
With with_latent = true the result additionally carries
lhflux— surface latent heat flux, upward-positive (W m⁻²),
which the TM5 boundary-layer diffusion scheme (bldiff) needs to form the surface virtual heat flux. It is opt-in so existing callers that only need the four PBL fields neither require slhf in the file nor change behaviour.
AtmosTransport.Preprocessing.PhysicsInputs.load_tm5_pbl_window Method
load_tm5_pbl_window(reader, endpoint_reader, record, FT=Float64;
endpoint_record=record+1, interval_seconds)Ten surface primitives for live Calc_Kzz. Instantaneous winds and roughness are means of hourly analysis endpoints; lsm and orography are constant. Hourly reanalysis accumulated heat/stress fields are the record ending at the right endpoint and are divided by the actual interval. Heat stays ECMWF downward-positive. Already exported W/m² and N/m² pass unchanged. The endpoint reader can be the next day's reader at midnight. fsr replaces TM5's Olsson roughness; when sr is absent, fsr supplies both roles.
AtmosTransport.Preprocessing.PhysicsInputs.open_tm5_pbl_surface_reader Method
Open native-resolution TM5 surface inputs, supporting plain, split ZIP and ARCO NetCDF layouts.
sourceAtmosTransport.Preprocessing.PhysicsInputs.surface_flux_to_upward_wm2 Method
surface_flux_to_upward_wm2(raw, ds, var_name, FT) -> Matrix{FT}Normalise an ERA5 surface turbulent heat flux to upward-positive W m⁻².
ERA5 reports sshf (sensible) and slhf (latent) as time-accumulated energy over the output interval (J m⁻², downward-positive). Two corrections recover an instantaneous, upward-positive flux:
divide by 3600 (
ERA5_MET_INTERVAL_SECONDS) — the accumulation window is one hour, so J m⁻² becomes W m⁻²;flip the sign — ERA5 uses downward-positive, while the boundary-layer scheme (and atmospheric convention) treats an upward surface flux of heat into the atmosphere as positive.
Fields already stored as a rate (units without J, e.g. a pre-divided W m⁻² export) pass through unchanged. The accumulated case is detected either from the units attribute containing J or from the canonical short/long names of the two accumulated fluxes.
AtmosTransport.Preprocessing.PhysicsInputs.tm5_bldiff_center_kz_column! Method
tm5_bldiff_center_kz_column!(kz, T, q, u, v, ps, hflux, lhflux, ustar,
A, B, c, scratch) -> pblhCompute the layer-centre TM5 eddy diffusivity (m² s⁻¹) for one column given the model's top-down profiles, writing into kz (top-down, length Nz) and returning the diagnosed PBL height (m).
Arguments
kz— output, top-down layer-centre Kz (m² s⁻¹), lengthNzT, q, u, v— top-down layer-centre temperature (K), specific humidity (kg kg⁻¹), and winds (m s⁻¹)ps— surface pressure (Pa)hflux, lhflux— surface sensible / latent heat flux (W m⁻², upward-positive)ustar— friction velocity (m s⁻¹)A, B— hybrid-σ half-level coefficients, lengthNz + 1, ordered TOA→surface, sop_edge_topdown[k] = A[k] + B[k]·psc—BLDiffConstantsscratch—BLDiffColumnScratchsized toNz
The hydrostatic layer thicknesses are derived internally via dz_hydrostatic_virtual!; heights are integrated upward from a zero surface reference. The column is flipped to the kernel's bottom-up convention, the interface diffusivities are mapped to centres, and the result is flipped back to top-down before storing.
AtmosTransport.Preprocessing.PhysicsInputs.tm5_bldiff_dkg_column! Method
tm5_bldiff_dkg_column!(dkg, T, q, u, v, air_mass, ps, hflux, lhflux,
ustar, A, B, c, scratch) -> pblhCompute TM5's interface dry-air exchange directly on one target-grid column:
dkg[k] = Kvh[k] * 2 * (m[k] + m[k+1]) / (dz[k] + dz[k+1])^2T is temperature [K], q is specific humidity [kg kg⁻¹], u and v are wind [m s⁻¹], air_mass is dry cell mass [kg], ps is surface pressure [Pa], hflux and lhflux are upward-positive sensible and latent heat flux [W m⁻²], and ustar is friction velocity [m s⁻¹]. A [Pa] and dimensionless B define top-down hybrid interfaces.
Output is top-down: dkg[k] exchanges layers k and k+1 [kg s⁻¹], and dkg[end] == 0 is the surface no-flux boundary. The function mutates dkg and scratch, allocates no column storage, and returns the diagnosed PBL height [m]. Non-negative dkg makes the implicit column solve conserve tracer mass exactly apart from floating-point roundoff.
AtmosTransport.Preprocessing.PhysicsInputs.tm5_bldiff_kvh_column! Method
tm5_bldiff_kvh_column!(kvh, T, q, u, v, p_edge, z_edge,
hflux, lhflux, ustar, c) -> pblhCompute the TM5 boundary-layer heat diffusivity profile for one atmospheric column and return the diagnosed PBL height (m).
All profile inputs are bottom-up (index 1 = surface layer). Layer-centre quantities have length Nz; half-level (interface) quantities have length Nz + 1, with index 1 at the surface and index Nz + 1 at the model top.
Arguments
kvh— output, lengthNz;kvh[l]is the diffusivity (m² s⁻¹) at the top of layerl.kvh[Nz]is set to 0.T— layer-centre temperature (K)q— layer-centre specific humidity (kg kg⁻¹)u,v— layer-centre wind components (m s⁻¹)p_edge— half-level pressure (Pa), lengthNz + 1z_edge— half-level geopotential height above the surface (m), lengthNz + 1, withz_edge[1] = 0hflux— surface sensible heat flux (W m⁻², upward-positive)lhflux— surface latent heat flux (W m⁻², upward-positive)ustar— friction velocity (m s⁻¹)c—BLDiffConstants
The scalar surface fluxes already use the upward-positive convention produced by the ERA5 surface reader, so — unlike the Fortran, which flips ERA5's downward-positive sign — no sign flip is applied here.
sourceAtmosTransport.Preprocessing.PhysicsInputs.tm5_convection_to_basis! Method
tm5_convection_to_basis!(basis, entu, detu, entd, detd, q) -> nothingPut one top-first column of TM5 layer-centre convection fields (kg m⁻² s⁻¹, per unit of total air, as in the TM5 meteo archive) on the air-mass basis. For MoistBasis() nothing changes.
For DryBasis() the draft mass fluxes are rebuilt from the TM5 budgets, converted where they live, and the entrainment re-derived from the converted budgets, as ecmwf_convection_to_basis! followed by ec2tm would do:
with the interface humidity q̂_k of interface_specific_humidity. Scaling every field by 1 − q_k instead would break the column closure Σ e = Σ d, because a draft entrains moist air low down and detrains drier air aloft. Each draft is converted only over its active span (the levels where its entrainment or detrainment is non-zero), so no rounding-level values appear above the cloud top, where TM5Convection diagnoses the cloud dimensions. A negative re-derived rate is moved to its partner rate as in TM5's ECconv_to_TMconv, which keeps e − d and so the fluxes.
AtmosTransport.Preprocessing.TransportBinary Module
Binary metadata, evidence, shared contracts, writers and day lifecycle.
sourceAtmosTransport.Preprocessing.TransportBinary.POLE_ROW_ZONAL_FLUX_KEY Constant
Header key with which the ERA5 spectral lat-lon writer (build_v4_header) records that the zonal faces of the two pole rows carry the synthesized flux ("open", issue #58). Binaries written before 2026-10-14 lack it: they zeroed the pole-row zonal fluxes before the column balance, which then put its correction there, so their stored pole-row am is neither zero nor the wind. regrid_ll_binary_to_cs refuses ERA5 spectral lat-lon sources without it.
AtmosTransport.Preprocessing.TransportBinary.AbstractBinaryWriter Type
AbstractBinaryWriter{G <: AbstractTargetGeometry, FT,
Basis <: AbstractMassBasis}Typed nominal for the topology's streaming binary writer. The third type parameter encodes the on-disk mass-basis convention (reusing State.AbstractMassBasis so the same nominal flows through the runtime reader path) so a writer↔reader pairing mismatch is a compile-time MethodError.
Concrete subtypes (writer_adapters.jl): LatLonBinaryWriter, ReducedGaussianBinaryWriter, CubedSphereBinaryWriter.
AtmosTransport.Preprocessing.TransportBinary.AbstractColumnClosureRecord Type
Per-window record of a cubed-sphere column balance and its cm diagnosis (balance_cs_column_mass_fluxes!, diagnose_cs_cm!): the largest projected column residual max_c |r_c^⊥| and its ratio to the cell's closure tolerance τ_c = max(closure_tol, 8 ε_FT Σ_{f∂c} Σ_k |F_{f,k}|), and the largest residual |R_c| folded into cm with its ratio to the cell's tolerance. Both ratios are at most 1 for a window that passed. The projected residual describes the fluxes as stored (full_window_column_closure_record for GEOS full-window amounts); the cm fields describe the diagnosis of cm.
AtmosTransport.Preprocessing.TransportBinary.AbstractWindowContract Type
AbstractWindowContract{G <: AbstractTargetGeometry, FT}Typed nominal owning a topology's per-window gate policy and the worst-window accumulator state. Concrete subtypes:
CubedSphereContract{FT}(cubed_sphere_contracts.jl)LatLonContract{FT}(latlon_contracts.jl)ReducedGaussianContract{FT}(reduced_gaussian_contracts.jl)
A concrete contract validates its policy at construction time (so e.g. positivity_cfl_limit = 0.0 errors before any window is preprocessed) and exposes the four-method trait surface:
verify_window!(window, contract, win_idx) -> (replay, positivity)
update_accumulator!(contract, positivity_diag, win_idx) -> nothing
summarize_status!(contract; quarantine_path) -> nothingwindow is the topology-specific window payload: a NamedTuple of typed buffers or a ReadyWindow{G, FT} wrapping one.
Keeps contract knobs from being drift-prone kwargs — each topology constructs its own contract once from config, with whatever fields IT needs (see DESIGN.md).
sourceAtmosTransport.Preprocessing.TransportBinary.AbstractWindowWorkspace Type
AbstractWindowWorkspace{G <: AbstractTargetGeometry, FT}Typed nominal for the per-day target-shape workspace buffers. Concrete subtypes: LatLonSpectralWindowWorkspace, CubedSphereSpectralWindowWorkspace, and GEOSCubedSphereWindowWorkspace.
AtmosTransport.Preprocessing.TransportBinary.CapturedNativeFluxSamples Type
Native (GEOS) amounts at the sampled faces, before the column balance.
sourceAtmosTransport.Preprocessing.TransportBinary.FidelitySampleMap Type
Canonical sampled face identifiers, stable across processes and Julia versions.
sourceAtmosTransport.Preprocessing.TransportBinary.FluxBalanceSample Type
One sampled native face/level: the native amount before and after the balance.
sourceAtmosTransport.Preprocessing.TransportBinary.FluxFidelitySample Type
One canonical face/level comparison; mirrors are represented by one face id.
sourceAtmosTransport.Preprocessing.TransportBinary.HybridLayerThickness Type
Moist hybrid layer thickness |ΔA_k + ΔB_k p_s| of the line-integral source cells, evaluated lazily at the sampled stencil cells (as the production line_integral_face_fluxes! with ps) instead of a full source-grid array.
AtmosTransport.Preprocessing.TransportBinary.LineIntegralFidelityStencil Type
Direct midpoint stencils for the sampled line-integral fidelity faces.
These are rebuilt from the source/target meshes and deliberately do not read the production sparse operator method.L. Repeated source-cell entries stay uncombined, preserving the defining 16-midpoint quadrature as the independent check rather than merely applying selected rows of the kernel under test.
AtmosTransport.Preprocessing.TransportBinary.NativeFluxEvidence Type
Native-flux windows (GEOS): no independent reconstruction exists, so the evidence records only how far the column balance moved the sampled native amounts; the certificate status is not_applicable.
AtmosTransport.Preprocessing.TransportBinary.NativeFluxesNotRederivable Type
Native (GEOS) fluxes have no independent source to rederive them from.
sourceAtmosTransport.Preprocessing.TransportBinary.NoColumnClosureRecord Type
No cubed-sphere column balance ran (lat-lon/reduced Gaussian, payload-only, pressure fixer).
sourceAtmosTransport.Preprocessing.TransportBinary.OmegaFidelityBaseline Type
OmegaFidelityBaseline(id; nrmse_limit, correlation_min, slope_min, slope_max)Named, versioned acceptance gates of a path's OMEGA comparison. A certificate passes when it has samples, every metric is finite, NRMSE < nrmse_limit, correlation > correlation_min and slope_min < slope < slope_max; the defaults are OMEGA_FIDELITY_NRMSE_LIMIT, OMEGA_FIDELITY_CORRELATION_MIN, OMEGA_FIDELITY_SLOPE_MIN and OMEGA_FIDELITY_SLOPE_MAX (Parameters).
AtmosTransport.Preprocessing.TransportBinary.OmegaFidelityCells Type
Sampled cubed-sphere cells of the OMEGA comparison, ranked once per workspace.
sourceAtmosTransport.Preprocessing.TransportBinary.PreprocessorRunCache Type
PreprocessorRunCache{G, FT}()Small typed cache for artifacts that should be built once per preprocessing run instead of once per day/window (for example spectral LL->CS regridders or RG compressed Laplacians). The ERA5 spectral entry point builds one per run and passes it to every day's process_day; each driver owns its own keys.
AtmosTransport.Preprocessing.TransportBinary.PreverifiedWindow Type
PreverifiedWindow(ready::ReadyWindow, contract_diag; accumulated=false)Typed event wrapper for topology hooks that have already run verify_window! before handing a window to the generic driver. When accumulated=true, the hook also guarantees it has already folded the positivity diagnostic into the contract accumulator.
AtmosTransport.Preprocessing.TransportBinary.ReadyWindow Type
ReadyWindow{G, FT}(index, payload::NamedTuple, fidelity::FluxFidelityEvidenceBundle)Typed wrapper for a topology-specific window payload that is ready to be verified and written. G is the target geometry, FT is the on-disk float type, payload is the existing topology NamedTuple (m_cur/am/... for LL/CS, m_cur/hflux/... for RG), and fidelity is the window's explicit flux-fidelity evidence (there is no default evidence).
The checked data is accessed explicitly through payload; the day driver receives this window inside a PreverifiedWindow.
AtmosTransport.Preprocessing.TransportBinary.StructuredFidelitySampler Type
Sampled faces of a structured lat-lon target (structured_hashed_faces_v1): canonical ids 1:na for the (Nx+1) × Ny x faces, na+1:na+nb for the Nx × (Ny+1) y faces, ranked once by the SplitMix64 hash. Built once per workspace; the check evaluates only these faces' columns.
AtmosTransport.Preprocessing.TransportBinary.UnifiedPreprocessorDay Type
UnifiedPreprocessorDay(reader, workspace, contract, writer; context=nothing)Bundle the four typed axes a unified preprocessing day needs. context is an opaque topology/source adapter payload used by hook methods during migration.
AtmosTransport.Preprocessing.TransportBinary.allocate_window_workspace Function
allocate_window_workspace(args...; kwargs...)Construct the topology-specific window workspace for one preprocessing day. Methods exist for the LL spectral, RG spectral, CS spectral, and GEOS CS paths.
sourceAtmosTransport.Preprocessing.TransportBinary.build_v4_header Method
build_v4_header(date, grid, vertical, settings, FT, counts, sizes, provenance)Construct the fixed-size JSON header for one v4 output file, including payload layout, vertical metadata, humidity timing semantics, and mass-fix provenance.
sourceAtmosTransport.Preprocessing.TransportBinary.cached_or_build! Method
Reuse one cached object, or build/store it once; return (value, reused).
Callers retain their own cache key and geometry construction policy.
sourceAtmosTransport.Preprocessing.TransportBinary.capture_cs_wind_flux_samples Method
capture_cs_wind_flux_samples(method::LineIntegralFaceFluxes, raw_am, raw_bm,
u, v, dp, ft, gravity, dt_factor, Nc, Nz;
sample_map, line_rows)Sampled line integrals from the source winds u, v (ncell × Nz) and layer thickness dp: a source-grid matrix (dry thickness) or a HybridLayerThickness evaluated lazily (moist), so no full source-grid buffer is built per endpoint.
AtmosTransport.Preprocessing.TransportBinary.capture_native_flux_samples Method
capture_native_flux_samples(am, bm, ft; sample_map) -> CapturedNativeFluxSamplesThe native amounts at the sampled faces before the column balance; the certificate later compares them with the stored (balanced) amounts. Native fluxes have no independent source, so nothing here can test their fidelity.
sourceAtmosTransport.Preprocessing.TransportBinary.capture_structured_wind_flux_samples Method
capture_structured_wind_flux_samples(sampler, am, bm, transform, qv, grid,
vertical, settings)Rebuild the sampled lat-lon face amounts from the staggered spectral winds, face pressure thickness and (dry basis) face humidity, column by column: the native column at the face, then the configured vertical map. The pole rows are ordinary cells whose zonal faces carry flux (issue #58); only the meridional faces on the poles (bm[:, 1, :], bm[:, Ny+1, :]) are closed. Memory is O(Nz); no full-grid flux array is built.
AtmosTransport.Preprocessing.TransportBinary.close_streaming_binary! Function
close_streaming_binary!(writer)Close a streaming binary writer. Implementations should be idempotent.
sourceAtmosTransport.Preprocessing.TransportBinary.drain_ready_windows! Function
drain_ready_windows!(workspace) -> iterator of `ReadyWindow`Return the windows that became write-ready after the last ingest.
sourceAtmosTransport.Preprocessing.TransportBinary.driver_after_write_window! Method
driver_after_write_window!(workspace, reader, ready, context)Post-write migration hook. GEOS-native CS uses this to advance its chained endpoint state; most topologies do nothing.
sourceAtmosTransport.Preprocessing.TransportBinary.driver_before_close_writer! Method
driver_before_close_writer!(workspace, reader, contract, writer, context)Final metadata hook before the streaming writer is closed. Variable-step writers use this to patch schedules into the fixed-size JSON header.
sourceAtmosTransport.Preprocessing.TransportBinary.driver_drain_ready_windows! Method
driver_drain_ready_windows!(workspace, contract, win, context)Return ready windows produced by the most recent ingest. A hook may return a single PreverifiedWindow or an iterator of preverified events.
AtmosTransport.Preprocessing.TransportBinary.driver_flush_final_windows! Method
driver_flush_final_windows!(workspace, reader, contract, context)Return final ready windows after all source windows have been ingested.
sourceAtmosTransport.Preprocessing.TransportBinary.driver_ingest_window! Method
driver_ingest_window!(workspace, reader, win, context)Migration hook for ingesting one source window into the target workspace. Topology/source adapters may override while legacy workspace signatures are being collapsed.
sourceAtmosTransport.Preprocessing.TransportBinary.driver_windows_per_day Method
driver_windows_per_day(reader, context) -> IntMigration hook for source readers whose window count needs adapter context.
sourceAtmosTransport.Preprocessing.TransportBinary.existing_output_schema_matches Function
existing_output_schema_matches(bin_path, total_bytes, expected_sections,
expected_header=nothing) -> (skip, reason)SKIP-or-regen decision used by process_day writers. Returns (true, "") when the file exists, byte size matches, AND the on-disk payload_sections set matches the caller's expected_sections. When an expected_header is supplied, the generation-defining metadata must match as well; provenance and run-produced diagnostics are intentionally excluded. Returns (false, reason) otherwise; reason is a human-readable diff ("size 41g vs 23g" or "schema added :pbl_hflux removed :hflux") the caller should @info so the user knows why the binary is being rebuilt rather than skipped.
AtmosTransport.Preprocessing.TransportBinary.expected_payload_sections Method
expected_payload_sections(settings) -> Vector{String}Canonical v4 LL payload-section list for the writer-side schema. Used by both build_v4_header and the SKIP-vs-regen gate in process_day, so the on-disk header and the existence check stay in lockstep.
AtmosTransport.Preprocessing.TransportBinary.flush_final_windows! Function
flush_final_windows!(workspace, args...; kwargs...)Emit any final cross-day/zero-tendency windows once the source stream is exhausted.
sourceAtmosTransport.Preprocessing.TransportBinary.flux_fidelity_header! Method
flux_fidelity_header!(header, acc) -> headerReplace every certificate key of header (FLUX_CERTIFICATE_KEY_PREFIXES) by the aggregate of acc. Consistency is enforced at write time: one kind of flux evidence for all windows, sample counts that cover nwindow windows and nlevel levels when the header has them, OMEGA evidence for all windows or none, and column-closure records for all windows or none. A failed aggregate OMEGA gate writes its failed certificate and then throws, so the staged binary is quarantined.
AtmosTransport.Preprocessing.TransportBinary.full_window_column_closure_record Method
full_window_column_closure_record(record, am, bm, m, m_next, ft, steps, scratch) -> record′Closure record of a payload stored as full-window amounts (GEOS): the balanced per-application fluxes multiplied by 2 steps in the storage type, a product that rounds unless 2 steps is a power of two. The column closure is evaluated again on the stored am, bm in per-application units (recheck_cs_column_closure with flux_scale = 1/(2 steps)), so the projected residual and its ratio describe the payload as written; kg values are stated in the stored (full-window) amounts. The cm fields keep the residual folded into cm when it was diagnosed, per application, in stored amounts.
AtmosTransport.Preprocessing.TransportBinary.ingest_window! Function
ingest_window!(workspace, args...; kwargs...) -> nothingConsume one source/met window into the topology workspace. Ready windows are exposed by drain_ready_windows!.
AtmosTransport.Preprocessing.TransportBinary.init_positivity_accumulator Method
Construct a typed worst-window record with N location coordinates.
AtmosTransport.Preprocessing.TransportBinary.output_binary_path Method
output_binary_path(date, out_dir, min_dp, FT) -> StringBuild the canonical output filename for one daily v4 binary.
sourceAtmosTransport.Preprocessing.TransportBinary.payload_only_fidelity_header! Method
payload_only_fidelity_header!(header, G, FT) -> headerThe certificate of a writer that only transforms an existing binary's payload (coarsening): flux and OMEGA fidelity not_applicable, reason source_payload_only, through the same serializer as every other writer.
AtmosTransport.Preprocessing.TransportBinary.process_day Method
process_day(date::Date, grid::AbstractTargetGeometry, settings, vertical; next_day_hour0=nothing)Topology-specific daily transport-binary preprocessor extension point.
Concrete target geometries implement this method with ordinary Julia multiple dispatch:
LatLonTargetGeometrywrites structured directional LL binaries.ReducedGaussianTargetGeometrywrites face-indexed RG binaries.CubedSphereTargetGeometrywrites panel-local CS binaries.
Every implementation must satisfy the same transport contract:
use explicit forward endpoint mass targets for every window, including the final cross-day window when
next_day_hour0is available;write declared payload semantics, including
delta_semantics;run a write-time replay check unless explicitly disabled for diagnostics;
produce binaries that the runtime driver can load with replay validation.
This fallback rejects unsupported source/target pairs after config parsing has already produced an AbstractTargetGeometry.
AtmosTransport.Preprocessing.TransportBinary.promote_streaming_binary! Function
promote_streaming_binary!(writer)Close and promote a staged binary file into its final path.
sourceAtmosTransport.Preprocessing.TransportBinary.quarantine_streaming_binary! Function
quarantine_streaming_binary!(writer)Close and remove a staged binary file after a failed validation pass.
sourceAtmosTransport.Preprocessing.TransportBinary.ranked_fidelity_ids Function
Rank canonical ids by the unchanged SplitMix64 sample rule and explicit salt.
sourceAtmosTransport.Preprocessing.TransportBinary.rescaled_column_closure_record Method
rescaled_column_closure_record(record, am, bm, m, m_next, ft, balanced_steps, steps, scratch) -> record′Closure record of a payload balanced for balanced_steps substeps and then rescaled to steps (the adaptive output schedule of the LL → CS regrid, rescale_substep_amounts!). The stored am, bm, cm are the balanced amounts times balanced_steps/steps in the storage type, a product that rounds unless the ratio is a power of two. The column closure is evaluated again on the stored am, bm for steps substeps (recheck_cs_column_closure), so the projected residual and its ratio describe the payload as written. The residual folded into cm is scaled with cm; its ratio to the tolerance is kept from the diagnosis (an upper bound: the tolerance floor closure_tol does not scale). With steps == balanced_steps nothing was rescaled and record is returned.
AtmosTransport.Preprocessing.TransportBinary.resolve_qv_requirements Method
resolve_qv_requirements(date, settings) -> (; needs_qv, thermo_path)Determine whether the current run needs humidity data and resolve the matching daily thermo file path.
Humidity is required whenever output.include_qv=true or mass_basis=:dry. The time convention is:
window
iuses the same day's thermo time indexithe next-day delta path uses the next day's time index
1
AtmosTransport.Preprocessing.TransportBinary.run_unified_preprocessor_day! Method
run_unified_preprocessor_day!(day::UnifiedPreprocessorDay; close_reader=true)Execute the additive unified-driver lifecycle for one day. The function is generic over concrete reader/workspace/contract/writer types and depends on hook methods for topology-specific ingest/drain/flush behavior.
The writer is closed before summarize_status!, so fatal positivity summaries can quarantine a closed staging file. Any exception before promotion closes and quarantines the writer, then closes the reader.
AtmosTransport.Preprocessing.TransportBinary.script_provenance Method
script_provenance() -> NamedTupleCollect reproducibility metadata for the preprocessing source directory.
sourceAtmosTransport.Preprocessing.TransportBinary.source_omega_evidence_cs Method
source_omega_evidence_cs(G, cm, omega, qv, ps, A, B, cell_areas, gravity,
amount_seconds, cells::OmegaFidelityCells;
source, sampling, baseline)Compare the downward interface velocity of the stored cm, ω_cm = g cm / (A_cell Δt_amount), with the source OMEGA averaged to the interface and put on the dry basis with the window's humidity qv, at the cached sample cells.
AtmosTransport.Preprocessing.TransportBinary.summarize_positivity_status Method
Log the worst-window outcome and enforce its configured positivity policy.
sourceAtmosTransport.Preprocessing.TransportBinary.summarize_status! Function
summarize_status!(contract::AbstractWindowContract;
quarantine_path::Union{Nothing, AbstractString} = nothing)
-> nothingPost-loop summary helper. Logs the worst-window outcome; if the contract's policy demands and the worst exceeds the gate, deletes quarantine_path (if given) and errors. Otherwise warns when the gate is violated but the policy is set to record-and-continue.
AtmosTransport.Preprocessing.TransportBinary.update_accumulator! Function
update_accumulator!(contract::AbstractWindowContract,
positivity_diag, win_idx::Int) -> nothingFold one window's positivity diagnostic into the contract's worst- window accumulator. Concrete contracts mutate their internal state and return nothing. Idempotent if positivity_diag.ratio does not exceed the current worst.
AtmosTransport.Preprocessing.TransportBinary.update_positivity_accumulator Method
Fold a diagnostic into a worst-window record, preserving first-worst ties.
sourceAtmosTransport.Preprocessing.TransportBinary.validate_staged_binary! Method
Validate a closed staging artifact before it can replace the final path.
sourceAtmosTransport.Preprocessing.TransportBinary.verify_flux_fidelity! Method
verify_flux_fidelity!(acc, bundle::FluxFidelityEvidenceBundle, win)Verify one window's evidence before its payload is written: sampled wind fluxes against their independent reconstruction (throws on a failed sample), non-empty and finite OMEGA samples, and a column-closure record within its per-cell tolerances. Aggregates are serialized by flux_fidelity_header!.
AtmosTransport.Preprocessing.TransportBinary.verify_substep_positivity_cs! Method
verify_substep_positivity_cs!(m, am, bm, cm; cfl_limit = DEFAULT_POSITIVITY_CFL_LIMIT,
m_next = nothing)Verify the per-substep horizontal+vertical positivity contract that the runtime's _cs_static_palindrome_subcycle_count depends on. For every interior cell on every panel (any rectangular block; the lat-lon gate verify_substep_positivity_ll! passes its window as one block):
The cell air mass itself must be positive (
m > 0), a preprocessing invariant enforced here (the runtime CFL scan skips such cells). A non-positive cell mass is reported withratio = Infregardless of flux magnitude.The combined Strang-palindrome outgoing budget
2 * (out_x + out_y + out_z)must not exceedcfl_limit * m_ref, wherem_ref = min(m, m_next)whenm_nextis supplied by a caller that wants endpoint tightening, andm_ref = motherwise. The factor of 2 is required because the CS runtime applies the direction sequenceX-Y-Z-Z-Y-Xfor every met substep.
Returns a NamedTuple (direction, ratio, ratio_xy, ratio_z, location, ok):
direction :: Union{Symbol, Nothing}— the dominant contributor among:x,:y,:z, ornothingwhen no cell was inspected.ratio :: Float64— worst observed palindrome outgoing budget over the reference mass, orInfif any inspected cell had invalid mass or flux.ratio_xy :: Float64— worst observed horizontal-only palindrome outgoing budget over the reference mass.ratio_z :: Float64— worst observed vertical-only palindrome outgoing budget over the reference mass.location :: NTuple{4, Int}—(panel, i, j, k)of the worst cell.ok :: Bool—trueiffratio <= cfl_limit.
The replay gate (verify_write_replay_cs!) only checks endpoint continuity. A binary that drives a cell mass negative mid-sweep can still pass replay because the cell re-fills from inflow before the window ends — but the runtime cannot recover. This gate is the actual contract the runtime depends on.
Panel arrays are stored without halos at preprocessing time.
sourceAtmosTransport.Preprocessing.TransportBinary.verify_window! Function
verify_window!(window, contract::AbstractWindowContract, win_idx::Int)
-> (; replay, positivity)Run the contract's replay and positivity gates for one window. The replay gate throws on violation; the positivity gate is non-fatal at this layer (the run-level accumulator + summarize_status! decides fatal-vs-warn based on require_substep_positivity).
window is the topology's per-window NamedTuple payload. Topology hooks verify it before returning a PreverifiedWindow to the day driver.
AtmosTransport.Preprocessing.TransportBinary.window_byte_sizes Method
window_byte_sizes(counts, FT, Nt) -> (; bytes_per_window, total_bytes)Translate payload element counts into byte counts for one window and the full daily file.
sourceAtmosTransport.Preprocessing.TransportBinary.window_element_counts Method
window_element_counts(grid, Nz; include_qv=false) -> NamedTupleReturn the per-window element counts for every payload section in the output binary.
sourceAtmosTransport.Preprocessing.TransportBinary.write_array! Method
write_array!(io, arr) -> IntWrite a dense Julia array to the binary stream without intermediate copies and return the number of bytes written.
sourceAtmosTransport.Preprocessing.TransportBinary.write_window! Function
write_window!(writer, ready)Write one validated ready window through a topology-specific binary writer. Concrete methods are topology-indexed by AbstractBinaryWriter and ReadyWindow so writer/window mismatches fail by dispatch.
AtmosTransport.Preprocessing.LatLonTarget Module
Lat-lon spectral staging, window contracts and daily preprocessing.
sourceAtmosTransport.Preprocessing.LatLonTarget.LLWorst Type
LLWorstType-stable shape of the LL positivity accumulator. Same role as CSWorst but with (i, j, k) cell coordinates (no panel axis). The LatLonContract.worst field is typed against this alias so accessor calls inside the accumulator/summarizer chain stay statically typed.
AtmosTransport.Preprocessing.LatLonTarget.LatLonBilinearWeights Type
LatLonBilinearWeights(src_lon, src_lat, dst_lon, dst_lat)Separable bilinear interpolation from point values on a latitude-longitude source grid to the target points (dst_lon[i], dst_lat[j]), all in degrees. src_lon is strictly increasing within one 360° period (periodic), src_lat strictly increasing. Target longitude i lies between the source columns i0[i] and i1[i] with weight wi[i] on i1[i]; target latitude j between the source rows j0[j] and j1[j] with weight wj[j] on j1[j]. A target latitude beyond the outermost source row takes that row's values.
The weights come from the source coordinates themselves, so a source whose points coincide with the target points (no shift) reduces to a copy, and a point-registered source is never read as cell-centred (issue #63).
sourceAtmosTransport.Preprocessing.LatLonTarget.LatLonContract Type
LatLonContract{FT} <: AbstractWindowContract{LatLonTargetGeometry, FT}Typed nominal owning an LL preprocessor's per-window gate policy and worst-window positivity accumulator. Construction validates positivity_cfl_limit ∈ (0, 1] and steps_per_window ≥ 1 so an invalid TOML value fails before any window runs.
AtmosTransport.Preprocessing.LatLonTarget.MergeWorkspace Type
MergeWorkspaceScratch storage used while collapsing native fields onto the merged transport levels and while forming forward differences for dam, dbm, dcm, and dm.
AtmosTransport.Preprocessing.LatLonTarget.NativeQVWorkspace Type
NativeQVWorkspaceHumidity workspace backed by daily ERA5 thermo NetCDF files.
qv_thermo holds the read on the thermo grid and weights bilinear- interpolates it into qv_native on the target cell centres, always: the thermo values are point values at the file coordinates (read_thermo_coordinates), which are not the target cell centres even when the two grids have the same dimensions. qv_daily is an optional in-memory daily preload in thermo-grid order; it avoids repeated NetCDF chunk decompression.
AtmosTransport.Preprocessing.LatLonTarget.NoQVWorkspace Type
NoQVWorkspacePlaceholder humidity workspace for moist-only runs.
sourceAtmosTransport.Preprocessing.LatLonTarget.SpectralTransformWorkspace Type
SpectralTransformWorkspaceScratch buffers and native-level output arrays for one spectral-to-gridpoint hour transform.
sourceAtmosTransport.Preprocessing.LatLonTarget.TM5PBLInputCache Type
Day-local ownership of thermo/surface readers, shared endpoints and remap weights.
sourceAtmosTransport.Preprocessing.LatLonTarget.WindowStorage Type
WindowStorageIn-memory storage for all windows of the current day before the final binary write.
sourceAtmosTransport.Preprocessing.LatLonTarget.allocate_merge_workspace Method
allocate_merge_workspace(grid, Nz_native, Nz, FT) -> MergeWorkspace{FT}Allocate merged-level work arrays and delta buffers for one day.
sourceAtmosTransport.Preprocessing.LatLonTarget.allocate_qv_workspace Method
allocate_qv_workspace(grid, settings, date, Nz_native, Nz, FT)Allocate the humidity workspace for the current day. Returns NoQVWorkspace when humidity is not required.
AtmosTransport.Preprocessing.LatLonTarget.allocate_transform_workspace Method
allocate_transform_workspace(grid, T, Nz_native) -> SpectralTransformWorkspaceAllocate the scratch state needed to synthesize one day's hourly spectral input onto the native target grid.
sourceAtmosTransport.Preprocessing.LatLonTarget.allocate_window_storage Method
allocate_window_storage(Nt, FT; include_qv=false,
include_surface=false) -> WindowStorage{FT}Allocate per-window storage for the daily output payloads.
sourceAtmosTransport.Preprocessing.LatLonTarget.apply_dry_basis_if_needed! Method
apply_dry_basis_if_needed!(basis, native, qv)Conditionally convert the native hourly mass and horizontal flux fields from moist to dry basis.
sourceAtmosTransport.Preprocessing.LatLonTarget.apply_mass_fix_if_needed! Method
apply_mass_fix_if_needed!(qv_workspace, transform, grid, vertical, settings, ps_offsets, slot)Apply the configured global dry-mass fix to the current hourly surface-pressure field and recompute native mass/flux fields afterward.
When humidity is available, the target dry surface pressure is matched using the actual hourly native q field. Otherwise the fallback global qv climatology is used.
AtmosTransport.Preprocessing.LatLonTarget.apply_poisson_balance! Method
apply_poisson_balance!(storage, last_hour_next, steps_schedule, contract, substep_policy;
write_replay_on=true, weights=MassWeightedColumn())Balance each LL window against its forward mass endpoint, diagnose explicit-dm vertical closure, and apply the replay and positivity contract. Fixed schedules also supply one step count per window.
sourceAtmosTransport.Preprocessing.LatLonTarget.close_pole_faces! Method
close_pole_faces!(bm)Zero the meridional fluxes through the two pole faces of a global lat-lon mesh, bm[:, 1, :] (φ = −90°) and bm[:, Ny+1, :] (φ = +90°). These faces have zero length and are the only closed faces of the mesh. The pole rows are ordinary cells and keep their zonal fluxes am[:, 1, :] and am[:, Ny, :]: zeroing those leaves a flow across the pole no path through the polar cap, and the column balance then re-routes bm at every latitude (issue #58; the same zeroing was removed once before, see docs/resources/bug_archive/SESSION1_GRID_CM_FIX_2026-04-03.md, section 3).
AtmosTransport.Preprocessing.LatLonTarget.compute_window_deltas! Method
compute_window_deltas!(merged, storage, win_idx, last_hour_next)Form the forward-in-time dam, dbm, dcm, and dm payloads for one window.
AtmosTransport.Preprocessing.LatLonTarget.fill_window_mass_tendency! Method
fill_window_mass_tendency!(dm_dt_buf, storage, last_hour_next, win_idx, steps_per_window)Fill the cell-mass target used by the Poisson horizontal-flux balance step.
The stored am/bm/cm fields are half-sweep transport amounts. A full Strang substep applies the horizontal fluxes twice, so the Poisson target must be the forward window mass difference divided by 2 * steps_per_window.
AtmosTransport.Preprocessing.LatLonTarget.init_ll_positivity_accumulator Method
init_ll_positivity_accumulator() -> NamedTupleZero-valued state for accumulating the worst per-window LL positivity diagnostic across a preprocessing loop. Pair with update_ll_positivity_accumulator.
AtmosTransport.Preprocessing.LatLonTarget.interpolate_ll_qv! Method
interpolate_ll_qv!(dst, src, weights::LatLonBilinearWeights)Bilinear-interpolate QV from the thermo grid src (point values, in the order of read_qv_from_thermo) to the target cell centres dst with the separable weights built from both grids' coordinates. For the ERA5 archive the source points are (−180 + (i − 1)Δ, −90 + (j − 1)Δ) (pole-inclusive) and the targets the LatLonMesh cell centres (−180 + (i − ½)Δλ, −90 + (j − ½)Δφ), so the interpolated QV lands at the same points as transform.sp, merged.m_merged and the other staging fields.
AtmosTransport.Preprocessing.LatLonTarget.load_tm5_pbl_target_window Method
load_tm5_pbl_target_window(date, win, settings, vertical, ps, grid, shape; cache)Assemble the optional LL/RG v5 group. T/q are interpolated at target cell centres, mass-weighted onto merged layers at each hourly endpoint, then averaged in time. Native moist Δp at the window surface pressure supplies the merge weights. Surface primitives are intensive cell-area means through Regridding.build_regridder/apply_regridder! on the actual LL/RG target mesh. A day-local cache reuses the shared thermo endpoint, surface readers and weights.
sourceAtmosTransport.Preprocessing.LatLonTarget.log_mass_fix_configuration Method
log_mass_fix_configuration(settings)Emit a short description of the dry-surface-pressure mass-fix mode selected for the current run.
sourceAtmosTransport.Preprocessing.LatLonTarget.merge_native_window! Method
merge_native_window!(merged, native, qv, vertical, settings)Collapse native hourly fields to the merged transport levels, recompute merged cm, and optionally produce merged qv.
AtmosTransport.Preprocessing.LatLonTarget.merge_qv_output! Method
merge_qv_output!(qv, merged, vertical, settings)Merge native humidity to the output vertical grid when qv is requested in the binary payload.
AtmosTransport.Preprocessing.LatLonTarget.next_day_merged_fields Method
next_day_merged_fields(next_day_hour0, date, grid, vertical, settings,
transform, merged, qv, ps_offsets)Process the next day's hour-0 spectral and humidity fields so the current day's final window can form forward deltas and carry a consistent mass-fix offset. Returns copies of the merged (m, am, bm, cm, qv) fields (qv is nothing unless settings.include_qv).
Returns nothing early when next_day_hour0 === nothing (no next-day data was loaded, e.g. at the end of the processed range).
AtmosTransport.Preprocessing.LatLonTarget.process_window! Method
process_window!(win_idx, hour, spec, grid, vertical, settings, transform, merged, qv, storage, ps_offsets)Run the full hourly processing chain for one analysis window: spectral synthesis, humidity load, optional dry-mass fix, optional dry-basis conversion, vertical merging, and storage.
sourceAtmosTransport.Preprocessing.LatLonTarget.read_next_day_qv! Method
read_next_day_qv!(qv, date, settings, Nx, Ny, Nz_native)Load next day's hour-0 humidity so the final window can form forward deltas with consistent dry-basis metadata.
sourceAtmosTransport.Preprocessing.LatLonTarget.read_window_qv! Method
read_window_qv!(qv, win_idx, Nx, Ny, Nz_native)Load the humidity field associated with one analysis window into the native humidity workspace: read it on the thermo grid and bilinear-interpolate it to the target cell centres (qv.weights).
AtmosTransport.Preprocessing.LatLonTarget.should_log_window Method
should_log_window(win_idx, Nt) -> BoolReturn true for the subset of windows that should emit per-window timing messages.
AtmosTransport.Preprocessing.LatLonTarget.store_qv_output! Method
store_qv_output!(storage, qv, win_idx)Persist the merged qv field for one window into the daily storage bundle.
AtmosTransport.Preprocessing.LatLonTarget.store_window_fields! Method
store_window_fields!(storage, merged, ps, qv, win_idx)Copy one processed window into the daily storage bundle.
sourceAtmosTransport.Preprocessing.LatLonTarget.summarize_ll_positivity_status Method
summarize_ll_positivity_status(worst; cfl_limit, steps_per_window,
require_substep_positivity = true,
quarantine_path = nothing)Post-loop summary helper for the LL positivity accumulator. Logs the worst-window outcome, and if it exceeds cfl_limit:
deletes
quarantine_path(if given) so a downstream consumer cannot pick up the half-written binary;errors when
require_substep_positivity = true, otherwise warns.
The error/warn message includes a recommended steps_per_window value that would satisfy the gate, computed from the observed worst ratio. The "no representable rescue" branch from CS round-3 is mirrored here.
AtmosTransport.Preprocessing.LatLonTarget.tm5_pbl_sample Method
Zero/neutral sample with valid shapes for declaring the optional v5 writer layout.
sourceAtmosTransport.Preprocessing.LatLonTarget.tm5_target_coordinates Method
Coordinate lists in Julia cell order for a structured target.
sourceAtmosTransport.Preprocessing.LatLonTarget.update_ll_positivity_accumulator Method
update_ll_positivity_accumulator(worst, diag, win_idx) -> NamedTupleReturn an updated LL accumulator from a fresh per-window diagnostic.
sourceAtmosTransport.Preprocessing.LatLonTarget.verify_ll_window_contract! Method
verify_ll_window_contract!(m_cur, am, bm, cm, m_next, steps_per_window, win_idx;
replay_tol, positivity_cfl_limit = DEFAULT_POSITIVITY_CFL_LIMIT,
replay_scratch = nothing)Single canonical per-window LL binary contract check. Runs the replay gate (errors on failure) followed by the per-substep positivity scan (verify_substep_positivity_ll!, returns a diagnostic).
replay_scratch (a ReplayScratch of the mass shape) may be pre-allocated by the caller (workspace-owned scratch) to suppress the per-window allocation. Default nothing → allocate locally.
Returns (; replay, positivity). Positivity is non-fatal here — callers aggregate the worst window across the loop and pass it to summarize_ll_positivity_status where the run-level require_substep_positivity policy decides whether to error or warn.
AtmosTransport.Preprocessing.LatLonTarget.verify_substep_positivity_ll! Method
verify_substep_positivity_ll!(m, am, bm, cm; cfl_limit = DEFAULT_POSITIVITY_CFL_LIMIT, m_next = nothing)Per-substep positivity contract of a structured lat-lon window, the same as the cubed-sphere one (verify_substep_positivity_cs!, here on one block). One stored flux amount is one application in the runtime palindrome X-Y-Z-Z-Y-X, so each direction acts twice per substep. For every cell (i, j, k):
m > 0(andm_next > 0when given); non-finite masses or fluxes and non-positive masses are reported withratio = Inf.The palindrome outflow
2 (out_x + out_y + out_z)must not exceedcfl_limit * m_ref, withm_ref = min(m, m_next)whenm_nextis given andmotherwise.out_dis the cell's outflow through its twodfaces for one application.
This bounds the outflow of a whole substep by the mass the cell has at either end of the window. The earlier lat-lon gate checked each direction's single application against m alone, so it admitted substeps the cubed-sphere gate rejects.
Returns (direction, ratio, ratio_xy, ratio_z, location, ok) as the cubed-sphere gate does, with location = (i, j, k).
AtmosTransport.Preprocessing.ReducedGaussianTarget Module
Reduced-Gaussian spectral staging, window contracts and daily preprocessing.
sourceAtmosTransport.Preprocessing.ReducedGaussianTarget.RGWorst Type
RGWorstType-stable shape of the RG positivity accumulator. Same role as CSWorst/LLWorst but with (cell, level) coordinates (no panel or explicit x/y axis).
AtmosTransport.Preprocessing.ReducedGaussianTarget.ReducedFidelitySampler Type
ReducedFidelitySampler(grid, face_left, face_right; samples = 256, lines = 32)Faces of a reduced-Gaussian target sampled by the write-time flux-fidelity check (rg_hashed_latitude_lines_v1). At most lines latitude lines are chosen by the SplitMix64 hash among the rings (zonal faces) and the interior ring boundaries (meridional faces), then faces within each chosen line, about samples in total. The check re-synthesizes the winds of the chosen lines only, with the same spectral transform as production (shared code, so this check does not test the transform itself), and keeps samples × levels values; production synthesizes 2 n_rings − 1 lines.
Per sample it stores the line, the point on the line, the face-table cells (face_left/face_right of Grids.face_cells: their ln p_s set the face pressure, and they drive the pin rescale and humidity), the edge length factor and cos φ (1 for meridional faces).
AtmosTransport.Preprocessing.ReducedGaussianTarget.ReducedGaussianContract Type
ReducedGaussianContract{FT} <: AbstractWindowContract{ReducedGaussianTargetGeometry, FT}Typed nominal owning an RG preprocessor's per-window gate policy and worst-window positivity accumulator. Holds the face connectivity (face_left / face_right) so the per-window call site doesn't need to thread it through every call.
Construction validates replay_tol, positivity_cfl_limit ∈ (0, 1], steps_per_window ≥ 1, boundary_stub_tol ≥ 0, and length(face_left) == length(face_right).
boundary_stub_tol (default 0.0) is the absolute tolerance for the boundary-stub flux gate (verify_boundary_stub_flux_rg). Default is strict; tighten only with caution.
AtmosTransport.Preprocessing.ReducedGaussianTarget.ReducedQVWorkspace Type
ReducedQVWorkspaceHumidity workspace for dry-basis conversion on reduced Gaussian grids. Loads QV from ERA5 thermo NetCDF on a regular LL grid and bilinear-interpolates to RG cell centers. The interpolation mapping is precomputed at allocation time.
sourceAtmosTransport.Preprocessing.ReducedGaussianTarget.SlidingWindowBuffer Type
SlidingWindowBuffer{FT}Two-slot circular buffer for streaming RG preprocessing. Only two windows' worth of (m, hflux, cm, ps) are kept in memory at any time, enabling O160/O320 binary generation without OOM.
AtmosTransport.Preprocessing.ReducedGaussianTarget.allocate_reduced_qv_workspace Method
allocate_reduced_qv_workspace(grid, Nz_native, thermo_path)Build the RG QV workspace with precomputed bilinear interpolation from the LL thermo grid to RG cell centers. The LL grid dimensions are read from the first available thermo file.
sourceAtmosTransport.Preprocessing.ReducedGaussianTarget.allocate_reduced_spectral_thread_cache Method
Allocate one ring synthesis cache; the caller retains its thread-count policy.
sourceAtmosTransport.Preprocessing.ReducedGaussianTarget.apply_dry_basis_reduced! Method
apply_dry_basis_reduced!(work, qv_cell)Convert RG native-level moist mass and horizontal face fluxes to dry basis. Face humidity is the average of the two adjacent cell values.
sourceAtmosTransport.Preprocessing.ReducedGaussianTarget.balance_window! Method
balance_window!(hflux_work, m_cur_work, m_next_work, cm_work, div_scratch,
dm_target_work, buf, slot, m_next, work, cL, steps_per_window;
weights = MassWeightedColumn(), tol, max_iter)Close the window in buffer slot against its end point m_next: the column Poisson balance of its horizontal fluxes (balance_compressed_column_fluxes!, one CG solve on the compressed Laplacian cL, correction spread over the layers by the column weights), then the vertical mass flux cm from the explicit endpoint tendency (recompute_cm_from_dm_target!, residual folded with the same weights). The balanced fluxes and cm are stored back into the buffer in its float type.
All scratch arrays are preallocated Float64 buffers — no per-call allocation. Returns the balance diagnostics.
sourceAtmosTransport.Preprocessing.ReducedGaussianTarget.fill_buffer_slot! Method
fill_buffer_slot!(buf, slot, merged, ps_vec, FT)Copy merged results into the given slot (1 or 2) of the sliding buffer.
sourceAtmosTransport.Preprocessing.ReducedGaussianTarget.init_rg_positivity_accumulator Method
init_rg_positivity_accumulator() -> NamedTupleZero-valued state for accumulating the worst per-window RG positivity diagnostic across a preprocessing loop.
sourceAtmosTransport.Preprocessing.ReducedGaussianTarget.load_rg_qv! Method
load_rg_qv!(qv_ws, thermo_path, hour_idx, Nz_native)Read QV from ERA5 thermo NetCDF for one hour, then bilinear-interpolate from the regular LL grid to all RG cell centers.
sourceAtmosTransport.Preprocessing.ReducedGaussianTarget.pin_convert_merge_window! Method
pin_convert_merge_window!(work, merged, vertical, settings, ps_offsets, slot, qv_ws)Finish a synthesized window: the global mass fix (offset stored in ps_offsets[slot]), the dry-basis conversion when qv_ws holds the window's humidity, and the level merge.
With humidity the fix pins the global dry surface pressure, as the lat-lon and cubed-sphere paths do: the vertical-flux closure needs the same global dry mass at both ends of a window. Without humidity it pins the total surface pressure with the climatological qv_global_climatology. The horizontal fluxes follow the pinned pressure: each is wind × Δp at the face, so it scales by the ratio of the face Δp after and before the pin.
AtmosTransport.Preprocessing.ReducedGaussianTarget.rescale_reduced_fluxes_to_ps! Method
rescale_reduced_fluxes_to_ps!(hflux, lnsp_old, sp_new, face_left, face_right, dA, dB)Scale the face mass fluxes hflux[f, k] (wind × Δp at the face) from the surface pressure exp.(lnsp_old) to sp_new: the face pressure is the geometric mean of the two cells' (as in compute_reduced_horizontal_fluxes!) and Δp = |dA_k + dB_k p|. Polar stub faces (a zero neighbour) are set to zero.
AtmosTransport.Preprocessing.ReducedGaussianTarget.sample_reduced_horizontal_fluxes! Method
sample_reduced_horizontal_fluxes!(out, sampler, lnsp_center, u_spec, v_spec, T,
dA_k, dB_k, grid, half_dt, cache)Scalar re-evaluation of the sampled reduced-grid face amounts of one level for the write-time fidelity check, F = u Δp R Δφ Δt/(g cos φ) (zonal) and F = v Δp R Δλ Δt/g (meridional), with Δp = |ΔA + ΔB exp((ln p_{s,a} + ln p_{s,b})/2)|. Only the sampler's lines are synthesized; out has one value per sample.
AtmosTransport.Preprocessing.ReducedGaussianTarget.spectral_to_ring! Method
spectral_to_ring!(dest, spec, T, lat_deg, cache; lon_shift_rad = 0.0) -> destSynthesise the spectral field spec[n + 1, m + 1] = f̂_n^m (truncation T) on the N = length(dest) equally spaced points λ_k = lon_shift_rad + 2πk/N of the ring at latitude lat_deg:
dest[k + 1] = G_0 + 2 Re Σ_{m=1}^{M} G_m e^{i m λ_k},
G_m = Σ_{n=m}^{T} f̂_n^m P̃_n^m(sin φ), M = ring_max_wavenumber(T, N),through fill_ring_spectrum! (shared with spectral_to_grid!) and one unnormalised inverse FFT. The term m = N/2 of an even ring is dropped (see ring_max_wavenumber).
AtmosTransport.Preprocessing.ReducedGaussianTarget.summarize_rg_positivity_status Method
summarize_rg_positivity_status(worst; cfl_limit, steps_per_window,
require_substep_positivity = true,
quarantine_path = nothing)Post-loop summary helper for the RG positivity accumulator. Mirrors summarize_cs_positivity_status (CS round-2 + round-3 escape-hatch semantics).
AtmosTransport.Preprocessing.ReducedGaussianTarget.synthesize_and_merge_window! Method
synthesize_and_merge_window!(work, merged, hour, spec, grid, vertical,
settings, ps_offsets, win_idx;
qv_ws=nothing, thermo_path="")Spectral synthesis → native fields → mass fix → dry conversion → level merge for one window. Results are left in merged.m_merged, merged.hflux_merged, work.sp (surface pressure). The balanced window diagnoses cm later.
When qv_ws is provided and settings.mass_basis == :dry, loads QV from the thermo file and interpolates it to RG cells; the window is then finished by pin_convert_merge_window!.
AtmosTransport.Preprocessing.ReducedGaussianTarget.synthesize_next_day_hour0! Method
synthesize_next_day_hour0!(work, merged, next_day_hour0, date, grid, vertical,
settings, ps_offsets; qv_ws=nothing)The next day's 00 UTC state, the end point of the day's last window, through the same synthesis, pin (offset stored in ps_offsets[end]), dry conversion (the next day's thermo file, time index 1) and merge as every window.
AtmosTransport.Preprocessing.ReducedGaussianTarget.update_rg_positivity_accumulator Method
update_rg_positivity_accumulator(worst, diag, win_idx) -> NamedTupleReturn an updated RG accumulator from a fresh per-window diagnostic.
sourceAtmosTransport.Preprocessing.ReducedGaussianTarget.verify_boundary_stub_flux_rg Method
verify_boundary_stub_flux_rg(hflux, face_left, face_right;
tol = 0.0) -> NamedTupleExplicit-invariant scan: any non-zero hflux value on a boundary stub (face_left ≤ 0 or face_right ≤ 0) is a contract violation. The runtime advection silently discards such fluxes (Advection/sweeps.jl), so a writer that produces them is emitting data the runtime cannot apply — almost always a sign-flip or boundary- masking bug in preprocessing.
Returns (violated, worst_flux, worst_face, worst_level):
violated :: Bool—trueiff any |flux| > tol on a boundary stub.worst_flux :: Float64— signed value of the worst-magnitude violation, or0.0if none.worst_face :: Int— face index of the worst violation, or0.worst_level :: Int— k-index of the worst violation, or0.
tol is the absolute tolerance below which a "near-zero" stub flux is permitted. Default 0.0 (strict) — RG writers should explicitly zero boundary stubs.
AtmosTransport.Preprocessing.ReducedGaussianTarget.verify_rg_window_contract! Method
verify_rg_window_contract!(m_cur, hflux, cm, m_next, face_left, face_right,
steps_per_window, win_idx;
replay_tol, positivity_cfl_limit = DEFAULT_POSITIVITY_CFL_LIMIT,
replay_scratch = nothing,
outgoing_h = nothing, bad_h = nothing,
boundary_stub_tol = 0.0)Single canonical per-window RG binary contract check. Runs three gates in order:
Boundary-stub flux gate — errors hard if any boundary stub (
face_left ≤ 0/face_right ≤ 0) carries non-zerohfluxaboveboundary_stub_tol. Norequire_*escape hatch: such fluxes are silently discarded by the runtime (Advection/sweeps.jl), so emitting them is always a writer bug.Replay gate —
verify_window_continuity_rg; errors on failure.Per-substep positivity scan —
verify_substep_positivity_rg!, returns a non-fatal diagnostic; the run-level accumulator +summarize_rg_positivity_statusdecides fatal-vs-warn.
replay_scratch (a ReplayScratch of the mass shape), outgoing_h, bad_h may be pre-allocated by the caller (workspace-owned scratch) to suppress per-window allocation. Default nothing → allocate locally.
Returns (; replay, positivity). Boundary-stub failure does not return; it errors out before the replay gate so a broken writer cannot silently emit a binary the runtime would partially evaluate.
AtmosTransport.Preprocessing.ReducedGaussianTarget.verify_substep_positivity_rg! Method
verify_substep_positivity_rg!(m, hflux, cm, face_left, face_right;
cfl_limit = DEFAULT_POSITIVITY_CFL_LIMIT,
outgoing_h = nothing, bad_h = nothing)Per-substep horizontal+vertical positivity scan for a face-indexed RG window. Mirrors verify_substep_positivity_cs! / ..._ll! but operates on the face-indexed RG mass-flux representation.
For every cell (c, k):
m > 0. A non-positive cell mass is reported withratio = Inf.Horizontal outgoing mass per substep ≤
cfl_limit * m. Only interior faces (face_left > 0 && face_right > 0) contribute, matching the runtime advection inAdvection/sweeps.jl. Boundary stubs are not counted as outflow here — seeverify_boundary_stub_flux_rgfor the separate "non-zero flux on a boundary stub" invariant.Vertical outgoing mass per substep ≤
cfl_limit * m. Same as CS / LL:max(0, -cm[c, k]) + max(0, cm[c, k+1]).
NaN/Inf cell mass and NaN/Inf fluxes are flagged as ratio = Inf (matches the CS round-2 fix).
outgoing_h and bad_h can be passed in as workspace-owned scratch to suppress per-window allocation once this is wired into the unified driver. Default nothing → allocate locally.
Returns (direction, ratio, location, ok) with:
direction :: Union{Symbol, Nothing}—:h/:z/nothing.ratio :: Float64— worstoutgoing / m.location :: NTuple{2, Int}—(cell, level).ok :: Bool—ratio ≤ cfl_limit.
AtmosTransport.Preprocessing.CubedSphereTarget Module
Cubed-sphere spectral staging, conservative regridding, coarsening and contracts.
sourceAtmosTransport.Preprocessing.CubedSphereTarget.CSWorst Type
CSWorstType-stable shape of the CS positivity accumulator. Pin the field types here so accesses inside update_cs_positivity_accumulator / summarize_cs_positivity_status and the CubedSphereContract.worst field are statically typed (the Julia-style reviewer flagged the worst :: NamedTuple field as dynamically dispatched).
AtmosTransport.Preprocessing.CubedSphereTarget.CubedSphereContract Type
CubedSphereContract{FT} <: AbstractWindowContract{CubedSphereTargetGeometry, FT}Typed nominal owning a CS preprocessor's per-window gate policy and worst-window positivity accumulator.
Fields:
replay_tol::Float64— relative replay tolerance.positivity_cfl_limit::Float64— per-substep positivity CFL gate. Must satisfy0 < limit ≤ 1; validated at construction.require_substep_positivity::Bool— whethersummarize_status!errors (true) or warns (false) on a positivity violation.steps_per_window::Int— for the recommended-steps message in the summary's escape-hatch detail. Must be ≥ 1.worst::NamedTuple— mutable accumulator (initially zero).
Construct with explicit kwargs; defaults match the CS round-2/round-3 production policy.
sourceAtmosTransport.Preprocessing.CubedSphereTarget.CubedSpherePreprocessWorkspace Type
CubedSpherePreprocessWorkspace{FT}Pre-allocated workspace for one or two CS transport windows. Holds all per-panel arrays needed by the regrid → wind recovery → flux reconstruction → balance → cm pipeline.
sourceAtmosTransport.Preprocessing.CubedSphereTarget.carried_tm5_convection_record Method
carried_tm5_convection_record(source_header, source_has_tm5) -> Dict{String, Any}Header record of TM5 convection sections that a binary-to-binary tool copies from its source: the source's TM5_CONVECTION_SOURCE_KEY ("unrecorded" when it has none) and its TM5_EC2TM_CONVENTION_KEY, if present. Empty when the source has no TM5 sections. Readers reject a lat-lon → cubed-sphere regrid with TM5 sections and no source record: it predates this record and copied sections of the retired lat-lon route.
AtmosTransport.Preprocessing.CubedSphereTarget.coarsen_nested_cs_transport_binary Method
coarsen_nested_cs_transport_binary(input_path, output_path; target_Nc=30, ...)Experimentally restrict a nested cubed-sphere transport binary (for example C90 to C30) one met window at a time. Cell-extensive quantities and dkg are block-summed, coarse boundary faces are summed, intensive surface fields are area weighted, and a new adaptive per-window transport schedule is selected.
This is a testing-only operator coarsener, not yet a validated substitute for direct preprocessing at target_Nc. The output header records that caveat. Only the payload used by the ERA5 N320 C90 L66 no-convection campaign is currently accepted; unfamiliar physics sections are rejected explicitly.
AtmosTransport.Preprocessing.CubedSphereTarget.convert_cs_mass_target_to_delta! Method
convert_cs_mass_target_to_delta!(m_target, m_cur)Convert an in-place CS endpoint target into the on-disk dm payload.
The CS writer stores forward endpoint differences. Call this only after all balance and replay checks that still need the absolute target endpoint.
sourceAtmosTransport.Preprocessing.CubedSphereTarget.derive_c180_dry_mass! Method
derive_c180_dry_mass!(m_dry, ps_dry, ps_dry_acc,
ps_panels, qv_panels, vc, cell_areas; grav=STANDARD_GRAVITY) -> nothingCubed-sphere dry-mass construction in Float64. Builds the dry-air layer mass and dry surface pressure for each of the 6 C-tier panels from the regridded moist PS + Q on C180. Same formula as the GEOS endpoint dry-mass derivation so Σ_k DELP_dry = PS_dry to roundoff on the target mesh too.
Inputs and outputs are NTuple{6, ...} panel tuples; ps_dry_acc is a panel-tuple Float64 accumulator (so a Float32 output preserves the multi-level summation precision). cell_areas[i, j] is shared across all 6 panels (the CS mesh is isotropic per panel).
AtmosTransport.Preprocessing.CubedSphereTarget.fill_cs_mass_delta_payload! Method
fill_cs_mass_delta_payload!(dm_payload, m_cur, m_next)Fill the on-disk forward endpoint-difference payload without mutating the absolute next endpoint. The ERA5 writer's sliding-window loop swaps m_next into m_cur after each write, so in-place conversion of the endpoint would make the following window start from m_next - m_cur.
AtmosTransport.Preprocessing.CubedSphereTarget.fill_cs_window_mass_tendency! Method
fill_cs_window_mass_tendency!(dm_panels, m_cur, m_next, steps_per_window)Fill the CS Poisson-balance target for one window.
m_cur and m_next are explicit endpoint masses. The stored CS horizontal fluxes are half-sweep amounts under Strang splitting, so the target is (m_next - m_cur) / (2 * steps_per_window) per panel cell.
AtmosTransport.Preprocessing.CubedSphereTarget.fill_dry_mass_flux_thickness! Method
fill_dry_mass_flux_thickness!(dp, m_dry, cell_areas, g)Fill native-level dry pressure thickness with g * m_dry / cell_areas. The mass includes the endpoint's global dry-mass pin. Arrays have horizontal axes matching cell_areas and a final level axis; CS panel tuples share one area matrix. Used before face interpolation or source-grid line integration.
AtmosTransport.Preprocessing.CubedSphereTarget.init_cs_positivity_accumulator Method
init_cs_positivity_accumulator() -> NamedTupleZero-valued state for accumulating the worst per-window positivity diagnostic across a preprocessing loop. Pair with update_cs_positivity_accumulator!.
AtmosTransport.Preprocessing.CubedSphereTarget.pin_cs_global_air_mass! Method
pin_cs_global_air_mass!(panels_m, panels_qv, cell_areas, g, target_kg, dB)Apply a uniform moist-surface-pressure offset to a cubed-sphere dry-air mass state so its global mass equals target_kg. For layer k, the correction is
This is the same hybrid-coordinate correction as the spectral path: layers with \Delta B_k = 0 are unchanged. panels_qv and dB are on the same target vertical grid as panels_m.
AtmosTransport.Preprocessing.CubedSphereTarget.pin_cs_global_air_mass_from_sensitivity! Method
pin_cs_global_air_mass_from_sensitivity!(panels_m, sensitivity, target_kg)Apply the global pin using a precomputed extensive sensitivity dm/dps = dB * (1-q) * area/g in kg/Pa. Building this field on native levels and summing it through a vertical transform preserves humidity covariance inside merged hybrid layers.
AtmosTransport.Preprocessing.CubedSphereTarget.ps_from_air_mass! Method
ps_from_air_mass!(ps, m, area, g, Nc, Nz)Set ps[i,j] = (Σ_k m[i,j,k]) · g / area[i,j] (Pa). Used to keep the binary's stored ps consistent with the chained pressure-fixer mass.
AtmosTransport.Preprocessing.CubedSphereTarget.rebuild_spectral_window_fluxes! Method
rebuild_spectral_window_fluxes!(workspace, end_am, end_bm, sampling,
base_steps, steps)Rebuild the unbalanced face amount for a window from immutable endpoint amounts. For window_mean, the trapezoidal approximation is
formed before the Poisson column balance. The factor base_steps / steps changes only the half-substep duration. Repeating this operation on an adaptive retry therefore never rescales a face field that has already been balanced.
AtmosTransport.Preprocessing.CubedSphereTarget.regrid_2d_to_cs_panels! Method
regrid_2d_to_cs_panels!(panels, regridder, src_2d, ws, Nc,
kind::QuantityKind = IntensiveCellField())2D analogue of regrid_3d_to_cs_panels!; same dispatch contract.
AtmosTransport.Preprocessing.CubedSphereTarget.regrid_3d_to_cs_panels! Method
regrid_3d_to_cs_panels!(panels, regridder, src_3d, ws, Nc,
kind::QuantityKind = IntensiveCellField())Conservatively regrid a 3D LL field (Nx, Ny, Nz) to 6 CS panels (Nc, Nc, Nz).
kind declares the field's regrid semantics and is passed to Regridding.apply_regridder!(dst, regridder, src, kind):
IntensiveCellField(default): regridded as given. Use forps,qv,T, cell-center wind components, mixing ratios.ExtensiveCellField: regridded as the densitysrc ./ regridder.src_areas, then multiplied byregridder.dst_areas. Required form(kg/cell) and any per-cell integral; without it the LL polar cells (230× smaller area than equator) drag CS polar mass to ~8% of physical and trigger runtime CFL inflation.HorizontalVectorField/HorizontalFluxField: not scalar regrids; they throw anArgumentError. Winds need component-wise intensive regrid plus rotation (rotate_winds_to_panel_local!); face fluxes are reconstructed from regridded winds.
Uses ws.src_flat_3d and ws.dst_flat_3d as I/O buffers and ws.density_scratch for the density of extensive fields, so repeated calls allocate nothing.
AtmosTransport.Preprocessing.CubedSphereTarget.regrid_ll_binary_to_cs Method
regrid_ll_binary_to_cs(ll_binary_path, cs_grid, out_path; FT=Float64, mass_basis=nothing)Regrid an existing LL transport binary to a cubed-sphere binary.
Reads each window from the LL binary, recovers cell-center winds from am/bm, conservatively regrids m/ps/winds to CS panels, rotates winds to panel-local coordinates, reconstructs CS face fluxes, closes continuity against forward mass endpoints, and stream-writes the CS binary.
This reuses the entire CS regrid/continuity/write infrastructure from the spectral→CS path — the only difference is the data source (binary reader instead of spectral synthesis).
The met interval comes from the source header. The LL winds of window w are recovered with that window's own source scaling, flux_application_seconds(dt_met, steps_w, flux_kind) with steps_w from steps_per_window_by_window (the stored am, bm are amounts of each window's own substep count). The CS output substep count is a property of the CS grid, not of the source, whose count the narrow lat-lon pole-row cells set: by default every CS window gets the smallest count whose per-substep Courant ratio meets positivity_cfl_limit (the fluxes are reconstructed for one substep, balanced, and rescaled), and the output carries that per-window schedule. Passing steps_per_window fixes one count for all windows instead.
The pole rows of the source are ordinary cells whose zonal faces carry flux, so the pole-row u is recovered from am like every other row. ERA5 spectral lat-lon binaries written before the fix of issue #58 (2026-10-14) closed those faces before the column balance; the stored pole-row am is then the balance correction, not the wind. They are recognised by their header (an ERA5 spectral lat-lon binary without pole_row_zonal_flux = "open") and refused before any output is opened. Regenerate them with the current preprocessor.
Keyword arguments
FT::Type = Float64— on-disk float type for the output CS binary.mass_basis::Union{Nothing, Symbol} = nothing— output mass-basis label.nothing(default) = match the source. Setting this to a value that differs from the source'smass_basiscurrently errors: actual dry↔moist conversion requires loading the source'sqvand applyingapply_dry_basis_native!, which this function does not do. Invariant 14 mandates:dryend-to-end; use a dry source.steps_per_window::Union{Nothing, Integer} = nothing— output substep count.nothing= per window from the CS Courant number (see above); an integer fixes the count for every window (stored per-substep fluxes scale with1/steps_per_window, the window-integrated transport does not).allow_terminal_zero_tendency::Bool = false— diagnostic-only escape hatch for legacy LL sources that do not carrydm. Production-safe regrids should leave this atfalseso the final CS window is closed against an explicit endpoint target instead of an inferred zero-tendency fallback.column_balance_weights::Symbol = :hybrid_mass— how the column Poisson balance spreads its correction over the levels (:mass,:hybrid_bor:hybrid_mass; seeAbstractColumnWeights), from the source binary's hybridBinterfaces. Other weights than:massare recorded in the header.write_replay_check::Bool = true— run the write-time replay-continuity gate.falseis a diagnostic escape hatch; the output header then recordswrite_replay_check = false.run_cache = nothing— optionalPreprocessorRunCacheused to reuse the LL→CS conservative regridder across calls in the same preprocessing run.
AtmosTransport.Preprocessing.CubedSphereTarget.regrid_transport_binary Method
regrid_transport_binary(input_path, target_grid, out_path; kwargs...)Generic transport-binary regrid extension point. Concrete target/source combinations implement methods here instead of adding new topology-specific scripts. The currently implemented production pair is LL transport binary to cubed sphere.
sourceAtmosTransport.Preprocessing.CubedSphereTarget.summarize_cs_positivity_status Method
summarize_cs_positivity_status(worst; cfl_limit, steps_per_window,
require_substep_positivity = true,
quarantine_path = nothing)Post-loop summary helper. Logs the worst-window outcome, and if it exceeds cfl_limit:
deletes
quarantine_path(if given) so a downstream consumer cannot pick up the half-written binary;errors when
require_substep_positivity = true, otherwise warns.
The error message includes a recommended steps_per_window value that would satisfy the gate, computed from the observed worst ratio.
AtmosTransport.Preprocessing.CubedSphereTarget.update_cs_positivity_accumulator Method
update_cs_positivity_accumulator(worst, diag, win_idx) -> NamedTupleReturn an updated accumulator from a fresh per-window diagnostic.
sourceAtmosTransport.Preprocessing.CubedSphereTarget.verify_cs_window_contract! Method
verify_cs_window_contract!(m_cur, am, bm, cm, m_next, steps_per_window, win_idx;
replay_tol, positivity_cfl_limit = DEFAULT_POSITIVITY_CFL_LIMIT,
replay_scratch = nothing)Single canonical per-window CS binary contract check. Runs the replay gate (verify_write_replay_cs!, errors on failure) followed by the per-substep positivity scan (verify_substep_positivity_cs, returns a diagnostic). Every CS-producing preprocessor (spectral, regrid, GEOS-native) should call this so no path can silently skip a gate.
Returns (; replay, positivity) with both diagnostics. Positivity is non-fatal here — callers aggregate the worst window and pass it to summarize_cs_positivity_status after the loop, where the run-level require_substep_positivity policy decides whether to error or warn.
AtmosTransport.Preprocessing.CubedSphereTarget.verify_write_replay_cs! Method
verify_write_replay_cs!(m_cur, am, bm, cm, m_next, steps_per_window, tol_rel, win_idx;
replay_scratch = nothing)Run the CS write-time replay gate for one window and return its diagnostic.
The check integrates the stored panel-local fluxes from m_cur under the runtime palindrome-continuity contract and verifies, cell by cell, that the result matches the explicit endpoint m_next (the metric of verify_window_continuity). A failure here means the binary would produce a runtime day-boundary or window-boundary mass inconsistency.
replay_scratch (a ReplayScratch) may be pre-allocated by the caller (workspace-owned scratch or contract-owned lazy scratch) so the gate doesn't allocate the panel-shared work arrays per call. Default nothing → allocate locally. Shape must match size(m_cur[1]).
AtmosTransport.Preprocessing.GEOS Module
GEOS meteorological input readers and transport-binary source workflows.
sourceAtmosTransport.Preprocessing.GEOS.GEOSDayHandles Type
GEOSDayHandlesOpen NCDataset handles for one UTC day's GEOS collections plus the resolved level orientation and the hybrid coordinate (loaded once for endpoint-DELP reconstruction). The orchestrator opens these once at the start of process_day and closes them at the end.
AtmosTransport.Preprocessing.GEOS.GEOSNativeReader Type
GEOSNativeReader{FT, S, CP, V, H} <: AbstractMetReader{FT, S, CP}Typed reader wrapping (GEOSSettings, handles) for one day, plus optional chained-mass state. Type parameters:
FT— preprocessing float type.S <: AbstractGEOSSettings— concrete settings (GEOSITSettings / GEOSFPSettings / …).CP <: AbstractChainPolicy—NoChainorChainedMass{T}.V— seed-field slot type.NothingforNoChain;Union{Nothing, NTuple{6, Array{FT, 3}}}forChainedMass. The V parameter is fixed at construction (Julia-style review round-1: value-dependent V was the type-instability foot-gun; we pin V to the unconditional Union on the chained path so the inner constructor specializes once).H— concrete handles type. Pinned totypeof(open_day(...))at construction soreader.handlesaccess is type-stable (replaces the previous:: Anyfield). Different GEOS flavors produce different handle structs (GEOSDayHandlesfor GEOS-IT,GEOSFPNativeDayHandlesfor GEOS-FP); each becomes its own concrete reader type via this parameter.
Constructor: open_reader(settings::AbstractGEOSSettings, date, FT; seed, next_day_handle). See the function docstring.
AtmosTransport.Preprocessing.GEOS.GEOSSettings Type
GEOSSettings{flavor} <: AbstractGEOSSettingsSettings for one of the two supported GEOS flavors:
flavor = :geosit— GEOS-IT (file patternGEOSIT.{date}.{collection}.C{Nc}.nc).flavor = :geosfp— GEOS-FP native hourlyGEOS.fp.asm.{tavg,inst}_1hr_ctm_cNNNN_v72files.
Auto-detection of level orientation runs at open_geos_day time when level_orientation = :auto. Set explicitly to :bottom_up or :top_down to skip the heuristic.
AtmosTransport.Preprocessing.GEOS.OmegaRegularization Type
OmegaRegularizationControls the scale-selective OMEGA prior used by :omega_regularized.
pressure_taper_hpa = (outer_top, inner_top, inner_bottom, outer_bottom) defines a smooth pressure window: the correction is zero outside the outer bounds and fully active between the inner bounds. smoothing_steps conservative graph-diffusion sweeps define the low-pass field; OMEGA contributes only the remaining high-pass difference from the endpoint-balanced vertical flux. max_relative_flux_correction caps the RMS X/Y face-flux increment separately at every level. max_bottom_flux_correction is a hard fidelity gate on the bottom three model layers, where surface-source transport must remain native.
AtmosTransport.Preprocessing.GEOS.detect_level_orientation Method
detect_level_orientation(ctm_a1::NCDataset) -> SymbolReturn :bottom_up if k=1 is the surface (mass-thicker) and :top_down if k=1 is TOA. Heuristic is unambiguous: surface DELP is O(1000 Pa), TOA DELP is O(1 Pa).
AtmosTransport.Preprocessing.GEOS.endpoint_dry_mass! Method
endpoint_dry_mass!(delp_dry, ps_dry, ps_total, qv, vc) -> (delp_dry, ps_dry)Reconstruct dry DELP and dry PS at one endpoint hour from the moist PS and QV provided by GEOS, using the hybrid coordinate vc. The output is on top-down level convention (k=1 = TOA).
Algorithm:
DELP_full[k] = ΔA[k] + ΔB[k] * PS_total
DELP_dry[k] = (1 - QV[k]) * DELP_full[k]
PS_dry = Σ DELP_dry[k]In-place: writes into delp_dry and ps_dry.
AtmosTransport.Preprocessing.GEOS.geos_collection_path Method
geos_collection_path(settings::GEOSITSettings, date::Date, collection) -> StringResolve the on-disk path of one GEOS-IT collection for date. Searches a flat root_dir and the per-day root_dir/YYYYMMDD/ layout.
AtmosTransport.Preprocessing.GEOS.open_geos_day Method
open_geos_day(settings, date; next_day_handle=true, adjacent_omega=false)
-> GEOSDayHandlesOpen per-collection NCDataset handles for date. When next_day_handle is true and the next-day CTM_I1 file exists, opens it too so the last window of date has its right endpoint available.
adjacent_omega (default false) opens the prev/next-day A3dyn (OMEGA) + I3 (QV) handles that the :omega_consistent cm closure needs to PCHIP-interpolate across midnight. Every other closure (incl. the validated :endpoint_balanced default and the GCHP VDIFF path) never reads them, so the default leaves all four handles nothing and opens nothing extra.
AtmosTransport.Preprocessing.GEOS.set_omega_level_parallel! Method
Select level parallelism before dispatching days; retains the existing execution policy.
sourceAtmosTransport.Preprocessing.ERA5 Module
ERA5 meteorological input readers and transport-binary source workflows.
sourceAtmosTransport.Preprocessing.ERA5.ERA5C180RawConvectionFields Type
Raw ECMWF convection diagnostics after conservative N320 → C180 mapping. Conversion to TM5 entrainment/detrainment deliberately happens only after this step, matching tmm_Read_Convec_EC in the vendored TM5 procedure.
AtmosTransport.Preprocessing.ERA5.ERA5C180RegridFields Type
ERA5C180RegridFields{FT}Per-window output container for fields regridded onto the C180 cubed-sphere target. Holds:
ps— 2D(Nc, Nc)matrix per panel (Pa, moist surface pressure),u,v,t,qv— 3D(Nc, Nc, Nz)arrays per panel (U/V in geographic east/north frame; rotation to panel-local axes happens in the breakpoint-F glue where the panel basis is known).
Mass fields (m_dry, delp_dry, ps_dry) are not regridded directly; they are re-derived on the C180 mesh from the regridded PS + Q so that Σ_k DELP_dry == PS_dry to roundoff on the target side as well.
AtmosTransport.Preprocessing.ERA5.ERA5C180RegridWorkspace Type
ERA5C180RegridWorkspace{FT, R}Owns the conservative regridder + flat scratch buffers used by regrid_n320_to_c180!. Allocated once per (source_grid, target_grid) pair and reused across every window. coverage is the fraction of each target cell covered by the source mesh (see _regrid_intensive!).
AtmosTransport.Preprocessing.ERA5.ERA5C180TM5ConvectionFields Type
ERA5C180TM5ConvectionFields{FT}TM5 convection fields derived on the C180 cubed-sphere target after the raw ECMWF diagnostics have been conservatively mapped there. Each field is a 6-tuple of (Nc, Nc, Nz) panel arrays, layer-centered, kg / m² / s.
AtmosTransport.Preprocessing.ERA5.ERA5GRIBDayHandles Type
ERA5GRIBDayHandles{S<:AbstractERA5GRIBSettings}Per-day source-file context. Carries the resolved on-disk paths to the day's GRIB streams plus the optional next-day core path that supplies the right endpoint of the last window.
convection_path is nothing unless settings.include_convection is set; likewise surface_path is nothing unless settings.include_surface is set. next_core_path is nothing either when the caller passed next_day_handle=false or when the next-day file is not on disk (last day of the available archive). core_index holds the ecCodes index of core_path once the first window has been read.
AtmosTransport.Preprocessing.ERA5.ERA5GRIBSettings Type
ERA5GRIBSettings{flavor} <: AbstractERA5GRIBSettingsTyped settings for one ERA5 native-GRIB flavor:
flavor = :n320— reduced linear-Gaussian N320, the default MARS native grid for ERA5 analyses (640 longitudes at the equator, 137 hybrid levels).
ERA5 archives and the runtime both use top-down hybrid levels (k = 1 is the TOA-side layer). Only the GRIB horizontal ring order is reversed on ingestion.
AtmosTransport.Preprocessing.ERA5.ERA5HumidityRemap Type
ERA5HumidityRemapSpecific humidity of one ERA5 N320 day conservatively remapped to another horizontal mesh, for converting convective fluxes that live on that mesh to dry air. Open with open_era5_humidity_remap, fill with remap_era5_humidity!, release with close.
AtmosTransport.Preprocessing.ERA5.ERA5N320ConvectionFields Type
ERA5N320ConvectionFields{FT}Per-window convection forecast fields on the N320 source mesh. All four fields are (n_cells, Nz):
udmf— updraft convective mass flux (kg m⁻² s⁻¹)ddmf— downdraft convective mass flux (kg m⁻² s⁻¹)udrf— updraft detrainment rate (kg m⁻³ s⁻¹)ddrf— downdraft detrainment rate (kg m⁻³ s⁻¹)
Downstream conversion to GEOS-style CMFMC + DTRAIN (or TM5-style entu/entd) happens in the breakpoint-F glue once both source and target geometries are known.
sourceAtmosTransport.Preprocessing.ERA5.ERA5N320DryMassFields Type
ERA5N320DryMassFields{FT}Per-window dry-basis output container. m_dry is dry-air mass per cell per layer (kg), delp_dry is dry pressure thickness per cell per layer (Pa), ps_dry is the column-integrated dry surface pressure (Pa). ps_dry_acc is a Float64 accumulator that backs ps_dry so Σ_k DELP_dry stays accurate even when FT = Float32 (137-layer summation with ~10 hPa values per layer would otherwise lose ~100 Pa to single-precision rounding).
AtmosTransport.Preprocessing.ERA5.ERA5N320SpectralWorkspace Type
ERA5N320SpectralWorkspace{FT, G}Per-window workspace for ERA5 N320 spectral synthesis. Owns:
the spectral coefficient cubes for T, VO, D, LNSP for the current hour (sized
(T+1) × (T+1) × NzinComplexF64),per-level scratch matrices
u_spec/v_specreused inside the synthesis loop,a
ReducedSpectralThreadCachewith Legendre column buffer plus FFT and real ring buffers sized to every unique ring length in the source mesh,a
read_bufscratch used byread_spectral_coeffs!for the raw ecCodescodes_get_double_arraypayload,completion bookkeeping (
have_t/have_vo/have_d/have_lnsp).
The cubes dominate memory: at T = 639 and Nz = 137 each cube is ≈ 0.9 GB. Workspaces are intended to be allocated once per day-handle and reused across the 24 hours.
Spectral buffers (vo_spec, d_spec, t_spec, lnsp_spec, u_spec, v_spec, synth_cache.P_buf) are unconditionally ComplexF64 / Float64 regardless of FT — read_spectral_coeffs! and vod2uv! only operate at that precision. FT only controls the eltype of the downstream gridpoint fields written via read_era5_n320_window_fields!.
AtmosTransport.Preprocessing.ERA5.ERA5N320ToC180Pipeline Type
ERA5N320ToC180Pipeline{FT, RW, CSGrid, SrcGrid, W}All-in-one container for the per-day ERA5 N320 → C180 preprocessing workspace. Holds the source-grid descriptor, the hybrid coordinate, the shared per-cell area vector, every read/derive/regrid workspace from breakpoints B-D, the convection workspace from E, and the per-window output fields on both the source mesh and the C180 target.
One pipeline allocated per day-handle, reused across the 24 hourly windows.
sourceAtmosTransport.Preprocessing.ERA5.ERA5N320WindowFields Type
ERA5N320WindowFields{FT}Per-window output container. u / v (m/s, geographic frame), t (K), qv (kg/kg specific humidity) are (n_cells, Nz); ps (Pa) is (n_cells,). Dry-basis layer mass derivation, regridding, and convection conversion are downstream of this struct.
AtmosTransport.Preprocessing.ERA5.ERA5ReducedGaussianGeometry Type
ERA5ReducedGaussianGeometry{FT}Reduced-Gaussian geometry read from a native ERA5 / IFS GRIB message.
Fields
latitudes– ring-center latitudes [degrees], ordered south -> northnlon_per_ring– number of longitude cells on each ring (pl)grid_type– GRIB grid type, expected to be"reduced_gg"gaussian_number– reduced-Gaussian resolution parameterNlongitude_first– longitude of first stored grid point [degrees]longitude_last– longitude of last stored grid point [degrees]j_scans_positively– raw GRIB scanning-direction flagj_points_are_consecutive– raw GRIB storage-order flag
AtmosTransport.Preprocessing.Common.read_era5_reduced_gaussian_geometry Method
read_era5_reduced_gaussian_geometry(path; FT=Float64, param_id=nothing,
level=nothing, date=nothing, time=nothing)Read reduced-Gaussian ring geometry from the first matching native GRIB message in path.
This is intended for ERA5 / IFS native fields already archived on the reduced Gaussian grid, for example q, o3, and many cloud/physics variables. Spectral files (gridType = sh) are intentionally rejected.
AtmosTransport.Preprocessing.Common.read_era5_reduced_gaussian_mesh Method
read_era5_reduced_gaussian_mesh(path; FT=Float64, radius=EARTH_RADIUS, kwargs...)Convenience wrapper that reads native reduced-Gaussian GRIB geometry and returns a ReducedGaussianMesh ready for src transport geometry.
AtmosTransport.Preprocessing.ERA5.allocate_era5_n320_spectral_workspace Method
allocate_era5_n320_spectral_workspace(source_grid, T, Nz)Allocate a fresh workspace sized to source_grid (build via discover_era5_n320_source_grid), spectral truncation T (from discover_era5_spectral_truncation) and vertical level count Nz (callers default to ERA5_NATIVE_LEVEL_COUNT = 137, but the workspace itself stays generic).
AtmosTransport.Preprocessing.ERA5.allocate_era5_n320_to_c180_pipeline Method
allocate_era5_n320_to_c180_pipeline(handles, target_grid;
Nz=ERA5_NATIVE_LEVEL_COUNT,
cache_dir=nothing,
include_convection=true)Build the full per-window pipeline for the ERA5 source described by handles (resolved via open_era5_day) and the C-tier target target_grid. Discovers the source mesh and spectral truncation from the day's core GRIB, loads the hybrid coordinate file declared in the settings, builds (or JLD2-loads from cache_dir) the conservative regridder, and allocates every B/C/D/E workspace.
Convection workspace allocation is gated on include_convection so the caller can opt out for a scalar-only smoke.
AtmosTransport.Preprocessing.ERA5.close_era5_day! Method
close_era5_day!(handles::ERA5GRIBDayHandles)Release the ecCodes index of the day's core GRIB file, if one was built. Idempotent — safe to call from a finally block.
AtmosTransport.Preprocessing.ERA5.derive_c180_tm5_convection! Method
derive_c180_tm5_convection!(tm5_fields, conv_fields, window_fields, vc, scratches;
basis, stats=nothing) -> tm5_fieldsTM5 entrainment and detrainment on every target column from the raw ECMWF diagnostics already mapped to the target (conv_fields), following TM5's tmm_Read_Convec_EC: UDMF/DDMF level k becomes interface k (the top of layer k) and the ground interface Nz + 1 is zero, layer thickness from the target T, q and ps (dz_hydrostatic_virtual!), the fluxes put on the air-mass basis of the binary with ecmwf_convection_to_basis! (DryBasis() multiplies them by 1 − q), then ec2tm_from_rates!.
AtmosTransport.Preprocessing.ERA5.derive_n320_dry_mass! Method
derive_n320_dry_mass!(dry, window, vc, cell_areas; grav=STANDARD_GRAVITY) -> dryReconstruct dry-air mass per layer, dry pressure thickness, and dry surface pressure from a populated window::ERA5N320WindowFields (moist PS, Q) using the hybrid coordinate vc (length Nz+1 A and B arrays in Pa and 1 respectively, top-down) and the per-cell areas (m²). Matches the GEOS endpoint_dry_mass! formula so the runtime sees a nominally bit-identical dry-basis contract regardless of source.
Asserts shapes and length(vc.A) == length(vc.B) == Nz + 1 so a coefficient table that does not match the workspace Nz fails immediately with a clear DimensionMismatch.
AtmosTransport.Preprocessing.ERA5.discover_era5_n320_source_grid Method
discover_era5_n320_source_grid(core_path; FT=Float64) -> ReducedGaussianTargetGeometryBuild the N320 source-grid descriptor from the first gridType=reduced_gg message in core_path (the q field is always present). The resulting mesh ring order is south→north — the GRIB stores rings north→south and the read_era5_reduced_gaussian_* helpers flip into the project convention.
AtmosTransport.Preprocessing.ERA5.discover_era5_spectral_truncation Method
discover_era5_spectral_truncation(core_path) -> IntRead the first spectral (gridType=sh) message in core_path and return its triangular truncation J = K = M. ERA5 native model-level analyses are T639 in the current archive; the helper avoids hard-coding that value in case a future archive convention shifts.
AtmosTransport.Preprocessing.ERA5.era5_convection_hour_address Method
era5_convection_hour_address(hour) -> (use_prev_day, data_time_hhmm, step_range)Map a UTC hour h ∈ 0..23 to the GRIB header tuple that addresses the matching ECMWF convection forecast sample (see read_era5_n320_convection_window! docstring for the cycle layout). Returns (::Bool, ::Int, ::String).
AtmosTransport.Preprocessing.ERA5.era5_grib_path Method
era5_grib_path(settings, date, stream) -> StringResolve the on-disk GRIB path for stream on date. stream must be one of :core, :convection, or :surface. Existence is not checked here — the caller (typically open_era5_day) decides whether a missing file is fatal or merely "no next-day endpoint available".
AtmosTransport.Preprocessing.ERA5.n320_cell_areas Method
n320_cell_areas(source_grid) -> Vector{Float64}Materialise per-cell areas (m²) for the N320 source mesh. Always returns Vector{Float64} regardless of source_grid's element type — downstream dry-mass arithmetic runs in Float64 for precision and the per-cell mesh quadrature is itself Float64. Cached by callers that derive dry mass for many windows of the same day.
AtmosTransport.Preprocessing.ERA5.open_era5_day Method
open_era5_day(settings, date; next_day_handle=true) -> ERA5GRIBDayHandlesResolve the GRIB stream paths for date and assert that today's required files are on disk. When next_day_handle=true and <date+1> has a core GRIB available, records its path so the last window's right endpoint can be read from the next day's hour-0 fields.
Errors are explicit about which file is missing so a misconfigured root_dir or an incomplete download is immediately visible.
AtmosTransport.Preprocessing.ERA5.open_era5_humidity_remap Method
open_era5_humidity_remap(root_dir, date, target_mesh; Nz=ERA5_NATIVE_LEVEL_COUNT,
cache_dir=nothing) -> ERA5HumidityRemapPrepare to read the ERA5 N320 specific humidity of date from the native GRIB archive under root_dir (ml_an_native_core/era5_core_YYYYMMDD.grib) and remap it conservatively, with the coverage normalisation of _regrid_intensive!, to target_mesh. The regridder weights are cached in cache_dir.
AtmosTransport.Preprocessing.ERA5.process_era5_n320_to_cs_day Method
process_era5_n320_to_cs_day(date, settings, target_grid;
out_path,
Nz = ERA5_NATIVE_LEVEL_COUNT,
vertical_plan = nothing,
mass_basis = :dry,
dt_met_seconds = ERA5_MET_INTERVAL_SECONDS,
steps_per_window = 8,
adaptive_substeps = true,
substep_cfl_target = ERA5_N320_SUBSTEP_CFL_TARGET,
max_steps_per_window = typemax(Int),
cs_balance_tol = DEFAULT_POISSON_BALANCE_TOL,
cs_balance_project_every = DEFAULT_POISSON_PROJECT_EVERY,
positivity_cfl_limit = DEFAULT_POSITIVITY_CFL_LIMIT,
require_substep_positivity = true,
write_replay_check = true,
cache_dir = nothing,
include_convection = false,
global_mass_pin = false,
global_mass_target_kg = NaN,
mass_fix_target_ps_dry_pa = NaN)The float type is the target grid's (target_grid::CubedSphereTargetGeometry{FT}).
Generate a v4 cubed-sphere transport binary for one UTC date from the ERA5 native-GRIB source described by settings, written to out_path.
mass_basis is fixed to :dry here — the writer pulls dry-basis layer mass and dry surface pressure (re-derived on the target from regridded PS + Q). Dry basis is the runtime default; a :moist request errors.
steps_per_window is the number of Strang substeps per met window. With adaptive_substeps = true (default) it is the floor: each window's count is raised until the per-substep CFL is under substep_cfl_target (at most max_steps_per_window), and the per-window schedule is written into the header. Each am / bm per-face slot stores the substep-mass amount. Per face, the Courant number of a substep is |F| / m_donor (the donor cell depends on the flux sign); the runtime subcycling gate sums each cell's outgoing x, y and z face fluxes over the palindrome and divides by its mass (cs_subcycling.jl).
The function writes through a unique sibling staging file and atomically publishes out_path on success — a partial run leaves no usable file at the requested path.
AtmosTransport.Preprocessing.ERA5.process_era5_n320_window! Method
process_era5_n320_window!(pipeline, handles, date, hour) -> pipelineDrive the per-window pipeline for (date, hour):
Synthesise PS / U / V / T / Q on the N320 source mesh (breakpoint B).
Derive dry-air mass + DELP_dry + PS_dry on the source mesh (breakpoint C).
Conservatively regrid PS / U / V / T / Q to the C-tier target.
Optionally read and regrid raw UDMF / DDMF / UDRF / DDRF, put them on the dry basis, and perform the nonlinear TM5 conversion and closure on the target columns.
After the call, pipeline.window_fields, pipeline.dry_fields, pipeline.convection_fields, and pipeline.c180_fields carry the window's data on their respective grids.
AtmosTransport.Preprocessing.ERA5.read_era5_n320_convection_window! Method
read_era5_n320_convection_window!(fields, handles, mesh, date, hour) -> fieldsFill fields with one hour's worth of N320 convection forecast fields for (date, hour). The reader picks handles.convection_path or handles.prev_convection_path based on the hour-address mapping and forward-iterates that file, matching messages whose (dataTime, stepRange, shortName) triple falls within the requested sample. Each matching message is decoded directly into the appropriate (n_cells, Nz) output slot via _reorder_grib_reduced_gg_to_mesh!.
Completeness gates name the missing field in any error so a corrupt or partial download is immediately visible. All four fields × 137 levels must be present for the call to succeed.
sourceAtmosTransport.Preprocessing.ERA5.read_era5_n320_humidity! Method
read_era5_n320_humidity!(qv, handles, mesh, date, hour) -> qvSpecific humidity (kg kg⁻¹) of (date, hour) from the day's ERA5 core GRIB, decoded into qv (n_cells × Nz, top-first levels) on the ReducedGaussianMesh cell centres exactly as read_era5_n320_window_fields! does, without the spectral fields. Errors if a level is missing.
AtmosTransport.Preprocessing.ERA5.read_era5_n320_window_fields! Method
read_era5_n320_window_fields!(fields, workspace, handles, date, hour) -> fieldsFill fields with one window's worth of N320 source-grid fields for (date, hour). Performs one forward pass over handles.core_path, decoding every message whose (dataDate, dataTime) matches into the workspace's level-indexed spectral cubes (for gridType=sh) or directly into the output qv array (for gridType=reduced_gg). After the pass the function synthesizes spectral T per level, applies vod2uv! per level and synthesizes U/V. PS comes from LNSP synthesis, or — when settings.arco_surface_pressure is set — from bilinear interpolation of the ARCO single_level sp netCDF (_fill_ps_from_arco_sp!). Errors loudly if any required level/field is absent so a partial download is immediately visible.
The function does not allocate beyond read_buf resizing inside read_spectral_coeffs!. Reusing (fields, workspace) across the 24 windows of a day is the intended call pattern.
AtmosTransport.Preprocessing.ERA5.regrid_n320_to_c180! Method
regrid_n320_to_c180!(c180_fields, n320_window, workspace, target_grid,
wind = ScalarWindRegrid()) -> c180_fieldsConservatively regrid PS (2D) and U, V, T, Q (3D) from the N320 source mesh to the C180 cubed-sphere target. PS, T and Q are intensive scalars; U and V go through wind, as two scalars (ScalarWindRegrid, the default) or as a vector (CartesianWindRegrid). The flat scratch buffers in workspace hold the intermediate Float64 arrays.
AtmosTransport.Preprocessing.ERA5.remap_era5_humidity! Method
remap_era5_humidity!(remap::ERA5HumidityRemap, hour) -> q_targetRead the specific humidity of hour (0–23 UTC) on the N320 mesh (read_era5_n320_humidity!) and remap it to the target mesh. Returns remap.q_target, (target cells, Nz) with top-first levels.
AtmosTransport.Preprocessing.MERRA2 Module
MERRA2 meteorological input readers and transport-binary source workflows.
sourceAtmosTransport.Preprocessing.MERRA2.MERRA2Archive Type
NASAArchive()
GEOSChemArchive()MERRA-2 file layouts. NASAArchive: the GES DISC collections under {root_dir}/M2{I,T}3NVASM/YYYY/MM/ (PS, QV, U, V only). GEOSChemArchive: the GEOS-Chem-processed files {root_dir}/YYYY/MM/MERRA2.YYYYMMDD.{tag}.05x0625.nc4, which also carry the convection and boundary-layer fields.
AtmosTransport.Preprocessing.MERRA2.MERRA2DayHandles Type
MERRA2DayHandlesOpen NCDataset handles for one UTC day:
inst3— PS/QV instantaneous endpoints (always open).tavg3— U/V time-averaged winds;nothingwhensettings.winds_collection == :inst3(winds then come frominst3).next_inst3— next day's inst3 dataset, for the final window's right endpoint look-ahead;nothingon the archive boundary or whennext_day_handle = false.a3mste,a3mstc,a1— GEOS-Chem A3mstE (CMFMC), A3mstC (DQRCU) and A1 (PBL surface fields); open only when the corresponding output is requested.level_order,next_level_order—TopDown()orSurfaceFirst(), detected from the day's and the next day's inst3 QV; the day's order applies to all of that day's collections (one archive, one convention).
AtmosTransport.Preprocessing.MERRA2.MERRA2LevelOrder Type
TopDown()
SurfaceFirst()Level order of a MERRA-2 file: the GES DISC files are top-down (k = 1 at the model top, like the L72 coefficient table), the GEOS-Chem files surface-first.
sourceAtmosTransport.Preprocessing.MERRA2.MERRA2Settings Type
MERRA2Settings <: AbstractMetSettingsSettings for the MERRA-2 wind-derived cubed-sphere preprocessor.
root_dir— directory holding the MERRA-2 collection trees ({root_dir}/M2{I,T}3NVASM/{YYYY}/{MM}/...nc4).coefficients_file— hybrid σ-pressure coefficient TOML (the GEOS L72 table; MERRA-2 shares the GEOS-5 L72 coordinate).winds_collection—:tavg3(time-averaged U/V, the default and the GEOS-Chem-faithful choice) or:inst3(instantaneous U/V from the inst3 collection, no separate tavg3 file needed;NASAArchiveonly).archive—NASAArchive()orGEOSChemArchive()(seeMERRA2Archive).include_surface— write PBLH, USTAR, HFLUX, T2M (GEOSChemArchiveonly).include_convection— write dry CMFMC and DTRAIN (GEOSChemArchiveonly).include_vdiff_fields— write the Holtslag-Boville VDIFF fields U, V, T, QV and the latent heat flux EFLUX (implies the surface fields;GEOSChemArchiveonly).include_convective_cloud_base— write GCHP's convective cloud base, the lowest layer with DQRCU > 0 (A3mstC; needsinclude_convection).
AtmosTransport.Preprocessing.MERRA2.MERRA2ToC180Pipeline Type
MERRA2ToC180Pipeline{FT, R, P, E, W}Per-day MERRA-2 → CS preprocessing workspace. Owns the conservative LL→CS regridder, the CS preprocess scratch, and the per-window regridded target-grid scalar fields (c180_fields.{ps, qv, u, v}, any Nc), laid out as NTuple{6, …} panels so the shared CS helpers (derive_c180_dry_mass!, rotate_winds_to_panel_local!, reconstruct_cs_fluxes!) work unchanged.
phys holds the regridded optional physics panels (cmfmc, dtrain, t, dqrcu and its cloud_base, and surface_hours, the three hourly A1 records of the block as (pblh, ustar, hflux, t2m[, eflux]) panels — only those requested; empty without physics); edge_src/edge_dst are the regridder buffers for the Nz+1-edge CMFMC; wind selects how U/V are regridded (ScalarWindRegrid or CartesianWindRegrid, which owns its buffers).
Two pipelines per day (block start and end), reused across the 8 blocks.
sourceAtmosTransport.Preprocessing.MERRA2.allocate_merra2_to_c180_pipeline Method
allocate_merra2_to_c180_pipeline(target_grid; Nz, cache_dir, settings) -> MERRA2ToC180PipelineBuild (or JLD2-load from cache_dir) the MERRA-2 LL → CS conservative regridder and allocate every per-window buffer, including the physics panels settings requests. The source LL mesh is built with the TARGET mesh radius so the two manifolds match (build_regridder rejects a radius mismatch).
AtmosTransport.Preprocessing.MERRA2.allocate_merra2_window_physics Method
allocate_merra2_window_physics(settings, Nc, Nz, FT) -> NamedTupleOutput buffers for one window's physics sections (see merra2_window_physics!); only the requested ones are allocated.
AtmosTransport.Preprocessing.MERRA2.close_merra2_day! Method
close_merra2_day!(handles)Close every open NCDataset. Idempotent — safe to call from a finally.
AtmosTransport.Preprocessing.MERRA2.convective_cloud_base! Method
convective_cloud_base!(cloud_base, dqrcu) -> cloud_baseGCHP's convective cloud base (convection_mod.F90, DO_RAS_CLOUD_CONVECTION): the lowest layer with convective rain production DQRCU > 0, or the surface layer when there is none. Levels are top-down, so this is the largest such k, stored as a float layer index.
AtmosTransport.Preprocessing.MERRA2.detect_merra2_level_order Method
detect_merra2_level_order(inst3, path) -> TopDown() or SurfaceFirst()Level order of an inst3/I3 file from its first-slice QV: the global-mean specific humidity is ≈7e-3 kg/kg in the surface layer and ≈2e-6 at the top, so the moist end is the surface. Errors unless one end is >100× the other. Neither archive carries DELP or pressure metadata to decide from.
sourceAtmosTransport.Preprocessing.MERRA2.merra2_archive Method
merra2_archive(name) -> MERRA2ArchiveThe archive for the [preprocessing] layout key: "nasa" or "geoschem".
AtmosTransport.Preprocessing.MERRA2.merra2_path Method
merra2_path(settings, date, collection) -> StringResolve the on-disk path for one MERRA-2 collection on date:
NASAArchive(:inst3,:tavg3):{root_dir}/{dir}/{YYYY}/{MM}/MERRA2_{stream}.{name}.{YYYYMMDD}.nc4GEOSChemArchive(:inst3→ I3,:tavg3→ A3dyn,:a3mste,:a3mstc,:a1):{root_dir}/{YYYY}/{MM}/MERRA2.{YYYYMMDD}.{tag}.05x0625.nc4
Existence is not checked here — open_day decides whether a missing file is fatal or merely "no next-day endpoint available".
AtmosTransport.Preprocessing.MERRA2.merra2_stream_code Method
merra2_stream_code(date) -> StringMERRA-2 production stream code for date (same year→stream map the download path uses): 100 (1980-91), 200 (92-00), 300 (01-10), 400 (2011 onward).
AtmosTransport.Preprocessing.MERRA2.merra2_window_physics! Method
merra2_window_physics!(out, settings, cur, nxt, h, nsub)
-> (; surface, cmfmc, dtrain, vdiff, cmfmc_cloud_base)Physics sections of output window h of the nsub equal windows that split the 3-hour block held in cur (nxt holds the block's right-endpoint QV and T). Sections not requested are nothing.
The window's start and end QV, and the VDIFF temperature, are linear in time between the block endpoints (
curexactly whennsub == 1).CMFMC and DTRAIN (3-hour averages) are copied into
outand converted to dry air there with the window's start and end QV, socur.physstays moist and can serve every window of the block.The PBL surface fields (and EFLUX) average the A1 hours inside the window.
The convective cloud base is the block's (from 3-hour DQRCU).
AtmosTransport.Preprocessing.MERRA2.open_merra2_day Method
open_merra2_day(settings, date; next_day_handle=true) -> MERRA2DayHandlesOpen the day's inst3 (and tavg3, when winds_collection==:tavg3) datasets, asserting both are on disk. When next_day_handle=true and the next-day inst3 file exists, opens it for the final-window endpoint look-ahead.
AtmosTransport.Preprocessing.MERRA2.process_merra2_to_cs_day Method
process_merra2_to_cs_day(date, settings, target_grid; out_path, dt_met_seconds, …)Write a v4 cubed-sphere transport binary for one UTC date from MERRA-2 to out_path (written through a unique sibling staging file and atomically published when the gates pass).
Horizontal mass fluxes come from the regridded 3-hour mean winds and are Poisson-balanced (a column pressure fix) against the dry-mass change between the 3-hourly inst3 endpoints. dt_met_seconds = 10800 (the default, GEOS_3HOURLY_INTERVAL_SECONDS) writes one window per 3-hour block (8 per day); 3600 splits each block into three hourly windows (24 per day) with endpoint mass, PS, QV and T linear in time, so the hourly A1 boundary-layer fields reach the runtime unaveraged. Optional convection, PBL, VDIFF and cloud-base sections follow settings. Only mass_basis = :dry.
AtmosTransport.Preprocessing.MERRA2.process_merra2_window! Method
process_merra2_window!(pipe, handles, win; FT) -> pipeRead native MERRA-2 LL fields for window win (PS/QV from inst3 slice win, U/V from tavg3 slice win) and conservatively regrid PS (2D intensive) and QV/U/V (3D intensive) onto the CS target panels. U/V/QV are intensive → default field type, as in the ERA5 path. The readers return top-down levels whatever the file order; requested physics fields are regridded into pipe.phys.
AtmosTransport.Preprocessing.MERRA2.read_merra2_next_day_endpoint Method
read_merra2_next_day_endpoint(handles, Nz; FT) -> (; ps, qv[, t])Read the next day's inst3 slice-1 PS/QV (and T when VDIFF fields are requested) — the right endpoint for the final window of handles.date. Returns nothing when no next-day inst3 handle is open (archive boundary).
AtmosTransport.Preprocessing.MERRA2.read_merra2_physics_window Method
read_merra2_physics_window(handles, win, Nz; FT) -> NamedTupleNative moist-basis physics fields for window win, top-down, from the GEOS-Chem archive. Keys present only for the requested outputs:
cmfmc(Nx, Ny, Nz+1) kg m⁻² s⁻¹ anddtrain(Nx, Ny, Nz) kg m⁻² s⁻¹: A3mstE / A3dyn slicewin(A3mstE labels CMFMC "kg m-2 s-2", a typo).dqrcu(Nx, Ny, Nz) kg kg⁻¹ s⁻¹: A3mstC slicewin, convective rain production (only its sign is used, to locate the cloud base).pblhm,ustarm s⁻¹,hfluxandefluxW m⁻² (upward positive),t2mK, each (Nx, Ny, 3): the hourly A1 records 3(win-1)+1 .. 3win (hour averages centred 30 min into each hour of the window);efluxonly with VDIFF fields.t(Nx, Ny, Nz) K: I3 slicewin, the window-start state (as QV).
AtmosTransport.Preprocessing.MERRA2.read_merra2_window_fields Method
read_merra2_window_fields(handles, win, Nz; FT)
-> (; ps, qv, u, v, omega)Read one window's worth of native MERRA-2 LL fields for 1-based window index win (1..8):
ps(Pa) andqv(kg/kg) from the inst3 handle slicewin(instantaneous mass endpoint),u,v(m/s) from the tavg3 handle slicewin(3-hr time-average advecting winds), or from inst3 whenwinds_collection==:inst3.
All arrays are (lon, lat[, lev]), top-down, no reorientation.
AtmosTransport.Preprocessing.MERRA2.validate_merra2_settings Method
validate_merra2_settings(settings) -> settingsReject unknown wind collections and requests the archive cannot serve (only the GEOS-Chem files carry CMFMC, DTRAIN, DQRCU and A1).
source