Skip to content

Adjoints and checkpointing API ​

The adjoint surface covers cubed-sphere objectives, observations, footprints, preconditioning, and 4D-Var solvers. Tape owns checkpoint schedules and device, pinned-host, and memory-mapped tape storage. Adjoints.Inversion.ObservationBinding owns inversion records, column binding, observation/departure IO and OCO-2 MIP conversion. Observations owns forward placement, retrievals and sampling; inversion exports remain available through the Inversion and Adjoints facades.

Adjoints ​

Configure optimizer settings and logging on CSGradientDescent or CSLBFGS and pass it as optimizer to cs_surface_flux_4dvar_optimize. Both accept the same opt-in stop rules, checked after every cost evaluation against the best cost so far: cost_rtol (stop after cost_rtol_improvements consecutive relative decreases of the best cost below it), stall_evaluations (stop after that many evaluations without a new best cost, as at the noise floor of a Float32 cost), max_evaluations and a callback(evaluation, result) -> Bool. The CS4DVarSolveResult holds the last accepted iterate (controls, last), the lowest-cost evaluation (best), the number of evaluations and a stop_reason. One cs_surface_flux_4dvar evaluation runs the forward model once: the run that samples the observations records the tape of the reverse pass; evaluation = CSCostOnly() runs it without a tape for the cost and simulated values alone. Footprint functions compute analytic adjoints; finite-difference perturbations belong to the caller's validation code. CSFootprintResult contains objective, footprints, lag_steps, dt, and initial_adjoint.

AtmosTransport.Adjoints Module

Cubed-sphere discrete adjoint core; replay and inversion live in its child modules.

source
AtmosTransport.Adjoints.AbstractTapeDependence Type
julia
AbstractTapeDependence

What the reverse pass of a cubed-sphere advection scheme reads of the forward run besides the met inputs, tape_dependence(scheme): AirMassDependence or TracerDependence.

source
AtmosTransport.Adjoints.AirMassDependence Type
julia
AirMassDependence()

The reverse reads the air mass only: a tape of the scheme does not depend on the tracer or the emissions, so one recording serves every tracer and every evaluation of an optimization (AirMassTape).

source
AtmosTransport.Adjoints.CSCellAverageObjective Type
julia
CSCellAverageObjective(panel, i, j, members, weights, ids;
                       measurement_sigma = NaN, model_sigma = NaN, correlation = NaN)

The weighted mean ∑nwnhn of column objectives members of one physical CS interior cell (panel, i, j) (CSRetrievalColumnObjectives or CSColumnMeanObjectives; weights positive, summing to 1; ids the record ids of the members): a cell average of soundings, built by bind_to_mesh with cell_averaging = CellAverage(...), the weights proportional to 1/σn2. The operators are linear, so its functional is the same weighted sum of the members' functionals: the gradient of the averaged observation is the weighted combination of the members' gradients. Sampled like its members (cs_surface_flux_4dvar(...; column_met)). The surface-pressure screen applies to records, not averages, so an averaging-kernel member must have no surface-pressure limit (max_surface_pressure_mismatch_pa = Inf). measurement_sigma, model_sigma and correlation record how the average's error was built (σmeas, σmod, ρ; departure files report them).

source
AtmosTransport.Adjoints.CSColumnMeanObjective Type
julia
CSColumnMeanObjective(panel, i, j)

Scalar objective equal to the final air-mass-weighted column mean mixing ratio at one physical CS interior cell.

source
AtmosTransport.Adjoints.CSLayerMeanObjective Type
julia
CSLayerMeanObjective(panel, i, j, level)

Scalar objective equal to the final-layer mixing ratio rm[panel][i, j, level] / m[panel][i, j, level] on the physical CS interior indices. level = Nz is the surface layer.

source
AtmosTransport.Adjoints.CSPlacedPointObjective Type
julia
CSPlacedPointObjective(panel, i, j, area, placement, pressure_basis)

Mixing ratio rm / m of the model layer that contains an in-situ sample, in the physical CS interior cell (panel, i, j) of area area (m², the cell that contains the sample). placement (an Observations.VerticalPlacement) says how the sample is placed in the column — its height above the model surface or its pressure — and is resolved once, by bind_to_mesh with Observations.resolve_placement, the rule of the forward observation sampler. The layer itself is chosen every time the objective is sampled, from the replayed air mass of that state and the CSObservationColumnMet (hypsometric layer heights and interface pressures, both on pressure_basis: total pressures and the virtual temperature from the humidity for TotalFromHumidity, the dry interfaces and the layer temperature for DryInterfaces), with Observations.sample_column_layer!. Sampling it therefore needs the column meteorology: cs_surface_flux_4dvar(...; column_met); the final-time footprint and Jacobian entry points do not take it.

source
AtmosTransport.Adjoints.CSRetrievalColumnObjective Type
julia
CSRetrievalColumnObjective(panel, i, j, area, retrieval, pressure_basis;
                           max_surface_pressure_mismatch_pa = Inf,
                           mismatch_policy = ErrorOnUnplaced())

Averaging-kernel column average of the physical CS interior cell (panel, i, j) (area area, m²): a retrieved column (satellite or TCCON sounding) compared with the model through the retrieval's own layers, pressure weights, averaging kernel and prior (retrieval, an Observations.RetrievalColumn). At every sampled state the model's interface pressures of pressure_basis (total pressures from the dry air mass and the specific humidity, TotalFromHumidity, or the dry interfaces, DryInterfaces) are stretched onto the retrieval column and the dry mixing ratios xk=rk/max(mk,ε) are mapped onto its layers or levels by the projection P of the retrieval's mapping (the rebin R of TM5-4DVar for a layer column, the hat projection for a level column; Observations.retrieval_column_weights!):

X=∑kHkxk+∑ihi(1−ai)xa,i,Hk=∑ihiaiPik.

max_surface_pressure_mismatch_pa bounds the time-weighted difference between the model and the retrieval surface pressure; a record above it is an error under mismatch_policy = ErrorOnUnplaced() and is left out of the cost (reported, not assimilated) under SkipUnplaced(). Sampling it needs the column meteorology (cs_surface_flux_4dvar(...; column_met)); built by bind_to_mesh from a column record with a retrieval block.

source
AtmosTransport.Adjoints.CSSeedObjective Type
julia
CSSeedObjective()

Marker objective used when the caller supplies an explicit final adjoint seed (dJ/drm_final) instead of one of the built-in scalar objectives.

source
AtmosTransport.Adjoints.TracerDependence Type
julia
TracerDependence()

The reverse also reads state that depends on the tracer: the limiter branches of a monotone or CW84 PPM sweep, the tracer masses of Lin–Rood's operators. Every forward run records its own tape (StateTape).

source
AtmosTransport.Adjoints.adjoint_support Method
julia
adjoint_support(x) -> Union{Nothing, String}

nothing if the cubed-sphere adjoint records and transposes x (a step-plan stage, an advection scheme or a diffusion, surface-flux, convection or chemistry operator), otherwise the reason it does not. See require_adjoint_support.

source
AtmosTransport.Adjoints.require_adjoint_support Method
julia
require_adjoint_support(plan::StepPlan, ops::StepOperators...) -> plan

Check that the cubed-sphere adjoint records and transposes every stage of plan and every operator those stages apply (one ops per distinct operator set, e.g. per step when the diffusion operator changes). Throws an ArgumentError naming every unsupported piece. Every adjoint entry point calls it before recording; DrivenSimulation and TransportModel setups can call it directly (require_adjoint_support(sim)).

source
AtmosTransport.Adjoints.require_adjoint_support Method
julia
require_adjoint_support(scheme) -> scheme

Return the advection scheme if the cubed-sphere reverse pass has an adjoint for it, otherwise throw an ArgumentError that names the missing piece and lists the supported choices. Dispatches on the union of supported schemes that the footprint and 4D-Var entry points also accept, so a configuration is rejected with an explanation before any tape is recorded.

Supported: UpwindScheme(), SlopesScheme(NoLimiter()), PPMScheme with NoLimiter, MonotoneLimiter or CW84Limiter and the default vertical reconstruction, and LinRoodPPMScheme (ORD 5 or 7) with any of its vertical sweeps: upwind or the FV3 kord = 8 profile (vertical = "fv3_kord8" or "fv3_kord8_signed"). Unsupported: limited SlopesScheme, the split-sweep PPMScheme with the FV3 vertical profile, NoAdvection, and every other scheme or limiter.

source
AtmosTransport.Adjoints.tape_dependence Method
julia
tape_dependence(scheme) -> AbstractTapeDependence

AirMassDependence() for the schemes whose sweep is linear in the tracer mass (UpwindScheme(), SlopesScheme(NoLimiter()), PPMScheme(NoLimiter())): their reverse, and that of every other operator with an adjoint (convection, diffusion, surface fluxes, air-mass resets), reads only the air mass, the met forcing and the clock. TracerDependence() for limited PPM and Lin–Rood, whose reverse replays limiter branches of the tracer. An AirMassTape needs AirMassDependence.

source
AtmosTransport.Adjoints.Footprint.AbstractCSWindowSource Type
julia
AbstractCSWindowSource

The met windows a cubed-sphere adjoint replay reads (met_source of the adjoint entry points). A source implements window_count, window_steps, window_layout, acquire_window! and release_window!; prefetch_window!, close and streaming have defaults (no-op, no-op, false). The entry points build a ResidentCSWindowSource from their per-step arguments when no source is given.

source
AtmosTransport.Adjoints.Footprint.CSFootprintResult Type
julia
CSFootprintResult

Reverse-mode result for one scalar objective. footprints[t] is an NTuple{6} of (Nc, Nc) arrays containing dJ / dE, where E is the per-cell model-storage emission rate the surface-flux operator applies at the palindrome center of model step t. Storage is dry mixing ratio × carrier-air mass; these rates are not physical kg-species per second and are not divided by cell area. The derivative includes the timestep factor. lag_steps[t] == nsteps - t. A step plan without a surface-flux operator (surface_flux = false) has no emission entry point and an empty footprints.

initial_adjoint is dJ/drm at the initial state: an NTuple{6} of halo-padded panels like the initial tracer mass (the halo cells are zero: halos are a function of the interiors).

source
AtmosTransport.Adjoints.Footprint.CSStepSchedule Type
julia
CSStepSchedule(; physics_cadence = nothing, binary_window_contract = false,
               air_mass_reset = :none, steps_per_window = 1, window_dt,
               start_time = 0, window_start_air_mass = nothing,
               window_end_air_mass = nothing)
CSStepSchedule(plan::StepPlan; steps_per_window = 1, window_dt, start_time = 0,
               binary_substeps = false, chemistry = NoChemistry(),
               window_start_air_mass = nothing,
               window_end_air_mass = nothing)

The production step a cubed-sphere adjoint differentiates: the step plan and the met windows it runs on. The keyword form builds the plan as DrivenSimulation does (StepPlan(; physics_cadence, window_contract = binary_window_contract, air_mass_reset)); DrivenSimulation's own schedule is CSStepSchedule(sim). That constructor validates the simulation's operators and retains its chemistry operator; replay never replaces it with a no-op. Unsupported chemistry is rejected by the adjoint setup guard.

  • steps_per_window — advection steps per met window: an integer (every window) or one entry per window (the run may not go beyond them). Step s of window w advances window_dt / steps_per_window[w], computed as DrivenSimulation computes Δt.

  • start_time — the run clock [s] at the first step, as DrivenSimulation's start_time; the replay's current_time follows production's clock.

  • binary_window_contract / binary_substeps — the transport binary's per-window contract: one palindrome subcycle per step (the binary's schedule), and with physics_cadence = :window (the default) convection and chemistry once per met window over window_dt.

  • air_mass_reset — :none, :preserve_tracer_mass or :preserve_vmr: the air mass is reset to window_start_air_mass[w] on entering window w > 1 and, with the window contract, to window_end_air_mass[w] before the window-end physics (vectors of NTuple{6} halo-padded panels, one per window; a reset refreshes the halos of its target in place, as production does). Pass nothing when a met source (met_source) carries the targets with its windows; the replay checks that the plan's targets exist when it is built.

The default (CSStepSchedule(window_dt = dt)) is one step per window and the full operator suite at every step, TransportModel.step!'s composition.

source
AtmosTransport.Adjoints.Footprint.CSTapeByteEstimate Type
julia
CSTapeByteEstimate

Counts and byte estimate for the CS adjoint tape. Each *_records field is an op count — the number of records of that type the forward pass will push onto the tape — except state_records which is a payload-staging count: the six-panel tuples staged (air masses, the limiter codes of monotone and CW84 PPM sweeps, the tracer masses of FV3 vertical sweeps), each once however many records read it.

state_bytes is the raw panel-data cost of the tape: bytes_per_state (one air-mass state) per staged air or tracer mass and bytes_per_state / sizeof(FT) per staged limiter-code tuple; Lin-Rood additionally retains face-shaped tuples whose exact byte cost is included in state_bytes. Halo, midpoint and end-of-step records and the diffusion records contribute scalar metadata only and are not counted in state_bytes. On a split-sweep tape the palindrome center's diffusion records and the reverse half's first Z sweep share one staged air mass, and a convection record shares the next step's first sweep's (or a :preserve_vmr reset's), staging its own only before a :preserve_tracer_mass reset or at the end of the run. step_records counts the end-of-step markers (one per step, after convection), where the reverse pass injects observation forcing.

total_records is the op count: sweep + halo + midpoint + diffusion + convection + reset + step; it is not in general related to state_records, since records share staged tuples and a limited PPM sweep stages two.

source
AtmosTransport.Adjoints.Footprint.HostCSWindowSource Type
julia
HostCSWindowSource(windows; device_like, device_slots = 2, host_budget_bytes = nothing)

A streamed window source: every met window of a run in host memory (windows, one CSWindowMet of host arrays per window 1:W, their steps consecutive from step 1), and device_slots windows on the backend of device_like (the replay's: the initial air mass). acquire_window!(source, w) returns the slot holding window w, or refills the least recently used slot without a lease from the host copy (one copy per array, in place; generation counts the fills); release_window! synchronizes the backend when a slot's last lease ends, so a refill never overwrites data a queued kernel still reads. Results are bitwise those of the resident windows: the slots hold copies of the same arrays, and the replay reads them through the same operators.

cs_adjoint_inputs(sim; residency = :host) builds it. Every window must have the layout of the first: the types of its pieces and the shapes of their arrays (its flux states, one per window or one per step, those of the first window's); a slot holds as many flux states as the window with the most. The diffusion operator of every window is validated as the entry points validate a per-step one. With host_budget_bytes, the host bytes of the windows (each array once) must fit it. The source is reusable across calls (each 4D-Var evaluation of an optimization); close(source) frees its slots. Arrays an operator holds outside its Adapt traversal (the host staging copy of a window Kz cache's panels) stay with each window's host copy, are not copied into the slots (the replay does not read them) and are not counted in host_bytes (the host bytes of the windows' arrays, each counted once).

source
AtmosTransport.Adjoints.Footprint.StaleWindowSlotError Type
julia
StaleWindowSlotError

The device slot of a window lease was refilled with another window (or freed by close) after the lease was acquired: whatever still reads the lease's met would read another window. require_current throws it.

source
AtmosTransport.Adjoints.Footprint.cs_surface_emission_footprint Method
julia
cs_surface_emission_footprint(..., objective; kwargs...) -> CSFootprintResult

Generate reverse-mode footprints for a scalar final-time objective with respect to surface-emission rates at each prior model step.

The tape is recorded from the production step plan of schedule (a CSStepSchedule; default: one step of dt per met window, the full operator suite every step), with a surface-flux operator in the plan (zero rates unless base_emission_rates is given), and walked backwards with each operator's adjoint. require_adjoint_support rejects a plan with an operator the tape cannot transpose before anything is recorded.

Supported CS schemes are the split-sweep UpwindScheme(), SlopesScheme(NoLimiter()), PPMScheme(NoLimiter()) and monotone PPMScheme(), and LinRoodPPMScheme (ORD 5 or 7) with upwind or FV3 kord = 8 vertical transport. The limited PPM paths, including the FV3 vertical sweeps, store tracer branch states from the base trajectory; pass base_emission_rates when differentiating around nonzero surface emissions. Optional ImplicitVerticalDiffusion support transposes the Backward-Euler column solve in kernels on CPU/GPU and uses the runtime's surface-flux coupling at the palindrome center (V(dt/2) -> emissions -> V(dt/2), or emissions -> V(dt) with DiffusiveSurfaceFluxBoundary). Optional CMFMCConvection support transposes the well-mixed sub-cloud, updraft, and tendency passes; optional TM5Convection and CMFMCMatrixConvection support replays the same column matrix and applies the transposed LU solve, at the plan's physics cadence (every step, or once per met window over the window).

The replay uses the caller's convection workspace with the persistent state of a fresh run (its ledger carry and CFL cache are reset when a replay starts); do not pass a live production model's convection workspace. The diffusion layer thickness (diffusion_layer_thickness, as for run_cs_footprint_forward) is only read; the replay owns the diffusion workspace and the reverse solves' scratch. cs_adjoint_inputs(sim) captures every input of a DrivenSimulation configuration, with a fresh convection workspace.

tape defaults to AutoTape, which resolves and reserves a concrete AdjointTape from the schedule, memory budgets and supplied constraints before recording. An explicit AdjointTape fixes the content, storage and checkpoint schedule and is reserved without replacement. TapeReservationError means no reservation fits; TapeReservationExceeded means recording outgrew the reservation. Stride may retain a resident_tail recorded by the forward run and use pinned host snapshots for the head. The call reuses its pools and frees them when it returns. The Lin–Rood tape is device-only; its horizontal records remain outside the pools and are sized by counting.

met_source replaces the per-step met arguments, as for run_cs_footprint_forward. A streamed source (HostCSWindowSource) keeps a few met windows on the device, so the tape must record one window at a time: AdjointTape(; checkpoint = MetWindowCheckpoint(...)) or AutoTape(; checkpoint = MetWindowCheckpoint(...)); Full, Stride, AirMassTape and an unconstrained AutoTape() are an ArgumentError before anything runs. Lin–Rood tapes are then sized from window 1 and the longest later window instead of a counting run over every step.

source
AtmosTransport.Adjoints.Footprint.cs_surface_emission_footprint_from_seed Method
julia
cs_surface_emission_footprint_from_seed(final_adjoint_rm, panels_m0,
                                        panels_am_steps, panels_bm_steps,
                                        panels_cm_steps, mesh; kwargs...)

General reverse-pass entry point. final_adjoint_rm is an NTuple{6} of halo-padded adjoint tracer-mass arrays containing dJ/drm_final for any scalar objective or observation operator; only its interior is read (the halos of the final state are not prognostic, so halo entries are ignored). The reverse pass and surface-gradient accumulation use the same CPU/GPU kernels as cs_surface_emission_footprint.

With surface_flux = true (the default) the step plan carries a surface-flux operator and the result holds the emission footprints. surface_flux = false replays a configuration without surface sources (palindrome center V(dt)): the result's footprints are empty and initial_adjoint is the initial-condition sensitivity dJ/drm_0, which every result also carries. tape defaults to AutoTape and met_source replaces the per-step met, as for cs_surface_emission_footprint.

source
AtmosTransport.Adjoints.Footprint.cs_tape_byte_estimate Method
julia
cs_tape_byte_estimate(panels_m0, panels_am_steps, panels_bm_steps,
                      panels_cm_steps, mesh, scheme;
                      cfl_limit = DEFAULT_CFL_LIMIT,
                      flux_scale = one(eltype(panels_m0[1])),
                      diffusion_op = NoDiffusion(),
                      convection_op = NoConvection(),
                      schedule = nothing, surface_flux = true, dt = nothing)
    -> CSTapeByteEstimate

Size the tape that cs_surface_emission_footprint records for the given problem (StateTape and AirMassTape stage the same records): per-record-class counts and the total state_bytes, the raw panel-data cost of the tape, independent of storage. The transport records (sweeps, halos, Lin-Rood horizontal records, palindrome centers and air-mass resets) are counted by replaying the transport with the counting recorder, which runs the tape recorder's own hooks; convection and diffusion do not change the air mass, so their records, and the air masses they stage, are counted from the step plan.

What a split-sweep tape stages per step (one palindrome pass, S the bytes of one air-mass state): 6S for the six sweeps' air masses (the palindrome center's diffusion records share the reverse half's first vertical sweep's, and a convection record the next step's first sweep's or a :preserve_vmr reset's), plus 6S / sizeof(FT) of limiter codes for a monotone or CW84 PPM sweep; 2S per :preserve_vmr reset, and S for a convection record that has no later air mass to share (the last one of the run, one before a :preserve_tracer_mass reset).

The same state_bytes figure applies to every storage of an AdjointTape, because none of them compresses the payload:

  • DeviceCSTapeStorage() — state_bytes is the device-resident cost; the reverse loop holds the full tape on the backend.

  • PinnedHostCSTapeStorage() — state_bytes is the pinned host cost (allocated in chunks of up to 1 GiB, each slot padded to 64 bytes); at most two staged panel sets (one per read role: the air mass, and the limiter codes or tracer mass) are mirrored on the device at a time.

  • MmapCSTapeStorage(dir) — state_bytes is the size of the scratch file with FullCheckpoint (StrideCheckpoint reserves its largest window), which needs 10 % more free space in dir; it is reserved before recording. The read caches hold one NTuple{6, T} per read role and distinct shape signature on top of that.

state_records counts the staged six-panel tuples (air masses, limiter codes, tracer masses), bytes_per_state is the size of one air-mass state. Lin-Rood's state_bytes also includes the face-panel tuples of its horizontal records, whose dimensions differ from a full state. Halo, midpoint, reset and end-of-step records carry only scalar metadata and are counted in total_records but NOT in state_bytes.

A convection_op that tape recording refuses (see _require_supported_cs_convection_variant) is refused here too.

source
AtmosTransport.Adjoints.Footprint.run_cs_footprint_forward Method
julia
run_cs_footprint_forward(..., objective; kwargs...) -> scalar

Run the cubed-sphere production step plan forward and return objective at the final time. Optional emission_rates[t][panel][i, j] entries are surface emission rates in model-storage units per second (dry mixing ratio × carrier air mass per second, integrated over the cell) that the surface-flux operator applies at the palindrome center of step t. Convert physical species-mass inventories and per-area rates before calling this low-level API.

Each step is the production step of schedule (a CSStepSchedule; default: one step of dt per met window and the full operator suite every step, as TransportModel.step!): the transport block — step-start halo refresh, palindrome and its center — and, at the plan's cadence, the convection column operator (CMFMCConvection(), TM5Convection() or CMFMCMatrixConvection) and the air-mass resets. With surface_flux = true (the default) the plan carries a surface-flux operator (zero rates when emission_rates = nothing) and the palindrome center follows the diffusion operator's surface_flux_coupling: V(dt/2) -> emissions -> V(dt/2) (SplitSurfaceFluxCoupling) or emissions -> V(dt) (DiffusiveSurfaceFluxBoundary); surface_flux = false replays a configuration without surface sources, whose center is one solve V(dt). Kz diffusion requires diffusion_layer_thickness: six (Nc, Nc, Nz) panels of layer thickness [m], one tuple for every step or one per step (a met window's steps may share one tuple); Dkg fields and TM5 Calc_Kzz read none (nothing). The replay owns its diffusion workspace and copies the step's layer thickness into it; it never writes the caller's panels. flux_scale multiplies all transport fluxes and is shared with the tape/reverse APIs so forward finite differences exercise the same model trajectory.

met_source (an AbstractCSWindowSource, e.g. the HostCSWindowSource of cs_adjoint_inputs(sim; residency = :host)) supplies the met per window instead: pass nothing for the three per-step flux vectors and omit diffusion_op, diffusion_layer_thickness, convection_forcing and flux_scale (an ArgumentError otherwise); the schedule then carries no reset targets (the source's windows do).

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.CELL_AVERAGE_PLACEMENT_CODE Constant

Stencil placement code of a cell average of column records (CSCellAverageObjective, CellAverage): every level of the cell, the inverse-variance-weighted mean of its members' operators.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.COLUMN_MEAN_PLACEMENT_CODE Constant

Stencil placement code of an observation whose objective is a column mean (CSColumnMeanObjective): every level of the column, no vertical placement. The point objectives use the Observations.VERTICAL_PLACEMENT_CODES.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.FIXED_LEVEL_PLACEMENT_CODE Constant

Stencil placement code of an observation whose objective has a fixed stencil instead of being placed: a CSLayerMeanObjective naming its level, or another fixed operator.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.RETRIEVAL_COLUMN_PLACEMENT_CODE Constant

Stencil placement code of an observation whose objective is an averaging-kernel column (CSRetrievalColumnObjective): every level of the column, weighted by the retrieval's pressure weights and averaging kernel on the model column stretched onto the retrieval column.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.AbstractCellAveraging Type
julia
AbstractCellAveraging

Whether bind_to_mesh averages column records that fall in one model cell: NoCellAveraging (the default) or CellAverage. The alternative that keeps every record and inflates its model error instead is inflate_cell_model_error.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.AbstractFlaggedRecordPolicy Type
julia
AbstractFlaggedRecordPolicy

What bind_to_mesh does with records whose flag is not 0 (not to be assimilated): DropFlaggedRecords ("drop", the default) or CosampleFlaggedRecords ("cosample").

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.AbstractObservationKind Type
julia
AbstractObservationKind

What an observation record measures, the kind column of the observation file: PointObservationKind ("point") or ColumnObservationKind ("column"). bind_to_mesh turns a point record into a CSPlacedPointObjective and a column record into a CSColumnMeanObjective.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.AbstractOutOfRangePolicy Type
julia
AbstractOutOfRangePolicy

Policy applied when an observation maps outside the valid model-step range. Use RejectOutOfRange, SkipOutOfRange, or ClampOutOfRange.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.CSDepartureRecord Type
julia
CSDepartureRecord(; id, tracer, instrument_type, date_components, lat, lon,
                    kind, time_window_s, clamped, panel, i, j,
                    vertical_placement, placement_height_agl_m, placement_pressure_pa,
                    steps, weights, levels,
                    observed_value, simulated_value, departure,
                    value_sigma, model_sigma, normalized_departure,
                    surface_pressure_mismatch_pa = NaN, retrieval_profile = Float64[],
                    profile_model_sigma = 0, assimilated = true, flag = 0, cell_average_id = 0,
                    cell_average_correlation = NaN)

One audit row of the CS departure file (schema v2): the observation record's provenance (id, tracer, instrument_type, date_components, Float64 lat/lon, kind, time_window_s; clamped when its time lies outside the run and ClampOutOfRange kept it), where it was sampled (the cell panel, i, j; the vertical_placement code — Observations.VERTICAL_PLACEMENT_CODES for point records, COLUMN_MEAN_PLACEMENT_CODE for column records — with the height above the model surface or the pressure that placed it, NaN when unused; the sampled steps, their time-sampling weights and the levels read at each, k = 1 at the top and 0 for a column mean), and the forward-pass values. An averaging-kernel column row (RETRIEVAL_COLUMN_PLACEMENT_CODE) also carries the model minus retrieval surface pressure surface_pressure_mismatch_pa (Pa), the model profile on the retrieval layers or levels retrieval_profile (surface first, mol/mol) and its profile model error profile_model_sigma (∑i(hiaiσi)2, 0 without a profile uncertainty); other rows have NaN, an empty profile and 0.

assimilated says whether the row itself is a term of the cost. It is false for a co-sampled record (its flag, the record's, is not 0: flagged_records = "cosample"), for a record averaged into a cell average (cell_average_id, the number of the average, 1, 2, … in observation order, is not 0; the average is in the cost, the record is reported on its own), and for an averaging-kernel column the surface-pressure screen left out; a row with a nonzero flag or a cell average is never assimilated.

A cell average itself (CELL_AVERAGE_PLACEMENT_CODE) is a row too, the term of the cost: its cell_average_id (shared with its member rows), an id above every record id of the observation set (the largest record id, at least 0, plus cell_average_id), the observed and simulated averages, value_sigma the measurement error of the average σmeas (with the correlation ρ between its records, cell_average_correlation; NaN on other rows), model_sigma its model error, assimilated, flag 0; tracer, instrument, date, coordinates and window are those of its earliest record. Over the assimilated rows, ∑normalized_departure2=2Jobs. The constructor rejects non-finite values and checks the sign convention departure = simulated_value − observed_value and normalized_departure = departure / σ, σ=value_sigma2+model_sigma2+profile_model_sigma2.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.CSDepartureSet Type
julia
CSDepartureSet(records; mesh_Nc, mesh_panel_convention, mesh_cs_definition_tag,
               t_start, dt_seconds, nsteps, run_id = nothing, iteration = nothing)

Collection of CSDepartureRecord rows together with the run-level metadata that lets a downstream consumer reconstruct the forward run that produced the file. mesh_panel_convention and mesh_cs_definition_tag pin the cubed-sphere geometry; t_start, dt_seconds, and nsteps pin the time grid. Optional run_id and iteration are caller-supplied attribution tags.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.CSObservation Type
julia
CSObservation(step, objective, value, sigma; id = 0, assimilate = true)
CSObservation(sampling::CSTimeSampling, objective, value, sigma; id = 0, assimilate = true)

Scalar observation of the CS 4D-Var surface-flux path: objective sampled as sampling says (one step, or a weighted window of steps; see CSTimeSampling), with observed value and error standard deviation sigma. step is the last sampled step, after which the observation is complete (the only one for an instantaneous observation). id is the identifier of the observation record it was bound from (bind_to_mesh), 0 for an observation built by hand.

assimilate = false makes it a co-sample: cs_surface_flux_4dvar simulates it on the forward replay and reports its simulated value, residual and stencil (with assimilated = false), but it adds nothing to the cost or the gradient, and does not extend the taped run. bind_to_mesh co-samples records with a nonzero flag under flagged_records = "cosample", and the members of cell averages (CellAverage).

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.CSObservationColumnMet Type
julia
CSObservationColumnMet(; p_top, gravity = STANDARD_GRAVITY,
                         temperature = 280.0, humidity = nothing, mass_basis = DryBasis())

The column meteorology with which CSPlacedPointObjective observations choose their model layer at each sampled state (cs_surface_flux_4dvar(...; column_met)). With the air mass mk (kg per cell, k = 1 at the top) of the sampled state and the cell area A:

  • interface pressures p1/2=ptop, pk+1/2=pk−1/2+gmk/A, from p_top (Pa, the model-top interface, the pure-pressure A_ifc[1] of the met model's hybrid coordinate) and gravity (m s⁻²);

  • hypsometric interface heights above the model surface, zk−1/2=zk+1/2+(RdTv,k/g)ln⁡(pk+1/2/pk−1/2), with the layer temperature Tk: a number (K, every layer; the forward sampler's layer_height_temperature_kelvin, 280 K by default), an Observations.AbstractLayerTemperature, per-layer panels (an NTuple{6} of arrays laid out like the air mass, with or without the halo, K, for every step), or a vector of such panels with one entry per model step (the state after that step). With the pressure basis TotalFromHumidity (the default) on a dry basis the pressures are the total ones below and Tv,k=Tk(1+0.61qk) the virtual temperature; with DryInterfaces the dry interfaces above and Tv,k=Tk;

  • for TotalFromHumidity on a dry basis (the heights of every placed point observation, pressure placement, averaging-kernel columns), the total interface pressures pk+1/2=pk−1/2+gmk/(A(1−qk)) with the specific humidity qk (kg kg⁻¹ of moist air; nothing, static panels, or one set of panels per step, as temperature).

mass_basis is the basis of the air mass (DryBasis(), the default of transport binaries, or MoistBasis()).

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.CSObservationRecord Type
julia
CSObservationRecord(id, date_components, lat, lon, kind,
                    elevation_m, intake_height_m, altitude_m, pressure_pa,
                    time_window_s, flag, value, value_sigma, model_sigma,
                    instrument_type, tracer, retrieval)
CSObservationRecord(; id, date_components, lat, lon, value, value_sigma,
                      instrument_type, tracer, kind = PointObservationKind(),
                      elevation_m = NaN, intake_height_m = NaN, altitude_m = NaN,
                      pressure_pa = NaN, time_window_s = 0, flag = 0, model_sigma = 0,
                      retrieval = nothing)

One observation row of the schema-v2 CSObservationSet.

  • date_components: (year, month, day, hour, minute, second) UTC, Int16, the centre of the sampling window.

  • lat, lon: degrees, Float64 (a point within Float32 rounding of a cell edge must bind to the cell that contains it).

  • kind: PointObservationKind or ColumnObservationKind (the keyword form also takes "point" / "column").

  • Vertical fields, NaN when the record does not give them: elevation_m (ground, m above sea level), intake_height_m (m above the ground), altitude_m (m above sea level), pressure_pa (total pressure, Pa, positive). Column records give none of intake_height_m, altitude_m, pressure_pa.

  • time_window_s: length (s, ≥ 0) of the sampling window centred on the record time; 0 samples the model state of one step.

  • flag: quality flag, 0 = assimilate; bind_to_mesh drops the others.

  • value, value_sigma: observation and its 1-σ error, in the tracer's native unit (dry mole fraction for trace gases); model_sigma (≥ 0) is a model/representation error added in quadrature (σ² = value_sigma² + model_sigma²).

  • instrument_type (e.g. "ICOS", "TCCON"), tracer (e.g. "CO2").

  • retrieval: the retrieval block of an averaging-kernel column record (an Observations.RetrievalColumn: pressures from the surface up, pressure weights, column averaging kernel, prior profile in mol/mol, optional model-profile uncertainty, and its mapping: layer means between interfaces, Observations.LayerRebin, or values on levels, Observations.HatLevelProjection), or nothing. Only column records carry one; such a record is an absolute column average, value in (0, 1] mol/mol with value_sigma and model_sigma not above it. Its model-error term ∑i(hiaiσi)2 (Observations.retrieval_model_error_variance, zero without a model-profile uncertainty) is added to σ².

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.CSObservationSet Type
julia
CSObservationSet(records, time_origin)

Collection of CSObservationRecord rows, with unique ids, that share an absolute time_origin string (an ISO-8601 timestamp, e.g. "1900-01-01 00:00:00"). The on-disk format always carries the origin even though the per-record dates are stored as absolute components — the origin tags the convention so a downstream consumer that wants to convert to seconds-since-origin can do so without parsing the per- record dates.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.CSObservationStencil Type
julia
CSObservationStencil(panel, i, j, steps, weights, levels, placement_method,
                     height_agl_m, pressure_pa,
                     surface_pressure_mismatch_pa, retrieval_profile, assimilated)

Where an observation was sampled in a 4D-Var evaluation, returned per observation in CS4DVarResult.stencils: the cell (panel, i, j), the sampled steps and their weights (its CSTimeSampling), the model level sampled at each step (levels, k = 1 at the top, resolved from the replayed column at the end of that step; 0 for an operator that reads more than one level, as a column mean), the placement_method (Observations.VERTICAL_PLACEMENT_CODES for a CSPlacedPointObjective, COLUMN_MEAN_PLACEMENT_CODE, RETRIEVAL_COLUMN_PLACEMENT_CODE, CELL_AVERAGE_PLACEMENT_CODE or FIXED_LEVEL_PLACEMENT_CODE otherwise), and the height above the model surface (m) or the pressure (Pa) that placed it (NaN when not used). An operator without a single cell has the cell (0, 0, 0).

For an averaging-kernel column (CSRetrievalColumnObjective): surface_pressure_mismatch_pa, the model minus the retrieval surface pressure (Pa; time-weighted over the sampled steps; NaN for other operators); retrieval_profile, the model's dry mixing ratios on the retrieval layers or levels (surface first, the projected profile Px, time-weighted; empty for other operators).

assimilated is false for a co-sample (an observation built with assimilate = false: a flagged record under flagged_records = "cosample", or a member of a cell average) and for an averaging-kernel column whose surface-pressure mismatch exceeded max_surface_pressure_mismatch_pa under SkipUnplaced(): the observation's simulated value is reported, but it is not in the cost.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.CSTimeSampling Type
julia
CSTimeSampling(steps, weights)
CSTimeSampling(step)

The model states an observation samples: the states after steps (strictly increasing, after convection: the state runtime output sees), averaged with weights (positive, summing to 1). The simulated value is H=∑swsh(rs), with h the objective evaluated on the state after step s. CSTimeSampling(step) samples one state (weight 1).

bind_to_mesh builds an instantaneous sampling for a record without a time window (the step whose interval contains the record time) and, for a record with time_window_s > 0, the steps whose intervals overlap the window with weights proportional to the overlap (TM5-4DVAR's Δt/ΣΔt window mean).

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.CellAverage Type
julia
CellAverage(; time_tolerance_s = 60.0, correlation = 0.0)

Average the assimilated column records (flag 0) of one tracer that fall in the same model cell, sample the same model steps with the same weights, and lie within time_tolerance_s of the earliest record of their group (records of one overpass: an OCO-2 orbit crosses a C90 cell in about 15 s, and the next orbit passes 99 minutes later). A group of n≥2 records yi with measurement errors σi (value_sigma) becomes one observation with weights wi=1/σi2:

y¯=∑iwiyi∑iwi,H¯=∑iwiHi∑iwi,σmeas2=∑i∑jwiwjρijσiσj(∑iwi)2,σ¯2=σmeas2+∑iwiσmod,i2∑iwi,

with ρii=1 and ρij= correlation between distinct records (0 by default: separate 10-s spans; their within-span correlation is already in σi), and σmod,i2 the record's model error (model_sigma² plus the profile term of an averaging-kernel column), added once, not reduced by the averaging. H¯ is a CSCellAverageObjective; the operators are linear, so its gradient is the w-weighted combination of the members'. The members stay bound as co-samples (assimilate = false), so every record keeps its own simulated value. Needs max_surface_pressure_mismatch_pa = Inf (the screen applies to records, not averages).

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.ClampOutOfRange Type

Keep observations outside the valid model-step range: a record whose time window reaches into the run samples the part inside it (truncated and renormalised), any other record the nearest step (first or last).

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.ColumnObservationKind Type

kind = "column": a column-averaged dry mole fraction (TCCON, a satellite sounding). A column record with a retrieval block (its layers, pressure weights, averaging kernel and prior, an Observations.RetrievalColumn) is bound to an averaging-kernel column (CSRetrievalColumnObjective); one without it to the air-mass-weighted column mean of its cell (CSColumnMeanObjective). A column record states no intake height, altitude or pressure.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.CosampleFlaggedRecords Type

flagged_records = "cosample": records with a nonzero flag are bound as co-samples (CSObservation(...; assimilate = false)): simulated on the forward replay and reported with their flag, never in the cost or the gradient. The OCO-2 MIP needs co-samples of every record, the withheld and evaluation-only ones included.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.DropFlaggedRecords Type

flagged_records = "drop" (default): records with a nonzero flag are not bound.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.NoCellAveraging Type

cell_averaging = NoCellAveraging() (default): every record is its own observation.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.PointObservationKind Type

kind = "point": an in-situ sample at one place in the column (surface station, tower, flask, aircraft, AirCore). Placed in the model column by its height above the ground or its pressure (intake_height_m, altitude_m with elevation_m or a DEM, pressure_pa); a point record that gives none of the vertical coordinates in use cannot be placed (unplaced_records).

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.RejectOutOfRange Type

Reject the first observation outside the valid model-step range.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.SkipOutOfRange Type

Drop observations outside the valid model-step range.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.bind_to_mesh Method
julia
bind_to_mesh(set::CSObservationSet, mesh::CubedSphereMesh, t_start::Dates.DateTime, dt::Real;
             nsteps = nothing, tracer_filter = nothing, out_of_range_policy = RejectOutOfRange(),
             placement = VerticalPlacementSpec(), terrain = ObservationTerrain(),
             max_surface_pressure_mismatch_pa = Inf, flagged_records = DropFlaggedRecords(),
             cell_averaging = NoCellAveraging())
    -> Vector{CSObservation}

Bind each record of set to a CSObservation of the CS 4D-Var path: its time sampling, the cell that contains it, and its objective.

  • Time. t_start is the model start (UTC) and dt the step length (s): step k covers [t_start + (k−1)dt, t_start + k dt) and is represented by the state at its end, after convection. A record with time_window_s = 0 samples the step whose interval contains its time. A record with time_window_s = W > 0 samples the window [t − W/2, t + W/2] around its time t: every step whose interval overlaps the window, with weight Δtk/∑Δt where Δtk is the overlap of step k's interval with the window (a step only partly inside counts its overlap; steps fully inside count dt, TM5-4DVAR's Δt/ΣΔt mean). The window is truncated at the run's ends (0 and nsteps·dt) and the weights are renormalised over the part inside the run. See CSTimeSampling.

  • Out of range. A record whose time falls outside 1:nsteps (only step >= 1 is enforced when nsteps === nothing) is handled by out_of_range_policy: RejectOutOfRange (default, "reject") throws, SkipOutOfRange ("skip") drops it, ClampOutOfRange ("clamp") samples the part of its window inside the run (truncated and renormalised) when the window reaches into the run, else step 1 or nsteps. Skipped and clamped records are counted in an @info. Records with a time window need nsteps.

  • Ids. Record ids must be unique (departures are joined to records by id).

  • Cell. (lat, lon) (Float64) → the cell containing the point (Observations.locate, the forward observation sampler's locator).

  • Point records (PointObservationKind) become CSPlacedPointObjectives, placed by the forward sampler's rule (Observations.resolve_placement) with placement (an Observations.VerticalPlacementSpec: the ordered vertical_coordinates, height above ground and/or pressure; the pressure basis; the altitude option; the unplaced policy) and the static ground fields of terrain (an Observations.ObservationTerrain: model surface height, point DEM). A point record that gives none of the coordinates in use is unplaced: an ArgumentError with unplaced_records = "error" (default), dropped and counted with SkipUnplaced().

  • Column records (ColumnObservationKind) with a retrieval block become CSRetrievalColumnObjectives: the averaging-kernel column on the interface pressures of placement.pressure_basis (total pressures from the humidity by default), with the surface-pressure limit max_surface_pressure_mismatch_pa (Pa, positive; Inf, the default, lets the stretch absorb any mismatch, as TM5) and the unplaced policy of placement as its mismatch policy: a record whose model surface pressure differs from the retrieval's by more than the limit is an error under unplaced_records = "error", and is left out of the cost (and counted) under "skip". The model surface pressure is known only at the sampled states, so the check runs in the 4D-Var's forward replay; it is the surface pressure of the pressure basis, so with DryInterfaces the mismatch also contains the weight of the water vapour (about 0.5 % of the surface pressure, more in the tropics). Column records without a block become CSColumnMeanObjectives.

  • Records with a nonzero flag are not assimilated: dropped with flagged_records = DropFlaggedRecords() ("drop", the default), bound as co-samples (CSObservation(...; assimilate = false): simulated and reported, never in the cost or the gradient) with CosampleFlaggedRecords ("cosample"). Records of another tracer are dropped when tracer_filter names one.

  • Cell averaging. With cell_averaging = CellAverage(...), assimilated column records of one cell, step sampling and overpass become one inverse-variance-weighted observation (CellAverage, CSCellAverageObjective), appended after the records, whose own observations become co-samples.

  • The observation sigma is σvalue2+σmodel2+σprof2 (exactly value_sigma without a model error), where σprof2=∑i(hiaiσi)2 is the model-error term of an averaging-kernel column with a profile uncertainty σi (Observations.retrieval_model_error_variance; fixed by the record, so the cost stays quadratic); the observation carries the record id.

set.time_origin is documentation only.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.build_departure_set Method
julia
build_departure_set(set::CSObservationSet, result::CS4DVarResult, mesh, t_start, dt, nsteps;
                    run_id = nothing, iteration = nothing) -> CSDepartureSet
build_departure_set(set, observations, simulated, stencils, mesh, t_start, dt, nsteps; ...)

Build a CSDepartureSet from a 4D-Var evaluation: its observations (bound from set by bind_to_mesh), simulated values and stencils (CSObservationStencil), joined to the records of set by record id, one row per observation in observation order. Co-sampled records (flagged_records = "cosample") are rows with their flag and assimilated = false. A cell average (CSCellAverageObjective) is a row (placement code CELL_AVERAGE_PLACEMENT_CODE, its measurement and model sigma and correlation, cell_average_id its number 1, 2, … and a row id above every record id of set), and so are its records, as co-samples with the average's cell_average_id; a hand-built average is checked against its records as bind_to_mesh builds it.

Validation (ArgumentError on any violation):

  • equal lengths; unique record ids in set; every observation's id names a record of set (hand-built observations have id 0 and no record);

  • every simulated value is finite;

  • each observation matches its record as bind_to_mesh binds it: the kind (point → CSPlacedPointObjective, column with a retrieval block → CSRetrievalColumnObjective with that block, column without one → CSColumnMeanObjective), the containing cell of the record's Float64 (lat, lon), the time sampling re-derived from the record date and window on the run grid t_start, dt, nsteps (for a record outside the run, as ClampOutOfRange binds it; such rows are marked clamped), the value, and σ=value_sigma2+model_sigma2+profile_model_sigma2;

  • each stencil matches its observation's cell and time sampling.

Averaging-kernel column rows take the surface-pressure mismatch, the retrieval-level model profile and assimilated from their stencil.

t_start is an ISO-8601 string (Dates.format(t, "yyyy-mm-dd HH:MM:SS")).

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.convert_oco2_mip_observations Method
julia
convert_oco2_mip_observations(path, output; partition = :day, time_range = nothing,
                              data_types = ("LN", "LG", "OG"), assimilate_flags = (1,),
                              model_sigma = :file, mapping = Observations.HatLevelProjection(),
                              instrument = nothing, tracer = "CO2") -> Vector{String}

Convert an OCO-2 or OCO-3 v11 MIP 10-second file to observation files of schema v2 (write_observations), one per day (partition = :day, output holds {YYYYMMDD}) or per month (:month, {YYYYMM}), for the records of time_range (all records without one); days or months without records get no file. The records are those of read_oco2_mip_observations with the same options; the files record the source file, the options and the mapping as root attributes. Returns the paths written, in time order.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.inflate_cell_model_error Method
julia
inflate_cell_model_error(set::CSObservationSet, mesh, t_start, dt; nsteps = nothing,
                         time_tolerance_s = 60.0, tracer_filter = nothing,
                         out_of_range_policy = RejectOutOfRange()) -> CSObservationSet

The alternative to CellAverage that keeps every record: the assimilated column records grouped as CellAverage groups them (same tracer, model cell and step sampling as bind_to_mesh would bind them, within time_tolerance_s of the group's earliest record) get their model-error variance multiplied by the number k of records in their group, model_sigma → √k · model_sigma, i.e. model_sigma² times k; the profile-error term ∑i(hiaiσi)2 of an averaging-kernel column (from its retrieval block) is not inflated. The model error of records that sample the same model column is correlated, so k records should not reduce it k-fold; inflating each by k gives the group the weight of one record's model error. Bind the returned set with the same run grid; departures built from it report the inflated model_sigma. Every other record is returned unchanged.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.read_departures Method
julia
read_departures(path::AbstractString) -> CSDepartureSet

Parse a schema-v2 departures NetCDF written by write_departures and return an in-memory CSDepartureSet.

Validation (fails fast with ArgumentError):

  • Root attribute cs_departures_schema must equal "v2" (schema-v1 files, with Float32 coordinates and a single step, are rejected).

  • Every required root attribute must be present: mesh_Nc, mesh_panel_convention, mesh_cs_definition_tag, t_start, dt_seconds, nsteps, departure_sign_convention (equal to "simulated_minus_observed"), and n_clamped (the number of rows marked clamped).

  • Every required variable must be present, date_components dimensioned (date_component = 6, obs), every obs variable of the obs length, and the sample_counts must add up to the sample length.

  • The averaging-kernel column block (surface_pressure_mismatch_pa, retrieval_model_profile (retrieval_level, obs), profile_model_sigma, with assimilated) is all or nothing; without it every row has the defaults (NaN, no profile, 0). assimilated, flag and cell_average_id are optional otherwise (defaults: assimilated, flag 0, no cell average). The profile must state ordering = "surface_to_top" and a mole-fraction unit, the mismatch a pressure unit (converted to mol/mol and Pa).

  • Every row must pass the CSDepartureRecord checks.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.read_observations Method
julia
read_observations(path::AbstractString) -> CSObservationSet

Parse a schema-v2 observation NetCDF written by write_observations and return an in-memory CSObservationSet.

Validation (fails fast with ArgumentError):

  • Root attribute cs_observations_schema must equal "v2". Schema-v1 files are rejected: their Float32 coordinates can bind a point near a cell edge to the neighbouring cell, and their single alt cannot place a record by its height above the ground. Rewrite them as v2 with write_observations.

  • Root attribute time_origin must be present.

  • Every v2 variable must be present, lat and lon stored as Float64, and date_components dimensioned (date_component = 6, obs).

  • elevation_m, intake_height_m, altitude_m and pressure_pa read NaN or a declared fill value (_FillValue, e.g. xarray's NaN) as absent; any other variable with a fill value is an error.

  • The optional retrieval block (see write_observations) is all or nothing: retrieval_pressure_pa, retrieval_pressure_weight, retrieval_averaging_kernel, retrieval_prior_profile and retrieval_surface_pressure_pa (retrieval_profile_sigma, retrieval_mapping and retrieval_prior_column optional), with retrieval_interface = retrieval_level + 1. retrieval_mapping names each block's mapping ("layer_rebin": the pressures are the N + 1 interfaces of N layers; "hat_levels": the N levels themselves); a file without it holds layer records only. Every retrieval-level variable states ordering = "surface_to_top" (index 1 is the retrieval surface); pressures state a pressure unit (converted to Pa), the prior and its uncertainty a mole-fraction unit ("mol mol-1", "1", "ppm", "ppb", …; converted to mol/mol), weights and kernel are dimensionless. A record's values come first and NaN pads the rest (the number of layers or levels is that of its pressure weights); a record whose block entries are all NaN has none. Each block must pass the Observations.RetrievalColumn checks (pressures strictly decreasing from the surface, weights ≥ 0 summing to 1, finite values, prior in [0, 1] mol/mol, surface pressure equal to the first pressure), and only column records may carry one.

  • value, value_sigma and model_sigma without a units attribute are in the tracer's native unit, read as they are. A dry mole-fraction unit ("mol mol-1", "1", "ppm", "ppb", …) is converted to mol/mol; it must then be stated on all three, and a file with averaging-kernel columns must state one on all three.

  • Every row must pass the CSObservationRecord checks, and record ids must be unique.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.read_oco2_mip_observations Method
julia
read_oco2_mip_observations(path; time_range = nothing, data_types = ("LN", "LG", "OG"),
                           assimilate_flags = (1,), model_sigma = :file,
                           mapping = Observations.HatLevelProjection(), instrument = nothing,
                           tracer = "CO2") -> CSObservationSet

The records of an OCO-2 or OCO-3 v11 MIP 10-second file (read-only) as an observation set of schema v2 (CSObservationRecord), one per record whose time (date, truncated to the second) lies in time_range = (start, stop) (DateTimes, half-open; nothing = all):

record fieldfrom the MIP file
idsounding_id
date_componentsdate[1:6] (UTC)
lat, lonlatitude, longitude
kind"column"
elevation_maltitude (m above sea level)
time_window_s0 (the model step containing the time)
value, value_sigmaxco2_2019_scale, xco2_uncertainty (ppm → mol/mol)
model_sigmamodel_error (model_sigma = :file), or a constant in ppm, or 0
flag0 when assimilate_flag ∈ assimilate_flags and the data type is in data_types; else 1 + assimilate_flag
instrument_type"<instrument>_<data type>", e.g. "OCO2_OG"
tracertracer
retrievalthe 20 levels (sigma_levels × psurf, hPa → Pa), pressure_weight, xco2_averaging_kernel, co2_profile_apriori (ppm → mol/mol), surface first, and the prior column xco2_apriori (ppm → mol/mol; Observations.read_oco2_retrieval_columns)

data_types name the experiment's data types (LN land nadir, LG land glint, LT land target, LTR land transition, ON ocean nadir, OG ocean glint, OT, OTR, MIX mixed land/water, SAM OCO-3 snapshot area maps; the MIP assimilates LN, LG and OG). assimilate_flags are the MIP assimilate_flag values to assimilate (1; TM5-4DVar's MIP setup also takes the withheld 2). Every record of the range is kept: flag 1 marks assimilate_flag = 0 (sparse, target, transition, mixed scenes; evaluation only), 2 an assimilable record whose data type is outside data_types, 3 a withheld record (assimilate_flag = 2), unless assimilate_flags selects them. Bind with flagged_records = "cosample" to co-sample them.

mapping is Observations.HatLevelProjection() (the levels as given, the default) or Observations.LayerRebin() (TM5-4DVar's 19 layers, Observations.tm5_layer_column; the CLI's --mapping tm5). instrument defaults to the first token of the file's ShortName ("OCO2", "OCO3"). Sounding ids are unique within one file; OCO-2 and OCO-3 ids can coincide, so give each instrument its own set.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.write_departures Method
julia
write_departures(path::AbstractString, set::CSDepartureSet) -> String

Write set to path as a schema-v2 NetCDF departures file (see schemas/cs_departures_v2.toml) and return path; an existing file is overwritten. The sampled steps form a contiguous ragged array on the sample dimension: observation n owns sample_count[n] consecutive entries of sample_step, sample_weight and sample_level. When any row is an averaging-kernel column, the file adds surface_pressure_mismatch_pa, retrieval_model_profile (on a retrieval_level dimension, surface first, NaN-padded) and profile_model_sigma for every row. assimilated is written when any row is an averaging-kernel column or not assimilated, flag when any row has a nonzero flag (co-sampled records), and cell_average_id when any row belongs to a cell average.

source
AtmosTransport.Adjoints.Inversion.ObservationBinding.write_observations Method
julia
write_observations(path::AbstractString, set::CSObservationSet; attributes = Dict()) -> String

Write set to path as a schema-v2 NetCDF observations file (schemas/cs_observations_v2.toml) and return path; an existing file is overwritten. attributes are extra root attributes (provenance; not read back), which may not replace cs_observations_schema or time_origin.

  • Dimensions: obs (unlimited), date_component (= 6).

  • Variables: id (i64), date_components (i16), lat, lon (f64), kind (string "point" / "column"), elevation_m, intake_height_m, altitude_m, pressure_pa (f64, NaN = absent), time_window_s (f64), flag (i8), value, value_sigma, model_sigma (f64), instrument_type, tracer (string).

  • Root attributes: cs_observations_schema = "v2", time_origin = set.time_origin.

  • When any record has a retrieval block (an averaging-kernel column): the dimensions retrieval_level (the most layers or levels of any record) and retrieval_interface (one more), retrieval_pressure_pa (Pa: the interfaces of a layer record, the levels of a level record), retrieval_pressure_weight, retrieval_averaging_kernel, retrieval_prior_profile (mol mol⁻¹) and, when any record gives one, retrieval_profile_sigma (mol mol⁻¹), each (retrieval_level or retrieval_interface, obs), surface first (ordering = "surface_to_top") and NaN-padded; retrieval_surface_pressure_pa (obs); and retrieval_mapping (obs), the record's mapping ("layer_rebin" or "hat_levels", empty without a block) and, when any record gives one, retrieval_prior_column (obs) (mol mol⁻¹, NaN = absent). Records without a block are NaN throughout. Such a file states units = "mol mol-1" on value, value_sigma and model_sigma: its values are dry mole fractions in mol/mol, the unit of the retrieval priors (every record of the file).

source
AtmosTransport.Adjoints.Inversion.Solver.AbstractCS4DVarEvaluation Type
julia
AbstractCS4DVarEvaluation

What one cs_surface_flux_4dvar evaluation computes: CSCostAndGradient (the default) or CSCostOnly.

source
AtmosTransport.Adjoints.Inversion.Solver.AbstractCSOptimType Type
julia
AbstractCSOptimType

Supertype for control-variable parameterizations used by the preconditioner. Concrete subtypes:

source
AtmosTransport.Adjoints.Inversion.Solver.AbstractCSOptimizer Type
julia
AbstractCSOptimizer

Supertype for CS 4D-Var optimization backends. Concrete subtypes implement cs_surface_flux_4dvar_solve(opt, cost_fn, controls) where cost_fn(controls) -> CS4DVarResult evaluates one cost-and-gradient pass through the 4D-Var driver.

Shipped backends:

Additional backends:

  • CSLBFGS — Optim.jl L-BFGS wrapper.

Both accept the same stop rules (cost_rtol, cost_rtol_improvements, stall_evaluations, max_evaluations, callback); see CSLBFGS.

source
AtmosTransport.Adjoints.Inversion.Solver.AbstractCSSurfaceFluxCovariance Type
julia
AbstractCSSurfaceFluxCovariance{FT, A}

Supertype for CS surface-flux background-error covariance operators. Concrete subtypes implement apply_B_half! and apply_B_half_adjoint! on a single CSSurfaceFluxControl-shaped tuple NTuple{6, A} of (Nc, Nc) matrices.

source
AtmosTransport.Adjoints.Inversion.Solver.CS4DVarResult Type
julia
CS4DVarResult

One 4D-Var cost and gradient evaluation (cs_surface_flux_4dvar): the total, observation and background costs, the simulated values and residuals H(x) − y per observation, the gradient per control (and by control name; both empty for a CSCostOnly evaluation), the controls and observations evaluated, and stencils, one CSObservationStencil per observation (the steps, weights and levels it was sampled at). An observation whose stencil is not assimilated (a co-sample, or an averaging-kernel column screened out by its surface-pressure mismatch) keeps its simulated value and residual but adds nothing to the cost and the gradient.

source
AtmosTransport.Adjoints.Inversion.Solver.CS4DVarSolveResult Type
julia
CS4DVarSolveResult

The outcome of cs_surface_flux_4dvar_solve (and cs_surface_flux_4dvar_optimize):

  • controls, last: the optimizer's last accepted iterate and its evaluation (CS4DVarResult).

  • best: the evaluation with the lowest cost among all evaluations, line-search trials included (the earliest one on ties); its controls hold that point. It is last unless a trial point beat the last accepted iterate, which happens when a stop rule ends the solve inside a line search or when the cost is noisy near its minimum.

  • cost_history, gradient_norm_history: one value per accepted iterate, the initial point first; step_history: the accepted steps (CSGradientDescent only).

  • iterations: accepted iterations (for CSLBFGS ended by Optim itself, Optim's count, which includes a final iteration whose line search failed).

  • evaluations: cost evaluations (cost_fn calls), the initial one included.

  • stop_reason: why the solve ended, one of :iterations, :gradient, :line_search (the line search found no acceptable step), :cost_rtol, :stall, :evaluations, :callback, and for CSLBFGS also :no_progress (an accepted step left the controls or the cost exactly unchanged) and :non_finite (any other Optim termination is reported as :optim_<TerminationCode>). A cost_rtol, stall or callback stop fires at the evaluation that triggers it and takes precedence over the optimizer's own criteria; the evaluation cap is checked only when another evaluation is requested.

  • log: the CSIterationLog, or nothing without log = true.

source
AtmosTransport.Adjoints.Inversion.Solver.CSCostAndGradient Type
julia
CSCostAndGradient()

A 4D-Var evaluation of the cost and its gradient (the default of cs_surface_flux_4dvar and the evaluation of every optimizer step): one forward run that samples the observations and records what the tape's checkpoint schedule needs, then one reverse pass.

source
AtmosTransport.Adjoints.Inversion.Solver.CSCostOnly Type
julia
CSCostOnly()

A 4D-Var evaluation of the cost and the simulated values only: one forward run without a tape, no reverse pass and no tape storage. The result's gradients and gradient_by_name are empty. For callers that need the simulated observations or the cost at a point but not the gradient there (for example, synthetic observations).

source
AtmosTransport.Adjoints.Inversion.Solver.CSGradientDescent Type
julia
CSGradientDescent(; iterations, initial_step, min_step,
                    step_shrink, gradient_tolerance, line_search,
                    log, cost_rtol, cost_rtol_improvements,
                    stall_evaluations, max_evaluations, callback)

Plain backtracking-line-search gradient descent. iterations is the maximum count of accepted descent steps; the loop terminates early when the gradient L2 norm falls below gradient_tolerance or the line search shrinks step below min_step. With line_search = false every candidate step is accepted (constant step size unless the loop exits on tolerance).

log = true captures per-iteration diagnostics into CS4DVarSolveResult.log (see CSIterationLog): cost decomposition (observation vs background), gradient L2 norm, accepted step size, and wall-clock elapsed seconds since the solve started. Default false matches the pre-C3 behavior.

The stop rules cost_rtol, cost_rtol_improvements, stall_evaluations, max_evaluations and callback are the same as CSLBFGS's and are off by default. Every line-search candidate is an evaluation.

source
AtmosTransport.Adjoints.Inversion.Solver.CSIterationLog Type
julia
CSIterationLog(entries)

Per-iteration diagnostic log for a CS 4D-Var solve. Populated by optimizers when their log::Bool field is set to true; otherwise the CS4DVarSolveResult.log field is nothing.

The log carries enough information for after-the-fact convergence diagnostics: a monotone cost trajectory check, gradient-norm decay curve, observation-vs-background cost decomposition, and a wall-clock time series.

source
AtmosTransport.Adjoints.Inversion.Solver.CSIterationLogEntry Type
julia
CSIterationLogEntry(iteration, evaluation, cost, observation_cost,
                    background_cost, gradient_norm, step_size,
                    elapsed_seconds)

One row of per-iteration solver diagnostics. Captures the cost-decomposition (observation vs background terms), the optimizer's documented gradient norm (L2 for CSGradientDescent, L-infinity for CSLBFGS), the line-search step accepted on this iteration (0 for optimizers that don't expose a step — e.g. L-BFGS), and the wall-clock time since the solve started. evaluation is the 1-based index of the cost evaluation (cost_fn call) that computed this iterate; evaluations between two rows are line-search trials.

The convention is that an iteration is logged AFTER the descent direction has been accepted; the iteration = 0 row records the initial probe (evaluation 1) before any descent step.

source
AtmosTransport.Adjoints.Inversion.Solver.CSLBFGS Type
julia
CSLBFGS(; iterations, gradient_tolerance, m, show_trace, log,
          cost_rtol, cost_rtol_improvements, stall_evaluations,
          max_evaluations, callback)

Limited-memory BFGS (L-BFGS) optimizer backed by Optim.jl. m is the history length; the line search is Optim's LBFGS default (Hager–Zhang). iterations is the max outer iteration count; gradient_tolerance is Optim's L-infinity stopping threshold on the χ-space / x-space gradient. The same L-infinity norm is recorded in gradient_norm_history and CSIterationLogEntry.gradient_norm for this backend. show_trace = true forwards verbose progress to Optim's logger. log = true records one CSIterationLogEntry for the initial state (iteration 0) and one per accepted iterate.

Stop rules (shared with CSGradientDescent; all off by default). They are checked after every cost evaluation, line-search trials included, against the best (lowest) cost evaluated so far, Jbest:

  • cost_rtol (default 0, off): an evaluation that lowers the best cost from Jbest to J is a small improvement when (Jbest−J)/|Jbest|< cost_rtol. The solve stops after cost_rtol_improvements (default 2) consecutive small improvements (stop reason :cost_rtol); a larger improvement resets the count, and evaluations that do not lower the best cost leave it unchanged.

  • stall_evaluations (default 0, off): stop after this many consecutive evaluations that do not lower the best cost (:stall). Near the optimum a Float32 cost has a noise floor, and the line search can keep evaluating without finding a decrease; this rule ends it. Every trial counts, also ordinary backtracking (each step halving of CSGradientDescent, an overshooting first L-BFGS line search), so choose it above the number of trials a healthy line search needs (the flux OSSE used 6 with L-BFGS).

  • max_evaluations (default 0, no cap): run at most this many cost evaluations, the initial one included (:evaluations). iterations caps accepted iterates; this caps the work. The cap is checked when another evaluation is requested, so a solve that ends on its own at the last allowed evaluation reports its own reason.

  • callback (default nothing): callback(evaluation::Int, result::CS4DVarResult) -> Bool, called after every evaluation with its 1-based index; returning true stops the solve (:callback). The result's controls are working storage that the next evaluation overwrites; copy what you keep.

A rule that fires stops the solve before its next evaluation, so no evaluation is wasted: at an accepted iterate Optim stops through its callback; inside a line search the wrapper interrupts Optim and returns the last accepted iterate. Either way the result's best holds the lowest-cost evaluation and stop_reason names the rule (see CS4DVarSolveResult).

Used by the polymorphic dispatch surface cs_surface_flux_4dvar_solve. The cost closure cost_fn(controls) -> CS4DVarResult is handed to Optim as one objective with value, gradient and combined value-and-gradient methods, flattening each control's NTuple{6, Matrix} to a Vector{FT} and back. Each cost_fn call is a forward run plus the adjoint, so all three methods share a cache of the last evaluation: cost_fn runs once per point Optim visits, and the initial point and the returned result reuse those evaluations.

source
AtmosTransport.Adjoints.Inversion.Solver.CSSurfaceFluxControl Type
julia
CSSurfaceFluxControl(window, value; background=nothing, sigma=nothing)

Surface-flux control block for the prototype 4D-Var path. value is an NTuple{6} of (Nc, Nc) rate arrays tied to window. Optional background and sigma add the standard diagonal background term 0.5 * ((value - background) / sigma)^2; sigma can be a scalar or matching panel arrays.

source
AtmosTransport.Adjoints.Inversion.Solver.CSSurfaceFluxPreconditioner Type
julia
CSSurfaceFluxPreconditioner(covariance, background, optim_type)

Bundle of (covariance, background, optim_type) that performs the change of variables between preconditioned χ-space and physical x-space for one CS surface-flux control. background is the prior x_b shaped as NTuple{6, Matrix{FT}} (matching the covariance's sigma shape and a single CSSurfaceFluxControl.value).

Constructor validates background shapes against the covariance and — for LogNormalOptimType — requires every background entry to be strictly positive (else log(x ./ x_b) is undefined and the log-normal transform is meaningless). It also pre-allocates a panel-tuple scratch buffer reused by the LogNormal variant of apply_preconditioner_adjoint!. The preconditioner is therefore not thread-safe — build one instance per worker thread if you intend to call these methods concurrently.

source
AtmosTransport.Adjoints.Inversion.Solver.CSSurfaceFluxWindow Type
julia
CSSurfaceFluxWindow(name, steps; weights=nothing, normalize=false)

Named surface-flux control window for Jacobian aggregation. steps can be a single step or any iterable of step indices. By default, a window sums per-step surface-emission footprints, which corresponds to perturbing the same rate over the whole window. Pass normalize=true for an average-rate control, or explicit weights for custom temporal basis functions.

source
AtmosTransport.Adjoints.Inversion.Solver.DiagonalCSCovariance Type
julia
DiagonalCSCovariance(sigma::NTuple{6, AbstractMatrix})

Pure-diagonal CS surface-flux covariance B = diag(σ)². sigma[p][i, j] is the background standard deviation at panel p, interior cell (i, j). All six panels must share the same (Nc, Nc) shape and every entry must be finite and strictly positive.

This is the cleanest baseline; B^(1/2) is self-adjoint, so apply_B_half_adjoint! reduces to apply_B_half!.

source
AtmosTransport.Adjoints.Inversion.Solver.IsotropicGaussianCSCovariance Type
julia
IsotropicGaussianCSCovariance(sigma::NTuple{6, AbstractMatrix},
                              correlation_length_cells::Real)

Panel-local CS surface-flux covariance B = D · C · D with isotropic separable Gaussian correlation of length correlation_length_cells (in interior-cell units).

Each panel's (Nc, Nc) grid is treated as periodic and the correlation matrix C is the circulant whose first row is the wrapped Gaussian. L = C^(1/2) (the symmetric square root) is applied via FFT: in spectral space L is multiplication by sqrt(C̃) where C̃ is the real, non-negative spectral eigenvalues of C. The factorization is B^(1/2) = D · L, so (B^(1/2))^T = L^T · D = L · D (since D and L are both symmetric).

The wrapped-Gaussian normalization pins C[i, i] = 1, hence B[i, i] = σ_i² — the diagonal of B recovers the per-cell variance, independent of correlation length.

To keep B^(-1/2) finite at operational Float32 resolutions, each one-dimensional factor of the separable spectrum is floored at its maximum times sqrt(eps(FT)), then renormalized to preserve the unit diagonal. The corresponding minimum two-dimensional covariance eigenvalue is therefore approximately its maximum times eps(FT). This is a precision-aware regularization of unresolved high-frequency modes.

Limitations:

  • Cross-panel correlation is dropped. Each panel is smoothed in isolation; the implicit wrap-around at panel boundaries leaves edge artefacts.

  • The FFT path is CPU-only.

  • The struct carries mutable fft_buf / fft_scratch scratch buffers reused by every apply_B_half! / apply_B_half_adjoint! call. As a consequence the covariance is not thread-safe — concurrent calls on the same instance race on the scratch. Build one instance per worker thread if needed.

source
AtmosTransport.Adjoints.Inversion.Solver.LinearOptimType Type
julia
LinearOptimType

Linear additive parameterization: x = x_b + B^(1/2) χ. The physical control x is unbounded; the only nonlinearity is in the cost via the observation operator H(x).

source
AtmosTransport.Adjoints.Inversion.Solver.LogNormalOptimType Type
julia
LogNormalOptimType

Log-normal multiplicative parameterization: x = x_b ⊙ exp(B^(1/2) χ). The physical control is guaranteed strictly positive for any finite χ, at the cost of the background x_b having to be strictly positive everywhere. Suitable for emissions, mole fractions, and other non-negative atmospheric quantities.

source
AtmosTransport.Adjoints.Inversion.Solver.apply_B_half! Function
julia
apply_B_half!(y::NTuple{6, AbstractMatrix},
              cov::AbstractCSSurfaceFluxCovariance,
              chi::NTuple{6, AbstractMatrix}) -> y

Apply the (non-symmetric) square root B^(1/2) to chi and write the result into y. Concretely, y = D · L · chi, where D is the diagonal scaling and L is the symmetric correlation square root. y and chi may alias; the implementation writes through a scratch buffer when needed.

source
AtmosTransport.Adjoints.Inversion.Solver.apply_B_half_adjoint! Function
julia
apply_B_half_adjoint!(g_chi::NTuple{6, AbstractMatrix},
                      cov::AbstractCSSurfaceFluxCovariance,
                      g_phys::NTuple{6, AbstractMatrix}) -> g_chi

Apply the adjoint (B^(1/2))^T to g_phys. With B^(1/2) = D · L and D, L both symmetric, this is g_chi = L · D · g_phys.

source
AtmosTransport.Adjoints.Inversion.Solver.apply_preconditioner! Method
julia
apply_preconditioner!(x, prec, chi) -> x

Forward change of variables. With Linear optim_type, x = x_b + B^(1/2) χ. With LogNormal, x = x_b ⊙ exp(B^(1/2) χ). x, chi are NTuple{6, AbstractMatrix}.

source
AtmosTransport.Adjoints.Inversion.Solver.apply_preconditioner_adjoint! Method
julia
apply_preconditioner_adjoint!(g_chi, prec, x, g_phys) -> g_chi

Adjoint of the tangent at base x. Linear: g_χ = (B^(1/2))^T g_phys. LogNormal: g_χ = (B^(1/2))^T (x ⊙ g_phys).

This is the observation part of the χ-space gradient under the chain rule of T. The caller adds χ from the 0.5 ‖χ‖² term of the preconditioned cost separately.

source
AtmosTransport.Adjoints.Inversion.Solver.cs_surface_flux_4dvar Method
julia
cs_surface_flux_4dvar(..., observations, controls; scheme, kwargs...) -> CS4DVarResult

Evaluate the prototype CS surface-flux 4D-Var cost and gradient. Controls are named CSSurfaceFluxControls over CSSurfaceFluxWindows. Observations are scalar CSObservations sampled after the model steps of their CSTimeSampling (one step, or a weighted time window; after convection, the state runtime output sees). CSPlacedPointObjective observations choose their layer, and CSRetrievalColumnObjective observations (averaging-kernel columns) build their weights, at each sampled state from column_met, a CSObservationColumnMet (required when there are any). An averaging-kernel column whose surface-pressure mismatch exceeds its limit is an error, or, under SkipUnplaced, is reported with its simulated value and residual but left out of the cost and the gradient (its stencil is not assimilated). Co-samples (CSObservation(...; assimilate = false): flagged records bound with flagged_records = "cosample", the members of cell averages) are simulated and reported the same way, never in the cost or the gradient, and do not extend the taped run: adding them leaves the cost and the reverse pass's forcing unchanged, bit for bit.

One cost-and-gradient evaluation is one forward run and one reverse pass (with FullCheckpoint; StrideCheckpoint adds the re-recording of its head). CFL-driven schedules add one cached sizing run per runtime; the binary-window contract uses a closed-form size, whatever the number of observations, as in TM5-4DVAR:

  1. the forward run gives the simulated values Hᵢ(x) = Σₛ ωᵢₛ hᵢ(rₛ), each observation's stencil (CSObservationStencil: steps, weights, levels) and its linear functional (weights from the replayed air mass at each sampled step, times ωᵢₛ), and records what the tape's checkpoint schedule needs through the last step of an observation with assimilate = true (the whole tape with FullCheckpoint, the K-step checkpoints with StrideCheckpoint(K));

  2. each observation contributes (Hᵢ(x) − yᵢ)/σᵢ² times its functional's weights to the adjoint forcing of each sampled step;

  3. one reverse pass from the last assimilated step (after the surface-pressure screen) back to the first, which adds each step's forcing at that step's end, gives ∂J_obs/∂E for every step; each control's window collects its steps.

The run replays the production step plan of schedule (a CSStepSchedule; default: one step of dt per met window, the full operator suite every step), with the controls' rates in its surface-flux operator. Steps after the last assimilated step do not affect the cost and get a zero gradient. tape defaults to AutoTape(), resolving and reserving one concrete AdjointTape before recording; explicit descriptors fix the choice, as in cs_surface_emission_footprint; the call frees its memory when it returns.

An averaging-kernel column the surface-pressure screen leaves out after the last assimilated step is taped but not walked: the tape (and the reservation of a MmapCSTapeStorage) covers the steps through the last observation with assimilate = true.

met_source (an AbstractCSWindowSource, e.g. the HostCSWindowSource of cs_adjoint_inputs(sim; residency = :host)) supplies the met per window instead of the per-step arguments: pass nothing for the three flux vectors and omit diffusion_op, diffusion_layer_thickness, convection_forcing and flux_scale. A streamed source needs a MetWindowCheckpoint tape (tape = AutoTape(; checkpoint = MetWindowCheckpoint()) or an explicit AdjointTape), also for a cost-only evaluation; anything else is an ArgumentError before the forward run. cs_surface_flux_4dvar_optimize reuses the source in every evaluation.

evaluation = CSCostOnly() computes the cost and the simulated values only: the forward run without a tape and no reverse pass (the result's gradients are empty; tape is validated but opens no memory); the default CSCostAndGradient() computes both.

scheme is required: inversion callers must name the advection operator whose forward and adjoint they intend to use; there is no hidden numerical default.

Two modes:

  • Unconditioned (default, preconditioner = nothing). Each control's .value is the physical-space control directly. Optional diagonal background terms come from .background + .sigma and are added per control via _background_cost_and_gradient!.

  • Preconditioned (preconditioner non-nothing). Each control's .value is the preconditioned-space variable χ. The function: (1) computes x_k = T(χ_k) per control via the preconditioner; (2) runs the forward simulation with x; (3) reverses through the existing observation-gradient path to get ∂J_obs/∂x_k per control; (4) applies T'(χ_k)^T to get ∂J_obs/∂χ_k and adds χ_k (the derivative of the 0.5 ‖χ‖² regularization). The reported cost is 0.5 ‖χ‖² + observation_cost, the reported gradient is ∂J/∂χ, and the reported controls are the original χ-space inputs. Per-control .background and .sigma are ignored in this mode — the background term comes from 0.5 ‖χ‖², and the background x_b is carried by the preconditioner itself.

preconditioner accepts either a single CSSurfaceFluxPreconditioner (broadcast to every control — the same preconditioner is used for each of them) or a Vector{<:CSSurfaceFluxPreconditioner} aligned 1-to-1 with the control vector. Any other length mismatch throws ArgumentError.

source
AtmosTransport.Adjoints.Inversion.Solver.cs_surface_flux_4dvar_optimize Method
julia
cs_surface_flux_4dvar_optimize(..., observations, controls;
                                optimizer = CSGradientDescent(...),
                                tape = AutoTape(), kwargs...)
    -> CS4DVarSolveResult

Run an optimization loop around cs_surface_flux_4dvar.

optimizer::AbstractCSOptimizer selects the backend; configure descent and logging on that object. The default uses the model precision for its step settings, including min_step = sqrt(eps(FT)).

tape (default AutoTape()) resolves to one AdjointTape, shared by every evaluation: they all record into one tape pool, opened by the first and rewound by each later one (an mmap file is reserved and its bytes counted once), and released when the optimization returns.

Remaining keyword arguments are forwarded to cs_surface_flux_4dvar on every cost evaluation — including preconditioner = ... for the preconditioned-cost path. Every evaluation computes the cost and the gradient, so evaluation is not accepted.

source
AtmosTransport.Adjoints.Inversion.Solver.cs_surface_flux_4dvar_solve Function
julia
cs_surface_flux_4dvar_solve(optimizer::AbstractCSOptimizer,
                             cost_fn,
                             controls) -> CS4DVarSolveResult

Run optimizer against the cost closure cost_fn(controls) -> CS4DVarResult starting from controls. Dispatches on the optimizer's concrete type — additional backends are added by defining a new method here, not by branching inside an existing one. The solver keeps earlier results (the best and the last accepted evaluation), so cost_fn must return arrays that later calls do not overwrite. See CS4DVarSolveResult for what it returns.

source
AtmosTransport.Adjoints.Inversion.Solver.cs_surface_flux_jacobian Method
julia
cs_surface_flux_jacobian(..., objectives, windows; kwargs...)

Compute surface-flux Jacobian maps for several layer/column objectives and named time windows. Each returned footprints[obj, window] entry is an NTuple{6} of (Nc, Nc) arrays. Window aggregation is a weighted sum of per-step emission-rate footprints; use CSSurfaceFluxWindow(...; normalize=true) for average-rate controls or explicit weights for a custom temporal basis. kwargs are those of cs_surface_emission_footprint, including tape (an AdjointTape). Every checkpoint schedule records the forward run once (StrideCheckpoint re-records each window once) and walks each tape once per objective; with StrideCheckpoint the adjoint states of all objectives are held at once.

source

The solver exposes the forward preconditioner and its adjoint. The unused inverse and tangent interfaces have been removed.

Tape and checkpointing ​

Every reverse-pass entry point defaults to tape = AutoTape(). It resolves one concrete AdjointTape after building the replay and reserves its pools before recording. The binary's per-window step schedule fixes a closed-form size; CFL-driven schedules and Lin–Rood use one counting replay, cached for all evaluations of an optimization. Auto reads the backend's free memory, including reclaimable allocator cache, subtracts reverse-workspace and output memory and max(10% of capacity, 4 GiB) on GPUs, and checks host availability against cgroup headroom, excluding reclaimable file cache. CPU selection holds back min(10% of capacity, 2 GiB), with capacity limited by the host and cgroup, plus the estimated reverse-pass workspace. The 2 GiB cap is Tape._CPU_TAPE_MARGIN_MAX_BYTES; it keeps small tapes feasible on large shared hosts when other jobs reduce headroom. Pinned-host selection alongside a GPU holds back max(10% of limit, 8 GiB). These margins apply only to Auto selection; explicit AdjointTape choices attempt reservation directly, with a hard headroom check for pinned memory.

The CPU budget policy changes only which candidate fits when memory is tight; forward and adjoint results remain bitwise identical on one CPU thread.

Supplied AutoTape fields constrain the choice: storage, checkpoint, content, budget_bytes (overrides the measured device tape/snapshot budget and margin, including shared host headroom on CPU) and scratch_dir (enables mmap). The order is device Full, device Stride with the largest fitting resident tail and device snapshots, device Stride with pinned-host snapshots, then mmap candidates only when scratch_dir is set. Pinned tapes are available explicitly; no pin-once GPU measurement has qualified them ahead of recomputation. Relative-time estimates use measured device forward/record/walk costs; unmeasured host and Lin–Rood relative times are logged as missing.

An explicit tape = AdjointTape(; content, storage, checkpoint) fixes what each record stages and how long a recording serves (StateTape(), recorded by every forward run, or AirMassTape(), recorded once per call or optimization for the schemes whose reverse reads the air mass only, tape_dependence), where the staged states live (DeviceCSTapeStorage(), PinnedHostCSTapeStorage(), MmapCSTapeStorage(dir)) and how much of the run is taped at once (FullCheckpoint(), StrideCheckpoint(K; resident_tail = 0, snapshots = DeviceCSTapeStorage()), MetWindowCheckpoint(; split_steps = 0, snapshots = PinnedHostCSTapeStorage()), whose segments are the met windows of the step schedule, optionally split; unconstrained Auto does not choose it, AutoTape(; checkpoint = MetWindowCheckpoint()) sizes and reserves it). A resident tail uses the tape’s selected storage and is recorded in the forward run; only the head's K-step windows are recomputed. Snapshots may use PinnedHostCSTapeStorage() for their tracer and air masses; persistent operator state retains its backend types. The value holds no memory: each call opens its tape's memory, reuses it for every stride window (and cs_surface_flux_4dvar_optimize for every evaluation) and frees it when it returns. The on-disk storage MmapCSTapeStorage(dir) takes a required scratch directory; each call reserves its tape there before recording.

A failed Auto reservation tries another allowed candidate. A failed explicit choice raises TapeReservationError with its estimate; it is never replaced. Device slabs, pinned chunks and mmap extents are reserved before recording; growth beyond a pool reservation raises TapeReservationExceeded. Lin–Rood's horizontal copies remain outside the pools and are counted in its device peak. Each runtime emits one @info "adjoint tape" with its choice, estimated and reserved bytes, budget and expected relative time. Mmap is scratch storage: persisted per-window tapes and bisection Revolve are absent.

Pinned reservations use chunks targeting at most 1 GiB (a larger indivisible slot gets its own chunk). Slots have reserved locations keyed by element type and panel shape, so recording them in a different order needs no extra bytes. Segment sizes exclude a preceding step's pending convection flush and include their own final pending convection slot. Stride head pools reserve the maximum per-key count across windows. Convection supplies checkpoint carry shapes from the mesh and tracer count through its operator-owned checkpoint interface.

A split-sweep tape stages each state once: the palindrome center's diffusion records and a convection call share the slots of the sweeps that read the same air mass, and a monotone or CW84 PPM sweep stages one byte of limiter branches per cell instead of the tracer mass (see what the tape stages).

AtmosTransport.Tape Module
julia
Tape

The adjoint tape of the AtmosTransport.jl cubed-sphere reverse pass: AdjointTape (content × storage × checkpointing), the storage descriptors (device, pinned host, mmap on disk) and the runtime pools a call records into, tape record types, and checkpoint schedules.

Tape imports nothing from other AtmosTransport modules. src/AtmosTransport.jl loads it before Adjoints, which imports these names with using ..Tape: .... The forward recorder, reverse loop and checkpoint drivers (src/Adjoints/Footprint/) and the 4D-Var code (src/Adjoints/Inversion/) are child modules of Adjoints.

Module dependency order: Tape → Adjoints core → Footprint → Inversion

source
AtmosTransport.Tape.AbstractCSTapeStorage Type
julia
AbstractCSTapeStorage

Where the staged states of a cubed-sphere adjoint tape live: the storage of an AdjointTape. The descriptors are immutable values (DeviceCSTapeStorage(), PinnedHostCSTapeStorage(), MmapCSTapeStorage(dir)); each reverse-pass call (or each cs_surface_flux_4dvar_optimize call) opens its own runtime pool from the descriptor and releases it when it returns, so one AdjointTape can serve any number of calls.

A new storage subtypes it and implements _open_tape_pool(storage, nbytes), returning a pool that implements _allocate_tape_slot, stage_panels!, _tape_panels(slot, role), _rewind_tape_pool! and _release_tape_pool!.

source
AtmosTransport.Tape.AbstractHostCSTapeStorage Type
julia
AbstractHostCSTapeStorage <: AbstractCSTapeStorage

Storage whose staged states live off the source device: host memory (PinnedHostCSTapeStorage) or a scratch file (MmapCSTapeStorage). Every read copies the state into a device read cache per read role and panel shape, so the two operands that one reverse kernel reads together (the air mass and tracer mass of a limited-PPM sweep record) are always distinct buffers.

source
AtmosTransport.Tape.AbstractTapeContent Type
julia
AbstractTapeContent

What the records of an adjoint tape stage, and how long a recording serves: the content of an AdjointTape. StateTape (the default) records every forward run; AirMassTape records the air mass once and reuses it.

source
AtmosTransport.Tape.AbstractTapeReadRole Type
julia
AbstractTapeReadRole

The reverse-kernel operand a tape read feeds, passed as _tape_panels(slot, role). Host-side storage keeps one read cache per role, and a read stays valid until the next read with the same role. A reverse kernel that takes two staged states therefore reads them with two different roles. Reading both through one shared cache gave the limited-PPM reverse sweep the same buffer for the air mass and the tracer mass (issue #57).

source
AtmosTransport.Tape.AdjointTape Type
julia
AdjointTape(; content = StateTape(), storage = DeviceCSTapeStorage(),
            checkpoint = FullCheckpoint())
AdjointTape(content, storage, checkpoint)

The tape of a cubed-sphere reverse pass, passed as tape to cs_surface_emission_footprint, cs_surface_emission_footprint_from_seed, cs_surface_flux_jacobian, cs_surface_flux_4dvar and cs_surface_flux_4dvar_optimize:

Every storage works with every schedule and gives the same gradients bit for bit on one CPU thread. The Lin–Rood tape supports DeviceCSTapeStorage only; AirMassTape takes FullCheckpoint only (an ArgumentError here). Each call opens the memory its tapes need from this descriptor, reuses it for every window (and, in cs_surface_flux_4dvar_optimize, every evaluation), and frees it when it returns.

source
AtmosTransport.Tape.AirMassRead Type
julia
AirMassRead()

Read role of staged air-mass states (sweep, diffusion and convection records).

source
AtmosTransport.Tape.AirMassTape Type
julia
AirMassTape()

The tape of a scheme whose reverse reads the air mass only, never the tracer (tape_dependence(scheme) isa AirMassDependence: upwind, unlimited slopes and unlimited PPM): recorded by the first forward run of a call and reused by every later one, whatever its tracer and emissions (every adjoint start of a call, every evaluation of cs_surface_flux_4dvar_optimize). Each reuse first checks that the met inputs (a checksum of their contents), the time windows, the scheme and operators, the grid, the taped steps and the pool's generation are those the tape was recorded with; a difference is an ArgumentError that names it. Takes FullCheckpoint. A scheme whose reverse reads the tracer (limited PPM, Lin–Rood) is an ArgumentError before any forward run.

source
AtmosTransport.Tape.AutoTape Type
julia
AutoTape(; storage = nothing, checkpoint = nothing, content = nothing,
         budget_bytes = nothing, scratch_dir = nothing)

Resolve and reserve an AdjointTape before recording, from the step schedule and the available backend and host memory. Supplied axes constrain the search: checkpoint may be a concrete schedule (FullCheckpoint(), StrideCheckpoint(K), MetWindowCheckpoint(); sized, checked against the budget and reserved as given) or a StrideSearch. Without a constraint the search considers Full and Stride schedules, not MetWindowCheckpoint. budget_bytes replaces the measured device tape and snapshot budget and its safety margin; on CPU it also replaces the shared host budget. scratch_dir enables the mmap candidate. With no fitting reservation, throw TapeReservationError. The default content is StateTape.

source
AtmosTransport.Tape.CSTapeSlot Type
julia
CSTapeSlot

One staged state of a device tape: six panel arrays on the source backend, owned by the pool and stamped with the pool generation that handed them out.

source
AtmosTransport.Tape.DeviceCSTapeStorage Type
julia
DeviceCSTapeStorage()

Keep the staged states on the backend of the source panels (device memory on a GPU). The fastest storage; the tape must fit beside the model on the device. The pool of a call reuses its arrays for every tape it records (each stride window, each 4D-Var evaluation of an optimization) and frees them when the call returns.

source
AtmosTransport.Tape.FullCheckpoint Type
julia
FullCheckpoint()

Default tape schedule. Every forward step contributes records to a single tape; the reverse pass walks the tape once with no recomputation. Peak storage is proportional to nsteps.

source
AtmosTransport.Tape.HostCSTapeSlot Type
julia
HostCSTapeSlot

One staged state of a host tape (pinned-host arena or mmap file): six views into the pool's host memory, each on a 64-byte boundary, stamped with the pool generation that handed them out. The views never leave the pool: _tape_panels copies them into a device read cache.

source
AtmosTransport.Tape.LimiterCodeRead Type
julia
LimiterCodeRead()

Read role of the limiter branch codes of a limited-PPM sweep record (six UInt8 panels), which the reverse sweep reads together with the record's air mass.

source
AtmosTransport.Tape.MetWindowCheckpoint Type
julia
MetWindowCheckpoint(; split_steps = 0, snapshots = PinnedHostCSTapeStorage())

Checkpoint at the met-window boundaries of the step schedule (CSStepSchedule.steps_per_window) and re-record one segment at a time during the reverse pass, with the driver of StrideCheckpoint. Each segment covers exactly one met window, whatever its number of steps (the MERRA-2 transport binaries have 2–3 steps per window at C24 and 8–11 at C90), so the met inputs of one window are all a segment's tape refers to.

split_steps > 0 splits a met window of n steps into cld(n, split_steps) segments of nearly equal length (lengths differ by at most one step, longer ones first), none longer than split_steps and none straddling a window boundary: the bound on the tape when one window's tape does not fit. split_steps = 0 (default) does not split. A run that ends inside a met window ends its last segment there.

The tape holds one segment (the call's pool is reserved for the largest per-type record count over the segments), plus one snapshot per segment. snapshots holds the snapshots' tracer and air masses: PinnedHostCSTapeStorage() (default; a month of C90 L72 Float32 snapshots is about 24 GB) or DeviceCSTapeStorage(); persistent operator state keeps its backend types. Every segment boundary is a step boundary, so the footprints and gradients equal FullCheckpoint's bit for bit on one CPU thread (see StrideCheckpoint, Parity). There is no resident tail. Takes StateTape() only (an AirMassTape is one recording for the whole run).

source
AtmosTransport.Tape.MmapCSTapeStorage Type
julia
MmapCSTapeStorage(dir)

Keep the staged states in a scratch file in dir, for tapes larger than device and host memory. dir is required (there is no default: a tape can be tens to hundreds of GB) and is created if it does not exist; a relative path is resolved when the storage is constructed.

Each reverse-pass call (footprint, Jacobian, 4D-Var gradient) first sizes its largest tape by running the forward replay with a counting recorder (one extra forward run with FullCheckpoint; the checkpoint propagation pass with StrideCheckpoint; a cs_surface_flux_4dvar_optimize call counts once for all its evaluations). It then checks that dir has that many bytes plus 10 % free, and reserves them with fallocate in one anonymous (unlinked) file before recording; later tapes of the call reuse the file. Too little space is a TapeReservationError naming the required and available bytes, raised after the sizing pass and before the tape is recorded. A file system that cannot reserve blocks for in-place writes (no fallocate, e.g. some NFS mounts, or ZFS) is an ArgumentError naming it; use a directory on a local file system such as ext4 or XFS. The file is unmapped, closed and its space returned to the file system when the call returns; tapes are not persisted.

Reads copy the staged state into read caches keyed by read role (AirMassRead, TracerMassRead) and panel shape (on the device for GPU panels), so the air mass and tracer mass that one reverse kernel reads together are distinct buffers.

source
AtmosTransport.Tape.PinnedHostCSTapeStorage Type
julia
PinnedHostCSTapeStorage(; max_bytes = nothing)

Keep the staged states in host memory and read them back through device read caches, one per read role and panel shape. The pool of a call allocates its host memory in large chunks, each registered with the GPU driver (page-locked) once when it is allocated (the CUDA and AMDGPU extensions), reuses them for every tape it records and frees them when the call returns; staging and reading are synchronous device↔host copies. With CPU panels it is plain host memory. max_bytes caps the reservation; current host/cgroup headroom always applies as well.

source
AtmosTransport.Tape.StaleTapeSlotError Type
julia
StaleTapeSlotError(msg)

A tape slot was read or written after its pool was rewound for a new tape (the next stride window or 4D-Var evaluation) or released (its call returned). The slot's memory belongs to another tape, or to nobody, so the read is refused rather than returning other data.

source
AtmosTransport.Tape.StateTape Type
julia
StateTape()

Every forward run records what each operator's reverse reads of its state: the air mass entering every advection sweep, diffusion solve, convection call and air-mass reset, and for a monotone or CW84 PPM sweep the limiter branch of every cell (one byte per cell, PPMLimiterCodes), whose reverse replays the forward's branches. A Lin–Rood tape also stages the tracer mass entering its horizontal operators and FV3 vertical sweeps.

The records share what is the same: the palindrome center's air mass is the one the next vertical sweep stages, and a convection call's air mass is the next step's first sweep's (or a following air-mass reset's) slot, since the convection reverse reads interior cells only.

source
AtmosTransport.Tape.StrideCheckpoint Type
julia
StrideCheckpoint(K; resident_tail = 0, snapshots = DeviceCSTapeStorage())

Save the replay state (tracer and air mass with halos, and the persistent operator state) every K forward steps and re-record each K-step window from its checkpoint during the reverse pass. K must be a positive integer; K = 1 checkpoints every step; K >= nsteps is a single window.

The tape holds one window at a time (~K times the per-step cost; the call's tape pool is rewound and reused for every window), plus cld(nsteps, K) checkpoints. Each window is recorded once and walked for every adjoint start (the objectives of a Jacobian), so the extra cost is one forward run.

resident_tail keeps the final steps recorded during the forward run, avoiding their recomputation; the head uses K-step windows. snapshots may be PinnedHostCSTapeStorage() to move checkpoint tracer and air masses to host memory; persistent operator state retains its backend types. Both pools and every checkpoint are reserved before recording.

Parity. Every recorded step starts with production's step-start halo refresh (fill_cs_step_start_halos!), so the halos a step reads are a function of its interior state and a window that restarts at a checkpoint records the same states as FullCheckpoint: the footprints agree bit for bit on one CPU thread for every supported scheme and storage (issue #60 was the missing refresh).

source
AtmosTransport.Tape.StrideSearch Type
julia
StrideSearch(K = nothing, resident_tail = nothing, snapshots = nothing)

Constrain AutoTape's stride search, leaving unspecified fields automatic. AutoTape resolves this request to a concrete StrideCheckpoint before recording.

source
AtmosTransport.Tape.TapeReservationError Type
julia
TapeReservationError(estimate_bytes, budget_bytes, msg)

No permitted tape candidate could be reserved before recording. The estimate and available budget are in bytes; msg describes the failed choices.

source
AtmosTransport.Tape.TapeReservationExceeded Type
julia
TapeReservationExceeded(capacity_bytes, requested_bytes)

Recording requested more memory than was reserved before the forward run. No storage spill or unreserved pool growth is allowed.

source
AtmosTransport.Tape.TracerMassRead Type
julia
TracerMassRead()

Read role of the staged tracer-mass state of an FV3-profile sweep record, which the reverse sweep reads together with the record's air mass, and of the target air mass of a :preserve_vmr reset record.

source
AtmosTransport.Tape._CSAirMassResetRecord Type
julia
_CSAirMassResetRecord(mode, panels_old_m, panels_new_m)

Forward-recorded air-mass reset to a met target. :preserve_tracer_mass leaves the tracer mass unchanged (no staged air masses); :preserve_vmr scales it by new_m / old_m and stages both air masses.

source
AtmosTransport.Tape._CSConvectionRecord Type
julia
_CSConvectionRecord{FT, T, C, F}

Forward-recorded convection application. op is the convection operator (CMFMCConvection, TM5Convection or CMFMCMatrixConvection), forcing is the ConvectionForcing it read, panels_m is the air-mass tape slot, dt the interval it integrated over (the advection step or the met window) and substeps the CFL sub-step count the forward call used (CMFMCConvection; 1 for the others). The convection reverse reads interior cells only, so a split-sweep tape's record shares the slot of the next air mass staged with the same interior: the next step's first sweep, or the old air mass of a :preserve_vmr reset.

source
AtmosTransport.Tape._CSDiffusionRecord Type
julia
_CSDiffusionRecord{FT, T, D, W}

Forward-recorded implicit vertical-diffusion application. op is the diffusion operator (e.g., ImplicitVerticalDiffusion), layer_thickness the caller's layer-thickness panels [m] of this step's met window (read, never written; nothing for an operator whose solve reads no layer thickness), panels_m is the air-mass tape slot, dt is the (half-)timestep size and time the clock (current_time) at which the forward evaluated the operator's Kz field. The reverse solve's scratch belongs to the replay, not to the record.

source
AtmosTransport.Tape._CSHaloRecord Type
julia
_CSHaloRecord(dir)

Forward-recorded cross-panel halo fill (dir ∈ (0, 1, 2): full / X-only / Y-only). The reverse pass applies the adjoint of the halo fill at the same dir.

source
AtmosTransport.Tape._CSMidpointRecord Type
julia
_CSMidpointRecord(step, dt)

Marker record where the surface-flux operator of model step step adds dt worth of emissions (the palindrome center). The reverse pass accumulates the step's surface footprint dt · λ at this op.

source
AtmosTransport.Tape._CSStepEndRecord Type
julia
_CSStepEndRecord(step)

Marker record at the end of model step step, after convection: the state that runtime output and the forward observation sampler see. Every recorder pushes one per step. The reverse pass injects the adjoint forcing of the observations sampled after step step here, so the forcing enters before the transpose of that step's convection (TM5-4DVAR adds its forcing just before the adjoint of the operator after which the forward run sampled). Without a forcing the record is a no-op.

source
AtmosTransport.Tape._CSSweepRecord Type
julia
_CSSweepRecord{FT, T, R, F3, S}

Forward-recorded per-direction advection sweep. direction ∈ (:x, :y, :z), scheme is the advection scheme used, panels_m is the tape slot of the air mass entering the sweep, and panels_tracer the slot of what the scheme's reverse reads of the tracer: nothing for the linear schemes, the limiter branch codes of a monotone or CW84 PPM sweep (six UInt8 panels, read with LimiterCodeRead()), the tracer mass entering an FV3-profile sweep (read with TracerMassRead()). panels_flux is the per-panel face-flux tuple, flux_scale the scaling applied during the subcycle.

source
AtmosTransport.Tape._MmapTapeFile Method
julia
_MmapTapeFile(dir, capacity) -> _MmapTapeFile

Create an anonymous scratch file of capacity bytes in dir: check the file system and its free space, create and unlink the file, reserve the extent and map it. Throws a TapeReservationError with the required and available bytes when the file system cannot hold it, or an ArgumentError naming an unsupported file system. _release_tape_pool! unmaps and closes it (without it, the GC does).

source
AtmosTransport.Tape._free_tape_array! Method
julia
_free_tape_array!(a)

Free the memory of a device array the tape owns now (unsafe_free! on a GPU). A no-op for host arrays, which the GC frees.

source
AtmosTransport.Tape._holds_tape_bytes Method
julia
_holds_tape_bytes(pool, nbytes) -> Bool

Whether an open pool can record a tape of nbytes after a rewind; reserved pools hold at most their reservation.

source
AtmosTransport.Tape._met_window_segments Method
julia
_met_window_segments(schedule::MetWindowCheckpoint, step_windows) -> Vector{UnitRange{Int}}

The segments of schedule over the steps whose met windows are step_windows, in step order, in one pass: each run of equal window indices is one segment, or cld(n, split_steps) nearly equal pieces of its n steps (the first n % pieces one step longer).

source
AtmosTransport.Tape._open_tape_pool Function
julia
_open_tape_pool(storage, nbytes) -> pool

The runtime pool a reverse-pass call records its tapes into, opened from the storage descriptor. This low-level constructor reserves an mmap extent of nbytes. The reverse-pass resolver uses _reserve_tape_pool to allocate the typed slabs or host chunks before running.

source
AtmosTransport.Tape._pin_host_chunk Method
julia
_pin_host_chunk(template, ptr, nbytes) -> registration

Register (page-lock) nbytes of host memory at ptr with the backend of template, once, when a pinned-host arena allocates a chunk. Returns a handle for _unpin_host_chunk, or nothing (CPU panels: nothing to register).

source
AtmosTransport.Tape._release_tape_pool! Function
julia
_release_tape_pool!(pool)

Free the pool's memory now (device arrays, pinned host chunks, the mmap file), not at a later GC; every slot becomes stale. Releasing twice is a no-op.

source
AtmosTransport.Tape._rewind_tape_pool! Function
julia
_rewind_tape_pool!(pool) -> pool

Start a new tape in the pool's memory: the next slots reuse it, and the slots of the previous tape become stale (StaleTapeSlotError on use).

source
AtmosTransport.Tape._stage_computed Method
julia
_stage_computed(fill_panels!, pool, template[, T]) -> slot

Allocate a slot shaped like template (six panels on the source backend) and fill it with fill_panels!(dest), which writes six panels of that shape (a kernel queued on the backend). Device pools accept an element type T, so the source panels can template a code slot without a scratch allocation. A device slot is filled in place; any other pool's slot (host memory) is filled through template as scratch, which is then staged.

source
AtmosTransport.Tape._stage_panels Method
julia
_stage_panels(pool, panels) -> slot

Allocate a slot in pool and copy panels into it.

source
AtmosTransport.Tape._tape_slot_bytes Method
julia
_tape_slot_bytes(panels::NTuple{6}) -> Int64

Bytes one staged state of panels takes in a host pool (each panel padded to the 64-byte alignment). The counting recorder sums these to size an mmap reservation.

source
AtmosTransport.Tape._tape_synchronize Method
julia
_tape_synchronize(template)

Wait for the backend of template (a zero-size array on the source backend) after a device↔host tape copy. A no-op on the CPU.

source
AtmosTransport.Tape._unpin_host_chunk Method
julia
_unpin_host_chunk(registration)

Undo _pin_host_chunk before the chunk is freed.

source
AtmosTransport.Tape.checkpoint_window_count Method
julia
checkpoint_window_count(schedule, nsteps) -> Int

Number of forward windows for schedule covering nsteps integration steps. FullCheckpoint is 1 (the existing single tape); StrideCheckpoint(K) is cld(nsteps, K). MetWindowCheckpoint segments follow the met windows, not a step count.

source
AtmosTransport.Tape.checkpoint_window_range Method
julia
checkpoint_window_range(schedule, window_index, nsteps) -> UnitRange{Int}

Step range covered by window_index (1-indexed) for schedule and a run of nsteps integration steps.

source