Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

CFD-craft

A Rust CFD research solver for incompressible flow and the dispersion of gases and particles around buildings on uniform Cartesian grids, used from Python, a JSON command line or Rust, with tools for city maps and mobile sensor rides and a bounded OpenFOAM Foundation 13 backend for cross-checks.

Version 0.2.0 is a research prototype. A numerically accepted run is not an experimentally validated prediction.

Start here

  • First run: install the Python package and compute one accepted concentration in a few minutes.
  • How do I …?: tasks in plain words, each linked to the section of the guide that does it.
  • CFD-craft, OpenFOAM and Ansys Fluent: what each tool is for, the committed measurements, and where the others are ahead.

What CFD-craft contains

  • Uniform Cartesian grids. Buildings are boxes or prisms with a polygon footprint, written by hand or imported from a GeoJSON or CityJSON map.
  • Laminar flow and one neutral k-epsilon package; optional porous vegetation.
  • Passive gases and particle size classes with settling, deposition and PM2.5 and PM10 sums.
  • Point, line and volume sources; point, volume and path receptors.
  • Bounded runs (steps, wall time, memory, output) with checksummed restart.
  • Strict case and result schemas, listed by cfd-craft describe.
  • Opt-in second-order momentum, implicit steady iteration and pressure multigrid, also with buildings; the defaults are unchanged.
  • Tools for measurement campaigns: wind-direction campaigns, virtual sensor rides, line sources from street data, street emissions inferred from rides, and route selection.
  • An optional, bounded OpenFOAM Foundation 13 backend for two generated cases: a laminar cavity and a turbulent backward-facing step.
  • Optimization examples: a linear program, sensor placement and a coupled-flow design.

What it does not contain

  • Body-fitted or stretched grids, terrain, LES, buoyancy or heat, chemistry or GPU execution.
  • Experimental validation. Every model is numerically verified only.
  • A qualified city-district workflow. Multigrid with buildings gave no consistent gain in run time; a canyon rotated by 45 degrees did not pass its grid study; no wind direction of the district demonstration converged within its short budget; inference from rides is verified on synthetic data of the same model only (urban record, mobile record).

The guide

24 chapters, ordered by difficulty; each starts with its own setup. The guide index lists them and says which interface to use.

  • Part I, First steps: run a case from Python, the case file, the command line and the run archive, how to read a result, sources and receptors.
  • Part II, Flow: a lid-driven cavity, budgets and previews, checkpoint and restart, opt-in numerics, buildings and a street canyon.
  • Part III, Automation: the Python binding in depth, many runs and source inference, optimization lessons, optimization jobs.
  • Part IV, OpenFOAM backend: install and run, compare two solvers and measurements, continuation and mesh initialization, a wall-resolved backstep, a bounded refinement campaign.
  • Part V, Embedding and help: the Rust library, troubleshooting.
  • Part VI, City blocks and mobile measurements: buildings from a map, particles and vegetation, routes and virtual sensor rides, street emissions inferred from rides.

Reference

Case and result schemas, the command line, the Python API, units and conventions, diagnostic codes and model cards: reference.

Evidence

The verification records, the comparisons with OpenFOAM and with measurements, and the optimization lessons’ records, failed rows included: evidence.

Developer

Architecture, the checks before a change, profiling, pressure multigrid, numerics decisions, the roadmap and releasing: developer.

History

Iteration plans as they were written, kept unchanged: history.

For AI agents

The run loop, the rules and the machine-readable entry points: agent entry point.

CFD-craft is one of 18 related repositories; the repository overview shows what each one does.

How do I …?

Tasks in plain words. Each link goes to the section of the guide or the reference that does it; the section starts from the setup of its chapter.

Install and first run

How do I …Section
install CFD-craft for Python?1 Setup
install the cfd-craft command?3 Setup
build from source?3 Setup
choose between Python, the command line and Rust?Guide Which interface
run my first case?1 Run it
run a case from the shell?3 Check, run, report
check a case before I run it?1 Check the case

Cases

How do I …Section
find out which fields a case may have?2 Find the allowed fields; case schema
change a parameter without editing the original case?2 Change a case without touching the original
understand an “unknown field” error?2 A wrong field is an error
know which unit a field has?2 Units and coordinates; units and conventions
know what the groups of a case mean?2 The groups of a case

Results

How do I …Section
read a concentration in micrograms/m3?1 Read a receptor
tell whether a run converged?4 Assessment: what the checks support
tell why a run stopped?4 Termination: why the run stopped
make a script fail on a result that is not accepted?4 Require a verdict in a script
interpret exit code 2?3 Exit codes; 4 An incomplete run is still a result
know what each file in a run directory is?3 The files of a run
verify that a run directory is intact?3 Check, run, report
check the stored fields independently of the solver?3 Check the fields independently
look at the fields in ParaView?3 Look at the fields in ParaView
know whether a result is experimentally validated?4 Experimental validation is a separate label

Sources, receptors, transport

How do I …Section
define a point, line or volume source?5 Three kinds of source, three rate units
convert a line or volume rate to kg/s?5 Three kinds of source, three rate units
add a sensor?5 Point and volume receptors
choose between linear_upwind and muscl?5 MUSCL is sharper and not linear
fix “steady sources need an open boundary” (CFD-E020)?5 A steady source needs a way out
simulate a release that is not steady?5 A release that is not steady
build a source-receptor response matrix?12 Unit responses and superposition
model particle size classes and get PM2.5 and PM10?22 Particle size classes
sample the concentration along a route?23 Declare a path receptor; Read the samples and the mean
turn street emission rates into line sources?24 Street emissions from map data

Flow

How do I …Section
compute a laminar flow with walls and a moving lid?6 The case: walls, a moving lid, one periodic direction
run to a steady state?6 Run to a steady state
run a two-dimensional case?6 Two-dimensional runs
compare a cavity result with the Ghia reference?6 Compare with a numerical reference
test the pressure solver on my grid?6 What the pressure step does

Budgets, preview, restart

How do I …Section
estimate memory and output before a run?7 What check estimates
limit steps, wall time, memory or threads?7 Budgets are part of the case
try a case on a coarser grid first?7 Preview on a coarser grid
understand why a preview was refused?7 When a preview is refused
stop a run at a wall-time limit?7 Stop on a time limit
cancel a run and keep what it computed?7 Cancel a run
resume an interrupted run?8 Stop by work, then resume
show that a restart reproduces the uninterrupted run?8 Is the resumed run the same run?
know which case changes keep a checkpoint usable?8 What a checkpoint fits

Opt-in numerics

How do I …Section
get second-order accuracy for momentum?9 Second-order momentum advection
make a steady run converge in fewer iterations?9 Implicit steady iteration; The implicit recipe
use multigrid for the pressure equation?9 Multigrid for the pressure equation
see where the solver spends its time?9 Where the time goes: profile

Buildings and canyons

How do I …Section
add buildings?10 The case: boxes, open top, wind
set the wind direction?10 The case: boxes, open top, wind; Another wind direction
model a traffic line source in a street?10 The case: boxes, open top, wind
understand warnings CFD-W001 to CFD-W003?10 Read the warnings before the result
speed up a canyon run?10 The same steady state faster
know what a coarse canyon result does not show?10 What this result is not
run all canyon scenarios as one study?10 All committed scenarios in one study
describe a building with a polygon footprint?22 A building with a polygon footprint
see how well the grid represents a building?22 A building with a polygon footprint
import buildings from a GeoJSON or CityJSON map?22 Import buildings from a map
add a hedge or trees?22 Hedges and trees
use multigrid with buildings?22 Multigrid with buildings
run a wind-direction campaign?22 One case, twelve wind directions
know what a city-block result does not show?22 What these results are not

Python and automation

How do I …Section
catch invalid input in Python?11 Errors carry diagnostics
pass a case as a dictionary, string or bytes?11 Inputs: dictionary, string or bytes
cancel a simulation from Python?11 Cancel from Python
run several simulations at once from Python?11 Threads, the GIL and concurrent calls
script the command line with subprocess?11 Drive the CLI from Python
write an objective function that is allowed to fail?12 A fallible objective
infer source strengths from sensor readings?12 What sensors identify: the source-inference study
check transport against an independent solver?12 An independent reference solve
decide between an LP and a black-box optimizer?13 F1: a linear problem hides in the simulator
choose sensor locations?13 F2: coverage is not identifiability
optimize a flow setting without exploiting a coarse grid?13 F3: a design must survive a finer grid
run CFD-craft as an optimization job?14 Run the four jobs
build and inspect the fcmaes worker?14 The application worker
run wind directions as optimization jobs?14 Wind-direction jobs for a city block
give an agent a bounded task?Agent entry point; A task for an agent in chapters 10, 12, 14, 16, 18, 19, 23

Mobile measurements

How do I …Section
simulate a sensor ride through a computed field?23 Simulate a ride
check path samples independently of the solver?23 Check the path independently
infer street emissions from rides?24 The smallest study
compute the response of rides to each street on one flow?24 One flow, one transport run per street
fit my own ride observations?24 Fit your own observations
find out which streets the rides cannot tell apart?24 Which streets can be told apart
plan how many passes a street needs?24 How many passes a street needs
choose routes under a time budget?24 Which routes under a time budget
know what a virtual ride or a fitted rate does not show?23 What a virtual ride is not; 24 What this is not

OpenFOAM backend

How do I …Section
install the pinned OpenFOAM runtime?15 Install the pinned runtime
run an OpenFOAM cavity through the adapter?15 Generate, run and inspect
compare the native solver and OpenFOAM on one case?16 Two solvers against a numerical reference
compare OpenFOAM with backstep measurements?16 One solver against measurements
time both solvers fairly?16 Time both backends on one host
continue a long steady OpenFOAM solve?17 Continue on the same mesh
start a finer mesh from a coarse result?17 Start a finer mesh
audit mesh, face flux and y+ of a backstep run?18 Audit mesh, flux and y+
run a bounded refinement campaign?19 Run the campaign

Rust, help, evidence

How do I …Section
use the solver as a Rust library?20 Depend on the crate; Solve in process
read a run archive from Rust?20 Read a CLI archive
find what a diagnostic code means?Diagnostics; 21 By symptom
find the measurement behind a number?Evidence; comparison
run the documentation check myself?Run the documentation check

CFD-craft, OpenFOAM and Ansys Fluent

Version 0.2.0 is a research prototype. A numerically accepted run is not an experimentally validated prediction.

This page compares CFD-craft with OpenFOAM (Foundation version 13, package 20260407; version 14 was released in July 2026 [O13], but the bounded backend pins 13) and, for features only, with Ansys Fluent (public documentation of Release 2026 R1). It was checked on 14 November 2026.

The short answer: OpenFOAM and Fluent cover far more physics, far more mesh and geometry types and far larger problems. CFD-craft covers one narrow task, neutral dispersion of gases and particles on uniform grids around box-like buildings, with scripts from a city map to a simulated sensor ride, and puts its effort into checked input, stated stopping reasons and recomputed evidence.

Every speed and accuracy number on this page comes from one case: the laminar, two-dimensional Re = 100 lid-driven cavity. None of it says anything about urban flows. There is no OpenFOAM canyon recipe, so no canyon comparison exists, and no particle, vegetation or district result has been compared with another code.

What CFD-craft is for

These properties can be checked in this repository:

  • One strict JSON case. A run is defined by one file. Unknown fields, unsupported variants and duplicate keys are rejected (case schema, result contract).
  • Coded diagnostics with field paths. cfd-craft check reports every problem with a code and the path of the field, for example CFD-E008 at run.threads and CFD-E010 at numerics.advective_cfl_max, and exits 1 (diagnostics, command line, guide chapter 2).
  • Budgets and a stated stopping reason. The case sets step, wall-time, memory and output budgets. SIGINT or SIGTERM ends a CLI run as cancelled; it still writes its archive and exits 2. The result names why the run stopped (termination) (case schema, Run, guide chapter 7).
  • Three separate verdicts. Termination (did the run complete?), numerical assessment (is the result accepted?) and experimental validation (describe reports not_validated) are separate fields (result contract, Status, guide chapter 4).
  • Provenance hashes. Every archive has a manifest with file hashes, the input case hash, the initial-state hash and source, executable and build identity, plus a completion marker written last (result contract, Files).
  • An independent field checker. validation/check_fields.py recomputes continuity, mass accounting, receptor values, building masks, deposition and path samples from the stored fields.
  • A bounded OpenFOAM backend as a cross-check. The same cavity runs through OpenFOAM Foundation 13 with recorded executable hashes (OpenFOAM backend model card).

Features

Cells about other tools are facts from their current public documentation (sources at the end). “None documented” names the pages read that do not describe the feature; it says nothing about features those pages do not cover. The Fluent column is features only: this repository has no Fluent measurement.

FeatureCFD-craftOpenFOAM Foundation 13Ansys Fluent 2026 R1
License and sourceMIT, source on GitHub (LICENSE)GNU GPL version 3, source pack published [O1]Licensed product; PyFluent needs a licensed local Fluent installation [F8]
Installpip install cfd-craft (Python binding) or cargo install cfd-craft-cli (releasing)Packages for Ubuntu 22.04, 24.04 and 25.04; Windows through WSL; macOS through Multipass; source pack [O1]Installers for Linux x64 (Red Hat, SUSE, Ubuntu 22.04 and 24.04, Rocky) and Windows 11 or Server 2022 and 2025 [F13, F14]; a license is required [F8]
Case definitionOne strict JSON file (case schema)A case directory of text dictionaries: system, constant, time directories [O5]GUI, text console in Scheme, journal files [F1, F6]; Python through PyFluent [F8]
Input check before a runcheck: coded diagnostics with field paths, memory and output estimates (diagnostics, chapter 2)checkMesh checks a mesh [O6]; a whole-case check is not documented in [O5, O6, O7, O11]Mesh check (topology, face handedness, volumes) and a case check of models, boundaries and solver settings with recommendations [F18, F19]
MeshUniform Cartesian only (flow model card)Arbitrary polyhedral cells; blockMesh, snappyHexMesh [O2, O6]Triangle to polyhedral cells; structured, unstructured, hybrid, non-conformal and overset meshes [F2]
Geometry and map importAxis-aligned boxes and vertical prisms with a polygon footprint, represented by whole cells of the uniform grid: no cut cells, no terrain (chapter 10, chapter 22); a converter for projected GeoJSON and CityJSON building footprints (chapter 22)snappyHexMesh refines and snaps to surface geometry [O6]CAD and STL import in meshing mode; watertight-geometry and fault-tolerant meshing workflows [F15, F16]
Flow modelsConstant-density incompressible: prescribed uniform, laminar, neutral RANSIncompressible, compressible, density-based, multiphase (VoF, Euler), films [O3]Pressure-based and density-based solvers [F4]; hypersonic, moving frames, dynamic meshes [F1]
TurbulenceOne neutral k-epsilon package with wall functions; no LES (flow model card)RAS (k-epsilon, k-omega SST, Reynolds stress and others), LES, DES [O4]Spalart-Allmaras, k-epsilon, k-omega, transition, Reynolds stress, SAS, DES, LES [F3]
Scalar transportPassive gases and particle size classes; point, line and volume sources; point, volume and path receptors; audited mass budget (transport model card)scalarTransport function object; multicomponent flow module [O3, O8]Species transport [F1]
Other physicsOpt-in, numerically verified and not validated: spherical particle size classes transported as concentrations, with settling and deposition on ground, roofs and leaves (chapter 22); porous vegetation with drag and canopy turbulence terms (chapter 22). No buoyancy, heat transfer, chemistry, multiphase or compressibilityHeat transfer, combustion, Lagrangian particles, multiphase, solids [O1, O3]Heat transfer, combustion, pollutants, discrete phase, multiphase, FSI, batteries and more [F1]
Steady algorithmExplicit pseudo-time (default); SIMPLEC-type implicit_projection (opt-in) (flow model card)SIMPLE for steady cases, PIMPLE, local pseudo-time stepping [O7, O9]SIMPLE, SIMPLEC, PISO, Fractional Step, Coupled [F4]; pseudo time method [F4]
Momentum advectionFirst-order donor-cell (default); second-order upwind, limited with van Albada, van Leer or monotonized central (opt-in)Upwind, linear, linearUpwind, LUST, limitedLinear and other schemes [O9]First- and second-order upwind, QUICK, third-order MUSCL, bounded central [F5]
Pressure solverIC(0)-preconditioned CG (default); geometric multigrid (opt-in) (pressure multigrid), also with buildings, where it cut pressure iterations but gave no consistent gain in run time (chapter 22)PCG or PBiCGStab with DIC, FDIC or GAMG preconditioning; GAMG solver [O7]Algebraic multigrid in the pressure-based and density-based implicit solvers [F17]
ParallelismThreads on one machine (1 to 64); no MPI, no GPU (chapter 7)MPI domain decomposition (decomposePar, Open MPI by default) [O10]MPI across compute nodes [F9]; native GPU solver on one or several GPUs [F10]
Budgets and cancellationSteps, wall time, memory and output in the case; signal or cancel file stops cleanly (chapter 7)End time; stopAtClockTime and stopAtFile function objects [O8, O11]Number of iterations and convergence conditions; the Stop button or Ctrl+C interrupts after the current iteration [F20, F21]; a wall-time budget is not documented there
What a result reportsTermination, assessment, recomputed checks, validation label (result contract, chapter 4)Logs and function-object output such as residuals and probes [O8]Convergence monitors and conditions [F4]; simulation reports [F1]
RestartChecksummed checkpoint bound to a physics hash (chapter 8)Start from the latest written time directory [O11]Case and data files together restart a solution [F7]
ProvenanceCase, physics, initial-state, source and executable hashes in a manifestEach data file has a header naming format, class and file; no hash or build record is documented in [O17]; output goes to a log by redirection [O16]Transcript files record a session [F6]; file hashes are not documented in [F6, F7]
Scripting and machine-readable interfaceIn-process Python, JSON command line, Rust library (Python API, chapters 11 and 20); describe prints the case and result schemas and exit codes as JSON (agent entry page)Command-line utilities; foamDictionary reads and edits dictionary entries [O6]; a Python interface is not documented in [O6, O12, O16]PyFluent Python library [F8]; Scheme text commands and journals [F6]
Post-processingVTK export for ParaView; no built-in viewer (chapter 3)ParaView reader, foamToVTK, writeVTK [O6, O8, O12]Built-in graphics and reports; export to EnSight and CFD-Post [F1, F6]
Experimental validationNone: not_validated; canyon data not available (data inventory, evidence index)Comparison with measurements is not documented in the tutorial pages [O14, O15]Verification manual: 78 Fluent and CFX cases against theory or published experiments [F11]
MaturityFirst version 0.1.0, 4 November 2026 (changelog)Major versions every July since at least 2017; 13 in July 2025, 14 in July 2026 [O1, O13]Releases 2024 R2, 2025 R1, 2025 R2 and 2026 R1 are supported by PyFluent [F8]
Measurement-campaign supportScripts, verified on synthetic data only: a wind-direction campaign that keeps failed rows (chapter 22), virtual sensor rides along a route (chapter 23), line sources from supplied street rates, emission rates fitted to rides with a rank report, pass planning and route selection (chapter 24)Probes and graph function objects sample fields at points and along lines [O8]; a moving sensor, source inference from measurements and route planning are not documented in [O8]Not documented in the chapter list of the user’s guide [F1]
OptimizationOptimization-job worker and fcmaes adapter (chapter 14); LP, MIP and black-box lessons (chapter 13)Not documented in the v13 user guide [O12]Adjoint solver, gradient-based optimizer, mesh morphing [F12]

Measured against OpenFOAM: the Re = 100 cavity

All measurements below are committed records listed in the evidence index. No new measurement was made for this page. Accuracy is the largest centerline-velocity difference from the Ghia et al. numerical reference, in units of the lid speed; it is a numerical reference, not an experiment. “Solver time” and “workflow time” are defined in each record. Both backends use one solver thread.

Default numerics (donor-cell momentum, explicit pseudo-time).

  • The backend comparison found OpenFOAM’s whole workflow 5.502 times faster than native steady mode on an AMD EPYC 9V74 virtual machine (Python 3.12) and 4.692 times faster on a GitHub runner (AMD EPYC 9V45, 4 CPUs, ubuntu-24.04, Python 3.12, run 41195406078); its solver process was 8.895 and 8.88 times faster. The record gives no date and no OpenFOAM version; it ran the adapter’s pinned runtime.
  • In the same backend comparison OpenFOAM was closer to the reference at 24×24 cells: 0.0090 against 0.0276 for native steady mode.
  • In Stage V (1 November 2026; AMD EPYC 9V74, Rust 1.88.0, Python 3.12.14, pinned OpenFOAM Foundation 13 package; native with the opt-in multigrid pressure preconditioner, which does not change the discretization) OpenFOAM reached 0.01 at 24² and native missed it on all four shared grids (16² to 48²). A separate native 96² run reached 0.00920541; among the tested grids that is the first native grid under 0.01. Its solver work was about 1076.02 s on the recording host; a cold run on a GitHub runner was accepted after 825.9 s.
  • The pressure multigrid results (31 October 2026; AMD EPYC 9V74, Rust 1.88.0) show that the opt-in multigrid preconditioner cut the accepted native 48² solver time from 180.665 s to 74.108 s with the default momentum scheme and explicit pseudo-time; the accuracy (0.01695144) did not change.
  • With default numerics the pressure projection took 77.92 % of native solver time on the 24² cavity and 88.34 % in one profiled 48² run (gap baseline, 31 October 2026; AMD EPYC 9V74, rustc 1.99.1, OpenFOAM Foundation 13 package 20260407).

Opt-in numerics. None of these settings is the default.

  • Opt-in second-order momentum advection brought the native 24² difference to between 0.00494 and 0.00589, depending on the limiter, and van Leer to 0.00544 (second-order momentum, 1 November 2026; native only, a 2-vCPU Intel Xeon virtual machine).
  • With second-order momentum but the default explicit pseudo-time, native took 13.25 times OpenFOAM’s solver time at 24² (11.19 s against 0.844 s) (matched accuracy, 1 November 2026, run 41346827479, AMD EPYC 7763, 4 CPUs).
  • With second-order momentum, the opt-in implicit_projection steady algorithm and the opt-in multigrid pressure preconditioner both backends first reached 0.01 at 24²; native took 0.74 times OpenFOAM’s solver time and 0.45 times its workflow time, at 0.0054 against 0.0090 (matched accuracy, 1 November 2026, run 41345659321, Intel Xeon Platinum 8370C, 4 CPUs).
  • With the final implicit recipe (pressure tolerance 0.1, a non-binding time-step cap, one span cell), native took 0.111 times OpenFOAM’s solver time (0.0698 s against 0.628 s) and 0.119 times its workflow time at 24², at 0.00543 against 0.00897 (performance iterations, 1 November 2026, run 41361132558, AMD EPYC 9V74, 4 CPUs; also in matched accuracy).

Memory. Native peak memory was 851.7 MiB for one million cells in a three-step canyon run on a 2-core Intel Xeon virtual machine with rustc 1.97.0 (native verification; the record gives no date). There is no OpenFOAM memory measurement beside it.

Limits of these comparisons.

  • The two configurations differ: the stopping rules differ (native assess gates, OpenFOAM residualControl 1e-7), and in run 41345659321 native computed two span cells and OpenFOAM one (matched accuracy, Scope). The ratios describe these recipes on these runners.
  • Every ratio is one thread against one thread. OpenFOAM supports MPI decomposition; the CFD-craft adapter runs it serially. Nothing about multi-core scaling follows (backend comparison).
  • Native canyon timings exist only for native: with the implicit recipe a 27k-cell canyon with its tracer took 57.6 s and a 93k-cell canyon 615 s on a 2-vCPU Intel Xeon virtual machine, and the canyon is not grid-converged (performance iterations, implicit RANS).
  • The backstep runs compare OpenFOAM with measurements, not one solver with another, and they were not numerically accepted (external backend).

Ansys Fluent

Fluent is a licensed commercial CFD code [F8]. Its public 2026 R1 user’s guide covers pressure-based and density-based solvers, structured, unstructured, hybrid, polyhedral, non-conformal and overset meshes, a wide range of turbulence models from Spalart-Allmaras to LES, and many physics modules (heat transfer, species transport and combustion, discrete particles, multiphase, fluid-structure interaction). It runs in parallel with MPI and has a native GPU solver. It is scripted with Scheme text commands, journal files and the PyFluent Python library, and it includes an adjoint solver for shape optimization.

This repository has no Fluent run. The page therefore makes no speed or accuracy statement about Fluent. Every Fluent cell rests on the public 2026 R1 documentation; the Ansys product pages redirected to a domain that could not be fetched.

Urban-dispersion tools

Practitioners in urban air quality also use dedicated tools. PALM is a large-eddy simulation model for atmospheric and oceanic boundary layers, built for massively parallel computers; its PALM-4U components add urban features such as radiation, land surface and chemistry, it is free software under the GPL version 3, and release 25.10 was presented in April 2026 [U1, U2, U3]. ENVI-met is commercial three-dimensional microclimate software that simulates wind, heat, humidity, radiation, vegetation and pollutant dispersion in cities [U4]. CFD-craft has neither LES nor thermal physics and is not a substitute for either.

Where the others are ahead

  • Physics. OpenFOAM and Fluent model heat transfer, compressible and multiphase flow and combustion [O3, F1]. CFD-craft has none of these, so it has no thermal effects such as buoyancy or stratification.
  • Particles and canopies. OpenFOAM tracks Lagrangian particle clouds and Fluent has a discrete phase model [O3, O8, F1], and porous zones are documented for Fluent [F1]. CFD-craft has concentration bins of spherical particles and one porous canopy model, both verified against analytic cases only and not validated.
  • Turbulence. They offer many RANS models plus LES and DES [O4, F3]. CFD-craft has one neutral k-epsilon package and no LES.
  • Geometry and meshing. They use unstructured and polyhedral meshes fitted to surface geometry [O2, O6, F2]. CFD-craft has uniform Cartesian grids on flat ground, without terrain; a slanted wall becomes a staircase of cells, and a canyon rotated by 45 degrees did not pass its grid study (urban record).
  • Validation. Fluent publishes a verification manual with cases against published experiments [F11]; the OpenFOAM v13 tutorial pages do not document a comparison with measurements [O14, O15]. CFD-craft has no experimental validation.
  • Community and maturity. OpenFOAM has released a major version every year since at least 2017 [O13], and Fluent names an R1 and an R2 release in each of 2025 and 2026 [F8]. CFD-craft had its first release on 4 November 2026.
  • Parallel scaling. Both run in parallel with MPI [O10, F9]; Fluent also on GPUs [F10]. CFD-craft uses threads on one machine.

Version 0.2.0 is a research prototype. A numerically accepted run is not an experimentally validated prediction.

When to use which

  • A real geometry, real physics or a result for a decision: OpenFOAM or Fluent.
  • Urban microclimate, heat or LES of a city quarter: PALM or ENVI-met.
  • Many small, scripted, checkable dispersion runs around box-like buildings, for example inside an optimizer or to plan a measurement campaign before any data exist: CFD-craft.
  • Testing what an agent or a script does with a CFD tool, with coded errors and stated stopping reasons: CFD-craft.
  • Checking a CFD-craft cavity result against an established code: the bounded OpenFOAM backend.

Sources

All checked on 14 November 2026.

IdToolClaimsURL
O1OpenFOAMVersion 13 release: license, platforms, physicshttps://openfoam.org/release/13/
O2OpenFOAMPolyhedral cells (v13 user guide)https://doc.cfd.direct/openfoam/user-guide-v13/mesh-description
O3OpenFOAMSolver modules (v13)https://doc.cfd.direct/openfoam/user-guide-v13/solvers-modules
O4OpenFOAMTurbulence models (v13)https://doc.cfd.direct/openfoam/user-guide-v13/turbulence
O5OpenFOAMCase file structure (v13)https://doc.cfd.direct/openfoam/user-guide-v13/case-file-structure
O6OpenFOAMUtilities: checkMesh, snappyHexMesh, foamDictionary, foamToVTK (v13)https://doc.cfd.direct/openfoam/user-guide-v13/standard-utilities
O7OpenFOAMLinear solvers, SIMPLE and PIMPLE (v13)https://doc.cfd.direct/openfoam/user-guide-v13/fvsolution
O8OpenFOAMFunction objects: scalarTransport, stop, residuals, probes, graphs, particles, writeVTK (v13)https://doc.cfd.direct/openfoam/user-guide-v13/post-processing-functionality
O9OpenFOAMDiscretization schemes (v13)https://doc.cfd.direct/openfoam/user-guide-v13/fvschemes
O10OpenFOAMParallel running (v13)https://doc.cfd.direct/openfoam/user-guide-v13/running-applications-parallel
O11OpenFOAMRun control and restart (v13)https://doc.cfd.direct/openfoam/user-guide-v13/controldict
O12OpenFOAMParaView chapter (v13 contents)https://doc.cfd.direct/openfoam/user-guide-v13
O13OpenFOAMRelease dates of versions 13 and 14https://openfoam.org/category/release
O14OpenFOAMTutorials (v13)https://doc.cfd.direct/openfoam/user-guide-v13/tutorials
O15OpenFOAMBackward-facing step tutorial (v13)https://doc.cfd.direct/openfoam/user-guide-v13/backwardstep
O16OpenFOAMRunning applications, log files (v13)https://doc.cfd.direct/openfoam/user-guide-v13/running-applications
O17OpenFOAMFile header format (v13)https://doc.cfd.direct/openfoam/user-guide-v13/basic-file-format
F1FluentUser’s guide 2026 R1, chapter listhttps://ansyshelp.ansys.com/public/Views/Secured/corp/v261/en/flu_ug/pt03.html
F2FluentCell shapes and mesh topologieshttps://ansyshelp.ansys.com/public/Views/Secured/corp/v261/en/flu_ug/flu_ug_GridTypes.html and https://ansyshelp.ansys.com/public/Views/Secured/corp/v261/en/flu_ug/flu_ug_chp_grid.html
F3FluentTurbulence modelshttps://ansyshelp.ansys.com/public/Views/Secured/corp/v261/en/flu_ug/flu_ug_chap_turbulence.html
F4FluentSolver types, coupling, pseudo time, convergencehttps://ansyshelp.ansys.com/public/Views/Secured/corp/v261/en/flu_ug/flu_ug_chp_solve.html and https://ansyshelp.ansys.com/public/Views/Secured/corp/v261/en/flu_ug/flu_ug_sec_uns_solve_pvel_1.html
F5FluentConvection schemeshttps://ansyshelp.ansys.com/public/Views/Secured/corp/v261/en/flu_ug/flu_ug_sec_solve_choose_disc.html
F6FluentText interface, journal files, exporthttps://ansyshelp.ansys.com/public/Views/Secured/corp/v261/en/flu_ug/flu_ug_chp_tui.html and https://ansyshelp.ansys.com/public/Views/Secured/corp/v261/en/flu_ug/flu_ug_chp_files.html
F7FluentCase and data files, restarthttps://ansyshelp.ansys.com/public/Views/Secured/corp/v261/en/flu_ug/flu_ug_CaseDataFiles.html
F8FluentPyFluent, license requirement, supported releaseshttps://pypi.org/project/ansys-fluent-core
F9FluentParallel processinghttps://ansyshelp.ansys.com/public/Views/Secured/corp/v261/en/flu_ug/flu_ug_parallel_intro.html
F10FluentNative GPU solverhttps://ansyshelp.ansys.com/public/Views/Secured/corp/v261/en/flu_ug/flu_ug_sec_gpu_solver_intro.html
F11FluentVerification manual 2026 R1https://ansyshelp.ansys.com/public/Views/Secured/corp/v261/en/fbu_vm/vmflintrochp.html
F12FluentAdjoint solver and optimizerhttps://ansyshelp.ansys.com/public/views/secured/corp/v261/en/flu_ug/flu_adj_usage.html
F13FluentLinux installation prerequisites, 2026 R1https://ansyshelp.ansys.com/public/Views/Secured/corp/v261/en/installation/unix_sysprereqs.html
F14FluentWindows installation prerequisites, 2026 R1https://ansyshelp.ansys.com/public/views/secured/corp/v261/en/installation/win_sysprereqs.html
F15FluentMeshing mode, CAD formatshttps://ansyshelp.ansys.com/public/views/secured/corp/v261/en/flu_ug/ch09s01.html and https://ansyshelp.ansys.com/public/Views/Secured/corp/v261/en/flu_ug/pt02.html
F16FluentWatertight and fault-tolerant workflowshttps://ansyshelp.ansys.com/public/Views/Secured/corp/v261/en/flu_ug/tgd_user_workflow_guided_watertight.html and https://ansyshelp.ansys.com/public/Views/Secured/corp/v261/en/flu_ug/tgd_user_workflow_guided_fault.html
F17FluentMultigrid methods (theory guide)https://ansyshelp.ansys.com/public/Views/Secured/corp/v261/en/flu_th/flu_th_MultigridMethod.html
F18FluentMesh checkhttps://ansyshelp.ansys.com/public/Views/Secured/corp/v261/en/flu_ug/flu_ug_GridCheck.html
F19FluentCase checkhttps://ansyshelp.ansys.com/public/Views/Secured/corp/v261/en/flu_ug/flu_ug_sec_solve_check.html
F20FluentSteady calculation, interruptinghttps://ansyshelp.ansys.com/public/Views/Secured/corp/v261/en/flu_ug/flu_ug_sec_solve_calc.html
F21FluentConvergence conditionshttps://ansyshelp.ansys.com/public/Views/Secured/corp/v261/en/flu_ug/flu_ug_convergence_conditions.html
U1PALMModel overview and PALM-4U (GMD, 2020)https://gmd.copernicus.org/articles/13/1335/2020/
U2PALMDescription and licensehttps://docs.csc.fi/apps/palm
U3PALMRelease 25.10 talk, April 2026https://tu-dresden.de/tu-dresden/veranstaltungen/veranstaltungskalender/zih-kolloqium/zih-kolloquium-the-palm-model-system-release-25-10-an-les-code-for-basic-and-environmental-research-capabilities-and-recent-applications
U4ENVI-metProduct description and licenseshttps://www.envi-met.com/software

Not fetched: the Ansys Fluent product pages (ansys.com/products/fluids/ansys-fluent, product updates and capabilities) redirect to a domain this check could not reach. The OpenFOAM v13 documentation pages are hosted by CFD Direct and linked from the Foundation site.

Agent entry point

CFD-craft is a CPU research solver for constant-density incompressible flow and the dispersion of gases and particles around buildings on uniform Cartesian grids. A case is one strict JSON file; a run is bounded and reports why it stopped, what its numerical checks support and an experimental-validation label. Scripts turn a city map and street data into a case and turn an accepted run into virtual sensor rides and estimates of street emissions. An optional adapter runs two generated cases on OpenFOAM Foundation 13 for cross-checks.

Version 0.2.0 is a research prototype. A numerically accepted run is not an experimentally validated prediction.

The run loop

Commands run from the root of a checkout, with the built command on PATH (cargo build --release --locked, then export PATH="$PWD/target/release:$PATH") and the packages of requirements-validation.txt installed. Without a checkout, pip install cfd-craft gives check and simulate in Python (chapter 1), but no fields or archives.

  1. Discover. cfd-craft describe prints the schemas, the allowed values and the exit codes.
  2. Choose or edit a case. Start from a committed case under cases/ or examples/manual/; write edits to a new file. For a city block, let integrations/urban_map.py write the case from a map and integrations/traffic_sources.py add line sources from supplied street rates; read their provenance files (assumed heights, dropped buildings, omitted streets) before you go on.
  3. Check. cfd-craft check CASE exits 1 on invalid input and prints each diagnostic with a code and the path of the offending field. Read all of them, warnings included, and check again after a fix: a parse error is reported alone, and the checks that need the grid run only when no other error is left.
  4. Bound the run. Set run.max_steps, run.wall_time_limit_s, run.threads, run.memory_limit_mib and output.max_total_mib. Choose a new output directory whose parent exists.
  5. Run. cfd-craft run CASE --output NEW_DIR. Read termination, assessment, every entry of checks and experimental_validation in summary.json.
  6. Verify. cfd-craft report NEW_DIR checks the archive against its hashes. python validation/check_fields.py NEW_DIR recomputes continuity, mass balances and receptor values from the stored fields, and also the building masks, deposition, vegetation drag and path samples of a case that has them.
  7. Derive, only from an accepted run. integrations/virtual_ride.py computes a sensor ride along a path receptor; tutorials/mobile_measurements.py builds a ride response matrix on one frozen flow per wind, fits street emissions and selects routes; validation/urban_campaign.py repeats steps 3 to 6 for twelve wind directions. The ride and study tools refuse a run that is not accepted; the study and the campaign keep failed rows.
cfd-craft describe > runs/describe.json
cfd-craft check examples/manual/point-source.json > runs/check.json
cfd-craft run examples/manual/point-source.json --output runs/point > /dev/null
cfd-craft report runs/point > /dev/null
python validation/check_fields.py runs/point > runs/fields-check.json
import json

s = json.load(open("runs/point/summary.json"))
print(s["termination"], s["assessment"], s["model_scope"])
print(all(c["passed"] for c in s["checks"]), s["experimental_validation"])
tracer = next(c for c in s["constituents"] if c["id"] == "tracer")
print(f"R_down = {tracer['receptors_kg_m3']['R_down'] * 1e9:.6g} micrograms/m3")
print("fields check passed:", json.load(open("runs/fields-check.json"))["passed"])
completed steady_discrete_solution prescribed_flow_passive_transport
True not_validated; see validation/data-inventory.json
R_down = 17.8118 micrograms/m3
fields check passed: True

Outputs on this page are real. The documentation check compares floating-point numbers with a relative tolerance of 1e-4; everything else must match exactly.

Rules

  • Use only the fields that describe lists. Do not invent fields from older proposals; an unknown field is an error (CFD-E000).
  • Never weaken a tolerance or a gate after a failure.
  • Keep failed and incomplete rows in every report, with their actual work counts.
  • completed is not accepted, and accepted is not validated. An iteration or time limit is incomplete even when some checks pass.
  • Exit 0 of report means an intact archive, not convergence.
  • Look up constituents and receptors by ID, never by position: receptor maps are sorted as text (R10 before R2).
  • Never write into a run directory, and never reuse one.
  • Never turn an earlier saved state of a failed run into a final result.
  • Compare settings only with the same source, geometry, sampling and numerical-fidelity definitions.
  • The canyon cases are illustrative research cases on a coarse grid, not a reproduction of a wind-tunnel experiment.
  • A campaign or study that finished is not a set of accepted results. Read accepted of every direction and the checks of every study; a timeout stays incomplete even when a mass balance closes.
  • Never invent an input that a tool asks for: building heights, emission rates, sensor noise and wind frequencies are supplied or reported as assumptions. No tool moves a source, a route or a receptor out of a solid.
  • A virtual ride is a pass through a steady mean field of the declared sources: no turbulence, no background, no measured sensor.
  • When a response matrix is rank deficient, report the ambiguous combination of streets; do not interpret their individual rates.
  • Particle, vegetation and path results carry the same three labels as every result. None is experimentally validated, and inference from rides is verified on synthetic data of the same model only.

Machine-readable entry points

Entry pointWhat it gives
cfd-craft describeJSON with case_schema, result_schema, phase_profile_schema, exit_codes, the allowed physics, scalar_advection, momentum_advection, steady_algorithms, pressure_preconditioners, geometry_kinds and receptor_kinds, the path_sampling limits, the defaults, limitations and the build identity
python -m cfd_craft describeFrom the Python package: the same case_schema and result_schema, the binding’s capabilities and its build identity. It has no exit_codes, value lists or limitations
cfd-craft check CASEcfd-craft.check/0.1: valid, cells, size estimates and diagnostics, each with code, severity and path
summary.json of a runcfd-craft.result/0.1: termination, assessment, checks, model_scope, experimental_validation, work counts, receptor values in kg/m3; per constituent also paths, deposited_kg and deposition_rate_kg_s; particulate_matter, vegetation and frozen_flow where they apply
geometry.json of a runCell counts, the mask hash and, per building under shapes, exact and represented volume and the narrowest street in cells
map-provenance.json, traffic-provenance.jsoncfd-craft.map-provenance/1, cfd-craft.traffic-provenance/1: input hashes, license, crop, rotation, assumed heights, dropped buildings, kept and omitted street lengths, the exit code of check
Output of virtual_ride.pycfd-craft.virtual-ride/0.1: parameters, times, positions, steady_field_kg_m3, sensor_kg_m3 and the hashes of the run it read
report.json of the mobile studycfd-craft.mobile-study-result/1: passed, gate_checks, inference (multipliers, rank, ambiguous combinations), pass_count_planning, route_selection
report.json of the wind campaigncfd-craft.urban-report/1: one row per direction with accepted, and within_budget
Exit codes0 success (valid case, accepted run, intact archive); 1 invalid input or an execution or I/O error; 2 a run without numerical acceptance, or an accepted run that omitted files over its output budget
DiagnosticsEvery CFD- code with its meaning; the scripts report CFD-M001 (map), CFD-M002 (streets), CFD-M003 (inference) and CFD-M004 (ride); the wind campaign reports an error text per row

Generated pages: case schema, result schema, command line, Python API; also the result contract.

Conventions that cause wrong cases

  • Coordinates are east, north, up, in meters. A meteorological wind direction is where the wind comes from, clockwise from north: 270 blows toward +x.
  • Stored pressure is kinematic pressure (m2/s2). In RANS cases the isotropic turbulent pressure is absorbed into it.
  • A point source declares kg/s, a line source kg/s per meter, a volume source kg/s per cubic meter. The solver integrates the represented support and rejects sources inside solids.
  • Use linear_upwind for an exact source-response matrix; the MUSCL limiter makes transport nonlinear.
  • A steady source needs an open boundary. A closed or fully periodic domain with a steady source has no steady solution (CFD-E020).
  • Give a trace gas its molecular diffusivity (of order 1e-5 m2/s). In RANS cases the turbulent diffusivity does the mixing; a large constant hides it.
  • Point receptors interpolate from cell centers and reject stencils through a wall; volume receptors integrate the exact overlap. A path receptor takes east and north coordinates and one height; its samples are at most sample_spacing_m apart, and a segment through a building is an error.
  • A building is a set of whole cells: a cell is solid when its center lies in the box or footprint. Read shapes in geometry.json for the volume error and the street width in cells.
  • A particle diameter_m is in meters (1e-6 is one micrometer). PM2.5 and PM10 are sums of whole bins by aerodynamic diameter.
  • A vegetation volume is fluid with drag, not a solid. A volume without a fluid cell center has no effect and draws no message.
  • A converted map is rotated. flow.direction_deg_from is in the model frame; map-provenance.json keeps the map direction and rotation_deg.

Units of every field: units and conventions.

Where to find what

TaskWhere
Run a first case from PythonFirst run
Read the files of a run directoryThe files of a run
Decide whether a result can be usedCan I trust this result?
Budgets, preview, cancellationBefore you spend compute
Resume a stopped runCheckpoint and restart
Buildings and a street canyonBuildings and a street canyon
Polygon footprints, a map, particles, vegetation, wind-direction campaignUrban geometry, particles and vegetation
Sample along a route, simulate a sensor rideMobile paths and virtual rides
Street emissions from rides, passes, routesSource inference and route selection from rides
Many runs, source inferenceMany runs
OptimizationOptimization lessons, optimization jobs
A diagnostic or an unexpected exitTroubleshooting
Any other taskHow do I …?

Chapters 10, 12, 14, 16, 18, 19 and 23 end with a section “A task for an agent”: a bounded task with its budgets and interpretation rules.

Opt-in numerics

The defaults are donor-cell momentum, explicit pseudo-time and an IC(0) pressure preconditioner, and they stay. For a steady run, opt in with numerics.momentum_advection = limited_upwind, steady_algorithm = implicit_projection, pressure_relative_tolerance 0.1, max_time_step_s 100 and, for a two-dimensional problem, one cell on the periodic axis. On the cavity this reaches the same accepted steady state in far fewer iterations. pressure_preconditioner = multigrid also works with buildings and separate fluid regions. There it needs fewer pressure iterations but gave no consistent gain in run time, and it is slower than the default on strongly anisotropic grids (CFD-W004); see chapter 22. See the implicit recipe and the implicit steady results.

OpenFOAM backend

  • It runs two generated cases (laminar cavity, turbulent backward-facing step); it does not translate native cases and runs no dispersion.
  • Its archives have their own schema and their own report (integrations/openfoam_backend.py report); do not give them to cfd-craft report.
  • Continuation needs a complete source archive whose stored face flux passes the independent gate; failed, timed-out and canceled runs are not eligible.
  • Mesh initialization needs an accepted, independently audited, cold-generated source; coarse face flux is never copied.
  • Code agreement, comparison with measurements and physical qualification are separate results; none of them qualifies the native canyon model.

Chapters 15, 16, 17, 18 and 19 cover it.

Scope

CFD-craft models uniform Cartesian grids with buildings as boxes or polygon prisms, laminar flow, one neutral k-epsilon package, optional porous vegetation, passive gases and particle size classes with settling and deposition. It does not model terrain, LES, buoyancy, chemistry, stretched grids or GPU execution. The fcmaes worker has two models: a prescribed-flow allocation of three sources and a wind-direction objective for a neutral_rans case.

Nothing is experimentally validated; the canyon validation gate (measured data and a grid study) is open. Four further gates are open for city blocks: multigrid with buildings has no consistent end-to-end gain; the canyon rotated by 45 degrees did not pass its grid study; no direction of the district demonstration converged within its short budget; inference from rides is verified on synthetic data of the same model only. The model cards state the scope of each component, and the evidence index lists the gates.

For contributors

Changing the solver: start at the developer pages and follow AGENTS.md.

About the guide

The guide teaches CFD-craft in 24 chapters, ordered by difficulty. Each chapter is self-contained: it starts with a setup, uses one small case and ends with links to the next steps. It covers the native solver (constant-density incompressible flow with passive gas and particles on uniform Cartesian grids), its Python binding, the tools for city blocks and mobile measurements, and the separate OpenFOAM backend.

Version 0.2.0 is a research prototype. A numerically accepted run is not an experimentally validated prediction.

Chapters

Chapters 1 and 2 need only pip install cfd-craft. From chapter 3 on, commands run from the root of a checkout. Part IV needs Linux and an OpenFOAM Foundation 13 runtime, which chapter 15 installs. Part VI builds on chapters 5 and 10; its map and inference tools need the optional Python packages of integrations/requirements-mobile.txt.

Which interface

GoalUseStart at
Get receptor values and checks in Pythoncfd_craft.check, cfd_craft.simulatechapter 1
Keep fields, a verified archive, restart, preview, profilethe cfd-craft commandchapter 3
Script many archived runsthe command through subprocesschapters 11 and 12
Embed the solver in a Rust programcfd_craft::solver::runchapter 20
Run optimization jobs or campaignsthe fcmaes worker and optimization-runchapters 13 and 14
Run or compare with OpenFOAMintegrations/openfoam_backend.pychapter 15
Import buildings from a map, run a wind-direction campaignintegrations/urban_map.py, validation/urban_campaign.pychapter 22
Simulate a sensor ridea path receptor and integrations/virtual_ride.pychapter 23
Infer street emissions from rides, plan routestutorials/mobile_measurements.py, integrations/mobile_inference.pychapter 24

The Python package installs from PyPI without a toolchain. The command and the library are built with Rust 1.88 or newer. The analysis scripts, the map and ride tools and the OpenFOAM tools are run from a checkout. The native solver does not need OpenFOAM, and the adapter starts OpenFOAM as separate programs.

How to read the code blocks

  • A python or bash block is meant to be run as it stands, in the order of its section, after the Setup section of its chapter. A sh block shows commands that install, build or take long; adapt them before you run them.
  • Every section starts from what Setup left, not from the section before it. When you run a whole chapter in order, first remove an output directory that an earlier section made (rm -r runs/point): a run never writes into an existing directory (CFD-E062, chapter 3).
  • A text block is the real output of the block before it. Outputs show a few chosen fields, never wall times or hashes.
  • A json block is a complete case, or a fragment that the text names.
  • scripts/check_docs.py runs the blocks of the chapters and compares the outputs: floating-point numbers within the tolerance a chapter states, everything else exactly. Part IV runs only where the runtime is installed.

Three words are kept apart on every page. A run completed or stopped (termination). A result is numerically accepted or not (assessment). A model is validated against measurements or not; in 0.2.0 none is.

First run

At the end of this chapter you have one numerically accepted result and one concentration with a unit, computed from Python. You need Python 3.10 or newer and nothing else: no checkout and no Rust.

Setup

Install the Python binding (wheels for Linux x86_64, Windows x64 and macOS):

python -m pip install cfd-craft

Save this case as point-source.json in an empty directory. It is the whole input.

{
  "schema_version": "cfd-craft.case/0.1",
  "name": "manual-point-source",
  "domain": {"size_m": [8.0, 4.0, 4.0]},
  "grid": {"cells": [16, 8, 8]},
  "boundaries": {"x": "open", "y": "periodic", "z": "periodic"},
  "flow": {"kind": "prescribed_uniform", "velocity_m_s": [1.0, 0.0, 0.0]},
  "geometry": [],
  "constituents": [{"id": "tracer", "diffusivity_m2_s": 0.05}],
  "initial_conditions": [],
  "sources": [{"kind": "point", "id": "S0", "constituent": "tracer",
    "point_m": [1.0, 2.0, 2.0], "rate_kg_s": 1e-7}],
  "receptors": [{"kind": "volume_average", "id": "R_down",
    "min_m": [5.0, 1.0, 1.0], "max_m": [6.0, 3.0, 3.0]}],
  "numerics": {
    "transport": "linear_upwind", "max_time_step_s": 0.1,
    "advective_cfl_max": 0.4, "pressure_relative_tolerance": 1e-10,
    "pressure_max_iterations": 1200, "steady_residual_tolerance": 1e-5,
    "steady_monitor_tolerance": 0.001, "monitor_window": 30
  },
  "run": {"mode": "steady", "end_time_s": 2.0, "max_steps": 2000,
    "wall_time_limit_s": 120.0, "threads": 1, "memory_limit_mib": 256},
  "output": {"fields": true, "checkpoint": true, "max_total_mib": 16}
}

The box is 8 m x 4 m x 4 m with 16 x 8 x 8 = 1,024 cells. The wind is prescribed (1 m/s along x), so no flow is computed. A point source emits 1e-7 kg/s of a passive tracer at (1, 2, 2) m. The box-shaped receptor R_down averages the concentration from x = 5 m to 6 m, downstream of the source. The run is steady: it stops when the concentration no longer changes. This is a synthetic example, not a calibrated pollution scenario.

Outputs on this page are real. The documentation check compares floating-point numbers with a relative tolerance of 1e-4; everything else must match exactly.

Check the case

check validates a case and counts its cells without solving anything.

import json
import cfd_craft as cfd

case = json.load(open("point-source.json"))
report = cfd.check(case)
print(report["valid"], report["cells"], len(report["diagnostics"]))
True 1024 0

The case is valid, with 1,024 cells and no diagnostics. Check before every run.

Run it

simulate solves the case in this process and returns a summary dictionary.

import json
import cfd_craft as cfd

case = json.load(open("point-source.json"))
result = cfd.simulate(case)
for key in ("termination", "assessment", "experimental_validation"):
    print(result[key])
completed
steady_discrete_solution
not_validated; see validation/data-inventory.json

These three fields answer three different questions. Read all three before you use a number; chapter 4 shows them on runs that stop early.

  • termination: why the run stopped. completed means it reached its goal, not a step limit, a time limit or a cancellation.
  • assessment: what the numerical checks support. steady_discrete_solution means the discrete equations on this grid are solved, so the run is numerically accepted.
  • experimental_validation: whether the model was compared with measurements for this use. In version 0.2.0 no result is.

Read a receptor

Concentrations are in kg/m3. Multiply by 1e9 for micrograms/m3.

import json
import cfd_craft as cfd

result = cfd.simulate(json.load(open("point-source.json")))
tracer = next(c for c in result["constituents"] if c["id"] == "tracer")
value = tracer["receptors_kg_m3"]["R_down"]
print(f"R_down = {value * 1e9:.6g} micrograms/m3")
R_down = 17.8118 micrograms/m3

Look up a constituent by its id and a receptor by its ID, never by position: the receptor map is sorted as text, so R10 comes before R2. A null (None in Python) means “not available in this context”, not zero.

The same from the shell

The package installs a small command that prints the same report and summary as JSON.

python -m cfd_craft check point-source.json > check.json
python -m cfd_craft simulate point-source.json > summary.json
echo "exit $?"
exit 0

Exit 0 means a valid case or an accepted run, 1 invalid input, 2 a run that is not numerically accepted. Fields and archives need the cfd-craft command.

Next

  • Chapter 2: what is in the case file and how to change it.
  • Chapter 3: the cfd-craft command and run archives.

The case file

At the end of this chapter you can read every group of a case, change a case safely and look up the allowed fields yourself. You need the Python binding of chapter 1: python -m pip install cfd-craft.

Setup

Save the case of chapter 1 as point-source.json in an empty directory:

{
  "schema_version": "cfd-craft.case/0.1",
  "name": "manual-point-source",
  "domain": {"size_m": [8.0, 4.0, 4.0]},
  "grid": {"cells": [16, 8, 8]},
  "boundaries": {"x": "open", "y": "periodic", "z": "periodic"},
  "flow": {"kind": "prescribed_uniform", "velocity_m_s": [1.0, 0.0, 0.0]},
  "geometry": [],
  "constituents": [{"id": "tracer", "diffusivity_m2_s": 0.05}],
  "initial_conditions": [],
  "sources": [{"kind": "point", "id": "S0", "constituent": "tracer",
    "point_m": [1.0, 2.0, 2.0], "rate_kg_s": 1e-7}],
  "receptors": [{"kind": "volume_average", "id": "R_down",
    "min_m": [5.0, 1.0, 1.0], "max_m": [6.0, 3.0, 3.0]}],
  "numerics": {
    "transport": "linear_upwind", "max_time_step_s": 0.1,
    "advective_cfl_max": 0.4, "pressure_relative_tolerance": 1e-10,
    "pressure_max_iterations": 1200, "steady_residual_tolerance": 1e-5,
    "steady_monitor_tolerance": 0.001, "monitor_window": 30
  },
  "run": {"mode": "steady", "end_time_s": 2.0, "max_steps": 2000,
    "wall_time_limit_s": 120.0, "threads": 1, "memory_limit_mib": 256},
  "output": {"fields": true, "checkpoint": true, "max_total_mib": 16}
}

Outputs on this page are real. The documentation check compares floating-point numbers with a relative tolerance of 1e-4; everything else must match exactly.

The groups of a case

Nothing outside the case file configures the solver. Its top-level fields are:

FieldsWhat they hold
schema_version, nameVersion of the case format; a label copied into the result
domain, gridLengths of the box in meters; three cell counts
boundariesOne condition per axis: periodic, open, wall, slip or, for z, ground_open_top
flow, moving_wallsPrescribed, laminar or neutral-RANS flow; moving lids
geometrySolid buildings, each with an ID: boxes, or prisms with a polygon footprint
constituents, initial_conditionsPassive gases and particle size classes with their diffusivity; their starting concentration
sources, receptorsWhere mass enters and where concentration is reported, each with an ID
numericsSchemes, time step limit, tolerances, monitor window
runMode (steady or transient), endpoint, and the budgets for steps, wall time, threads and memory
outputWhether fields and a checkpoint are kept; the output budget
vegetation, building_roughness_m, geometry_min_passage_cellsOptional fields for city blocks (chapter 22)

The six lists (moving_walls, geometry, constituents, initial_conditions, sources, receptors) are empty when omitted, and the opt-in numerics of chapter 9 have defaults. The fields of the last row may be omitted. Every other field is required. The case schema lists each field with its type, default and meaning.

Units and coordinates

Every quantity has one unit, and the field name carries it. Nothing is converted silently. This case uses:

FieldUnit or convention
size_m, point_m, min_m, max_mmeters; x east, y north, z up
velocity_m_sm/s
diffusivity_m2_sm2/s
rate_kg_skg/s
end_time_s, max_time_step_s, wall_time_limit_sseconds
receptors_kg_m3 (in the result)kg/m3; multiply by 1e9 for micrograms/m3

The grid is uniform: the cell size is the domain length divided by the cell count, here 8 m / 16 = 0.5 m along x and 4 m / 8 = 0.5 m along y and z. There is no mesh file and no mesh generator. The full table is in units and conventions.

Change a case without touching the original

Load the case, change a copy, give the copy a new name and check it. Here one copy has half the source rate and another has only a smaller step budget.

import copy
import json
import cfd_craft as cfd


def r_down(result):
    tracer = next(c for c in result["constituents"] if c["id"] == "tracer")
    return tracer["receptors_kg_m3"]["R_down"]


case = json.load(open("point-source.json"))
half = copy.deepcopy(case)
half["name"] = "point-half-rate"
half["sources"][0]["rate_kg_s"] *= 0.5
budget = copy.deepcopy(case)
budget["name"] = "point-other-budget"
budget["run"]["max_steps"] = 1000
print(cfd.check(half)["valid"], cfd.check(budget)["valid"])
base, changed, same = (cfd.simulate(c) for c in (case, half, budget))
print(changed["assessment"])
print(f"ratio = {r_down(changed) / r_down(base):.6g}")
print(changed["physics_sha256"] == base["physics_sha256"])
print(same["physics_sha256"] == base["physics_sha256"])
True True
steady_discrete_solution
ratio = 0.5
False
True

Half the rate gives half the concentration, and the run is numerically accepted. Every result carries physics_sha256, a hash of grid, flow, sources, receptors and numerics. A changed source is a different problem (False). A changed budget is not (True): name, run and output are outside the hash (chapter 8 builds on this).

A wrong field is an error

A field name from another CFD package is not accepted, and nothing is ignored. The coordinate of a point source is point_m. Rename it to position_m:

import json
import cfd_craft as cfd

bad = json.load(open("point-source.json"))
bad["sources"][0]["position_m"] = bad["sources"][0].pop("point_m")
report = cfd.check(bad)
print(report["valid"], [(d["code"], d["path"]) for d in report["diagnostics"]])
try:
    cfd.simulate(bad)
except cfd.CfdError as error:
    print("CfdError", [(d["code"], d["path"]) for d in error.diagnostics])
False [('CFD-E000', 'sources[0]')]
CfdError [('CFD-E000', 'sources[0]')]

check returns the diagnostic; simulate raises CfdError with the same diagnostics and never starts, so a typo cannot run silently with a default. Each diagnostic has a code, a severity, the path of the offending element and a message. Use code and path in programs; the message is for people and here names the allowed fields. All codes: diagnostics.

Find the allowed fields

describe returns the schemas of the installed version, generated from the types the solver uses.

import cfd_craft as cfd

described = cfd.describe()
schema = described["case_schema"]
definitions = schema["definitions"]
print([kind["properties"]["kind"]["enum"][0] for kind in definitions["Flow"]["oneOf"]])
print(definitions["Advection"]["enum"])
print("termination" in described["result_schema"]["properties"])
['prescribed_uniform', 'laminar', 'neutral_rans']
['linear_upwind', 'muscl']
True

These are the three flow kinds, the two schemes of numerics.transport, and a test that the result schema describes the summary. Both are JSON Schema (draft-07): jsonschema.validate(case, schema) checks names and types in your own tool. Ranges, units, geometry and budgets are checked only by check.

Next

  • Chapter 3: the command line and the files of a run.
  • Chapter 5: sources, receptors, schemes.

The command line and the run archive

At the end of this chapter you have the fields of a run on disk, know every file of a run directory, and have checked and viewed the fields. You need the cfd-craft command and, for the last two sections, a checkout of the repository with its Python requirements.

Setup

The command is built from source with Rust 1.88 or newer. There is no prebuilt binary. Either install the released command:

cargo install cfd-craft-cli --locked

or build it in a checkout and put it on PATH:

git clone https://github.com/dietmarwo/CFD-craft.git
cd CFD-craft
cargo build --release --workspace --locked
export PATH="$PWD/target/release:$PATH"

From here on, the guide runs every command from the root of a checkout, because the cases and the Python tools live there. The tools of the last two sections need NumPy and a few other packages:

python -m venv .venv
. .venv/bin/activate
python -m pip install -r requirements-validation.txt

Run outputs go to runs/, which Git ignores. describe prints the schemas, the exit codes and the build identity of the command as JSON:

mkdir -p runs
cfd-craft describe > runs/describe.json

Outputs on this page are real. The documentation check compares floating-point numbers with a relative tolerance of 1e-4; everything else must match exactly.

Check, run, report

The case is the point source of chapter 1, which is committed as examples/manual/point-source.json.

cfd-craft check examples/manual/point-source.json
cfd-craft run examples/manual/point-source.json --output runs/point
cfd-craft report runs/point

Each command prints JSON. check prints the check report and the geometry counts. run solves the case, writes the directory runs/point and prints the summary. report verifies that directory against its checksums and prints the summary again. The summary is also the file summary.json:

import json

s = json.load(open("runs/point/summary.json"))
print(s["termination"], s["assessment"])
tracer = next(c for c in s["constituents"] if c["id"] == "tracer")
print(f"R_down = {tracer['receptors_kg_m3']['R_down'] * 1e9:.6g} micrograms/m3")
completed steady_discrete_solution
R_down = 17.8118 micrograms/m3

This is the value the Python binding returned in chapter 1. Both call the same solver.

The output directory must be new, and its parent must exist. A run never writes into an existing directory, not even after a failed run. To repeat a run, choose a new name or delete the old directory yourself.

Exit codes

OutcomeExit
A valid case (check), a numerically accepted run with all its files (run), an intact archive (report), a passed fixture (verify)0
Invalid input, or an execution or I/O error. A check report is on stdout; other errors are on stderr as {"error": "..."}1
A run that ended without numerical acceptance, or an accepted run that had to omit files over its output budget; a failed verify fixture2

Two errors every user meets once are an existing output directory and a missing parent directory:

cfd-craft run examples/manual/point-source.json --output runs/twice > /dev/null
echo "first run: exit $?"
cfd-craft run examples/manual/point-source.json --output runs/twice \
  2> runs/second.err || echo "second run: exit $?"
grep -o "CFD-E[0-9]*" runs/second.err
cfd-craft run examples/manual/point-source.json --output missing/point \
  2> runs/third.err || echo "missing parent: exit $?"
grep -o "CFD-E[0-9]*" runs/third.err
first run: exit 0
second run: exit 1
CFD-E062
missing parent: exit 1
CFD-E063

Both are found before the solve starts. Exit 2 is shown in chapter 4.

report exits 0 for every intact archive, also for one whose run was stopped early. Never use the exit code of report as a convergence test. Read termination and assessment.

The files of a run

cfd-craft run examples/manual/point-source.json --output runs/point > /dev/null
ls runs/point
case.json
checkpoint.json
complete.json
fields.json
geometry.json
manifest.json
probes.csv
summary.json
FileWhat to read in it
case.jsonThe case as the solver used it, with omitted lists written out
summary.jsonWhy the run stopped, the checks, the work done, receptor values, model scope
geometry.jsonFluid and solid cell counts, solid volume, cells per box, connected fluid regions, a hash of the cell mask
probes.csvThe final receptor values in kg/m3, one line per constituent and receptor
fields.jsonThe final state: concentrations, pressure, face velocities, mass budgets. Written when output.fields is true
checkpoint.jsonA checksummed state for restart (chapter 8). Written when output.checkpoint is true
manifest.jsonA hash of every file above, omitted files with the reason, and the identity of the input file, the source code, the executable and the initial state
complete.jsonThe hash of the manifest. It is written last

complete.json marks an archive whose files are all written. It says nothing about convergence: an incomplete run also has one. The hashes detect damage and mix-ups. They are not signatures, so they do not prove who made an archive.

Keep notes, plots and logs beside a run directory, not inside it. report rejects an archive that contains a file the manifest does not list. The result contract has the details.

Check the fields independently

check_fields.py is a second implementation, in Python with NumPy, that reads the archived fields and recomputes what the solver claimed.

cfd-craft run examples/manual/point-source.json --output runs/point > /dev/null
python validation/check_fields.py runs/point > runs/point-audit.json
import json

audit = json.load(open("runs/point-audit.json"))
print(audit["passed"], [scalar["id"] for scalar in audit["scalars"]])
True ['tracer']

It recomputes the velocity divergence of every cell, the mass of each constituent, the emitted mass from source rate and time, the recorded mass budget, the receptor values and the cell mask, and it requires finite fields. It does not rebuild the history of fluxes over all time steps, and it does not test the turbulence model. It is a numerical cross-check of one archive, not a validation against measurements.

Look at the fields in ParaView

cfd-craft run examples/manual/point-source.json --output runs/point > /dev/null
python validation/export_vtk.py --run runs/point --output runs/point.vtr

Open runs/point.vtr in ParaView. It is a rectilinear grid with cell data. Threshold by fluid_mask before you look at a case with buildings, so solid cells do not enter color scales or averages. The exported velocity is a cell value reconstructed from the faces. The solver’s own face velocities, which satisfy continuity, are in fields.json. The exporter needs a run with fields and refuses to overwrite an existing file.

Next

  • Chapter 4: what termination, assessment and the validation label mean, on an accepted, an incomplete and a transient run.
  • Command line reference: every command and option.

Can I trust this result?

At the end of this chapter you can tell three things apart on any run: why it stopped, what its numerical checks support, and whether the model was compared with measurements. You need the cfd-craft command and a checkout, as in chapter 3.

Setup

Commands run from the root of a checkout with cfd-craft on PATH. Every section reads the point-source run that this block makes:

mkdir -p runs
cfd-craft run examples/manual/point-source.json --output runs/point > /dev/null

Outputs on this page are real. The documentation check compares floating-point numbers with a relative tolerance of 1e-4; everything else must match exactly.

Four questions, four kinds of evidence

QuestionWhere the answer is
What stopped the run?termination, error, steps, physical_time_s in summary.json
Is the requested discrete calculation solved?assessment and checks, recomputed from the final fields
Are these files the ones the run wrote?manifest.json, complete.json and cfd-craft report
Does the model match experiments for this use?experimental_validation, and a validation report for a named data set

A converged residual, a matching checksum, a good mesh, a plausible plot and a fitted optimizer objective each answer one row of this table, never all four.

flowchart TD
  A["Bounded run"] --> B{"Numerical checks pass?"}
  B -->|yes| C["Accepted discrete result"]
  B -->|no| D["Kept incomplete or failed result"]
  C --> E["Comparison with a reference or with measurements"]
  D --> F["Find the stopping reason"]
  E --> G["Decision for one data set and one use"]

Termination: why the run stopped

Situationterminationassessment
A steady run met all its criteriacompletedsteady_discrete_solution
A transient run reached its end time and its checks passedcompletedtransient_interval_completed
A budget ran out, or the run was cancelediteration_limit, wall_time_limit or cancelledincomplete
The run finished and a check failedcompletedfailed_checks
A time step failed numericallydivergedincomplete

Only the first two rows are numerically accepted results. completed alone is not enough: read the pair.

Assessment: what the checks support

The solver recomputes its checks from the final fields and records each one with its value and its limit.

import json

s = json.load(open("runs/point/summary.json"))
print(s["termination"], s["assessment"])
for check in s["checks"]:
    print(f"{check['name']:27} {check['passed']}  limit {check['threshold']:g}")
completed steady_discrete_solution
local_continuity            True  limit 0.0001
boundary_volume_balance     True  limit 1e-05
tracer.mass_budget          True  limit 1e-09
tracer.negative_mass        True  limit 1e-12
tracer.steady_equation      True  limit 1e-05
tracer.steady_mass_balance  True  limit 1e-06
monitor_stability           True  limit 0.001

A steady run is accepted when all of these hold: the velocity divergence (local_continuity) and the net boundary flux are within their limits, each constituent’s mass budget closes and no concentration is negative, the steady equation residual is below numerics.steady_residual_tolerance, sources and inflow balance outflow, and the monitored values (here the receptor) changed by less than numerics.steady_monitor_tolerance over three windows of numerics.monitor_window steps. The run stops at the first step where all of this holds, not at run.end_time_s.

A transient run has a different goal: reach run.end_time_s with the conservation checks passing.

cfd-craft run cases/verification/periodic-tracer.json --output runs/tracer > /dev/null
import json

s = json.load(open("runs/tracer/summary.json"))
print(s["termination"], s["assessment"], s["steps"])
print([check["name"] for check in s["checks"]])
completed transient_interval_completed 20
['local_continuity', 'boundary_volume_balance', 'tracer.mass_budget', 'tracer.negative_mass']

This case moves a cloud of tracer through a periodic box for 2 s. There is no steady state to reach, so there are no steady checks.

An incomplete run is still a result

Give the point-source case a budget of five steps:

import json

case = json.load(open("examples/manual/point-source.json"))
case["name"] = "point-five-steps"
case["run"]["max_steps"] = 5
json.dump(case, open("runs/point-5.json", "w"), indent=2)
cfd-craft run runs/point-5.json --output runs/point-5 > /dev/null || echo "run: exit $?"
cfd-craft report runs/point-5 > /dev/null
echo "report: exit $?"
run: exit 2
report: exit 0
s = json.load(open("runs/point-5/summary.json"))
print(s["steps"], s["termination"], s["assessment"])
print(f"physical time {s['physical_time_s']:g} s, error: {s['error']}")
5 iteration_limit incomplete
physical time 0.5 s, error: None

The run exits 2 and writes a complete archive, which report verifies with exit 0. The archive shows how far the run got, and its checkpoint can be continued (chapter 8). It is not a converged result, even where single checks already pass.

The saved state is always the last accepted state. A time step that fails is not committed: summary and checkpoint keep the state before it, error records the failure, and steps counts kept steps only.

Require a verdict in a script

A script that uses a number must test the verdict first, not an exit code.

import json
from pathlib import Path

s = json.loads(Path("runs/point/summary.json").read_text())
if s["assessment"] not in {"steady_discrete_solution", "transient_interval_completed"}:
    raise RuntimeError((s["termination"], s["assessment"], s["error"]))
if not all(c["passed"] for c in s["checks"]):
    raise RuntimeError("A recorded numerical check failed")

The block prints nothing for this accepted run. For a five-step run it raises.

Experimental validation is a separate label

import json

s = json.load(open("runs/point/summary.json"))
print(s["experimental_validation"])
print(s["model_scope"])
not_validated; see validation/data-inventory.json
prescribed_flow_passive_transport

Every result of version 0.2.0 carries this label, whatever its assessment. Version 0.2.0 is a research prototype. A numerically accepted run is not an experimentally validated prediction.

  • What exists is verification: comparison with analytic solutions and with numerical references such as the lid-driven cavity of chapter 6, recorded in native verification; the evidence index lists every record.
  • What is missing is validation: no result has been compared with measured street-canyon data. The raw wind-tunnel files could not be obtained (the data inventory records each attempt), and the first study on finer grids did not finish within its compute budgets.

model_scope names the model that produced the numbers; the model cards say what each model assumes.

Next

Sources, receptors and transport

At the end of this chapter you can declare emissions and sensors in the right units and choose a transport scheme knowingly. You need a checkout and the Python binding (python -m pip install cfd-craft); all runs are short.

Setup

Run the blocks from the root of a checkout. They read the point-source case of chapter 1 and two cases from cases/verification/. Each has one constituent, so the blocks take constituents[0].

Outputs on this page are real. The documentation check compares floating-point numbers with a relative tolerance of 1e-4; everything else must match exactly.

Three kinds of source, three rate units

kindFieldsRate field and unitTotal emission
pointpoint_mrate_kg_s, kg/sthe declared rate
linefrom_m, to_mrate_kg_s_m, kg/s per meterrate times line length
volumemin_m, max_mrate_kg_s_m3, kg/s per m3rate times box volume

A line or volume rate is a density, not a total: 5e-8 kg/s/m over 2 m emits 1e-7 kg/s, and so does 5e-8 kg/s/m3 in a 1 m x 2 m x 1 m box. Save these two objects as line-source.json and volume-source.json. The block after them puts each in place of the point source and runs it.

{"kind": "line", "id": "S_line", "constituent": "tracer",
 "from_m": [1, 1, 2], "to_m": [1, 3, 2], "rate_kg_s_m": 5e-8}
{"kind": "volume", "id": "S_volume", "constituent": "tracer",
 "min_m": [1, 1, 1], "max_m": [2, 3, 2], "rate_kg_s_m3": 5e-8}
import copy
import json
import cfd_craft as cfd

case = json.load(open("examples/manual/point-source.json"))
sources = {"point": case["sources"][0]}
for kind in ("line", "volume"):
    sources[kind] = json.load(open(f"{kind}-source.json"))
for kind, source in sources.items():
    variant = copy.deepcopy(case)
    variant["sources"] = [source]
    valid = cfd.check(variant)["valid"]
    tracer = cfd.simulate(variant)["constituents"][0]
    r_down = tracer["receptors_kg_m3"]["R_down"] * 1e9
    print(f"{kind:6} {valid} {tracer['source_rate_kg_s']:.3g} kg/s, {r_down:.6g}")
point  True 1e-07 kg/s, 17.8118
line   True 1e-07 kg/s, 15.8814
volume True 1e-07 kg/s, 14.472

The columns are validity, the integrated rate the solver used (source_rate_kg_s) and R_down in micrograms/m3. Equal total emission does not make different source shapes the same problem.

Point and volume receptors

import json
import cfd_craft as cfd

case = json.load(open("examples/manual/point-source.json"))
case["receptors"].append({"kind": "point", "id": "P_mid", "point_m": [5.5, 2.0, 2.0]})
tracer = cfd.simulate(case)["constituents"][0]
for name, value in tracer["receptors_kg_m3"].items():
    print(f"{name} = {value * 1e9:.6g} micrograms/m3")
P_mid = 30.3316 micrograms/m3
R_down = 17.8118 micrograms/m3

A point receptor interpolates between the eight surrounding cell centers. A volume_average receptor weights each cell by its exact overlap with a box. P_mid sits on the plume axis in the middle of R_down and reads higher than the box average. Neither kind bounds the peak concentration. A source or receptor in a solid cell is rejected, not moved (chapter 10).

Double the rate, double the concentration

With numerics.transport set to linear_upwind and a fixed flow, the concentration is linear in the source strengths. source-response.json has three volume sources of 1e-7 kg/s/m3 in boxes of 0.64 m3, 1.92e-7 kg/s in all:

import json
import cfd_craft as cfd

case = json.load(open("cases/verification/source-response.json"))
values = []
for factor in (1, 2):
    for source in case["sources"]:
        source["rate_kg_s_m3"] = 1e-7 * factor
    result = cfd.simulate(case)
    tracer = result["constituents"][0]
    values.append(tracer["receptors_kg_m3"]["R1"])
    print(result["assessment"], f"{tracer['source_rate_kg_s']:.6g} kg/s")
print(f"R1 ratio = {values[1] / values[0]:.6g}")
steady_discrete_solution 1.92e-07 kg/s
steady_discrete_solution 3.84e-07 kg/s
R1 ratio = 2

Linearity makes response matrices work (chapter 12).

MUSCL is sharper and not linear

linear_upwind is first-order upwind and smears a plume; muscl adds a limited second-order slope. Run each with one source, another one, and both:

import copy
import json
import cfd_craft as cfd

case = json.load(open("examples/manual/point-source.json"))
first = case["sources"][0]
second = dict(first, id="S1", point_m=[2.0, 1.5, 2.5])
for scheme in ("linear_upwind", "muscl"):
    values = []
    for sources in ([first], [second], [first, second]):
        variant = copy.deepcopy(case)
        variant["numerics"]["transport"] = scheme
        variant["sources"] = sources
        tracer = cfd.simulate(variant)["constituents"][0]
        values.append(tracer["receptors_kg_m3"]["R_down"])
    defect = abs(values[2] - values[0] - values[1]) / values[2]
    print(f"{scheme:13} R_down = {values[0] * 1e9:.6g}  sum holds: {defect < 1e-6}")
linear_upwind R_down = 17.8118  sum holds: True
muscl         R_down = 18.1504  sum holds: False

The MUSCL value is higher: with less numerical diffusion, more tracer stays near the plume axis, where the receptor is. The last column tests whether the run with both sources equals the sum of the single runs within 1e-6. With muscl it does not: the limiter is nonlinear (transport model card).

A steady source needs a way out

import json
import cfd_craft as cfd

case = json.load(open("examples/manual/point-source.json"))
case["boundaries"]["x"] = "periodic"
report = cfd.check(case)
print(report["valid"], [(d["code"], d["path"]) for d in report["diagnostics"]])
False [('CFD-E020', 'run.mode')]

A source that emits forever into a box with no outlet has no steady state, so the case is rejected at run.mode. It needs an open boundary downstream.

A release that is not steady

A fixed amount of tracer in a closed box is a transient problem: here a Gaussian cloud of 1e-6 kg in a fully periodic box, for 2 s.

import json
import cfd_craft as cfd

result = cfd.simulate(json.load(open("cases/verification/periodic-tracer.json")))
tracer = result["constituents"][0]
print(result["termination"], result["assessment"])
print(f"mass {tracer['mass_kg']:.6g} kg, emitted {tracer['emitted_kg']:.6g} kg")
print(abs(tracer["relative_budget_defect"]) < 1e-9)
completed transient_interval_completed
mass 1e-06 kg, emitted 0 kg
True

Every constituent carries a mass budget: mass in the domain, emitted mass, inflow, outflow and their defect. Nothing is emitted or leaves here, so the mass stays at 1e-6 kg. Negative concentrations are never clipped: they fail.

Next

Compute a flow

At the end of this chapter you have computed a velocity and pressure field, steady and transient, and compared it with a published numerical reference. You need the cfd-craft command, a checkout and its Python requirements (chapter 3).

Setup

Commands run from the root of a checkout with cfd-craft on PATH. The case is the lid-driven cavity at Reynolds number 100, cases/verification/lid-cavity.json. It is committed as a transient case. This block writes a steady copy on one thread and checks it:

mkdir -p runs
import json

case = json.load(open("cases/verification/lid-cavity.json"))
case["name"] = "cavity-steady"
case["run"]["mode"] = "steady"
case["run"]["threads"] = 1
json.dump(case, open("runs/cavity-steady.json", "w"), indent=2)
cfd-craft check runs/cavity-steady.json > runs/cavity-steady.check.json

Outputs on this page are real. The documentation check compares floating-point numbers with a relative tolerance of 1e-4; everything else must match exactly.

The case: walls, a moving lid, one periodic direction

Until now the wind was prescribed. Here flow.kind is laminar: the solver computes velocity and pressure of an incompressible fluid with constant viscosity. These are the fields of the case that matter:

import json

case = json.load(open("runs/cavity-steady.json"))
for key in ("domain", "grid", "boundaries", "flow", "moving_walls"):
    print(key, "=", json.dumps(case[key]))
domain = {"size_m": [1.0, 1.0, 1.0]}
grid = {"cells": [24, 2, 24]}
boundaries = {"x": "wall", "y": "periodic", "z": "wall"}
flow = {"kind": "laminar", "initial_velocity_m_s": [0.0, 0.0, 0.0], "viscosity_m2_s": 0.01, "acceleration_m_s2": [0.0, 0.0, 0.0]}
moving_walls = [{"axis": 2, "upper": true, "velocity_m_s": [1.0, 0.0, 0.0]}]
  • The box is 1 m x 1 m x 1 m. x and z end in no-slip walls. y is periodic, so the flow is two-dimensional in the x-z plane, with z up.
  • moving_walls makes the upper z wall (axis 2, upper true) slide at 1 m/s along x. This is the lid.
  • With a lid speed of 1 m/s, a box of 1 m and viscosity_m2_s of 0.01, the Reynolds number is 100.
  • The grid has 24 x 2 x 24 uniform cells.

Velocity components are stored on cell faces and pressure in cell centers (a staggered grid). Pressure is kinematic pressure, p / rho, in m2/s2.

Run to a steady state

cfd-craft run runs/cavity-steady.json --output runs/cavity-steady > /dev/null
import json

s = json.load(open("runs/cavity-steady/summary.json"))
print(s["termination"], s["assessment"], s["model_scope"])
print([check["name"] for check in s["checks"]])
print(f"velocity_max = {s['velocity_max_m_s']:.6g} m/s")
print(s["steps"] > 1000, s["pressure_iterations"] > s["steps"])
completed steady_discrete_solution incompressible_laminar
['local_continuity', 'boundary_volume_balance', 'steady_momentum_equations', 'monitor_stability']
velocity_max = 0.858562 m/s
True True

The run is numerically accepted. For a flow, the steady checks are continuity, the boundary balance, the residual of the momentum equations and the stability of the monitored values.

With the default numerics a steady run marches explicit time steps until those checks pass. It needs about 2,000 steps here, each with a pressure solve, and takes 6 to 8 s on the documentation host. run.end_time_s does not bound a steady run; run.max_steps and run.wall_time_limit_s do. The physical_time_s of a steady result is pseudo-time, not a physical duration. Chapter 9 shows opt-in numerics that reach the same state in far fewer iterations.

Transient mode completes an interval

The committed case has run.mode set to transient and run.end_time_s to 30. A transient run integrates exactly that physical interval and ends as completed / transient_interval_completed when the conservation checks pass. It does not test whether the flow has stopped changing. That is your judgment, or a steady run. The next section runs the committed transient case.

Compare with a numerical reference

Ghia, Ghia and Shin (1982) tabulate the horizontal velocity on the vertical centerline of this cavity. validation/cavity.py runs the committed case, interpolates the computed profile to their stations and reports the largest difference in units of the lid speed. It takes 14 to 21 s on the documentation host.

python validation/cavity.py --output runs/cavity-ghia > /dev/null
import json

report = json.load(open("runs/cavity-ghia/report.json"))
print(report["passed"], report["grid"], report["target_max"])
print(f"largest difference = {report['maximum_centerline_absolute_error']:.4g}")
True [24, 2, 24] 0.06
largest difference = 0.02755

The difference is below the fixed limit of 0.06 for this coarse grid. The reference is itself a numerical solution on a fine grid, so this is a numerical verification of the flow solver. It is not an experiment and says nothing about street canyons. The script also writes cavity.png with both profiles. The default momentum scheme is first order. The committed matched accuracy record reports 0.0276 for it and 0.0054 for the opt-in second-order scheme of chapter 9, in steady mode on a 24 x 24 grid.

What the pressure step does

Each step first advances the velocity without the new pressure and then projects it: a pressure equation is solved so that the corrected face velocities are divergence free. The same discrete divergence and gradient are used in the equation and in the correction. A region of fluid that no open boundary touches, like this cavity, determines pressure only up to a constant; the solver fixes the mean to zero in each such region. The pressure equation is solved by conjugate gradients with an incomplete Cholesky preconditioner, to numerics.pressure_relative_tolerance.

A result records the pressure work (pressure_iterations) and, as separate checks, the continuity of the final face velocities and the balance of the boundary fluxes. The pressure solver can also be tested alone on the grid of a case. verify builds a known pressure field, applies the operator and solves for the field again:

cfd-craft verify cases/verification/pressure.json \
  | python -c "import json, sys; v = json.load(sys.stdin); print(v['fixture'], v['passed'])"
pressure_discrete_recovery True

verify exits 0 when the fixture passes and 2 when it fails. It tests the pressure solve on that grid, not the flow of the case.

Two-dimensional runs

A periodic axis may have a single cell. The faces along that axis then join a cell to itself and carry no flux, so the run is two-dimensional:

import json

case = json.load(open("runs/cavity-steady.json"))
case["name"] = "cavity-2d"
case["grid"]["cells"] = [24, 1, 24]
json.dump(case, open("runs/cavity-2d.json", "w"), indent=2)
cfd-craft run runs/cavity-2d.json --output runs/cavity-2d \
  | python -c "import json, sys; s = json.load(sys.stdin); print(s['assessment'], f\"{s['velocity_max_m_s']:.6g}\")"
steady_discrete_solution 0.858562

The maximum speed agrees with the two-cell run above to the printed digits, at about half the work. Every other axis needs at least two cells.

Next

  • Chapter 7: estimate, bound and stop a run before you spend compute on it.
  • Chapter 9: the defaults used here are first order and explicit; the opt-in choices are faster and more accurate on this case.
  • Flow model card: what the flow model assumes.

Before you spend compute

At the end of this chapter you can estimate a run before it starts, bound it, try it on a coarser grid, and stop it without losing the result. You need the cfd-craft command and a checkout (chapter 3).

Setup

Commands run from the root of a checkout with cfd-craft on PATH. The setup writes the steady cavity of chapter 6 and a copy with a wall-time limit of one second.

mkdir -p runs
import json

case = json.load(open("cases/verification/lid-cavity.json"))
case["name"] = "cavity-steady"
case["run"]["mode"] = "steady"
case["run"]["threads"] = 1
json.dump(case, open("runs/cavity-steady.json", "w"), indent=2)
case["name"] = "cavity-1s"
case["run"]["wall_time_limit_s"] = 1
json.dump(case, open("runs/cavity-1s.json", "w"), indent=2)

Outputs on this page are real. The documentation check compares floating-point numbers with a relative tolerance of 1e-4; everything else must match exactly.

What check estimates

check counts the cells and estimates the peak memory of the run and the size of its output directory, both in MiB, without building any field.

cfd-craft check runs/cavity-steady.json > runs/check.json
import json

report = json.load(open("runs/check.json"))["check"]
print(report["valid"], report["cells"])
peak, output = report["estimated_peak_mib"], report["estimated_output_mib"]
print(f"peak {peak:.3g} MiB, output {output:.3g} MiB")
True 1152
peak 26.2 MiB, output 2.35 MiB

A case whose estimate exceeds its own budget is invalid. Lower the memory budget of the cavity to 8 MiB:

case = json.load(open("runs/cavity-steady.json"))
case["run"]["memory_limit_mib"] = 8
json.dump(case, open("runs/cavity-small.json", "w"), indent=2)
cfd-craft check runs/cavity-small.json > runs/small.json || echo "exit $?"
python -c "import json; print([(d['code'], d['path']) for d in json.load(open('runs/small.json'))['check']['diagnostics']])"
exit 1
[('CFD-E006', 'run.memory_limit_mib')]

An output estimate above output.max_total_mib is rejected the same way (CFD-E007). run also refuses a case whose estimate exceeds 80 percent of the memory available on this host (CFD-E070); check then only warns (CFD-W070) and skips the checks that need the grid.

Budgets are part of the case

FieldWhat it bounds
run.max_stepsTime steps, or outer iterations of an implicit steady run
run.wall_time_limit_sWall time of the solve, at most seven days
run.threadsWorker threads
run.memory_limit_mibThe estimated peak memory, tested before the run
output.max_total_mibThe estimated and the actual size of the run directory
output.fields, output.checkpointWhether the two large files are written at all

Every case states all of them, so there is no unbounded run. Fields or a checkpoint that would exceed the output budget after all are left out and listed in the manifest, and the run exits 2 with CFD-E061.

Preview on a coarser grid

preview runs the case with every cell count divided by 2, or by --factor N.

cfd-craft preview examples/manual/point-source.json --output runs/preview > /dev/null
import json

s = json.load(open("runs/preview/summary.json"))
tracer = next(c for c in s["constituents"] if c["id"] == "tracer")
print(s["name"], s["fluid_cells"], s["assessment"])
print(s["model_scope"])
print(f"R_down = {tracer['receptors_kg_m3']['R_down'] * 1e9:.6g} micrograms/m3")
manual-point-source-preview 128 steady_discrete_solution
preview: prescribed_flow_passive_transport
R_down = 16.3951 micrograms/m3

The preview has 128 cells where the case has 1,024. Its name ends in -preview and its model_scope starts with preview:, so it cannot be mistaken for the real run. Its receptor reads 16.4 where the full grid gives 17.8 micrograms/m3: a preview tests the workflow, not the accuracy of the full grid. An axis keeps at least two cells; a one-cell axis stays at one.

When a preview is refused

Coarsening can destroy a geometry. Halve the grid of the street-canyon case of chapter 10:

cfd-craft preview cases/canyon/wh1-wind270.json --factor 2 \
  --output runs/preview-canyon > runs/refused.json || echo "exit $?"
python -c "import json; print(*[(d['code'], d['path']) for d in json.load(open('runs/refused.json'))['check']['diagnostics'] if d['severity'] == 'error'], sep='\n')"
exit 1
('CFD-E040', 'sources[0]')
('CFD-E042', 'receptors[0]')
('CFD-E042', 'receptors[1]')
('CFD-E042', 'receptors[2]')
('CFD-E042', 'receptors[3]')

On the coarse grid the buildings fill the street, so the line source (CFD-E040) and all four receptors (CFD-E042) lie in solid cells. The preview exits 1 with the check report and writes nothing. It is also refused when coarsening changes the solid volume by more than 20 percent or the number of separate fluid regions (CFD-E072), or when the original mask is too large to count on this host (CFD-E073). A refusal describes the coarse geometry.

Stop on a time limit

cfd-craft run runs/cavity-1s.json --output runs/limited > /dev/null || echo "exit $?"
python -c "import json; s = json.load(open('runs/limited/summary.json')); print(s['termination'], s['assessment'])"
exit 2
wall_time_limit incomplete

After one second the solver stops, writes the complete archive of the last accepted state and exits 2. A step limit does the same with iteration_limit.

Cancel a run

Ctrl-C (SIGINT) or SIGTERM cancels a run: the solver stops at the next safe point. Here timeout from GNU coreutils sends SIGINT after one second:

timeout --preserve-status -s INT 1 \
  cfd-craft run runs/cavity-steady.json --output runs/cancelled > /dev/null || echo "exit $?"
cfd-craft report runs/cancelled > /dev/null
echo "report: exit $?"
python -c "import json; s = json.load(open('runs/cancelled/summary.json')); print(s['termination'], s['assessment'])"
exit 2
report: exit 0
cancelled incomplete

The run ends as cancelled / incomplete and exits 2. Its archive is complete and verified, with a checkpoint (chapter 8). From Python, cfd.simulate(case, cancel_file=PATH) does the same (chapter 11).

Threads

The command and the Python binding build a pool of exactly run.threads threads per run. Keep runs times threads within the number of cores.

Next

Checkpoint and restart

At the end of this chapter you have stopped a run by its step budget, resumed it from the checkpoint and shown that the resumed fields equal those of an uninterrupted run, byte for byte. You need the cfd-craft command and a checkout (chapter 3).

Setup

Commands run from the root of a checkout with cfd-craft on PATH. The case is the transient tracer cloud periodic-tracer.json: 20 steps to 2 s. The setup writes runs/full.json and runs/partial.json, limited to five steps.

mkdir -p runs
import json

case = json.load(open("cases/verification/periodic-tracer.json"))
case["name"] = "tracer-full"
case["run"]["threads"] = 1
json.dump(case, open("runs/full.json", "w"), indent=2)
case["name"] = "tracer-partial"
case["run"]["max_steps"] = 5
json.dump(case, open("runs/partial.json", "w"), indent=2)

Outputs on this page are real. They contain no floating-point numbers, so the documentation check requires an exact match.

Stop by work, then resume

cfd-craft run runs/partial.json --output runs/partial > /dev/null || echo "partial: exit $?"
cfd-craft report runs/partial > /dev/null
echo "report: exit $?"
cfd-craft run runs/full.json --restart runs/partial/checkpoint.json \
  --output runs/resumed > /dev/null
echo "resumed: exit $?"
python -c "import json; s = json.load(open('runs/resumed/summary.json')); print(s['steps'], s['termination'], s['assessment'])"
partial: exit 2
report: exit 0
resumed: exit 0
20 completed transient_interval_completed

The first run stops at its step limit and exits 2. Its archive is intact, so report exits 0, and it contains checkpoint.json because the case sets output.checkpoint. The third command continues the full case from that checkpoint at step 5, ends at step 20 and is numerically accepted. The step count of a resumed run includes the steps before the checkpoint.

--restart takes a checkpoint file, not a run directory. The new run gets a new output directory, and the stopped archive stays as it is.

Is the resumed run the same run?

Run the full case without interruption and compare.

cfd-craft run runs/partial.json --output runs/partial > /dev/null || true
cfd-craft run runs/full.json --restart runs/partial/checkpoint.json \
  --output runs/resumed > /dev/null
cfd-craft run runs/full.json --output runs/cold > /dev/null
import json
from pathlib import Path

resumed, cold = Path("runs/resumed"), Path("runs/cold")
print((resumed / "fields.json").read_bytes() == (cold / "fields.json").read_bytes())
first = json.loads((resumed / "summary.json").read_text())
second = json.loads((cold / "summary.json").read_text())
print(first["physics_sha256"] == second["physics_sha256"])
print(first["initial_state_sha256"] != second["initial_state_sha256"])
True
True
True

The final fields are identical in every byte: a restart replays the same arithmetic. The two results solve the same physics and still record different initial states. initial_state_sha256 is in the summary and the manifest of every run, so a result that started from a checkpoint can always be told from one that started cold. Keep the parent checkpoint if the start of a run must be reproducible. Byte equality is measured here on one host with one build: test it on your platform, as this block does.

What a checkpoint fits

A checkpoint carries the physics hash of chapter 2 and a checksum of its state. The hash covers grid, flow, sources, receptors and numerics, not name, run or output. A checkpoint therefore continues under another budget, thread count or output policy, and under nothing else:

import json

case = json.load(open("runs/full.json"))
case["numerics"]["transport"] = "linear_upwind"
json.dump(case, open("runs/other-scheme.json", "w"), indent=2)
cfd-craft run runs/partial.json --output runs/partial > /dev/null || true
cfd-craft run runs/full.json --output runs/cold > /dev/null
cfd-craft run runs/other-scheme.json --restart runs/partial/checkpoint.json \
  --output runs/other 2> runs/other.err || echo "exit $?"
grep -o "CFD-E[0-9]*" runs/other.err
cfd-craft run runs/partial.json --restart runs/cold/checkpoint.json \
  --output runs/beyond 2> runs/beyond.err || echo "exit $?"
grep -o "CFD-E[0-9]*" runs/beyond.err
exit 1
CFD-E060
exit 1
CFD-E066

CFD-E060 rejects a checkpoint whose identity or checksum does not match the case: here another transport scheme, and likewise another grid. CFD-E066 rejects a checkpoint that lies beyond run.max_steps of the case, or beyond run.end_time_s in transient mode: here the final state of the full run offered to the five-step case. Both exit 1 and write nothing. CFD-E065 reports a checkpoint that cannot be read or exceeds half the memory budget.

Why the endpoint stays fixed

The partial case changed run.max_steps and kept run.end_time_s, on purpose. The last step of a transient run is shortened to land exactly on the endpoint. With a shorter endpoint instead of a smaller step budget, the partial run would shorten its last step there, and the resumed run would take different steps from the uninterrupted one: a valid run of the same physics, but not an exact replay. To test replay, interrupt by work.

Next

Opt-in numerics

At the end of this chapter you have switched on second-order momentum advection, the implicit steady iteration and multigrid, and seen that the acceptance checks do not move. You need the cfd-craft command, a checkout and its Python requirements (chapter 3).

Setup

Commands run from the root of a checkout with cfd-craft on PATH. The setup writes four copies of the steady cavity of chapter 6. Each copy adds options to the one before it:

mkdir -p runs
import json

case = json.load(open("cases/verification/lid-cavity.json"))
case["run"].update(mode="steady", threads=1)
copies = {
    "second": {"momentum_advection": "limited_upwind", "momentum_limiter": "van_leer"},
    "implicit": {"steady_algorithm": "implicit_projection"},
    "recipe": {"pressure_relative_tolerance": 0.1, "max_time_step_s": 100},
    "recipe-mg": {"pressure_preconditioner": "multigrid"},
}
for name, options in copies.items():
    case["name"] = f"cavity-{name}"
    case["numerics"].update(options)
    if name == "recipe":
        case["grid"]["cells"] = [24, 1, 24]  # one span cell, see chapter 6
    json.dump(case, open(f"runs/{name}.json", "w"), indent=2)

The setup also runs the second-order copy (8 to 11 s on the documentation host):

cfd-craft run runs/second.json --output runs/second > /dev/null

Outputs on this page are real. The documentation check compares floating-point numbers with a relative tolerance of 1e-4; everything else must match exactly.

The defaults and why they stay

Field of numericsDefaultOpt-in values
momentum_advectiondonor_cell (first order)second_order_upwind, limited_upwind
momentum_limiternonevan_albada, van_leer, monotonized_central
steady_algorithmexplicitimplicit_viscous, implicit_projection
pressure_preconditioneric0multigrid

A case that names none of these fields runs exactly as it did before they existed, and its hashes and checkpoints stay valid. Every option is part of the physics hash. The options are opt-in: nothing selects them for you, and a change of defaults is an open item of the roadmap.

Second-order momentum advection

limited_upwind replaces the first-order donor-cell flux of the momentum equations with a conservative second-order upwind flux and a slope limiter; second_order_upwind has no limiter. A limiter is required with limited_upwind and not allowed otherwise (CFD-E037). The setup’s run:

import json

s = json.load(open("runs/second/summary.json"))
print(s["termination"], s["assessment"])
print([check["name"] for check in s["checks"]])
print(f"velocity_max = {s['velocity_max_m_s']:.5g} m/s", s["steps"] > 2000)
completed steady_discrete_solution
['local_continuity', 'boundary_volume_balance', 'steady_momentum_equations', 'monitor_stability']
velocity_max = 0.86857 m/s True

It is accepted by the same four checks as the default run of chapter 6. The solution differs: the maximum speed is 0.86857 m/s, against 0.85856 m/s first order. The committed matched accuracy record gives the difference from the Ghia reference as 0.0276 for the default and 0.0054 for this scheme on a 24 x 24 grid. It works with all boundary kinds, buildings and neutral_rans, and leaves numerics.transport alone.

Implicit steady iteration

The explicit steady mode marches small time steps. implicit_projection takes one implicit momentum correction and one projection per outer iteration.

cfd-craft run runs/implicit.json --output runs/implicit > /dev/null
import json

explicit = json.load(open("runs/second/summary.json"))
implicit = json.load(open("runs/implicit/summary.json"))
print(implicit["termination"], implicit["assessment"])
print(explicit["steps"] > 2000, implicit["steps"] < 400)
key = "momentum_solver_iterations"
print(key in explicit, key in implicit)
completed steady_discrete_solution
True True
False True

The implicit run is accepted by the same checks after a few hundred outer iterations, where the explicit run needs more than 2,000 steps: about 0.5 s against 8 to 11 s on the documentation host (implicit steady results). steps now counts outer iterations and momentum_solver_iterations the inner iterations of the momentum solves; an explicit run omits that field. The implicit algorithms need steady mode (CFD-E045) and a computed flow (CFD-E047). implicit_viscous treats only viscosity implicitly, for laminar flow.

The implicit recipe

Two more settings shorten the path to the same steady state: a loose inner pressure tolerance (pressure_relative_tolerance 0.1) and a step cap that no longer binds (max_time_step_s 100).

cfd-craft run runs/implicit.json --output runs/implicit > /dev/null
cfd-craft run runs/recipe.json --output runs/recipe > /dev/null
import json

speeds = []
for name in ("second", "implicit", "recipe"):
    s = json.load(open(f"runs/{name}/summary.json"))
    speeds.append(s["velocity_max_m_s"])
    print(f"{name:8} {s['assessment']}  velocity_max = {speeds[-1]:.5g} m/s")
print((max(speeds) - min(speeds)) / min(speeds) < 1e-4)
second   steady_discrete_solution  velocity_max = 0.86857 m/s
implicit steady_discrete_solution  velocity_max = 0.86857 m/s
recipe   steady_discrete_solution  velocity_max = 0.86857 m/s
True

All three runs are accepted and agree within the tolerance of this page. The recipe changes the path of the iteration, not the steady state or the checks. It takes about 0.1 s on the documentation host. Two cautions: a recipe run that is stopped early is only loosely divergence free and fails check_fields.py, and the gain is measured on this cavity and the coarse canyon of chapter 10 (implicit RANS results).

Multigrid for the pressure equation

cfd-craft run runs/recipe.json --output runs/recipe > /dev/null
cfd-craft run runs/recipe-mg.json --output runs/recipe-mg > /dev/null
import json

ic0 = json.load(open("runs/recipe/summary.json"))
mg = json.load(open("runs/recipe-mg/summary.json"))
print(mg["assessment"], mg["pressure_iterations"] < ic0["pressure_iterations"])
print(abs(mg["velocity_max_m_s"] / ic0["velocity_max_m_s"] - 1) < 1e-4)
steady_discrete_solution True
True

multigrid preconditions the same pressure equation and needs fewer pressure iterations for the same result. It costs setup time and memory, so compare total run times; on this small grid they are equal on the documentation host. A case with geometry uses a separate multigrid path without line smoothing; chapter 22 has its measurements. See pressure multigrid, also for CFD-W004.

Where the time goes: profile

profile runs a case like run and records the time of each solver phase.

cfd-craft profile runs/recipe.json --output runs/profile > /dev/null
python validation/check_profile.py runs/profile > runs/profile-check.json
import json

checked = json.load(open("runs/profile-check.json"))
for key in ("integrity_passed", "numerical_accepted", "physical_qualification"):
    print(key, checked[key])
timing = json.load(open("runs/profile/profile.json"))["timing"]
print(timing["accounted_exclusive_s"] <= timing["elapsed_s"])
integrity_passed True
numerical_accepted True
physical_qualification False
True

runs/profile holds the ordinary run archive in run/ and profile.json. Each phase has calls, inclusive and exclusive seconds. Phases nest, so add exclusive times only. check_profile.py ties the profile to its archive and runs the field audit. physical_qualification is always false: a timing is not a validation. See profiling.

With turbulence and a tracer

implicit_projection also runs neutral_rans cases and constituents (chapter 10). Constituents advance in at most 16 explicit sub-steps per outer iteration and can cover less pseudo-time than the flow (scalar_time_s). Their steady state and its checks are unchanged.

Next

Buildings and a street canyon

At the end of this chapter you have run a street between two buildings with a turbulence model and a line source, and can say what the result supports. You need the cfd-craft command, a checkout and its Python requirements (chapter 3). The grid is too coarse for a physical claim: every concentration here is a workflow example, not a prediction.

Setup

Commands run from the root of a checkout with cfd-craft on PATH. Every section reads this default-numerics run (36 to 47 s on the documentation host):

mkdir -p runs
cfd-craft run cases/canyon/wh1-wind270.json --output runs/canyon > /dev/null

Outputs on this page are real. The documentation check compares floating-point numbers with a relative tolerance of 1e-4; everything else must match exactly.

The case: boxes, open top, wind

The case is cases/canyon/wh1-wind270.json: 18 m x 16 m x 6 m with 18 x 16 x 12 cells of 1 m x 1 m x 0.5 m.

  • geometry lists solid boxes as {"id": "west", "min_m": [x, y, z], "max_m": [x, y, z]}: two buildings, 1 m wide, 10 m long and 1 m high, with a 1 m street between them (W/H = 1). A cell is solid when its center lies inside a box; a box without a cell center is rejected (CFD-E028).
  • flow.kind is neutral_rans: a neutral boundary layer with a k-epsilon model and rough walls. The inlet is a logarithmic profile with speed_m_s (2 m/s) at reference_height_m (1 m) over roughness_m.
  • flow.direction_deg_from is the meteorological wind direction: where the wind comes from, clockwise from north. 270 blows toward +x, across the street.
  • boundaries.z is ground_open_top: rough ground and a top that carries the boundary-layer stress, required by neutral_rans. The open sides become inlet, outlet or slip faces from the wind direction.
  • The source is a line along the street at 0.15 m height, 1e-8 kg/s per meter over 10 m (1e-7 kg/s). Four point receptors sit in the street.

Read the warnings before the result

cfd-craft check cases/canyon/wh1-wind270.json > runs/canyon-check.json
import json

checked = json.load(open("runs/canyon-check.json"))
print(checked["check"]["valid"], checked["check"]["cells"])
print([(d["code"], d["path"]) for d in checked["check"]["diagnostics"]])
geometry = checked["geometry"]
print(geometry["solid_cells"], geometry["box_cells"], geometry["fluid_components"])
True 3456
[('CFD-W001', 'geometry[0]'), ('CFD-W001', 'geometry[1]'), ('CFD-W003', 'domain.size_m[0]'), ('CFD-W003', 'domain.size_m[1]'), ('CFD-W002', 'geometry')]
40 {'east': 20, 'west': 20} 1

The case is valid and carries five warnings. CFD-W001: each building spans 2 cells in height, fewer than the 10 needed for a physical interpretation. CFD-W003: the clearance to the domain sides is below the COST 732 guideline along x and y. CFD-W002: the buildings block more than 3 percent of the cross-section. Warnings do not stop a run; they say what the result cannot be used for. The last line: 20 solid cells per building, one fluid region.

The result

import json

s = json.load(open("runs/canyon/summary.json"))
print(s["termination"], s["assessment"])
print(s["model_scope"], s["turbulent_floor_events"])
print(s["experimental_validation"])
tracer = next(c for c in s["constituents"] if c["id"] == "tracer")
print({k: f"{v * 1e9:.4g}" for k, v in tracer["receptors_kg_m3"].items()})
completed steady_discrete_solution
neutral_k_epsilon_rough_wall 0
not_validated; see validation/data-inventory.json
{'sensor0': '96.5', 'sensor1': '230.7', 'sensor2': '97.09', 'sensor3': '141'}

The run completed and is numerically accepted: continuity, the momentum and turbulence equations, the tracer balance and the monitors pass, and no turbulence floor was hit (one event would prevent acceptance). It is not experimentally validated. The values, in micrograms/m3, are what this model gives on a grid whose street is one column of cells, not a real canyon.

Another wind direction

cases/canyon/wh1-wind225.json differs only in direction_deg_from: 225, a south-west wind with components toward +x and +y, oblique to the street.

cfd-craft run cases/canyon/wh1-wind225.json --output runs/canyon-225 > /dev/null
import json

for run in ("canyon", "canyon-225"):
    s = json.load(open(f"runs/{run}/summary.json"))
    values = s["constituents"][0]["receptors_kg_m3"]
    print(run, s["assessment"], [f"{values[k] * 1e9:.4g}" for k in sorted(values)])
canyon steady_discrete_solution ['96.5', '230.7', '97.09', '141']
canyon-225 steady_discrete_solution ['28.54', '60.11', '93.7', '19.42']

With the oblique wind all four values (micrograms/m3) are lower and rise from sensor0 to sensor2. On this grid they are not a physical result.

The same steady state faster

The default run takes about 3,800 explicit steps. The opt-in implicit recipe of chapter 9 reaches the same discrete steady state:

import json

case = json.load(open("cases/canyon/wh1-wind270.json"))
case["name"] = "canyon-recipe"
case["numerics"]["steady_algorithm"] = "implicit_projection"
case["numerics"]["pressure_relative_tolerance"] = 0.1
case["numerics"]["max_time_step_s"] = 100
json.dump(case, open("runs/canyon-recipe.json", "w"), indent=2)
cfd-craft run runs/canyon-recipe.json --output runs/canyon-recipe > /dev/null
default = json.load(open("runs/canyon/summary.json"))
recipe = json.load(open("runs/canyon-recipe/summary.json"))
print(recipe["assessment"], recipe["steps"] * 5 < default["steps"])
a, b = (r["constituents"][0]["receptors_kg_m3"] for r in (default, recipe))
print(all(abs(b[k] / a[k] - 1) < 1e-4 for k in a))
steady_discrete_solution True
True

The recipe run is accepted by the same checks, and its four sensors equal the default ones within the tolerance of this page. On the documentation host it takes about 2 s where the default takes 36 to 47 s. The recipe is opt-in (implicit RANS results has the measurements and limits), and the grid is still too coarse for a physical claim.

Molecular and turbulent diffusivity

Give a trace gas its real molecular diffusivity_m2_s, of order 1e-5 m2/s. In a neutral_rans case the turbulent diffusivity, eddy viscosity over flow.turbulent_schmidt, does the mixing. A large constant would hide it.

All committed scenarios in one study

tutorials/canyon_study.py runs the three committed canyon cases (W/H of 1 and 2, winds from 270 and 225 degrees), audits each archive with the checker of chapter 3 and writes a report and a figure. It runs two cases at a time and takes about a minute on the documentation host.

python tutorials/canyon_study.py --preset smoke --output runs/canyons > /dev/null
import json

report = json.load(open("runs/canyons/report.json"))
print(report["passed"], report["numerical_accepted"], len(report["runs"]))
print(report["empirical_validation"], report["physical_claim"])
True 3 3
blocked_data none
python tutorials/canyon_study.py --preset sensitivity --output runs/canyon-sensitivity
python tutorials/canyon_study.py --preset study --output runs/canyon-study

sensitivity adds two Schmidt numbers and a longer outlet domain. study also tries two finer grids with the default numerics. In the recorded run neither finished within its 300 s budget; the report keeps those rows as incomplete (native verification).

What this result is not

  • Not resolved. Each building is one cell wide and two cells high, and the street is a single column of cells. No canyon vortex can form on this grid.
  • Not grid-converged. No refinement study has finished, and by default the building-wall roughness depends on the cell width, so refining also changes the wall model (building_roughness_m of chapter 22 fixes the roughness).
  • Not the CODASC wind-tunnel geometry or inflow. The boxes are illustrative.
  • Not validated. The measured data could not be obtained, so no comparison with experiments exists.

It is evidence that the coupled flow, turbulence and tracer workflow runs, conserves mass and reaches a steady discrete state (flow model card, roadmap).

A task for an agent

Give this to a coding agent that has the checkout:

Read docs/ai-context.md and the flow and transport model cards. Run the smoke canyon workflow with no more than its two concurrent processes and two solver threads per process. Explain meteorological wind direction, source normalization, finite-canyon geometry and receptor support. For each scenario show the stopping reason, the independent continuity and mass audit, the equation residuals and the receptor values. Keep a timeout or a failed numerical check in the report. If capacity permits, run the sensitivity preset. Distinguish numerical parameter sensitivity from experimental validation. Consult validation/data-inventory.json and the frozen-protocol requirements before proposing a comparison with measured data. Return a compact report with figures and the limits of its interpretation. A full resolution study requires a separate explicit compute budget.

Next

  • Chapter 11: the Python binding in depth.
  • Chapter 12: many runs, response matrices, source inference.
  • Chapter 22: polygon footprints, buildings from a map, particles and vegetation in this canyon.

Python

At the end of this chapter you know what the Python binding accepts, returns and raises, how to cancel it, and how to script the cfd-craft command. You need the binding; the last two sections also need the command and a checkout.

Setup

The binding is a Rust extension without Python dependencies, for Python 3.10 and newer. Where no wheel exists, pip builds from source with Rust 1.88. The second block builds the binding of a checkout instead.

python -m pip install cfd-craft
python -m pip install maturin==1.9.6
maturin build --release --locked --out dist
python -m pip install dist/*.whl

An installed package has no checkout, so this block fetches the point-source case of chapter 1 and makes a directory for outputs:

import os
import urllib.request

URL = "https://raw.githubusercontent.com/dietmarwo/CFD-craft/main/examples/manual/point-source.json"
urllib.request.urlretrieve(URL, "point-source.json")
os.makedirs("runs", exist_ok=True)

Outputs on this page are real. They contain no floating-point numbers, so the documentation check requires an exact match.

Inputs: dictionary, string or bytes

import json
import math
import cfd_craft as cfd

text = open("point-source.json").read()
case = json.loads(text)
print([cfd.check(value)["valid"] for value in (case, text, text.encode())])
twice = text.replace('"name":', '"name": "first", "name":', 1)
print([d["code"] for d in cfd.check(twice)["diagnostics"]])
case["sources"][0]["rate_kg_s"] = math.nan
try:
    cfd.check(case)
except cfd.CfdError as error:
    print([(d["code"], d["path"]) for d in error.diagnostics])
[True, True, True]
['CFD-E000']
[('CFD-P001', 'python.case')]

check and simulate take a dictionary, JSON text or bytes. Text and bytes reach the native parser unchanged, so it can reject a key that occurs twice (CFD-E000). NaN or infinity in a dictionary raises CfdError (CFD-P001).

Errors carry diagnostics

import json
import cfd_craft as cfd

case = json.load(open("point-source.json"))
case["run"]["threads"] = 0
try:
    cfd.simulate(case)
except cfd.CfdError as error:
    print(isinstance(error, ValueError), sorted(error.report))
    print([(d["code"], d["severity"], d["path"]) for d in error.diagnostics])
True ['cells', 'diagnostics', 'estimated_output_mib', 'estimated_peak_mib', 'schema_version', 'valid']
[('CFD-E008', 'error', 'run.threads')]

For an invalid case check returns its report and simulate raises CfdError, a ValueError, before any work is done. error.report is that report and error.diagnostics its findings. Branch on code and path.

What check and simulate return

import json
import cfd_craft as cfd

case = json.load(open("point-source.json"))
case["run"]["max_steps"] = 5
result = cfd.simulate(case)
print(result["termination"], result["assessment"], result["steps"])
print(set(result) <= set(cfd.describe()["result_schema"]["properties"]))
iteration_limit incomplete 5
True

check returns the check report; the cfd-craft check command wraps it as {"check": ..., "geometry": ...} and adds geometry counts. simulate returns the summary that the command writes as summary.json, schema cfd-craft.result/0.1; describe()["result_schema"] lists its fields. A run that stops early is returned, not raised, so test the assessment first.

Threads, the GIL and concurrent calls

A call releases the GIL while it solves and has its own state and its own pool of run.threads threads. Concurrent calls are safe; limit their number so the pools fit the cores. run.memory_limit_mib bounds an estimate, not the Python process, and the host-memory refusal (CFD-E070) is Linux only.

Cancel from Python

simulate(case, cancel_file=PATH) stops when another thread or process creates the file (polled at most every 20 ms). Ctrl-C in the main thread also cancels, then raises KeyboardInterrupt. Here the file exists from the start:

import json
from pathlib import Path
import cfd_craft as cfd

case = json.load(open("point-source.json"))
Path("runs/cancel").touch()
result = cfd.simulate(case, cancel_file=Path("runs/cancel"))
print(result["termination"], result["assessment"], result["steps"])
cancelled incomplete 0

The console script

python -m cfd_craft (also cfd-craft-python) has describe, check CASE and simulate CASE [--cancel-file PATH].

python -m cfd_craft check point-source.json > /dev/null
echo "check: exit $?"
python -c "import json; c = json.load(open('point-source.json')); c['run']['max_steps'] = 5; json.dump(c, open('runs/five.json', 'w'))"
python -m cfd_craft simulate runs/five.json > /dev/null || echo "simulate: exit $?"
check: exit 0
simulate: exit 2

Exit 0 is a valid case or an accepted run, 1 invalid input or an error, 2 a run without numerical acceptance. The name never hides the cfd-craft command.

Drive the CLI from Python

For fields or an archive, call the command with subprocess:

import json
import subprocess

command = ["cfd-craft", "check", "point-source.json"]
checked = subprocess.run(command, capture_output=True, text=True, timeout=20)
body = json.loads(checked.stdout)
if checked.returncode != 0 or not body["check"]["valid"]:
    raise RuntimeError(body["check"]["diagnostics"])
print(checked.returncode, body["check"]["cells"])
0 1024

Pass the arguments as a list and leave shell off. An I/O error exits 1 with {"error": ...} on stderr and no JSON on stdout, so keep both streams.

The whole native workflow in one script

examples/manual/cli_workflow.py does all of this in one script: schemas, check, run, report, audit, doubled sources, an invalid case, an incomplete archive, a restart, a preview and a VTK export. Its checks raise explicit exceptions, so they also hold under python -O:

python examples/manual/cli_workflow.py --output runs/manual-cli > /dev/null
python -O examples/manual/cli_workflow.py --output runs/manual-cli-optimized > /dev/null
import json

for name in ("manual-cli", "manual-cli-optimized"):
    report = json.load(open(f"runs/{name}/report.json"))
    print(name, report["passed"], report["resumed_equals_cold"])
manual-cli True True
manual-cli-optimized True True

Build identity

Every summary carries source_sha256 and build_version. The binding hashes its own Rust sources and lockfile with those of the core library, so a wheel and a checkout build can differ in identity with the same numerics.

Next

Many runs

At the end of this chapter you have turned one run into a function that can fail, built a response matrix and run two study scripts. You need cfd-craft, a checkout with its Python requirements, and the Python binding.

Setup

Commands run from the root of a checkout with cfd-craft on PATH. All runs use source-response.json: three volume sources, six receptors, linear_upwind.

mkdir -p runs

Outputs on this page are real. The documentation check compares floating-point numbers with a relative tolerance of 1e-4; everything else must match exactly.

A fallible objective

An optimizer or a parameter study calls the solver as a function: write a new case, run it into a new directory, return receptor R1 (kg/m3) of a numerically accepted result, and raise an exception for everything else.

import json
import subprocess
from pathlib import Path

ACCEPTED = {"steady_discrete_solution", "transient_interval_completed"}
BASE = json.loads(Path("cases/verification/source-response.json").read_text())


def objective(name, multipliers, max_steps=6000):
    case = json.loads(json.dumps(BASE))
    case["name"] = name
    case["run"].update(threads=1, max_steps=max_steps)
    for source, factor in zip(case["sources"], multipliers, strict=True):
        source["rate_kg_s_m3"] *= factor
    Path(f"runs/{name}.json").write_text(json.dumps(case, indent=2))
    command = ["cfd-craft", "run", f"runs/{name}.json", "--output", f"runs/{name}"]
    done = subprocess.run(command, capture_output=True, text=True, timeout=180)
    if done.returncode == 1:
        raise RuntimeError("rejected input or execution error")
    summary = json.loads(done.stdout)
    if summary["assessment"] not in ACCEPTED:
        raise RuntimeError(f"{summary['termination']} / {summary['assessment']}")
    return summary["constituents"][0]["receptors_kg_m3"]["R1"]


trials = [("equal", (1, 1, 1), 6000), ("shifted", (0.7, 1.3, 1.0), 6000)]
trials += [("cut-short", (1, 1, 1), 5), ("negative", (1, -1, 1), 6000)]
for name, multipliers, steps in trials:
    try:
        print(name, f"{objective(name, multipliers, steps) * 1e9:.6g} micrograms/m3")
    except RuntimeError as error:
        print(name, "failed:", error)
equal 18.6825 micrograms/m3
shifted 21.5709 micrograms/m3
cut-short failed: iteration_limit / incomplete
negative failed: rejected input or execution error

Two trials return a value. The run that hit its step limit and the case with a negative rate are recorded as failures. Never turn a failure into a large finite number: an optimizer would count it as a solved point.

Unit responses and superposition

With linear_upwind and a fixed flow, receptor values are linear in the source rates (chapter 5): one run per source gives one column of a response matrix. The block uses the binding:

import json
import cfd_craft as cfd

base = json.load(open("cases/verification/source-response.json"))
rates = [0.7, 1.3, 0.9]
combined = json.loads(json.dumps(base["sources"]))
for source, rate in zip(combined, rates, strict=True):
    source["rate_kg_s_m3"] *= rate
r1 = []
for sources in [[source] for source in base["sources"]] + [combined]:
    result = cfd.simulate(dict(base, sources=sources))
    if result["assessment"] != "steady_discrete_solution":
        raise RuntimeError(result["assessment"])
    r1.append(result["constituents"][0]["receptors_kg_m3"]["R1"])
predicted = sum(rate * value for rate, value in zip(rates, r1[:3], strict=True))
print(f"R1 predicted {predicted * 1e9:.5g}, computed {r1[3] * 1e9:.5g}")
print(abs(predicted - r1[3]) / r1[3] < 1e-4)
R1 predicted 21.269, computed 21.269
True

Three unit runs predict receptor R1 of the combined run (micrograms/m3). A response matrix holds for one flow, grid and scheme; with muscl not at all.

What sensors identify: the source-inference study

tutorials/source_inference.py builds the same matrix and then works backward, from receptor values to source rates.

python tutorials/source_inference.py --output runs/inference > /dev/null
import json

report = json.load(open("runs/inference/report.json"))
print(report["passed"], [f"{q:.4g}" for q in report["fitted_rate_multipliers"]])
print(report["heldout_relative_error"] < 1e-9, report["ambiguous_rank"])
for key in ("bounded_noise", "model_mismatch"):
    print(key, f"{report[key]['relative_rate_error']:.3g}")
True ['0.7', '1.3', '0.9']
True 2
bounded_noise 0.0201
model_mismatch 0.059
  • Four receptors fit three non-negative rate multipliers. Same-model observations recover 0.7, 1.3 and 0.9 and predict the two held-out receptors.
  • Two sources with the same column give rank 2: their rates cannot be separated.
  • bounded_noise: a 2 percent observation error moves the rates by 2 percent.
  • model_mismatch: observations from a run with 15 percent more wind give a 6 percent rate error. A good fit does not prove rates under a wrong model.

Synthetic rates, not a posterior. study also refines the mismatched run to 48 x 18 x 18:

python tutorials/source_inference.py --preset study --output runs/inference-study

An independent reference solve

validation/scipy_reference.py assembles the steady transport equations of the same case as a sparse matrix and solves them with SciPy.

python validation/scipy_reference.py --output runs/scipy-reference \
  | python -c "import json, sys; r = json.load(sys.stdin); print(r['passed'], r['relative_field_difference'] < 5e-5)"
True True

The two fields agree within 5e-5 (record). This is numerical verification, not validation: both solve the same equations.

Compare settings fairly

  • Compare runs only under the same sources, geometry, receptors and numerical settings. A lower value from a moved sensor or a coarser grid is no gain.
  • Keep failed rows and real work counts, and reserve held-out observations before you select anything.
  • An inverse fit or an optimizer returns numbers that fit this model, not a calibrated posterior and not a measured emission.

A task for an agent

Give this to a coding agent that has the checkout:

Read docs/ai-context.md and the transport model card. Build the locked workspace and inspect the actual schemas. Run the source-inference smoke tutorial within its declared budgets and a fresh output directory. Check every unit-source and combined result with the archived-field auditor. Verify that the response matrix uses linear transport. Explain the recovered rate multipliers, held-out prediction error, singular values and the deliberately ambiguous case. Then run the study preset and explain how a changed forward model affects fitted rates. Return the report and figure, actual run identities, failed checks if any, and one useful next investigation. Do not describe alternative optimizer outputs as a calibrated posterior.

Next

Chapter 13 builds optimization lessons on this chapter. Chapter 24 infers street emissions from sensor rides. The transport model card states the model’s limits.

Optimization lessons F1 to F3

This chapter runs three complete optimization exercises on the real solver: a linear program hidden in a transport problem (F1), a sensor-placement problem where the optimum does not identify the sources (F2), and a coupled-flow design that must survive a finer grid (F3). Each lesson ends with checks that are allowed to say “no design is supported”. You need a checkout with the release build, the validation requirements and two Python packages; F1 also needs the job runner of chapter 14.

The lessons read cases/verification/source-response.json (F1, F2) and cases/verification/lid-cavity.json (F3) and write every native case, summary and field they produce.

Setup

Run all commands from the root of a checkout. Build the command line, install the validation requirements and the two optimization packages:

cargo build --release --locked
python -m pip install -r requirements-validation.txt
python -m pip install fcmaes-rust==0.5.0 lp-ip-craft==0.33.0

fcmaes-rust provides BiteOpt; lp-ip-craft provides the native LP and MIP solvers. The outputs below were made with fcmaes-rust 0.2.1 and lp-ip-craft 0.29.0; the documentation check reproduces them with fcmaes-rust 0.5.0, whose BiteOpt evaluates the same points, and lp-ip-craft 0.33.0. The lesson scripts find target/release/cfd-craft in the checkout by default (--binary changes it).

mkdir -p runs

Each lesson is one command, python tutorials/optimization/run.py LESSON --output NEW_DIRECTORY, with --preset smoke (default) or --preset study. The lessons are implemented in allocation.py (F1), sensors.py (F2) and coupled.py (F3); support.py holds the bounded CFD runs, the native LP and MIP models and the independent checks of their answers. The output directory must be new. Its summary.json keeps every solve, including rejected ones, and two fields that mean different things:

  • passed is true when the lesson ran to the end and all its checks held. It is a workflow verdict.
  • supported_at_requested_fidelity (F3 only, one per design) is the scientific gate: does the design survive a finer grid? A lesson can pass with zero supported designs.

Neither field is experimental validation of a real site. The checks stay active under python -O. F1 and F2 use prescribed flow and serial transport, so they run with one thread; only F3 solves momentum and pressure.

Outputs on this page are real. The documentation check compares floating-point numbers with a relative tolerance of 1e-4; everything else must match exactly.

F1: a linear problem hides in the simulator

With fixed flow, diffusivity, geometry and boundaries, the linear_upwind transport of the source-response case is linear in its source strengths. Three equal sources (same base rate, same volume) feed six receptors. One unit-source run per source gives one column of a response matrix A (concentrations divided by 1e-8 kg/m3). With source multipliers q, the receptor responses are A q. Minimizing the largest receptor concentration at a fixed total emission is then a linear program with an epigraph variable t:

minimize t
A q <= t
q0 + q1 + q2 = 3
0.1 <= q0,q1 <= 1.4
0.2 <= q2 <= 2.8

These are the bounds and the fixed total of the worker model app.cfd.source-allocation (chapter 14), whose two search coordinates are q0, q1 with q2 = 3 - q0 - q1. Equal source volumes matter: equal rate densities alone would not give equal base emissions for arbitrary source shapes.

The lesson solves the same problem three ways:

  1. LP. The native LP of lp-ip-craft. An independent reference eliminates q2, enumerates the intersections of three active inequalities and checks every candidate against all inequalities. The two optima must agree within 1e-7.
  2. BiteOpt. Every evaluation is a full CFD run with its native and independent field checks. An unacceptable solve returns an unusable objective and stays in the report.
  3. GP. A deterministic Gaussian-process surrogate (fcmaes.surrogate/1: seed 601 as for BiteOpt, four initial points, 64 candidates, ten fit iterations, one fit restart) runs through the fcmaes worker on a local foreground node of optimization-run. Its search evaluations are accepted on the worker’s native steady assessment; the independent field check applies to its answer at the final replay. The lesson fails if this arm has failed or canceled evaluations.

The smoke preset requests 16 BiteOpt and 16 GP evaluations; the study requests 128 each.

python tutorials/optimization/run.py F1 \
  --runner ../optimization-jobs/target/release/optimization-run \
  --output runs/f1 > /dev/null
import json

s = json.load(open("runs/f1/summary.json"))
print("passed:", s["passed"])
for arm in s["arms"]:
    print(arm["method"], arm.get("replay_objective"), arm.get("heldout_wind_objective"))

--worker and --binary take other locations of the worker and the solver. The study preset is a separate command:

python tutorials/optimization/run.py F1 --preset study \
  --runner ../optimization-jobs/target/release/optimization-run --output runs/f1-study

Charge the setup. The LP pays for three unit-response solves before it solves a small model; BiteOpt and GP pay for each objective solve. Compare total cost with response construction, search, the GP’s native recheck and the final replays included. The GP’s work counters are additional to work.full_field_solves, because its worker does not export full fields at each objective; its job handle, inputs, snapshots and result stay under gp/ in the output.

Replay the answers. Each chosen multiplier vector is replayed with a fresh full CFD run. The replay must be a steady discrete solution, pass the independent field checks, and match A q for every receptor within 1e-4 * max(1, r), where r is the replay’s largest normalized receptor value. No replay may beat the LP optimum beyond that tolerance.

Change the wind. Finally every answer is replayed with the wind raised from 1.0 to 1.15 m/s. This is a separate model-mismatch exercise: the training matrix is not exact for the new wind, and the best training allocation need not be best there. Switching the transport to MUSCL would also break the premise, because the limiter is nonlinear and superposition no longer holds exactly.

To go further, try more receptors or another fixed total. For uncertain winds, build one response matrix per frozen wind scenario, put all their receptor inequalities into one robust LP, and replay every selected allocation under its matching conditions.

F2: coverage is not identifiability

Sensor coverage asks whether a release is detected. Source inversion asks which rates produced the observations. F2 solves the first problem exactly and tests the second separately.

There are six candidate receptors and a budget of at most three sensors. Response matrices at training winds 0.85 and 1.15 m/s and six source vectors per wind give twelve scenarios: three single-source releases (weight 3) and three two-source releases (weight 1). A sensor detects a scenario when its normalized concentration reaches 0.24: a physical threshold of 0.22 x 1e-8 kg/m3 plus a noise allowance of 0.02 x 1e-8 kg/m3, both fixed before the search. With binary z_i (sensor chosen) and y_j (scenario covered), the native MIP is:

maximize sum_j weight_j * y_j
sum_i z_i <= 3
y_j <= sum_i detection_ij * z_i
z_i,y_j in {0,1}

All variable bounds are finite, as the native MIP backend requires. The lesson checks the returned candidate’s bounds, row activities and integrality itself, enumerates all twenty three-sensor subsets to confirm the optimum, and runs a greedy baseline that adds the sensor with the largest marginal coverage three times. Each wind’s matrix comes from three accepted unit-source solves with independent field checks; scenario columns are linear combinations of them, exact for linear transport. The study preset uses the same small scenario design.

Then it tests the chosen sensors on held-out source multipliers [0.7, 1.3, 0.4]: a calibration matrix at wind 1.0 and fresh observations at winds 1.0 (in-model) and 1.3 (a deliberate mismatch), with bounded uniform noise from a fixed seed. For each subset it reports singular values, rank, nullity, condition number, the nonnegative least-squares residual and the relative source-rate error.

python tutorials/optimization/run.py F2 --output runs/f2 > /dev/null
import json

s = json.load(open("runs/f2/summary.json"))
print("passed:", s["passed"])
for arm in s["arms"]:
    print(arm["method"], "sensors", arm["sensors"], "covered weight", arm["coverage"])
c = s["coverage_optimal_subsets"]
print("coverage-optimal subsets:", c["count"], c["by_size"])
print("rank deficient:", c["rank_deficient"])
low, high = c["full_rank_condition_range"]
print(f"condition numbers of the full-rank ones: {low:.6g} to {high:.6g}")
for arm in s["arms"]:
    noisy = arm["inversion"][0]["noisy"]
    print(
        f"{arm['method']}: rank {noisy['rank']}, nullity {noisy['nullity']}, "
        f"rate error at wind 1.0 with noise {noisy['relative_rate_error']:.6g}"
    )
passed: True
MIP sensors [4] covered weight 24.0
greedy sensors [1, 0, 2] covered weight 24.0
coverage-optimal subsets: 35 {'1': 2, '2': 13, '3': 20}
rank deficient: 15
condition numbers of the full-rank ones: 2.00322 to 259.403
MIP: rank 1, nullity 2, rate error at wind 1.0 with noise 0.627158
greedy: rank 3, nullity 0, rate error at wind 1.0 with noise 0.00699284

Both methods reach the coverage optimum of 24. In this deliberately permissive fixture two single receptors already detect all twelve scenarios, so every three-sensor subset is optimal too: the instance cannot separate MIP from greedy, and which optimal subset each returns is decided by solver and index order, not by the objective. The MIP’s one sensor gives a rank-1 inverse that cannot recover three rates (a deficient inverse reports its nullity and a null condition_number); greedy’s three sensors give rank 3. An optimal solver status says nothing about identifiability. Inspect scenario-matrix.json, exhaustive.json, optimal-subsets.json and the inversion rows of summary.json before reading anything into it. NNLS here is a separate inverse-problem check; it does not solve or replace the MIP.

To separate the methods, predeclare a stricter detection threshold (one at which no single receptor covers every scenario), scenario costs or more candidates, and repeat. If identifiability is the real objective, state it directly: Fisher-information or continuous-location criteria give a different, nonlinear design problem, not the same MIP.

F3: a design must survive a finer grid

The optimizer searches a coarse grid; a separate fixed gate decides whether its design holds on a finer one. The problem is the laminar lid-driven cavity with the lid speed in [0.6, 1.4] m/s as the only design variable, training kinematic viscosities 0.01 and 0.015 m2/s, and 0.0125 m2/s withheld. The solves use supported box geometry and the opt-in numerics of chapter 9: implicit_projection, limited_upwind momentum advection with the van Leer limiter and multigrid pressure. There are no masks and no new physics.

The objective targets a mean squared fluid speed of 0.04 m2/s2: ((mean_square_speed - 0.04) / 0.04)^2 + 0.02 * lid_speed^2, worst case over the two training viscosities. mean_square_speed is the trapezoid volume mean of the squared face-normal velocities of the staggered grid. The target is a teaching criterion, not a measured requirement.

Frozen before any search: at most 5,000 steps and 30 s of wall time per native solve, the case’s residual tolerance 1e-5 and monitor tolerance 0.001, and at most a 10 % relative change of the mean squared speed between grids. The 30 s limit makes acceptance depend on host load. A solve counts only if the native summary reports steady_discrete_solution and the independent field checks pass; rejected or timed-out solves stay in the evidence with an unusable objective.

The smoke preset trains on 8 x 2 x 8 cells and replays on 16 x 2 x 16 with twelve BiteOpt calls; the study uses 16 x 2 x 16 and 32 x 2 x 32 with 64 calls. Both compare a fixed lid speed of 1.0, five evenly spaced samples and the BiteOpt incumbent, then replay every nominee on the fine grid at both training viscosities and at the withheld one (a convergence check only: it must be accepted, its objective is not gated).

python tutorials/optimization/run.py F3 --output runs/f3 > /dev/null
import json

s = json.load(open("runs/f3/summary.json"))
print("passed:", s["passed"])
print("solves:", s["work"]["full_field_solves"], "accepted:", s["work"]["accepted"])
for arm in s["arms"]:
    print(
        f"{arm['method']}: lid speed {arm['training']['speed']:.6g} m/s, "
        f"grid change {arm['relative_energy_grid_change']:.6g}, "
        f"supported {arm['supported_at_requested_fidelity']}"
    )
print(
    "distinct designs:",
    s["distinct_designs"],
    "supported designs:",
    s["supported_designs"],
)
passed: True
solves: 45 accepted: 45
fixed: lid speed 1 m/s, grid change 0.321019, supported False
sampling: lid speed 1 m/s, grid change 0.321019, supported False
BiteOpt: lid speed 1 m/s, grid change 0.321019, supported False
distinct designs: 1 supported designs: 0

Every native solve was accepted, and the lesson passed, yet no design is supported: the mean squared speed changes by about 32 % between the grids, against the 10 % gate. passed: True must not be read as supported_designs > 0. All three arms return the same lid speed here, so they are one design, and their order in coarse_ranking and fine_ranking is a tie, not a reversal. The study preset is a separate command:

python tutorials/optimization/run.py F3 --preset study --threads 2 --output runs/f3-study

Two-grid agreement is a screening criterion, not a grid-convergence proof. A supported design would still need a systematic refinement study and a physical validation case. The source-allocation worker of chapter 14 never runs this pressure and momentum problem; F3 uses a fallible Python callback, which can be wrapped in a command job. To go further, run the study preset, add a third grid level and report cost to accepted quality.

Unit checks of the lessons

Eight unit and negative checks cover the steady gate (it refuses partial and transient work), a small minimax LP, a rank-deficient coverage optimum, the list of coverage ties, the mean squared speed measure and the record writer (it refuses incomplete runs). They run in about a second and must pass with and without -O:

python -m unittest discover -s tutorials/optimization -p 'test_*.py'
python -O -m unittest discover -s tutorials/optimization -p 'test_*.py'

Recorded results

The lesson record (the record gives no date) holds one complete smoke and one complete study run of all three lessons. In it the F1 LP and the vertex enumeration agree on the normalized optimum 1.6662105873, and the fresh replays match A q to within 1.8e-15 for all three arms; F2 matches the run above; F3 supports zero designs in both presets, with grid changes of 32 % in smoke and 10.4 % to 12.1 % in the study. Every F3 solve in that record was accepted numerically; none of it is experimental validation.

Next

  • Chapter 14: run the solver as a job of optimization-run, which lesson F1 needs.
  • Chapter 12: response matrices and source inference without an optimizer.

Optimization jobs

This chapter runs the solver as jobs of optimization-run, the runner of the separate optimization-jobs project: once as a plain command, and once through the optional fcmaes application worker with an evaluation, a BiteOpt retry and a Gaussian-process surrogate job. You need Rust, a checkout, the worker crate built with its own lockfile and optimization-run built from the pinned optimization-jobs revision.

The standalone solver does not depend on optimization-jobs. The command launcher and the worker live in integrations/ of the checkout; the job and result protocols are those of optimization-jobs, unchanged.

Setup

Run all commands from the root of a checkout. Build the solver and the worker; the worker crate is outside the core workspace and has its own lockfile:

cargo build --release --locked
cargo build --release --locked --manifest-path integrations/fcmaes-cfd-worker/Cargo.toml
python -m pip install -r requirements-validation.txt

The worker pins its two dependencies to exact revisions: fcmaes-rust 2960f434da30b7da80db8cbcea1fd3c2e0e2792e (main after release 0.5.0, the merge that moves its own optimization-jobs pin there; its job crates are 0.5.0) and the optimization-jobs job API ded566f6505efedbf3f2b55fac67e3ae79474616 (main after its 0.5.0 release, with command progress files; its job crates are 0.5.0 and its job API files equal those of the release). Build optimization-run from that same optimization-jobs revision, next to the checkout, as the CI job runner-integration does:

git clone https://github.com/dietmarwo/optimization-jobs ../optimization-jobs
git -C ../optimization-jobs checkout ded566f6505efedbf3f2b55fac67e3ae79474616
cargo build --release --locked --manifest-path ../optimization-jobs/Cargo.toml -p optimization-runner

The commands on this page then name the runner as ../optimization-jobs/target/release/optimization-run; any other location works when given as --runner.

mkdir -p runs

The application worker

integrations/fcmaes-cfd-worker/target/release/fcmaes-cfd-worker describe > runs/worker-description.json
import json

d = json.load(open("runs/worker-description.json"))
print(sorted(x["profile"] for x in d["examples"]))

The worker registers two models. app.cfd.source-allocation, version 1, is the model of this chapter’s four jobs. It consumes a hashed case and requires prescribed flow, exactly three sources with equal positive base rates, one constituent and at least one receptor. Its built-in example uses cases/verification/source-response.json. app.cfd.wind-direction, version 1, is described below.

It exposes two box-bounded parameters, x0 and x1 in [0.1, 1.4]. The three source multipliers are x0, x1 and 3 - x0 - x1; the third lies in [0.2, 2.8], so every source stays positive and the total emission is preserved for equal base rates. The objective is the largest receptor concentration divided by 1e-8 kg/m3. Lesson F1 of chapter 13 solves the same problem as a linear program.

Each evaluation is one full in-process CFD run. It must end as steady_discrete_solution; any incomplete calculation returns an error to the optimizer, never a large number. The job’s deadline and cancellation reach the solver through its Control. Prescribed transport is serial per evaluation; the SDK decides how many evaluations run at once.

Run the four jobs

python integrations/run_jobs.py \
  --runner ../optimization-jobs/target/release/optimization-run \
  --output runs/jobs > /dev/null
import json

r = json.load(open("runs/jobs/report.json"))
print("passed:", r["passed"])
print("command job:", r["command_result"]["state"])
for profile in ["fcmaes.evaluate/1", "fcmaes.retry/1", "fcmaes.surrogate/1"]:
    execution = r[profile]["execution"]
    work = execution["known_work_lower_bound"]
    print(
        profile,
        execution["state"],
        "failed",
        work["failed_evaluations"],
        "cancelled",
        work["cancelled_evaluations"],
    )

--binary and --worker default to the release builds of the checkout. The script makes a local foreground node in runs/jobs/node and submits four jobs:

  1. A command job (execution.command/0.1): a 12 x 6 x 6 copy of periodic-tracer.json, run by the CLI through the launcher, with the case, the launcher and the solver binary staged as hashed inputs.
  2. fcmaes.evaluate/1: the original layout and one more point.
  3. fcmaes.retry/1: BiteOpt with a hard cap of 24 new evaluations and a recheck of the best point.
  4. fcmaes.surrogate/1: the experimental GP surrogate, also 24 evaluations with a recheck.

It checks terminal states, that every requested task completed, that the failed and canceled evaluation counters are present and zero, and the runner’s result manifests. It does not take a zero exit of the runner as proof that a job completed. The job files it writes (command.json, and fcmaes.json for the optimizer jobs, each overwriting the previous one) are the inputs to inspect; do not reconstruct their fields from memory.

Recorded values. The native verification record (the record gives no date) reports a run with optimization-run built at 12f9d57: all three optimizer jobs completed, retry and GP each used 24 new CFD evaluations and one recheck with no failed or canceled evaluations, and the objectives were 1.8682465 for the original layout and 1.8657713 and 1.6799143 for the BiteOpt and GP selections (largest receptor concentration over 1e-8 kg/m3). Each value is an accepted steady discrete solution; none is an experimental result, and one small seeded run does not rank BiteOpt against GP.

The command launcher

integrations/launch_command.py is the program a command job runs. The runner creates the declared output parent directories before launch, but the CLI refuses an existing run directory. The launcher therefore runs cfd-craft run case.json --output simulation in a fresh child directory and then copies simulation/summary.json to the flat output the job declares. An empty prepared parent does not switch off the CLI’s overwrite protection.

On SIGTERM or SIGINT (a runner deadline or a cancellation) the launcher forwards the signal to the solver and waits, so the canceled summary is still collected. Its handlers are installed before the solver starts; a signal that arrives during start-up is delivered once the solver exists.

What a job result is not

An execution.command/0.1 envelope describes a process and the outputs it collected. An optimization.job/0.1 envelope also names a registered optimizer worker and a versioned payload profile. A completed command state is not an optimization claim, and an optimizer’s best-found and rechecked value is neither a CFD archive nor a calibrated posterior nor an experimental claim. Where a physical result is needed, attach separate CFD evidence (a native run archive, chapter 4).

Keep objective calls, SDK rechecks, failed and canceled work and CFD steps apart when you report cost. The worker runs CFD for every evaluation; reusing a response matrix (chapter 12) is a different technique with its own fixed-flow and linear-transport assumptions.

Campaigns

The command and optimizer files written by run_jobs.py are ordinary execution.command/0.1 and optimization.job/0.1 envelopes, so experiment-craft can schedule them as dependent campaign steps without a new CFD protocol or server. experiment-craft owns placement, dependencies and transfer; CFD-craft owns cases and CFD evidence. command.json names the Python interpreter that ran run_jobs.py as argv[0]; replace it with the interpreter of the target node when reusing the file.

Not tested in this release: a full multi-node CFD campaign, remote machine commissioning and transfer of large fields.

Wind-direction jobs for a city block

app.cfd.wind-direction optimizes over the wind direction of a case with buildings. It consumes a checked neutral_rans case with one constituent, sources and receptors. Its one parameter is the meteorological wind direction in the model frame, where the wind comes from, in [0, 360]. The objective is the largest receptor concentration divided by 1e-8 kg/m3. Every evaluation starts cold and must end as an accepted steady solution; anything else is returned to the optimizer as an error, never as a number. The model returns a scalar, not a field archive, and it has no automated test in the repository yet.

For full archives use the campaign of chapter 22 with --runner PATH/optimization-run:

python validation/urban_campaign.py run runs/district/case.json \
  --output runs/district-rose-jobs --run-budget-s 120 --campaign-budget-s 1200 \
  --runner ../optimization-jobs/target/release/optimization-run

Each direction becomes an execution.command/0.1 job with the case, the job description, the launcher integrations/launch_urban_command.py, the campaign worker, the field checker and the solver binary as hashed inputs. A job returns its result row and the complete run archive as a ZIP file; the runner limits each collected file to 64 MiB. Failed and timed-out directions are kept as rows. Without --runner the same campaign runs as local processes.

Limits:

  • An accepted command job is not an accepted run, and neither is a validated result. Read the row of each direction.
  • On a timeout the campaign stops only the runner process. The processes the runner started (launcher, worker, solver) may keep running; check for them and stop them yourself.

A task for an agent

Build the optional worker with its lockfile. Register it on a new local foreground optimization-jobs node, then run integrations/run_jobs.py. Use cases/verification/source-response.json; keep geometry, source support, total integrated emission and receptor IDs fixed.

Confirm that the case is a consumed, hashed input, that the CFD callback respects cancellation, and that every accepted objective comes from a checked steady simulation. Compare the original layout, BiteOpt and GP selected values with equal budgets of 24 new calls per optimizer. Count new evaluations, failed and canceled calls and rechecks separately, and retain failures.

Treat this as an integration demonstration, not a statistical ranking. Preserve the optimization result contract and attach separate CFD evidence where a physical result is needed. Report concentrations in kg/m3 and micrograms/m3, keep numerical checks apart from physical validation, and use fresh output directories.

For a new application, define the objective and the conservation constraints before choosing an optimizer. Do not reward a lower concentration obtained by moving a sensor, changing the source inventory or lowering numerical fidelity.

Next

  • Chapter 15: Part IV, the OpenFOAM backend, starting with install and a first cavity.
  • Chapter 13: the same allocation problem solved as a linear program.

Install OpenFOAM and run a cavity

This chapter installs the pinned OpenFOAM Foundation 13 runtime without root, then generates, runs and checks one laminar cavity through CFD-craft’s bounded OpenFOAM adapter, from the command line and from Python. You need Ubuntu 24.04 on x86_64, a checkout, Python 3.10 or newer, Rust 1.88 or newer and dpkg-deb.

No output is shown on the OpenFOAM pages: the documentation check runs them only in the opt-in CI job that installs the runtime, and the outputs of this host would be invented. Recorded numbers are quoted from the evidence pages, with their date.

Setup

Run all commands from the root of a checkout:

cargo build --release --locked
python -m pip install -r requirements-validation.txt
mkdir -p runs

The pages of this part write the runtime root as runs/openfoam13/runtime/opt/openfoam13, the directory the installer below produces.

What the backend is and is not

The adapter supports two generated cases on OpenFOAM Foundation 13: a laminar Re = 100 lid-driven cavity and a turbulent backward-facing step (the Driver and Seegmiller experiment) with the k-omega SST model. It is a bounded workbench for numerical cross-checks and for comparison with measurements.

It is not a translator: a native CFD-craft case (for example a street canyon) cannot be run in OpenFOAM, OpenFOAM runs no scalar dispersion here, and there is no fcmaes worker for it. The native solver and its worker are unchanged by it.

OpenFOAM is licensed under the GNU GPL, version 3 or later. CFD-craft runs its programs (blockMesh, checkMesh, foamRun, field post-processing) as separate, bounded processes and neither links nor imports them; no OpenFOAM source, library or executable is part of the repository. The generated dictionaries and the Python adapter are CFD-craft code. A velocity comparison on these cases cannot qualify the native canyon’s concentrations. The OpenFOAM backend model card states the supported scope.

Install the pinned runtime

python integrations/install_openfoam13.py --output runs/openfoam13

The installer downloads one pinned Ubuntu package (118,586,852 bytes), checks its size and SHA-256 and extracts it with dpkg-deb into a new directory. It installs no system packages and needs no root. OpenFOAM’s serial Pstream library is used, so MPI is not needed. --package-file PATH reuses a local copy of the same package; its size and hash are still checked.

The tested build is package 20260407 (build 13-441953dfbb42, double precision, 32-bit labels). The adapter checks the executable’s own version and records the hashes of the executables and solver libraries: another Foundation major version or an OpenCFD fork is rejected, and another build of Foundation 13 is identified by its hashes and needs its own review. An existing Foundation 13 installation can be given as the runtime root instead. The CI jobs that run these pages install the runtime in a step of their own.

Generate, run and inspect

python integrations/openfoam_backend.py prepare --case cavity --level 1 \
  --iterations 3000 --output runs/foam-cavity-input
python integrations/openfoam_backend.py run --case runs/foam-cavity-input \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 \
  --timeout-s 180 --output runs/foam-cavity
python integrations/openfoam_backend.py report runs/foam-cavity

prepare writes the generated case: dictionaries, mesh description and its own case.json record. Level 1 is a 24 x 24 cavity, levels 2 and 3 are 48 x 48 and 72 x 72. run copies the input into the new archive, checks the copy against the sealed identities and runs mesh generation, the mesh check, the solver and post-processing as separate processes, each under a shared deadline (--timeout-s), an output budget (--output-mib, default 256) and an address-space limit (--memory-mib, default 2048). report reads the archive back and checks it.

A convergence message in the log is not enough. The adapter also requires final residuals, continuity and stored-field checks, and it records the runtime, dictionary, mesh, log and output identities. Each output directory must be new and its parent must exist. If the generator changes, prepare a new case. Execution is shell-free, single-process and serial.

Exit codes of the adapter

Command021
prepare, prepare-mapped, prepare-restartprepared–invalid request or ineligible source
runaccepted numerical evidencecompleted, timed out or canceled without itthe execution itself failed (runtime, input, I/O)
reportas run for the archived resultas runfailed execution, or an archive that fails verification
validation/compare_backstep.pynumerical gate and development screen passeither failsoutput cannot be written
tutorials/external_cfd.py, tutorials/backstep_resolution.pyeverything passesfailed, unaccepted or canceled evidence recordedworkflow error
validation/audit_openfoam_mesh.pychecks passchecks fail, or no final fieldinvalid archive or output path
validation/compare_restart.py, validation/restart_equivalence.pybounds holdbounds do not holdinvalid input

In the resolution tutorial of chapter 18 a completed stage that cannot seed the next stage is recorded evidence (exit 2), not a workflow error. No exit code sets physical qualification to true. Read all four levels separately: execution, numerics, measurement screen and physical qualification.

The external archive

The result of run is an archive of schema cfd-craft.external-run/0.1. It is not a native run archive and not an optimization result: the native cfd-craft report does not read it; use the adapter’s report.

The archive has a checksummed manifest and a completion marker, written also when the run fails. Completion means the evidence has been written. passed additionally requires numerical acceptance and valid final samples. Child failure, cancellation and timeout stay distinct. The command record keeps the real return code and log; the progress record lists the iterations started and the snapshots saved, which may precede a partial last iteration. A symbolic link left by a child marks the run failed.

report checks consistency: file hashes, the consumed inputs, that the case holds nothing but solver outputs, the numerical summary recomputed from the returned log and fields, status and error codes, return codes, the runtime and log identity, progress and samples. Unkeyed hashes are not tamper evidence: a consistent rewrite of log, fields and summary cannot be detected this way.

Use the adapter from Python

python examples/manual/openfoam_api.py \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 --output runs/manual-foam

examples/manual/openfoam_api.py imports openfoam_backend from the checkout’s integrations/ directory and calls prepare, run and verify on a level-1 cavity with 3,000 iterations, a 180 s deadline and 64 MiB of output. It writes runs/manual-foam/report.json with passed, archive_consistent and physical_qualification (always false). An intact archive can still hold an unaccepted solve, so the script checks numerical.passed of the verified archive explicitly. The adapter is a source-checkout module: it is not part of the installed cfd_craft Python package, and its results are not native result schemas.

Trusted inputs only

The backend executes only dictionaries it generated, in a copied fresh directory. Input hashes detect changes; they are not a signature that authorizes untrusted OpenFOAM code, and OpenFOAM itself can load user code, so do not substitute unreviewed case directories.

Each child process gets a fixed environment (the runtime paths, single-threaded BLAS and OpenMP, HOME=/nonexistent, nothing inherited from the caller’s OpenFOAM settings), a hard address-space limit and a per-file size limit. The output budget and the wall time are polled every 50 ms, so a small overshoot is possible. SIGTERM, SIGINT and the deadline terminate the process group, with a forced kill after one second if needed; the log and the failure archive are kept. A NaN or infinite residual, or a mean continuity error of at least 1 (in units of the reference velocity over the step height), stops the process group with CFD-X010, also when the child exits 0. Earlier saved snapshots are never promoted to final solutions. The model card’s execution limits give the details.

Tests without a runtime

The contract tests use synthetic fixtures, including a stand-in for the four Foundation 13 programs that drives run and report end to end. They test contracts, not physical accuracy, and need no runtime:

python validation/test_openfoam.py -v
python -O validation/test_openfoam.py -v
python validation/test_resolution.py -v
python validation/test_restart.py -v
python validation/test_mapping.py -v

With CFD_OPENFOAM_ROOT set, the same files add tests with real solves: cavity runs, an iteration-limit failure, corrupted fields and face fluxes that must be rejected, the wall-resolved blockMesh output against the generated first-cell heights, continued runs against uninterrupted controls, and mapped fields at the next level:

CFD_OPENFOAM_ROOT="$PWD/runs/openfoam13/runtime/opt/openfoam13" \
  python validation/test_openfoam.py -v
CFD_OPENFOAM_ROOT="$PWD/runs/openfoam13/runtime/opt/openfoam13" \
  python validation/test_resolution.py -v
CFD_OPENFOAM_ROOT="$PWD/runs/openfoam13/runtime/opt/openfoam13" \
  python validation/test_restart.py -v
CFD_OPENFOAM_ROOT="$PWD/runs/openfoam13/runtime/opt/openfoam13" \
  python validation/test_mapping.py -v

The CI job external-contracts runs the contract tests normally and under -O, together with validation/test_refinement.py (chapter 19); the runtime tests run in the opt-in external-backend job.

Next

  • Chapter 16: compare the cavity with the native solver and the backstep with measurements.
  • Chapter 17: continue this cavity on the same mesh or start a finer one from it.

Compare solvers and measurements

This chapter makes three comparisons with the OpenFOAM backend: the native solver and OpenFOAM on the same cavity against a numerical reference, OpenFOAM on the backward-facing step against public measurements under a frozen protocol, and the cost of both backends on one host. You need the runtime of chapter 15, a checkout with the release build and the validation requirements.

The three comparisons answer different questions. The cavity is a numerical cross-check. The backstep is a first screen against measurements, which a calculation may enter only after it passes the numerical gate. The timing compares configured workflows, not equal work.

Setup

Run all commands from the root of a checkout, with the runtime installed as in chapter 15 at runs/openfoam13/runtime/opt/openfoam13:

mkdir -p runs

Two solvers against a numerical reference

python tutorials/external_cfd.py --preset cavity \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 --output runs/two-cavities

The cavity preset runs the Re = 100 lid-driven cavity with the native solver (--binary, default the checkout’s release build) and with OpenFOAM, samples both along the centerlines with shared helpers, and compares each with the Ghia, Ghia and Shin (1982) stations and with the other solver. The native case uses x and z, OpenFOAM x and y; the mapping between the vertical axes is explicit. Ghia et al. is a numerical benchmark, not an experiment, so this is a numerical cross-check. Its report is runs/two-cavities/cavity-comparison.json.

In the external-backend record (a GitHub-hosted run of the study preset; the record gives no date), the maximum centerline velocity error over the lid speed was 0.0275488 for native against Ghia, 0.00896632 for OpenFOAM against Ghia and 0.0311705 between the two solvers, each against a target of 0.06. Both runs completed and were numerically accepted; the native case ran transient to 30 s, OpenFOAM converged in 696 steady iterations.

One solver against measurements

The backstep uses the raw Driver and Seegmiller measurements published by the Turbulence Modeling Resource. Fetch them once; the script checks frozen SHA-256 identities and never substitutes synthetic data:

python validation/backstep_data.py --output runs/backstep-measurements
python tutorials/external_cfd.py --preset smoke \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 \
  --data runs/backstep-measurements --timeout-s 300 \
  --output runs/external-smoke || echo "exit $?"

Without --data, the smoke and study presets download the same pinned files into their output. The smoke preset runs the cavity and the level-1 backstep (legacy recipe, 6,000 iterations) with a 300 s budget per case. It exits 0 when everything passes, 2 when it recorded failed, unaccepted or canceled evidence, and 1 on a workflow error.

The same backstep with the single commands, so that each verdict can be read on its own:

python integrations/openfoam_backend.py prepare --case backstep --level 1 \
  --iterations 6000 --data runs/backstep-measurements --output runs/backstep-input
python integrations/openfoam_backend.py run --case runs/backstep-input \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 --timeout-s 300 \
  --memory-mib 2048 --output-mib 512 --output runs/backstep-run || echo "exit $?"
python integrations/openfoam_backend.py report runs/backstep-run || echo "exit $?"
python validation/compare_backstep.py --run runs/backstep-run \
  --data runs/backstep-measurements --output runs/backstep-comparison || echo "exit $?"

The profile at x/H = -4 defines the inlet. The stations x/H = 1, 4, 6 and 10 (112 velocity samples) and 17 lower-wall skin-friction values are evaluation data; no case parameter is fitted to them. Pressure coefficients are fetched for provenance and are not scored. The comparison is assessed only when the run passed its numerical gate; otherwise it reports the screen as not_assessed and its metrics describe the final iterate only.

In the external-backend record the level-1 legacy backstep (22,656 cells) ran all 6,000 iterations and did not pass the numerical gate: its final pressure residual was 1.19e-3 against 1e-7, and the solve was stalled, so the measurement screen was not assessed. A plausible velocity plot does not change that. The wall-resolved recipe of chapter 18 is the one that passes.

The frozen protocol

The screen’s stations, pairing rules and targets are in validation/protocols/backstep-v1.json, and the evaluator checks its hash, so a local edit cannot relax a threshold. A justified change needs a new reviewed protocol version with its own identity and reason, and a fresh evaluation; keep the previous report. Measurement error, mesh sensitivity and uncertain inlet or model assumptions are separate quantities.

Mesh levels and the study preset

python tutorials/external_cfd.py --preset study --timeout-s 300 \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 --output runs/external-study

The study preset runs backstep levels 1, 2 and 3 (22,656, 90,624 and 203,904 cells) under the same per-case budget and keeps timeouts and incomplete rows. Levels 2 and 3 need far more than 300 s of serial time for their 6,000 iterations; in the external-backend record they timed out. An incomplete mesh series gives no GCI and no mesh-independent physical claim.

Time both backends on one host

python validation/compare_backends.py \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 \
  --repeats 1 --timeout-s 180 --output runs/backend-timing

--binary defaults to the checkout’s release build. The script runs the cavity three ways (OpenFOAM steady, native steady and native transient to 30 s), one solver thread each. After warmups, each repeat runs all six orders of the three methods. It requires accepted runs, identical repeated work, profiles and producer identities, and stable input hashes; any failed run fails it. The CI selection external=comparison runs it with --repeats 2.

Workflow time and solver time are different measurements. OpenFOAM’s workflow includes meshing, sampling, runtime hashing and process polling; its solver time is the foamRun child. The native solver time is its own elapsed_s, not the Python helper’s total time.

Cost at a declared accuracy

The grid sweep asks a different question: how much does each backend cost to reach a stated centerline accuracy?

python validation/compare_backends.py --grid-sweep \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 \
  --levels 1 2 --sweep-rounds 3 --accuracy-target 0.01 \
  --native-wall-s 180 --timeout-s 180 --native-max-steps 20000 \
  --foam-iterations 3000 --output runs/accuracy-sweep

Levels 1 and 2 are 24 x 24 and 48 x 48 cells in the flow plane; --grids 16 24 32 48 gives an explicit list instead. The sweep alternates the backends within each grid, keeps one warmup per configuration and adds a native 12 x 12 diagnostic. Native uses two periodic span cells (--native-span 1 for one); OpenFOAM one empty span cell. Opt-in native numerics are given as JSON with --native-numerics and the pressure preconditioner with --native-pressure-preconditioner.

Every row keeps numerical acceptance, the independent checks, the frozen 0.06 Ghia screen and the measured error apart. The best cost at the target uses only configurations whose timed repeats are all accepted and repeat their work, producer and samples. If a backend misses the target on every grid, its best cost and the ratio are null; no crossing is extrapolated. The sweep exits 0 when all rows pass the existing checks, 2 when it holds unaccepted evidence, and 1 for an invalid workflow, changed input or inconsistent repeat; missing the 0.01 development target alone is a recorded outcome. The CI selection external=accuracy runs this sweep with a 600 s native budget. The profiling page describes the timers and memory observations.

What the committed measurements say

All of them come from one laminar two-dimensional case, the Re = 100 cavity. With the default native numerics, the backend comparison (the record gives no date) found OpenFOAM’s workflow 4.7 to 5.5 times faster than native steady mode on two hosts, its solver process about 9 times faster, and OpenFOAM closer to Ghia. With the opt-in limited_upwind, implicit_projection and multigrid settings, the matched-accuracy record of 1 November 2026 found native at 24 x 24 cells with solver time 0.549 s and Ghia error 0.00543 against 0.743 s and 0.00897 for OpenFOAM, all 32 rows accepted. The comparison page puts these in context; none of it says anything about urban flows.

A task for an agent

Use CFD-craft’s external backend and the OpenFOAM backend model card.

  1. Check out a named revision and build the native CLI with --locked. Install the pinned Foundation 13 package with the provided installer on Ubuntu 24.04.
  2. Run tutorials/external_cfd.py --preset cavity first. Check each solver against Ghia and against the other solver, including the different vertical coordinates.
  3. Run the smoke backstep experiment with the frozen protocol and the raw-data hashes. Use a fresh output directory and a declared per-case wall budget.
  4. Inspect every execution and numerical status before discussing measurement errors. Preserve failed rows. Do not increase tolerances to obtain a pass.
  5. Use the study preset for mesh sensitivity only when the smoke calculation and the resources justify it. Incomplete meshes cannot support grid convergence.
  6. Report what is measured, which data define the inlet, which are held out, the turbulence assumptions, and what remains unqualified. A velocity comparison does not validate concentrations or the native canyon solver.

Deliver the report, paired samples, runtime and input identities, and figures. Do not contact data owners or publish results.

Next

  • Chapter 17: continue a solve on the same mesh, or start a finer mesh from an accepted one.
  • Chapter 18: the wall-resolved backstep that passes the numerical gate.

Continue a solve, start a finer mesh

This chapter shows the two ways to reuse an OpenFOAM result of the backend: continue a steady solve on the same mesh in a fresh, bounded stage, and start the next finer mesh from an accepted coarse solution. Both start new local work, and both need the unchanged final gates again. You need the runtime of chapter 15 and a checkout with the validation requirements.

A single run of the adapter is limited to 3,600 s and 20,000 iterations. Continuation lets a long steady solve progress in separately bounded, auditable stages; mapping lets a finer mesh start from a converged coarse field. Neither restores a transient time history.

Setup

Run all commands from the root of a checkout, with the runtime at runs/openfoam13/runtime/opt/openfoam13. Both sections start from the cold level-1 cavity of chapter 15:

mkdir -p runs
python integrations/openfoam_backend.py prepare --case cavity --level 1 \
  --iterations 3000 --output runs/foam-cavity-input
python integrations/openfoam_backend.py run --case runs/foam-cavity-input \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 \
  --timeout-s 180 --output runs/foam-cavity

Continue on the same mesh

python integrations/openfoam_backend.py prepare-restart --source runs/foam-cavity \
  --iterations 3000 --output runs/foam-continuation-input
python integrations/openfoam_backend.py run --case runs/foam-continuation-input \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 \
  --timeout-s 180 --output runs/foam-continuation

prepare-restart turns a completed archive into the input of a fresh steady stage: the source’s verified final fields and face flux become the initial state, and the case, mesh and controls stay the source’s. The new stage starts its local pseudo-time and residual history at zero. --iterations (default 6,000) is the new stage’s limit. Eligibility to continue is separate from final numerical or measurement acceptance: the continued run must pass every gate on its own.

Which sources are eligible

A source must be a complete archive (case, mesh, final fields, logs, summary, manifest and completion marker); a summary or a log alone cannot supply a restart. It is eligible when:

  • its seals verify and its execution completed with a final field; failed, timed-out and canceled runs are rejected, including any older snapshots they contain;
  • its final fields are finite, with nonnegative k and nut and positive omega;
  • it was generated by the current case generator, with the generated steady controls;
  • its stored face flux passes the auditor’s independent local gate, max abs(div(phi)) * H / U <= 1e-4.

A completed but unconverged stage can be eligible: report then exits 2, and the source is still accepted. prepare-restart exits 0 for a prepared stage and 1 otherwise, with a coded field path: CFD-X012 at initial_state.* for eligibility and receipt errors, CFD-X006 for an archive that fails verification or an invalid final field, and CFD-E062 or CFD-E063 for the output path. A failed preparation leaves no partial stage.

The flux gate is strict for early stages. It follows the last pressure solve’s relative tolerance and tightens with refinement. In the continuation record (the record gives no date) the wall-resolved simplec backstep scores 0.0048 at iteration 500 (rejected), 2.7e-9 at 6,000 and 6.6e-10 at 10,000, and a cold start scores 5.6; use stages of thousands of iterations. Whether this gate suits continuation is recorded there as an open decision.

The general form, for any completed source (SOURCE_RUN, NEW_* and ROOT are placeholders):

python integrations/openfoam_backend.py report SOURCE_RUN
python integrations/openfoam_backend.py prepare-restart --source SOURCE_RUN \
  --iterations 6000 --output NEW_INPUT
python integrations/openfoam_backend.py run --case NEW_INPUT \
  --foam-root ROOT --timeout-s 3500 --output-mib 512 --output NEW_RUN
python validation/audit_openfoam_mesh.py --run NEW_RUN --output NEW_AUDIT.json

No change of physics, mesh or solver profile is accepted; prepare an ordinary cold case for another model. The exact runtime and the rebuilt mesh must match the recorded identities before the solve.

What is carried forward

U, p and phi and, for SST, k, omega and nut are copied byte for byte from the source’s final field directory into the new 0 directory, with their boundary definitions; their headers keep the source time as location, which the receipt checks. The physics, mesh and sampling dictionaries keep their source identities. The new controls are the source’s with only endTime and writeInterval replaced.

numerical.iterations counts the new stage only; the receipt’s source_completed_iterations plus it counts solver work along the chain, not physical time. In the continuation record a laminar cavity split into 400 and 200 iterations reproduces the uninterrupted 600 to round-off (1.03e-15 m/s in U). In the SST backstep the residuals of the restarted iteration differ by about 1e-4 relative, where some turbulence-model state is not carried by the copied fields; a converged staged solve still ends within about 2e-12 in U of the single run.

The receipt in case.json and summary.json records the parent case and manifest, source acceptance and work, source metadata and controls, copied field hashes, the actual mesh, fixed inputs, runtime identity and the source flux check. They are checked before the solve and when an archive is verified. Keep the parent archives: the parent hash alone does not hold their contents. Checksums establish consistency, not authenticity.

Start a finer mesh

python integrations/openfoam_backend.py prepare-mapped --source runs/foam-cavity \
  --level 2 --iterations 3000 \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 \
  --output runs/foam-finer-input

Run the prepared level-2 case like any other, into a new directory:

python integrations/openfoam_backend.py run --case runs/foam-finer-input \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 \
  --timeout-s 180 --output runs/foam-finer

This is a new-mesh start, not a continuation. The source must be a cold-generated case that is numerically accepted and independently audited; a restarted or mapped source is refused. Level 1 maps to level 2 and level 2 to level 3; the case, mesh family, turbulence model and solver profile cannot change, and the source inputs must equal what the current generator writes for that recipe (with the verified measurement files for the backstep). The fine case starts at local pseudo-time zero and must earn its own numerical and measurement results; the thresholds do not change.

prepare-mapped exits 0 when the case is prepared and 1 otherwise; exit 0 says nothing about the fine flow. Checks of the source and runtime run before the output is created. A later failure leaves a directory without case.json, which cannot run, holding mapping-failure.json and the logs of the utilities that ran.

The general form for the backstep, which also audits the fine run and compares it with the measurements (placeholders as above; VERIFIED_DATA is a directory from validation/backstep_data.py):

python integrations/openfoam_backend.py prepare-mapped --source COARSE_RUN \
  --level 2 --iterations 3000 --foam-root ROOT --data VERIFIED_DATA \
  --timeout-s 600 --output-mib 1024 --output NEW_FINE_INPUT
python integrations/openfoam_backend.py run --case NEW_FINE_INPUT \
  --foam-root ROOT --timeout-s 3500 --output-mib 1024 --output NEW_FINE_RUN
python validation/audit_openfoam_mesh.py --run NEW_FINE_RUN --output NEW_AUDIT.json
python validation/compare_backstep.py --run NEW_FINE_RUN --data VERIFIED_DATA \
  --output NEW_COMPARISON

For the cavity omit --data. The accepted wall-resolved simplec level-1 backstep of chapter 18 is a valid source.

What is mapped and how it is checked

Foundation 13’s mapFields -consistent -mapMethod mapNearest runs on checked copies of the source and of the generated target case. Only the mapped internal U and p and, for SST, k, omega and nut enter the fine case. The target’s boundary conditions, dimensions and controls are written by the generator and kept byte for byte; the mapper’s boundary values are discarded. Field counts, finite values and turbulence signs are checked. Nearest-cell initialization is not conservative interpolation and makes no accuracy claim.

There is no fine 0/phi: a coarse face flux means nothing on another mesh. The solver builds phi from the new U and corrects it as usual.

case.json carries a mesh_initialization receipt (cfd-craft.mesh-initialization/0.2), and the consumed inputs include mapping_evidence/: the checked source copy, the generated target templates, the mapper’s output and mesh, and the utility logs and arguments. Before every solve and when an archive is verified, the adapter:

  • checks the source chain: manifest, summary, case record, audit, field identities and snapshot times, acceptance, work and runtime;
  • checks that the utilities ran in order on this case’s own copies, with the recorded source time, -consistent and mapNearest, and that the mapper’s log names Foundation 13, the method and every field;
  • replays the mapping with its own mesh reader: each consumed internal value must equal the value of the source cell whose center is nearest to the target cell’s center;
  • rebuilds each consumed field from its stored template and the mapper output, and compares the controls with the generator.

A mapped run can later be continued with prepare-restart under the unchanged flux gate. Its parent identity binds the mapping history; the coarse work is recorded as source_iterations and not counted as fine-grid work.

Budgets

Preparation of a mapped case defaults to 300 s, 512 MiB of output and a 2,048 MiB child address space (--timeout-s, --output-mib, --memory-mib); the limits are 3,600 s, 2,048 MiB and 8,192 MiB. The mapping evidence counts toward the output and is copied into the run, so a mapped run needs more output room than a cold one: validation/mapped_start.py gives both level-2 runs 1,024 MiB.

A run that stops at its iteration limit writes a final field only when the limit is a multiple of the write cadence. Preparation therefore uses the largest divisor of the limit up to 250 as the cadence and rejects limits without a divisor between 50 and 250. Multiples of 50 are always accepted.

Four operations compared

OperationMeaningNew final gates required?
Native checkpoint (chapter 8)Compatible discrete state and cumulative budgets, same grid and physicsYes
External steady restart (prepare-restart)Fresh steady stage, same mesh, physics and runtimeYes
External mapNearest (prepare-mapped)Fresh target mesh, mapped volume initial guessYes
Refinement campaign (chapter 19)Bounded composition with complete provenanceYes

In the mapping record (the record gives no date) a mapped and a cold level-2 cavity converged to the same fields (5.1e-9 in U) and passed every declared check. Two accepted meshes allow an observable comparison, not a claim of mesh independence or a GCI.

Check the tools themselves

python validation/restart_equivalence.py --case backstep --solver-profile simple \
  --first 250 --second 250 --timeout-s 600 --data VERIFIED_DATA \
  --foam-root ROOT --output NEW_EQUIVALENCE
python validation/compare_restart.py --run NEW_RUN --control CONTROL_RUN \
  --mode fixed-work --output NEW_COMPARISON
python validation/mapping_equivalence.py --foam-root ROOT --timeout-s 120 \
  --output NEW_CAVITY_EXPERIMENT
python validation/mapped_start.py --source COARSE_RUN --iterations 3000 \
  --timeout-s 3500 --data VERIFIED_DATA --foam-root ROOT --output NEW_REPORT
CFD_OPENFOAM_ROOT=ROOT python validation/test_restart.py -v
CFD_OPENFOAM_ROOT=ROOT python validation/test_mapping.py -v
  • restart_equivalence.py (shown with the fixed-work check the external-backend job runs) runs FIRST iterations, continues them for SECOND, runs FIRST + SECOND uninterrupted, and compares the two final fields.
  • compare_restart.py compares any continued run with a control: --mode fixed-work for equal work (both final face fluxes must also pass the local continuity gate) and --mode converged for two converged runs, including their work, audits and measurement metrics. Invalid input is CFD-X013 at comparison.*.
  • mapping_equivalence.py compares a converged mapped level-2 cavity with a cold one, with bounds declared before the runs; it exits 0 when they hold, 2 for unaccepted runs and 1 for an input, workflow or archive error.
  • mapped_start.py runs a mapped and a cold start of the next level with equal limits and reports both; it applies no gate.
  • The tests run without a runtime; with CFD_OPENFOAM_ROOT they add real cavity continuations and mappings, and map synthetic SST fields between the real level-1 and level-2 backstep meshes (a utility check, not a turbulent solve). Run each normally and under -O.

The continuation record and the mapping record keep software equivalence, nonlinear convergence, measurement screening and physical qualification apart.

Next

  • Chapter 18: audit a wall-resolved backstep and continue it in bounded stages.
  • Chapter 19: map once and continue on the fine mesh until the gates pass or the budget ends.

Audit a wall-resolved backstep

This chapter decides whether a backward-facing-step calculation may be compared with measurements at all: it runs the wall-resolved reference recipe, audits its mesh, face fluxes and near-wall resolution independently, and reads the report level by level. You need the runtime of chapter 15, a checkout with the validation requirements and about an hour of one CPU core.

No GPU and no MPI are needed. The experimental protocol stays frozen, and no parameter is fitted to the downstream measurements.

Setup

Run all commands from the root of a checkout, with the runtime at runs/openfoam13/runtime/opt/openfoam13. Fetch the hash-checked measurements, then run the reference recipe once; the later sections read this run:

mkdir -p runs
python validation/backstep_data.py --output runs/measurements
python tutorials/backstep_resolution.py --preset smoke \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 --data runs/measurements \
  --iterations 20000 --timeout-s 3500 --output runs/resolution-smoke

The question

Can a backstep calculation pass three checks: the existing numerical gate (every final initial residual at most 1e-7 and the solver’s own convergence report), an independent local face-flux check, and a consistent near-wall resolution check? A plausible velocity plot or a small global mass imbalance does not answer this. The legacy recipe of chapter 16 fails the first check. Only a calculation that passes all three reaches the measurement screen.

Run the reference recipe

The setup ran the smoke preset: the wall-resolved mesh with the simplec profile at level 1, in one stage of at most 20,000 iterations and 3,500 s. Its run archive is runs/resolution-smoke/wall-resolved-simplec-level1 and its report runs/resolution-smoke/report.json:

import json

r = json.load(open("runs/resolution-smoke/report.json"))
print("workflow completed:", r["workflow_completed"], "passed:", r["passed"])
for row in r["rows"]:
    print(
        row["name"],
        "accepted:",
        row["accepted"],
        "passed:",
        row["passed"],
        "stop:",
        row.get("continuation_stop_reason"),
    )
print("physical qualification:", r["physical_qualification"])

The tutorial exits 0 when every requested case was accepted and passed its screen, and 2 when it kept unaccepted evidence; then read every row’s execution, error, progress and limits in report.json. Exit 1 means a workflow, input or runtime error, including a failure to prepare a case. A NaN or infinite value in the solver log, or a diverging continuity error, stops a solve early with CFD-X010. A timeout or failure has no accepted final field, so its measurement comparison is not assessed. Without --data the tutorial fetches the frozen measurement files itself.

In the resolution record (the record gives no date) this run converged after 18,412 iterations, executed in 3,037.4 s of its 3,500 s budget, passed the independent audit and the measurement screen, and exited 0. Three reruns on other runners converged at the same iteration. It is one mesh: no mesh pair, no GCI, no physical qualification, and the screen’s targets are broad (a predictor that ignores the step scores 0.067 at x/H = 1, inside the 0.10 target).

Presets and budgets

PresetCasesPurpose
smokewall-resolved / simplec, level 1The reference recipe on its coarse mesh
controlslegacy and wall-resolved meshes, each with the legacy and simplec profiles, level 1A 2 x 2 design: each pair changes only the mesh or only the pressure coupling
studywall-resolved / simplec, levels 1, 2, 3Same-recipe sensitivity; finer levels are skipped after a coarser one is not accepted

Each stage has its own wall-time budget covering mesh generation, solve and post-processing: --timeout-s (default 900 s, at most 3,600 s) and --iterations (default 6,000, at most 20,000). The reference recipe needs more than 6,000 iterations to be accepted, so pass the limits of the setup. The output budget is 512 MiB and the child address-space limit 2,048 MiB per stage. The controls preset can spend up to four times --max-stages stage budgets, the study preset three times.

Continue in bounded stages

With --max-stages N (1 to 8, default 1) a completed but unaccepted stage seeds the next stage on the same mesh with its verified fields and face flux (chapter 17). The recorded staged run of the reference recipe is (ROOT and VERIFIED_DATA stand for the runtime root and a measurement directory):

python tutorials/backstep_resolution.py --preset smoke --iterations 6000 \
  --max-stages 4 --timeout-s 3500 --foam-root ROOT --data VERIFIED_DATA \
  --output runs/resolution-staged

Every stage is kept, as wall-resolved-simplec-level1, then wall-resolved-simplec-level1-stage2 and so on. In a row, execution and the comparison describe the last stage, completed_solver_iterations and started_iterations count work across stages, and continuation_stop_reason says why the chain ended:

ReasonMeaning
numerically_acceptedThe stage passed the nonlinear gate; the audit and the screen still decide acceptance
converged_without_numerical_acceptanceThe solver reported convergence but the gate failed; another stage would report convergence again at its first iteration
stage_limitThe last permitted stage completed without convergence
execution_failed, execution_timeout, execution_cancelled, no_final_fieldThe stage stopped without an eligible final field
cancelledThe study was canceled between stages
source_ineligible: …The completed stage fails the source flux gate and cannot seed the next (exit 2; finer meshes are skipped)

Other preparation, archive or I/O errors stop the workflow with exit 1. Disk use and time grow with the number of stages; there is no automatic resume across separate CI jobs. Iteration limits need a divisor between 50 and 250 for the write cadence (any multiple of 50 works), so that a stopped stage still writes a final field. In the continuation record (the record gives no date) four stages of 6,000, 6,000, 6,000 and 412 iterations reached the same converged solution as the single run, at the same cumulative iteration, with final fields about 2e-12 apart in U.

Audit mesh, flux and y+

python validation/audit_openfoam_mesh.py \
  --run runs/resolution-smoke/wall-resolved-simplec-level1 --output runs/audit.json

The audit reads the archive’s actual mesh, not a nominal cell count. It recomputes Cartesian cell volumes and each cell’s divergence from the owner and neighbor face fluxes, because an internal flux error can cancel globally while violating local continuity. The frozen target is max abs(div(phi)) * H / U <= 1e-4. This complements the reported local continuity and boundary-flux gates; it does not replace or relax them.

For the wall-resolved mesh it also reads the first-cell distances on all four solid walls, checks them against the generated geometric-series heights, and computes y+ from the tangential stored wall traction. It requires max(y+) <= 1 on every wall and reports where the maximum lies. It supports only the bounded, conforming, axis-aligned hexahedral cases of the backend.

It exits 0 when its checks pass, 2 when they fail or the archive has no final field, and 1 for an invalid archive or output path. Its own passed is separate from numerical_passed. In the resolution record the reference run’s largest local divergence was 6.38e-11 H/U, and the largest first-cell y+ was 0.963 (on the step wall, just below the lip), both within their limits.

Read the report

Keep five levels apart: execution, numerical acceptance, the independent continuity and wall-resolution audit, the measurement screen, and physical qualification. A wall-resolved calculation reaches the measurement screen only after both the numerical gate and the audit pass. Compare two mesh levels only when both are accepted under the same wall treatment and solver profile. Do not infer a GCI from two grids or from an incomplete series. This workflow always leaves physical qualification open (physical_qualification.passed is false).

Recipes

The legacy mesh with wall functions stays the default of openfoam_backend.py prepare. The wall-resolved mesh (--mesh-family wall-resolved) refines the lower, upper, upstream and step walls without cell-size jumps between its blocks; SST uses k = 0, omegaWallFunction and zero wall eddy viscosity through nutLowReWallFunction. The reference simplec profile (--solver-profile simplec) uses SIMPLEC with pressure relaxation 1 and transport relaxation 0.7. The first-order simple profile (classic SIMPLE, relaxation 0.1, PCG pressure, zero initial interior velocity) is a stability reference, not an accuracy reference. For example:

python integrations/openfoam_backend.py prepare --case backstep --level 1 \
  --mesh-family wall-resolved --solver-profile simplec --iterations 20000 \
  --data VERIFIED_DATA --output NEW_INPUT

The benchmark has no scalar measurements and cannot validate gas dispersion, the native k-epsilon model or a street canyon.

A task for an agent

Using the pinned Foundation 13 runtime, a fresh output directory and the verified Driver and Seegmiller measurements, determine whether the wall-resolved simplec backstep at level 1 passes the numerical gate, the independent local face-flux audit and the all-wall y+ check. Run tutorials/backstep_resolution.py --preset smoke with the limits of this chapter, then validation/audit_openfoam_mesh.py on the returned archive.

Report execution, numerical acceptance, the audit, the measurement screen and physical qualification separately, with the actual returned fields. Keep every failed or stopped stage. Do not change the protocol, fit downstream measurements, loosen a gate or promote a saved snapshot to a final result. If you continue in stages, explain the continuation_stop_reason. Compare mesh levels only when both are accepted, and state that two grids give no GCI.

Next

  • Chapter 19: map the accepted level-1 result to level 2 and continue it in a bounded campaign.
  • Chapter 17: how continuation and mapping work.

A bounded refinement campaign

This chapter maps an accepted coarse backstep once to the next finer mesh, continues the fine solve in bounded stages, and reports honestly when the fine grid does not earn acceptance. You need the runtime of chapter 15, a checkout with the validation requirements, and several hours of one CPU core for the declared campaign; a quick cavity variant is at the end.

validation/refinement_campaign.py composes the one-level mapping and the same-mesh continuation of chapter 17 with the unchanged final gates. It is a serial CPU workflow; GPUs and MPI are not needed. The SST recipe, the restart and mapping schemas and the measurement protocol are unchanged by it.

Setup

Run all commands from the root of a checkout, with the runtime at runs/openfoam13/runtime/opt/openfoam13. Fetch the measurements and produce the coarse source with the reference recipe of chapter 18 (about an hour):

mkdir -p runs
python validation/backstep_data.py --output runs/measurements
python tutorials/backstep_resolution.py --preset smoke --iterations 20000 \
  --timeout-s 3500 --data runs/measurements \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 \
  --output runs/coarse-reference

The goal and its limits

A fine-grid result must earn acceptance: the same numerical, audit and measurement gates as the coarse one, with no gate loosened, no output resealed and no pre-failure snapshot promoted. A completed campaign can therefore produce scientifically unaccepted evidence, and that is a valid outcome.

The refinement record of 31 October 2026 is such an outcome. All three declared stages of 4,000 iterations completed and every stage passed the independent audit (local flux and wall y+), but none passed the numerical gate: after 12,000 fine iterations the final initial residuals of Uy (1.81e-7) and k (1.05e-7) were still above 1e-7. The stop reason was stage_limit, the workflow completed, passed was false, the two-grid comparison was not assessed, and physical qualification stayed false. The residuals were still falling; whether one more stage would pass is an extrapolation the campaign does not show. More stages are not an accuracy argument.

Produce the accepted coarse source

The setup ran the coarse reference. Continue only when its report passes:

import json

r = json.load(open("runs/coarse-reference/report.json"))
if not r["passed"]:
    raise SystemExit("the coarse reference is not accepted; do not start a campaign")
print("source:", "runs/coarse-reference/" + r["rows"][0]["name"])

Before it creates its output, the campaign verifies the source itself and requires its numerical acceptance, the full independent audit and its measurement screen (for the cavity, the Ghia reference check). Supported sources are cold-generated level 1 or 2 cavity archives and cold wall-resolved / simplec backstep archives; the target is exactly the next level. A mapped or continued archive cannot be mapped again.

Run the campaign

python validation/refinement_campaign.py \
  --source runs/coarse-reference/wall-resolved-simplec-level1 \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 --data runs/measurements \
  --iterations 4000 --max-stages 3 --timeout-s 3500 --preparation-s 900 \
  --output-mib 1024 --memory-mib 4096 --output runs/refinement-campaign || echo "exit $?"
python validation/external_notices.py runs/refinement-campaign/report.json \
  "refinement campaign"

These are the declared campaign of three 4,000-iteration stages, also the script’s defaults. The output path must be new, its parent must exist, and it may not lie inside the source; a rerun never overwrites or resumes an old campaign, so use a new path for another declared trial. The notices summarize the report: one for the campaign, one per stage and one for the implementation identities. GitHub keeps 4,096 characters of an annotation, so a longer notice is split at line ends into numbered parts.

import json

r = json.load(open("runs/refinement-campaign/report.json"))
print("workflow completed:", r["workflow_completed"], "passed:", r["passed"])
print("stop reason:", r["stop_reason"])
print(
    "fine iterations completed / started:",
    r["completed_fine_iterations"],
    r["started_fine_iterations"],
)
print("coarse source iterations (separate):", r["source_iterations"])
print("physical qualification:", r["physical_qualification"])

Limits and stop reasons

--iterations is a per-stage maximum from 50 to 20,000, with the divisor-based write cadence of chapter 17. --max-stages is 1 to 8. The time limits --timeout-s and --preparation-s must lie in (0, 3600] seconds; output is 1 to 2,048 MiB per stage and the child address space 256 to 8,192 MiB. The preparation has one shared deadline for its utilities; each execution has its own deadline for its child commands. Hashing, copying, auditing and collection add host overhead. The stage count bounds cumulative requested work and retained output; it is not a CPU or file-system quota. The copied source must fit one stage’s output allowance.

The plan, source identities, limits and producer hashes are written before mapping, and mapping is performed once. A stage that completes without convergence is continued only when prepare-restart accepts its final fields and face flux. stop_reason is one of:

ValueMeaning
acceptedThe stage converged and passed the numerical, audit and measurement (cavity: Ghia reference) checks
converged_without_numerical_acceptance, converged_without_independent_acceptance, measurement_screen_failedConverged, but a check failed
execution_timeout, execution_failed, execution_cancelledThe stage stopped
no_final_fieldIt completed without a final field
source_ineligibleThe next stage’s source failed the flux gate; its diagnostic and archive remain evidence
stage_limitEvery declared stage completed without convergence
cancelled, workflow_errorThe campaign was canceled, or hit a workflow error

Timeouts and canceled or failed executions are never continued. A cancellation overrides acceptance if it arrives after a solver returned, but an integrity or workflow error stays an error after a cancellation. If the audit or the measurement comparison of a returned stage cannot be read (for example when sampling hit the deadline), the stage records that failure and the campaign continues with the stop reason of its execution.

The script exits 0 when the declared scientific gates passed, 2 for retained unaccepted or canceled evidence, and 1 for invalid input or a workflow error. workflow_completed describes the collection of a valid bounded trial, not its acceptance. completed_fine_iterations counts stages with a final field; started_fine_iterations also counts stopped ones.

The evidence directory

PathContent
report.jsonThe frozen plan and its hash; phase, stop reason, per-stage assessments, work and archive checkpoints
source/A complete checked copy of the accepted coarse archive, with its seals
mapped-input/Generated fine boundaries and controls, mapped volume fields and the replayed mapping evidence
stage-01/, stage-02/, …Complete returned archives: consumed inputs, mesh, fields, logs, summary, manifest, completion marker
stage-02-input/, …Verified same-mesh initialization receipts and copied inputs

For one stage use python integrations/openfoam_backend.py report STAGE and python validation/audit_openfoam_mesh.py --run STAGE --output NEW_AUDIT.json. A summary alone cannot replace the retained fields. Coarse iterations and historical coarse wall time stay separate from the new fine work and the campaign wall time.

Integrity checkpoints

Source bytes are checked during copying, both inventories afterwards, and the copy must have the manifest the plan froze. Every complete parent and stage is verified again after each stage returns and at final collection. At each of these checkpoints:

  • continuation receipts must bind the retained parent’s manifest, case, final time, fields, mesh, runtime, acceptance and cumulative fine work, and the first mapping must bind the retained coarse parent;
  • every archive must keep the manifest it had at its first checkpoint, so the last stage, which no child receipt binds, cannot be resealed unnoticed;
  • each stage’s sealed summary must state the execution status, verdict, error and numerical assessment its run returned;
  • the stage records and producing files must have the implementation identities the plan froze.

An extra file or a changed archive stops collection with CFD-X015 at refinement.archives.* and the underlying diagnostic. The campaign does not delete an extra time directory, reseal an archive or accept an earlier field to make the result pass. Unkeyed hashes detect inconsistency; they do not authenticate an untrusted producer.

An OpenFOAM time directory can be empty and still be part of the evidence (see the archive investigation, which did not establish the root cause of such a directory reappearing on a cloud machine). Keep empty directory entries when you copy or zip a campaign; a file-only copy loses them, and the copy then fails verification.

What the verdicts mean

Each stage keeps separate execution, numerical, independent-audit and measurement verdicts. Backstep measurement screening stays unassessed unless the numerical and independent gates pass.

Only two numerically accepted, independently audited grids enter mesh_sensitivity. Velocity samples are paired by exactly matching station, sample ID and physical height; skin friction is interpolated at the same experimental x/H positions without extrapolation. Changes of reattachment length, velocity and skin friction are descriptive; no new inter-grid tolerance is invented. mesh_sensitivity.passed means both grids pass their original checks. It does not mean their differences are small or that mesh independence was shown.

Two grids do not give a GCI. physical_qualification stays false even when every screen passes: inlet uncertainty, another refinement, model-form sensitivity and measurement uncertainty still need work. The backstep has no passive-gas data and does not qualify the native canyon.

A quick exercise with the cavity

An accepted cold cavity works as a source without --data, and stages of 400 iterations (up to four) are enough for a quick real-solver check. Its Ghia reference is numerical, not experimental:

python integrations/openfoam_backend.py prepare --case cavity --level 1 \
  --iterations 3000 --output runs/foam-cavity-input
python integrations/openfoam_backend.py run --case runs/foam-cavity-input \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 \
  --timeout-s 180 --output runs/foam-cavity
python validation/refinement_campaign.py --source runs/foam-cavity \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 \
  --iterations 400 --max-stages 4 \
  --output runs/cavity-campaign

Tests and the hosted run

CFD_OPENFOAM_ROOT=ROOT python validation/test_refinement.py -v
CFD_OPENFOAM_ROOT=ROOT python -O validation/test_refinement.py -v

Without CFD_OPENFOAM_ROOT the contract tests run and the five real-solver tests are skipped. The real tests cover a converged mapped and continued cavity, a bounded unconverged cavity, an occupied output, and post-seal file and empty-time-directory corruption. Synthetic records and mocked runs exercise every receipt, checkpoint, stop and verdict rule; they are not flow evidence.

The manual CI selection external=refinement (not part of all) runs the level-1 reference solve and then the declared campaign, and uploads runs/refinement-campaign-evidence.zip with the fine fields and explicit directory entries; symbolic links are rejected before the zip is written.

A task for an agent

Inspect a complete accepted cold level-1 wall-resolved SIMPLEC backstep archive. Verify its seals, actual returned fields, independent local-flux and all-wall y+ audit, measurement screen and exact runtime. Freeze a new trial before execution: target level 2, at most three stages of 4000 iterations, 3500 seconds per execution, preparation deadline 900 seconds, 1024 MiB output per stage and 4096 MiB child address space. Use the campaign driver in a fresh directory. Map once and continue only eligible completed fine stages.

Keep every returned stage and the complete source. Report the final stage’s iterations, cumulative completed fine iterations and the coarse source’s historical work separately. Preserve numerical failures, stopped executions, source rejection and archive mismatches. Never loosen a gate, reseal changed output or use a pre-failure snapshot. Explain the actual stopping reason.

If both grids pass the numerical and independent gates, compare their observables at the same physical sample identities. State their original measurement verdicts and the size of the grid changes. If either grid is not accepted, state that mesh sensitivity was not assessed. Two grids provide neither a GCI nor physical qualification. Describe the remaining inlet, refinement and model-form work. GPU and MPI work is out of scope.

The finished report must answer:

  1. Which source bytes, producer code and runtime were actually consumed?
  2. Which stage first met each gate, and what work was performed on each mesh?
  3. Did the final source, parent and archive checks still pass at collection?
  4. Which comparisons are assessed, and what does each passed field mean?
  5. Which remaining scientific question can the next bounded trial resolve?

Next

The Rust library

At the end of this chapter you have called the solver in process from Rust, canceled it, round-tripped a checkpoint and read a run archive. It is for readers who embed the solver in a service or a worker. You need Rust 1.88 or newer and a checkout.

Setup

Commands run from the root of a checkout. Build the command and the example programs once:

cargo build --release --workspace --examples --locked
export PATH="$PWD/target/release:$PATH"

The sections run the built examples from target/release/examples/. cargo run --release --locked -p cfd-craft --example NAME builds and runs one in a single step. The archive reader needs an accepted and an incomplete run:

mkdir -p runs
cfd-craft run examples/manual/point-source.json --output runs/point > /dev/null
python -c "import json; c = json.load(open('examples/manual/point-source.json')); c['run']['max_steps'] = 5; json.dump(c, open('runs/point-5.json', 'w'))"
cfd-craft run runs/point-5.json --output runs/partial > /dev/null || true

Outputs on this page are real. The documentation check compares floating-point numbers with a relative tolerance of 1e-4; everything else must match exactly.

Depend on the crate

The package is cfd-craft; the import name is cfd_craft.

[dependencies]
cfd-craft = "0.2"
serde_json = "1"
rayon = "1"

To build against a reviewed checkout instead, write cfd-craft = { path = "/path/to/CFD-craft/crates/cfd-craft" }. Commit your application’s own Cargo.lock.

The API in one table

APIUse
serde_json::from_slice::<Case>Parse the typed case; unknown fields are rejected
Case::check()CheckReport: validity, estimates, diagnostics
Case::validate()Result with the check report, or the report as the error
Grid::build(&case)The grid, masks and fluid regions
Source::rate()Integrated rate in kg/s of any source kind
Control::new(seconds)A wall-time allowance; holds the cancellation flag
Control::with_poll(seconds, closure)Adds an external deadline or cancellation check
solver::run(&case, &control, restart)Result<RunResult>: summary, state, geometry
output::checkpoint_bytes, read_checkpointWrite and read a checksummed state
output::create_run_dir, write_runPublish a run archive; the caller supplies its build identity
output::read_verifiedRead and verify a run archive

cfd_craft::Result<T> has a String error. Read the diagnostic code or the check report in it; do not parse its English text. Control::new expects finite positive seconds. The modules for grid, faces and state vectors are public for research use; prefer the calls above. The full API is on docs.rs.

Solve in process

manual_library.rs loads source-response.json, validates it, builds a one-thread pool, runs the solver, requires steady acceptance and reads receptor R1.

target/release/examples/manual_library \
  | python -c "import json, sys; r = json.load(sys.stdin); print(r['passed'], r['assessment'], abs(r['source_total_kg_s'] - 1.92e-7) < 1e-19, f\"R1 = {r['R1_ug_m3']:.6g} micrograms/m3\")"
True steady_discrete_solution True R1 = 18.6825 micrograms/m3

The third value tests that the three volume sources integrate to 1.92e-7 kg/s within 1e-19. The central calls of the example are:

#![allow(unused)]
fn main() {
let control = Control::new(case.run.wall_time_limit_s);
let run = pool.install(|| solver::run(&case, &control, None))?;
// Ok(RunResult) can also contain cancellation or an incomplete solve.
if run.summary.assessment != "steady_discrete_solution" {
    return Err(format!(
        "CFD-U001 manual.library.assessment: {} / {}",
        run.summary.termination, run.summary.assessment
    ));
}
}

Ok(RunResult) means the solver returned a result you can inspect. That result can be canceled, incomplete or numerically failed. Always test summary.assessment.

Cancellation and deadlines

manual_control.rs cancels in two ways: a flag that is set before the run starts, and a poll closure that returns an error during the run.

target/release/examples/manual_control \
  | python -c "import json, sys; r = json.load(sys.stdin); print(r['passed'], r['termination'], r['assessment'], r['queued_steps'], r['external_steps'] > 0)"
True cancelled incomplete 0 True

Both runs come back as Ok with cancelled / incomplete and the steps they really took: none for the flag set in advance, a few for the poll. Any poll error ends the run as cancelled, or as wall_time_limit when the poll returns exactly that text. The poll’s own message is not kept, so record it in the caller. A job worker passes its own deadline check as the poll. Cancellation is cooperative: the solver polls between pieces of work.

Checkpoint round trip

manual_checkpoint.rs stops the periodic tracer case after five steps, writes a checkpoint file, reads it back, resumes the full case and compares the final state with an uninterrupted run.

target/release/examples/manual_checkpoint runs/lib-checkpoint.json \
  | python -c "import json, sys; r = json.load(sys.stdin); print(r['passed'], r['partial_steps'], r['final_steps'], r['same_state_as_cold'], r['initial_state_id_differs'])"
True 5 20 True True

The resumed state equals the cold one, and the two runs report different initial-state identities, as in chapter 8. The file must be new. It is a checkpoint only, not a run archive.

Read a CLI archive

manual_archive.rs reads a run directory with output::read_verified. A Rust service that collects the output of cfd-craft run jobs does this.

target/release/examples/manual_archive runs/point \
  | python -c "import json, sys; r = json.load(sys.stdin); print(r['archive_consistent'], r['numerically_accepted'], r['termination'], r['assessment'])"
True True completed steady_discrete_solution
target/release/examples/manual_archive runs/partial \
  | python -c "import json, sys; r = json.load(sys.stdin); print(r['archive_consistent'], r['numerically_accepted'], r['termination'], r['assessment'])"
True False iteration_limit incomplete

Both archives are consistent. Only the first is numerically accepted. Integrity and acceptance are separate answers, and the example prints the validation label as a third.

Threads, pools and build identity

The library does not create a thread pool from case.run.threads. The caller installs a Rayon pool, as the examples do with pool.install; without one the solver runs on Rayon’s global pool. The command and the Python binding do this for you.

A bare library result identifies the core package: its source fingerprint, version and compiler. The command and the binding add the identity of their own wrapper sources. Before you call write_run in your application, put your application’s build identity into those fields. Do not copy the command’s identity into another producer.

Profile from Rust

Phase timing (chapter 9) is a property of the control. These lines are from a test of the library:

#![allow(unused)]
fn main() {
let control = Control::new(60.0).with_profiling();
let r = pool.install(|| solver::run(&c, &control, None)).unwrap();
let p = control.profile().unwrap().unwrap();
}

Control::profile returns None without with_profiling. See profiling.

Select multigrid from Rust

Set the preconditioner on the case before the grid is built or the solver is called. pressure::multigrid_stats reports the hierarchy after the first pressure solve. From a test of the library:

#![allow(unused)]
fn main() {
c.numerics.pressure_preconditioner = PressurePreconditioner::Multigrid;
let stats = pressure::multigrid_stats(&g).unwrap();
}

See pressure multigrid.

Next

Troubleshooting

This chapter leads from a symptom to a diagnostic code and an action, and reproduces the five most common failures. You need the cfd-craft command and a checkout (chapter 3).

Setup

Commands run from the root of a checkout with cfd-craft on PATH. The setup writes three broken copies of examples/manual/point-source.json: one with an unknown field, one whose steady source has no outlet, and one with a budget of five steps.

mkdir -p runs
import json


def variant(name, change):
    case = json.load(open("examples/manual/point-source.json"))
    change(case)
    json.dump(case, open(f"runs/{name}.json", "w"), indent=2)


variant(
    "unknown-field",
    lambda c: c["sources"][0].update(position_m=c["sources"][0].pop("point_m")),
)
variant("no-outlet", lambda c: c["boundaries"].update(x="periodic"))
variant("five-steps", lambda c: c["run"].update(max_steps=5))

Outputs on this page are real. They contain no floating-point numbers, so the documentation check requires an exact match.

Where the message is

  • Exit 1 with JSON on stdout. check, run, profile and preview print the check report for an invalid case. Read check.diagnostics: each entry has a code, a severity, the path of the field and a message.
  • Exit 1 with {"error": "CFD-..."} on stderr. An I/O problem, a rejected archive or a rejected restart. Nothing was solved.
  • Exit 2. The run ended and wrote its archive, without numerical acceptance or without all files. Read termination, assessment and error in summary.json, and omitted in manifest.json.
  • Exit 0 means a valid case, an accepted run with all files, or an intact archive. For report it does not mean the run converged.

By symptom

SymptomLook atAction
Unknown field or variantCFD-E000 and its pathCorrect the name; nothing is ignored. Chapter 2
Memory or output estimate too largeCFD-E006, CFD-E007, CFD-E070Reduce the case or use a larger budget or host. Chapter 7
check skipped the grid checksCFD-W070Check again on a host that can hold the case. Chapter 7
Source or receptor in a solid cellCFD-E040, CFD-E042Move it into the fluid or resolve the gap; nothing is moved for you. Chapter 5
Steady source without a way outCFD-E020, CFD-E043Give the region an open boundary, or run transient. Chapter 5
Output exists or parent is missingCFD-E062, CFD-E063Use a new directory inside an existing one. Chapter 3
A run exits 2termination, assessment, omittedKeep the archive; tell a budget from a failed check from omitted files. Chapter 4
report rejects an archiveCFD-E064Keep the archive as it is; do not rewrite its hashes. Chapter 3
Restart rejectedCFD-E060, CFD-E065, CFD-E066Compare physics, checksum, memory budget and the new horizon. Chapter 8
Preview refusedCFD-E072, CFD-E073, CFD-E040, CFD-E042The coarse geometry differs; use a smaller factor or the full grid. Chapter 7
Pressure iteration limitCFD-E033 in errorLook at resolution and conditioning; the saved earlier state is not a converged result. Chapter 6
Turbulence floors or very large eddy viscosityturbulent_floor_events, CFD-E054A numerical failure of this regime, not something to clip away. Chapter 10
OpenFOAM timeout or invalid meshCFD-X004, CFD-X006 and the logsAn earlier snapshot is not a final solution. Chapter 15
An example script failsCFD-U001 manual.<field> and the saved logsBuild the examples and check the paths. Chapter 11
A building footprint is rejectedCFD-E084 at geometry[i].footprint_mRemove crossing edges, holes and a repeated last vertex; make min_m and max_m the bounds of the polygon. Chapter 22
A building or a street is too small for the gridCFD-E028, CFD-W011Refine the grid or drop the shape yourself; read shapes in geometry.json. Chapter 22
Building roughness is rejectedCFD-E085Use a positive value with neutral_rans flow. Chapter 22
Multigrid is slower than the defaultCFD-W004With buildings and strongly unequal cell widths keep ic0. Chapter 22
The map converter stopsCFD-M001 map and check.json in the outputReproject to meters, check heights and holes, or give a --template with larger budgets. Chapter 22
A particle bin is rejectedCFD-E080, CFD-E081Keep diameter, density and speeds in range; above a particle Reynolds number of 0.1 give settling_velocity_m_s. Chapter 22
A vegetation volume is rejected or has no effectCFD-E082, CFD-E083; volume_fluid_cells of 0Fix the box or the range; use drag 0 with prescribed flow; make the volume contain a fluid cell center. Chapter 22
A wind-direction campaign exits 2accepted and error of each row in report.jsonA timeout is an incomplete run; raise the budgets or coarsen the case. Chapter 22
A path receptor is rejectedCFD-E086, CFD-E087, CFD-E088Keep the route inside the domain and out of buildings; use fewer samples. Chapter 23
The ride tool refuses a runCFD-M004 virtual_rideGive it an accepted steady run, an existing path and a new output file. Chapter 23
The street converter stopsCFD-M002 and diagnostic.json in the outputSupply rates in kg/s/m; a street that touches a building is rejected, not moved. Chapter 24
A frozen-flow response or the study is rejectedCFD-E089, CFD-M003 mobile_inferenceUse steady linear_upwind transport without initial concentration on an accepted flow. Chapter 24

Reproduce the common ones

codes() { grep -o "CFD-[A-Z][0-9]*" "$1" | sort -u | tr "\n" " "; echo; }
cfd-craft check runs/unknown-field.json > runs/1.out || echo "unknown field: exit $?"
codes runs/1.out
cfd-craft check runs/no-outlet.json > runs/2.out || echo "no outlet: exit $?"
codes runs/2.out
cfd-craft run examples/manual/point-source.json --output runs/point > /dev/null
cfd-craft run examples/manual/point-source.json --output runs/point 2> runs/3.err || echo "occupied output: exit $?"
codes runs/3.err
cfd-craft run examples/manual/point-source.json --output absent/point 2> runs/4.err || echo "missing parent: exit $?"
codes runs/4.err
cfd-craft run runs/five-steps.json --output runs/five-steps > runs/5.out || echo "five steps: exit $?"
python -c "import json; s = json.load(open('runs/5.out')); print(s['termination'], s['assessment'])"
unknown field: exit 1
CFD-E000
no outlet: exit 1
CFD-E020
occupied output: exit 1
CFD-E062
missing parent: exit 1
CFD-E063
five steps: exit 2
iteration_limit incomplete

The first four fail before any work is done and write nothing. The fifth is not an error of the program: the run stopped at its budget, exits 2 and leaves a complete archive in runs/five-steps.

What to attach to a report

Report problems at github.com/dietmarwo/CFD-craft/issues with:

  • the exact command and its exit code;
  • stdout and stderr of the command;
  • for an invalid case, the case file;
  • for a run, case.json, summary.json and manifest.json from the run directory. They hold the consumed case, the stopping reason and the checks, and the version, compiler and hashes of the build. Do not attach fields.json unless asked; it is large.

All codes

Every code with its meaning is in the diagnostics catalog. The native solver, the Python package, the OpenFOAM adapter and the scripts use separate code families, so a code also tells you which part reported it.

Next

Urban geometry, particles and vegetation

A real street is not two boxes and a gas. Buildings have footprints from a map, traffic emits particles of several sizes that settle and stick to surfaces, and hedges and trees slow the wind and collect particles. This chapter adds each of these to the street canyon of chapter 10, one optional field at a time. A case that uses none of the fields runs exactly as before.

These models are numerically verified and not experimentally validated: the tests show that the equations are solved as written, not that a city behaves this way. The urban evidence record lists what was measured and what failed.

Setup

You need the cfd-craft command, the Python package cfd_craft and a checkout (chapter 3). The case fields of this chapter work in both. The map converter and the campaign script run from the checkout; the converter needs Shapely (python -m pip install -r integrations/requirements-urban.txt).

Every section starts from runs/block.json: the canyon of chapter 10 with the opt-in implicit recipe of chapter 9, so a run takes 2 to 5 s on the documentation host. runs/block/ holds its result.

mkdir -p runs
import json

case = json.load(open("cases/canyon/wh1-wind270.json"))
case["name"] = "block"
case["numerics"].update(
    steady_algorithm="implicit_projection",
    pressure_relative_tolerance=0.1,
    max_time_step_s=100,
)
json.dump(case, open("runs/block.json", "w"), indent=2)
cfd-craft run runs/block.json --output runs/block > /dev/null

Outputs on this page are real. The documentation check compares floating-point numbers with a relative tolerance of 1e-4; everything else must match exactly.

A building with a polygon footprint

A geometry entry with footprint_m is a prism: a polygon in the horizontal plane between the heights min_m[2] and max_m[2]. Without footprint_m the entry is the box of chapter 10. Save this building with one slanted wall as east.json; the next block puts it in place of the east box.

{"id": "east", "min_m": [7.0, 3.0, 0.0], "max_m": [9.0, 13.0, 1.0],
 "footprint_m": [[7.0, 3.0], [9.0, 3.0], [8.4, 13.0], [7.0, 13.0]]}
import json

case = json.load(open("runs/block.json"))
case["geometry"][1] = json.load(open("east.json"))
case["geometry_min_passage_cells"] = 2
json.dump(case, open("runs/prism.json", "w"), indent=2)
cfd-craft check runs/prism.json > runs/prism-check.json
checked = json.load(open("runs/prism-check.json"))
east = checked["geometry"]["shapes"]["east"]
print(checked["check"]["valid"], east["solid_cells"])
print(east["exact_volume_m3"], east["represented_volume_m3"], east["volume_error_m3"])
print(east["narrowest_fluid_passage_cells"])
print(sorted({d["code"] for d in checked["check"]["diagnostics"]}))
True 36
17.0 18.0 1.0
1
['CFD-W001', 'CFD-W002', 'CFD-W003', 'CFD-W011']

The grid stays Cartesian. A cell is solid when its center lies inside the footprint, so a slanted wall becomes a staircase. check and geometry.json say what that costs, per shape: the prism has 17 m3, its 36 solid cells hold 18 m3, and the narrowest street next to it is 1 cell wide. The case asks for at least 2 cells (geometry_min_passage_cells), so check adds the warning CFD-W011. A shape without any cell center is an error (CFD-E028); a building is never dropped silently.

  • A footprint has 3 to 2048 vertices in meters, in either direction, without repeating the first vertex at the end. Concave footprints work.
  • min_m and max_m must equal the bounds of the polygon in x and y.
  • Holes, crossing edges and zero area are rejected (CFD-E084). Split a courtyard building into simple polygons.
  • A cell center exactly on a slanted edge belongs to the footprint whose interior lies on the +x side of that edge. Two footprints that share an edge therefore leave no gap and do not overlap.

Wall roughness. By default the roughness length of building walls is the smaller of the ground roughness and 0.001 cell widths, so it changes with the grid. building_roughness_m sets it in meters, independent of the grid, for neutral_rans flow (CFD-E085); the ground keeps flow.roughness_m. Setting it changes the physics hash and the result. Neither wall treatment is validated against measurements (flow model card).

Multigrid with buildings

The opt-in multigrid preconditioner of chapter 9 also works with buildings and with several separate fluid regions. Save these numerics fields as recipe.json: the implicit recipe plus multigrid.

{"steady_algorithm": "implicit_projection", "pressure_relative_tolerance": 0.1,
 "max_time_step_s": 100, "pressure_preconditioner": "multigrid"}
import json
import cfd_craft as cfd

case = json.load(open("cases/canyon/wh1-wind270.json"))
case["numerics"].update(json.load(open("recipe.json")))
ic0, mg = json.load(open("runs/block/summary.json")), cfd.simulate(case)
print(mg["assessment"], mg["pressure_iterations"] < ic0["pressure_iterations"])
a, b = (s["constituents"][0]["receptors_kg_m3"] for s in (ic0, mg))
print(all(abs(b[k] / a[k] - 1) < 1e-4 for k in a))
steady_discrete_solution True
True

Both runs solve the same pressure equation to the same checks, so the result does not change. Fewer iterations are not a faster run. On canyon grids with equal cell widths multigrid needed about 3 to 6 times fewer pressure iterations than the default ic0, but the whole runs took about the same time: ic0 time over multigrid time was 1.05 at 27,648 cells, 0.94 at 93,312 cells and 0.91 on a 37,500-cell block (below 1, ic0 was faster). With strongly unequal cell widths (CFD-W004) multigrid was slower, because its path for buildings has no line smoothing. The default stays ic0 (measurements).

Import buildings from a map

integrations/urban_map.py converts building footprints to a case with prisms. It reads GeoJSON polygons or CityJSON solids in a projected coordinate system in meters. Input that declares longitude and latitude is refused, and undeclared degrees cannot be detected: reproject first, for example with GDAL or QGIS. Convert CityGML to CityJSON with citygml-tools. For OpenStreetMap, export the footprints to GeoJSON and keep the ODbL attribution.

python integrations/urban_map.py integrations/fixtures/urban-synthetic.geojson \
  --template runs/block.json \
  --crop 90 190 145 245 --cell-m 4 --coordinate-system 'local metric synthetic' \
  --license 'CC0-1.0 synthetic fixture' --attribution 'CFD-craft synthetic fixture' \
  --output runs/district
import json

case = json.load(open("runs/district/case.json"))
p = json.load(open("runs/district/map-provenance.json"))
print(case["grid"]["cells"], case["domain"]["size_m"])
print([(g["id"], g["max_m"][2]) for g in case["geometry"]])
print([(a["id"], a["height_method"]) for a in p["assumptions"]])
print(p["rotation_deg"], p["dropped"], p["check_exit_code"])
[54, 32, 14] [216.0, 128.0, 56.0]
[('building-0', 8.0), ('building-1', 8.0), ('building-2', 9.0)]
[('a', 'attribute'), ('b', 'levels'), ('c', 'default'), ('touching', 'attribute')]
0.0 [] 0

The converter crops the map to --crop (xmin ymin xmax ymax) and rotates it so that the dominant building edges follow the grid (--rotation-deg sets the angle). It merges footprints that touch and have equal height (here a and touching) and adds clearance: 5 building heights upstream, to the sides and above the roofs, 15 downstream; --ensemble-clearance gives 15 on every side for a study of several wind directions. It writes case.json, check.json (the report of cfd-craft check) and map-provenance.json, and exits 1 with CFD-M001 when the input or the check fails. Inspect before you run the case:

  • Heights come from the attribute named by --height-attribute, else from the level count building:levels times 3 m, else from the default of 8 m. The provenance records the method per building. These are assumptions, not measurements.
  • Dropped buildings. A building narrower or lower than two cells is left out and listed under dropped.
  • Flat ground. There is no terrain. Input whose building base heights differ by more than --max-ground-range-m (default 0.5 m) is refused, and so are holes in footprints and CityJSON geometry templates.
  • Wind. The wind direction is rotated with the buildings; the provenance keeps the map direction and the model direction.
  • Budgets and numerics are copied from --template: here runs/block.json with the implicit recipe, so the converted case was accepted after 400 steps in 21 s. Without --template the converter takes the canyon case of chapter 10 with its default numerics, which are slow for a district: the same conversion then stopped at its wall-time limit of 240 s after 1545 steps (incomplete). A finer grid needs a template with larger budgets: with --cell-m 2 this example fails check with CFD-E007 (64 MiB of output).
  • Sources and receptors. The converted case has buildings and wind only: its sources and receptors are empty. Add your own, or line sources from street data (chapter 24).
  • Where it runs. The defaults of --template and of --binary (the cfd-craft command used for the check) are files of the checkout, with the command built in target/release.

Particle size classes

A constituent with particle is a size class (a bin) of spherical particles with one diameter and one density. It settles and deposits. A constituent without particle is a gas as before. Save this bin as coarse.json:

{"id": "coarse", "diffusivity_m2_s": 1.5e-5, "particle": {
 "diameter_m": 5e-6, "density_kg_m3": 1500.0,
 "ground_deposition_velocity_m_s": 0.001, "roof_deposition_velocity_m_s": 0.001}}

The block adds a 1 micrometer bin fine and a 20 micrometer bin grit without extra deposition velocity, and gives each bin the traffic source.

import json
import cfd_craft as cfd

case = json.load(open("runs/block.json"))
traffic = case["sources"][0]
bins = [json.load(open("coarse.json"))]
for name, diameter in (("fine", 1e-6), ("grit", 2e-5)):
    particle = {"diameter_m": diameter, "density_kg_m3": 1500.0}
    bins.append({"id": name, "diffusivity_m2_s": 1.5e-5, "particle": particle})
case["constituents"] = bins
case["sources"] = [dict(traffic, id=b["id"], constituent=b["id"]) for b in bins]
s = cfd.simulate(case)
print(s["termination"], s["assessment"])
for c in s["constituents"]:
    rate = c["deposition_rate_kg_s"]
    print(
        c["id"],
        f"{c['settling_velocity_m_s']:.4g} m/s",
        f"{c['aerodynamic_diameter_m'] * 1e6:.4g} um",
        f"{c['receptors_kg_m3']['sensor1'] * 1e9:.4g}",
        f"{rate['ground']:.4g} {rate['roof']:.4g}",
    )
for name, pm in sorted(s["particulate_matter"].items()):
    print(name, f"{pm['receptors_kg_m3']['sensor1'] * 1e9:.4g}")
completed steady_discrete_solution
coarse 0.001165 m/s 6.143 um 223.2 3.922e-09 1.578e-10
fine 5.26e-05 m/s 1.242 um 230.6 9.791e-11 3.963e-12
grit 0.0182 m/s 24.52 um 185.7 2.83e-08 1.039e-09
PM10 453.8
PM2.5 230.6

Each line gives the settling speed, the aerodynamic diameter, the concentration at sensor1 in micrograms/m3 and the deposition rates on the ground and on roofs in kg/s. All bins emit the same 1e-7 kg/s; the larger the particle, the more is deposited and the less reaches the sensor.

  • Settling follows the Stokes law with the Cunningham slip correction for air at 293.15 K and 101325 Pa. The formula holds up to a particle Reynolds number of 0.1; beyond it check fails (CFD-E081) and you give settling_velocity_m_s yourself.
  • Deposition. Ground and upward-facing roofs take the settling flux plus the declared deposition velocity. Vertical walls collect nothing. deposited_kg is the accumulated mass per surface, deposition_rate_kg_s the current rate; the mass balance and the checkpoint include both.
  • PM2.5 and PM10. particulate_matter adds the bins whose aerodynamic diameter (that of a sphere of density 1000 kg/m3 with the same settling speed) is at most 2.5 or 10 micrometers. A bin counts completely or not at all: PM2.5 is fine, PM10 is fine plus coarse, grit is in neither.
  • Closed domains. A steady particle source may have deposition as its only way out; a gas still needs an open boundary (CFD-E020).

The values are concentration increments from the declared sources: no background, chemistry, coagulation or resuspension, and not what a regulatory PM monitor reports. The transport model card has the equations.

Hedges and trees

A vegetation entry is a box of porous fluid, not a solid: air flows through it and loses momentum, and particles stick to the leaves. Save this hedge behind the east building as hedge.json:

{"id": "hedge", "min_m": [9.0, 3.0, 0.0], "max_m": [10.0, 13.0, 1.0],
 "leaf_area_density_m2_m3": 2.0, "drag_coefficient": 0.2,
 "leaf_deposition_velocity_m_s": 0.005, "turbulence_closure": "green1992"}
import json
import cfd_craft as cfd

case = json.load(open("runs/block.json"))
case["constituents"][0]["particle"] = {"diameter_m": 1e-6, "density_kg_m3": 1500.0}
case["vegetation"] = [json.load(open("hedge.json"))]
s = cfd.simulate(case)
v = s["vegetation"]
print(s["assessment"], v["volume_fluid_cells"], v["validation"])
print(f"{v['drag_power_per_density_m5_s3']:.4g}")
rate = s["constituents"][0]["deposition_rate_kg_s"]
print({k: f"{x:.4g}" for k, x in sorted(rate.items())})
steady_discrete_solution {'hedge': 20} verified_numerics_unvalidated_physics
0.5386
{'ground': '9.753e-11', 'roof': '3.966e-12', 'vegetation': '4.749e-10'}

The hedge covers 20 fluid cells. Its leaves take 4.7e-10 kg/s of the 1e-7 kg/s emitted, more than ground and roofs together.

  • Drag. leaf_area_density_m2_m3 (LAD) is leaf area per volume of canopy. The drag acceleration is -Cd LAD |U| U with drag_coefficient Cd. Overlapping volumes add. Prescribed flow cannot respond to drag: use Cd 0 there (CFD-E083).
  • Turbulence. turbulence_closure selects the canopy terms of the k-epsilon model: green1992 (default) or sanz2003, the set of Sanz (2003) as tabulated by Viana Parente Lopes, Palma and Silva Lopes (2021), who list it under Katul et al. (2004). The other model constants do not change (flow model card).
  • Leaf deposition removes LAD times leaf_deposition_velocity_m_s times the concentration of a particle bin. A gas is not affected.
  • summary.vegetation reports the drag work rate and the drag force, both per unit air density, and the fluid cells of each volume.

Limits: a volume that contains no fluid cell center is accepted without a message and has no effect; only volume_fluid_cells shows 0 (a building in that situation is CFD-E028). Drag in a transient run is first-order accurate in time. There is no heat, shading, season or leaf size.

One case, twelve wind directions

validation/urban_campaign.py runs a case for the wind directions 0, 30, …, 330 degrees. Each direction starts cold with its own time budget, and each is kept, also one that failed or timed out: the consumed case, the run archive, the independent field check and the result.

python validation/urban_campaign.py run runs/district/case.json \
  --map-provenance runs/district/map-provenance.json \
  --output runs/district-rose --run-budget-s 120 --campaign-budget-s 1200 \
  --threads 1 --workers 2

The script exits 0 only when all twelve directions are accepted within the campaign budget, and 2 otherwise. A direction is accepted when its run is a steady discrete solution and its stored fields pass validation/check_fields.py. Directions are in the rotated model frame; with --map-provenance each row also gives the map direction. For the small district converted above (24,192 cells of 4 m, two cells per building height), all twelve directions were accepted, in 134 s on a host with two CPUs; that is a statement about the numerical checks on a coarse grid, not about a district (below). Twelve equal directions are not a wind climate: weight them with measured frequencies in your own analysis. --runner sends the directions through optimization-run (chapter 14).

What these results are not

  • Not validated. No particle, canopy or building result here has been compared with measurements.
  • Not shown to be independent of grid orientation. In the recorded study of a canyon rotated by 45 degrees the coarse rotated case was rejected and both finer runs timed out; no rotation error is known.
  • Not a qualified district workflow. In the recorded Delft demonstration (183,260 cells, 45 s per direction) none of the twelve directions converged within its budget. A completed campaign is not twelve accepted fields.
  • Not total air quality. Concentrations are increments from the declared sources in neutral mean flow, without background or short peaks.

When you compare two grids, convert the map once and refine the same footprints; importing each grid separately can drop different buildings.

Next

Mobile paths and virtual rides

A sensor on a bicycle does not stand at one point. It moves through the concentration field along a route, and it reacts with a delay. This chapter samples a computed field along a route (a path receptor) and then computes what an idealized sensor would record on one ride through it (a virtual ride). At the end you have both for a small plume.

The field is the steady mean concentration from the declared sources. A virtual ride is therefore a model of the observation, not of the atmosphere: it contains no turbulent fluctuations, no traffic pulses and no background, and it is not experimentally validated.

Setup

You need the cfd-craft command and a checkout (chapter 3). Path receptors also work in the Python package. The ride tool integrations/virtual_ride.py and the field checker run from the checkout and need only the Python standard library.

Every section reads this run of examples/manual/path-ride.json: a point source in a uniform wind of 1 m/s toward +x, on 16 x 8 x 8 cells of 0.5 m.

mkdir -p runs
cfd-craft run examples/manual/path-ride.json --output runs/path-field > /dev/null

Outputs on this page are real. The documentation check compares floating-point numbers with a relative tolerance of 1e-4; everything else must match exactly.

Declare a path receptor

A path is a receptor of kind path. The example case contains this one:

{
  "kind": "path",
  "id": "ride",
  "polyline_m": [[2.0, 1.0], [4.0, 1.0], [6.0, 3.0]],
  "height_m": 2.0,
  "sample_spacing_m": 0.25
}
  • polyline_m lists the corners of the route as east and north coordinates in meters. The route may bend and may visit a place twice.
  • height_m is the constant height above the flat ground.
  • sample_spacing_m is the largest distance between two samples. The solver divides the length of the route into equal intervals no longer than this and samples both ends.

The solver never moves or clips a route. A route outside the domain or with an invalid height or spacing is an error (CFD-E086). A route that enters a building is an error even when all samples lie in the air, and so is a sample whose interpolation would use a solid cell (CFD-E087). A path has at most 4097 corners and 20001 samples, a case at most 50000 path samples (CFD-E088).

Read the samples and the mean

import json

s = json.load(open("runs/path-field/summary.json"))
tracer = next(c for c in s["constituents"] if c["id"] == "tracer")
ride = tracer["paths"]["ride"]
print(s["termination"], s["assessment"], len(ride["distance_m"]))
print(f"{ride['distance_m'][1]:.4g} {ride['distance_m'][-1]:.4g}")
print(ride["points_m"][0], ride["points_m"][-1])
print([f"{c * 1e9:.4g}" for c in ride["concentrations_kg_m3"][::5]])
mean = ride["mean_kg_m3"]
print(f"{mean * 1e9:.4g}", mean == tracer["receptors_kg_m3"]["ride"])
completed steady_discrete_solution 21
0.2414 4.828
[2.0, 1.0, 2.0] [6.0, 3.0, 2.0]
['1.828', '3.676', '9.418', '37.26', '15.66']
14.89 True

The route is 4.828 m long. With a spacing of at most 0.25 m it gets 20 intervals of 0.2414 m, so 21 samples. Each constituent has, under paths["ride"], the sample positions points_m, the distance along the route distance_m, the concentrations and their mean. The fourth line shows every fifth sample in micrograms/m3: the route enters the plume near its end.

The mean (14.89 micrograms/m3) is the average along the route, by the trapezoid rule over the samples. It also appears in receptors_kg_m3 and in probes.csv under the id of the path, so everything that works with point receptors works with a path, for example the response matrix of chapter 12. Each sample interpolates the cell-center values linearly, as a point receptor does.

Check the path independently

validation/check_fields.py rebuilds every sample position, its interpolation weights, the test of whole segments against buildings, the concentrations and the mean from the stored fields, without the solver:

python validation/check_fields.py runs/path-field > runs/path-check.json
python -c "import json; print(json.load(open('runs/path-check.json'))['passed'])"
True

Simulate a ride

The ride tool takes a run directory, a constituent and a path, and needs a riding speed, the interval between sensor readings and the response time of the sensor.

python integrations/virtual_ride.py runs/path-field --constituent tracer --path ride \
  --speed-m-s 3 --sampling-interval-s 0.1 --response-time-s 2 --output runs/ride.json > /dev/null
import json

r = json.load(open("runs/ride.json"))
print(len(r["time_s"]), f"{r['time_s'][-1]:.4g} s", r["position_geometry"])
for i in (0, 5, 10, 15, 17):
    field, sensor = r["steady_field_kg_m3"][i] * 1e9, r["sensor_kg_m3"][i] * 1e9
    print(f"{r['time_s'][i]:.4g} s  field {field:.4g}  sensor {sensor:.4g}")
print(r["provenance"]["experimental_validation"])
18 1.609 s declared_polyline
0 s  field 1.828  sensor 1.828
0.5 s  field 4.059  sensor 2.095
1 s  field 23.31  sensor 3.888
1.5 s  field 22.04  sensor 9.877
1.609 s  field 15.66  sensor 10.35
not_validated; see validation/data-inventory.json

At 3 m/s the ride takes 1.609 s. steady_field_kg_m3 is what a sensor without delay would read; sensor_kg_m3 is the reading of a sensor with a response time of 2 s. On this short ride the slow sensor reaches less than half of the peak. Values are in micrograms/m3.

How the tool works:

  • Field. It accepts only a completed, accepted steady run and checks the manifest and the hashes of the consumed case and summary. A transient or incomplete run is refused (CFD-M004). The output records those hashes, the route and all parameters.
  • Motion. The speed is constant. Positions follow the declared route with its corners; the concentration is linear between the path samples.
  • Sensor. The reading y follows response_time * dy/dt = concentration - y, a first-order lag. The tool integrates it exactly between samples, so a shorter reading interval does not change the values. The last reading is at the end of the route, even when the ride time is not a multiple of the interval.
  • Start. The sensor starts at the first field value. --initial-kg-m3 0 starts it at zero instead. --response-time-s 0, the default, gives a sensor without delay.
  • Bounds. A ride has at most 200000 readings, and an existing output file is never overwritten.

What a virtual ride is not

  • Not a time series of the atmosphere. Variation along the ride is variation in space of a steady mean field.
  • Not a model of a particular sensor. No commercial sensor is claimed to follow the first-order lag without calibration.
  • Not validated. The sampling and the lag are verified against analytic cases (mobile evidence record); no measured ride has been compared.
  • Not exact superposition by itself. Samples are linear in the field, but the field is linear in the sources only with fixed flow and linear_upwind transport (chapter 5).

A task for an agent

Read docs/ai-context.md. Add a path receptor to a case whose route stays in resolved air; declare height and sample spacing. Run the case, keep the archive and run validation/check_fields.py on it. Simulate one ride with a stated speed, reading interval, response time and start value. Report the termination, the assessment, the path mean and the ride, and say that the ride is an idealized pass through a steady mean field, not a measurement.

Next

  • Chapter 24: infer street emissions from rides and plan routes.
  • Chapter 22: buildings from a map, particles and vegetation.

Source inference and route selection from rides

Which street emits how much? Rides with a sensor give concentrations along routes. If a model gives the concentration that each street alone would cause on each ride, the emission rates can be fitted to the rides. This chapter builds that table (the response matrix), fits rates, shows which streets the rides cannot tell apart, estimates how many passes a street needs and selects routes under a time budget.

Everything here is verified on synthetic data that the same model produced. A successful recovery tests the numerical workflow. It validates no sensor and no urban air, and no measured ride has been used.

Setup

You need a checkout with the command and the example mobile_response built, and the optional Python packages: NumPy, SciPy and LP-IP-craft for the study, Shapely for the street converter.

cargo build --release --workspace --locked
cargo build --release --locked -p cfd-craft --example mobile_response
python -m pip install -r integrations/requirements-mobile.txt

Every section reads this study of 4 s on the documentation host. It writes its plan and its acceptance thresholds before the first solve.

mkdir -p runs
python tutorials/mobile_measurements.py run --preset source-response --output runs/study > /dev/null

Outputs on this page are real. The documentation check compares floating-point numbers with a relative tolerance of 1e-4; everything else must match exactly.

The smallest study

The preset has three streets (line sources street-a to street-c), two wind directions (270 and 250 degrees), two training rides and two held-out rides that the fit never sees. The true rates are 0.7, 1.3 and 0.4 times the reference rate of each street.

import json

r = json.load(open("runs/study/report.json"))
fit = r["inference"]
print(r["passed"], r["experimental_validation"])
print([f"{m:.4g}" for m in fit["multipliers"]], fit["estimate_label"])
print(fit["identifiability"]["rank"], fit["heldout_relative_error"] < 1e-3)
print(r["relative_superposition_defect"] < 1e-4)
print(sorted(k for k, passed in r["gate_checks"].items() if passed))
True not_validated
['0.7', '1.3', '0.4'] unique_nonnegative_estimate
3 True
True
['ambiguity_reported', 'full_rank_training', 'heldout_recovery', 'rate_recovery', 'route_integer_optimal', 'superposition']

The fit recovers the three multipliers from the training rides, the matrix has full rank 3, and the held-out rides are predicted within the threshold of 1e-3. The study exits 0 when all six checks pass and 2 otherwise; failed solves and partial results stay in the output directory. The second preset, --preset canyon, does the same in the street canyon of chapter 10; --config PLAN.json runs your own plan.

One flow, one transport run per street

For each wind the study solves the flow once and accepts it by the usual steady checks. Then it solves one transport run per street on that frozen flow, each from zero concentration: the flow is not updated again. A fourth transport run with all streets at their true rates is the reference; it is never used to build the matrix. Each run is a normal archive that passes validation/check_fields.py. The checker recomputes a hash of the frozen velocity, pressure and turbulence fields of each archive, and the study requires the same hash in all runs of one wind.

The matrix has one row per ride sample and one column per street. A row is the virtual ride of chapter 23 through one street’s field: constant speed, a first-order sensor that starts at zero. The matrix maps dimensionless multipliers to kg/m3; the reference rate of each column converts a fitted multiplier back to kg/s.

Conditions for an exact matrix: steady linear_upwind transport, no initial concentration, and the same flow for all columns (CFD-E089 otherwise). The MUSCL scheme is not linear. Particle bins and leaf deposition stay linear. The Rust interface is mobile_response::PreparedFlow (transport model card).

Fit your own observations

fit takes a response matrix and a CSV with exactly the columns wind,ride,sample_index,concentration_kg_m3, one row per sample of the matrix. The study wrote such a file from its reference run:

python tutorials/mobile_measurements.py fit runs/study/mobile-response-matrix.json \
  runs/study/virtual-observations.csv --train train-near train-far \
  --heldout heldout-mid heldout-reverse --output runs/fit.json
python -c "
import json
f = json.load(open('runs/fit.json'))
print([f'{m:.4g}' for m in f['multipliers']], f['individual_rates_unique'])
p = f['input_provenance']
print(len(p['matrix_sha256']), len(p['observations_sha256']))"
['0.7', '1.3', '0.4'] True
64 64

The fit is a nonnegative least-squares fit on the training rides, weighted by the declared noise. Held-out rides only test the prediction. The result keeps the SHA-256 hashes of the matrix and of the CSV it read (second line). Real sensor data must first be aligned to the samples, calibrated and reduced to the increment above background, in kg/m3 of the same constituent; the fit does none of that.

Which streets can be told apart

Two streets with the same response on every ride cannot be separated: only their sum is known. identifiability reports the rank of the matrix and names the combinations that the rides do not determine.

import sys

sys.path.insert(0, "integrations")
from mobile_inference import identifiability, required_passes

report = identifiability([[1.0, 1.0], [2.0, 2.0]], ["street-a", "street-b"])
print(report["rank"], report["nullity"], report["full_column_rank"])
passes = required_passes(
    1e-8,
    sensor_sigma_kg_m3=2e-10,
    pass_scatter_sigma_kg_m3=1e-9,
    effective_samples_per_pass=5,
    relative_half_width=0.1,
    confidence_z=1.96,
    systematic_sigma_kg_m3=0.0,
)
print(passes["passes"], passes["simulated"])
1 1 False
4 False

Rank 1 of 2: the fitted rates of the two streets are one of many equally good answers and must not be read one by one. The rank uses a relative threshold on the singular values (default 1e-10). The study also adds a copy of street-b on purpose and reports rank 3 of 4.

How many passes a street needs

The second result above is a planning number. A pass is one ride of a route in one wind. The noise model has two declared parts: readout noise of the sensor, independent per sample, and scatter between passes, one offset per pass. With n effective independent samples per pass the variance of a pass mean is v = pass scatter² + sensor noise² / n. To know the mean within a half width h at confidence factor z you need at least ceil(v / ((h/z)² − systematic²)) passes. A mean of 1e-8 kg/m3 with the values above needs 4 passes for 10 percent. When the systematic part alone exceeds the target, no number of passes is enough and the function says so.

No noise is simulated and none is estimated from data. Drift, calibration error and the error of the CFD model are not reduced by repetition.

Which routes under a time budget

A candidate is one route in one wind, with its riding and setup time. A wind direction is an opportunity to wait for, not something the rider controls. The selection picks the set of candidates within the time budget whose weakest-determined combination of streets is determined best (an E-optimal design: it maximizes the smallest eigenvalue of the summed information matrices).

import json

sel = json.load(open("runs/study/report.json"))["route_selection"]
print(sel["selected"], sel["certified"])
print(f"{sel['riding_time_s']:.4g} of {sel['riding_time_budget_s']:.4g} s")
rank = sel["selected_identifiability"]["rank"]
print(sel["exhaustive_check"]["checked_patterns"], rank)
['wind-270:train-near', 'wind-250:train-near'] True
26.67 of 36 s
16 3

The mixed-integer solver of LP-IP-craft solves a sequence of bounded linear models with added cuts. certified means that the selection is optimal within the declared floating-point gap, measured against the solver’s proven bound; it is not an exact proof. Limits and solver failures are kept in the report and are never certified. For the four candidates here all 16 subsets were also enumerated.

Street emissions from map data

integrations/traffic_sources.py turns street centerlines and a table of emission rates into line sources of a case made by the map converter:

python integrations/traffic_sources.py --case mapped/case.json \
  --map-provenance mapped/map-provenance.json --streets streets.geojson \
  --rates rates.csv --height-m 0.3 --output mapped-traffic

The streets are GeoJSON lines in the coordinate system of the buildings. The CSV has the columns street_id, constituent, rate_kg_s_m and units, where units must be kg/s/m. The tool invents no rate: no emission factor and no traffic count is assumed. It reuses the recorded map transformation, clips streets to the domain and records kept and omitted lengths, the total in kg/s and the hashes of its inputs. A street that touches a building is rejected (CFD-M002), never moved. See the street-emission input contract.

What this is not

  • Not validated. Inference and route selection are verified on synthetic data from the same model only. The protocol for measured rides lists what must be fixed before measured data are opened.
  • Not a bike-against-station comparison. The report gives the ratio of a modeled path mean and of a modeled lagged sensor mean to a modeled station value. On a short ride the lagged ratio is dominated by the sensor starting at zero.
  • Not total concentration. Rows are increments from the declared streets in a steady mean field.
  • Not better than the flow under it. The open questions of chapter 22 apply to every matrix built on a district flow.

Next

Reference

Look-up pages. They state facts and do not teach; the guide does that.

Three pages and two blocks of the command line page are generated from the code by scripts/generate_reference.py (--check fails when a committed page differs from the current build, and when a CFD- code in the Rust or Python sources is missing from the diagnostics catalog). Do not edit generated text by hand.

PageMade howWhat it holds
Case schemagenerated from cfd-craft describeEvery field of a case file: type, required or default, description
Result schemagenerated from describeFields of summary.json and of the phase profile
Python APIgenerated from the docstringsdescribe, check, simulate, CfdError and the console script
Command linehand-written, with two generated blocksEach cfd-craft command: inputs, outputs, exit codes
Units and conventionshand-writtenUnits, coordinates, wind direction, particles, rotated map frames, array ordering
Scriptshand-writtenThe Python tools: arguments and exit codes

Reference pages that live one level up:

The Rust API is on docs.rs.

Case schema

This page lists every field of a case file. It is generated from the case_schema field of cfd-craft describe, whose descriptions are the doc comments of the Rust types. The schema dialect is JSON Schema draft-07. Units are in the field names; see units and conventions. Tables are sorted by field name. The order in a case file does not matter.

Case

A complete native case, schema version cfd-craft.case/0.1. Nothing outside the case configures the solver. Unknown fields are rejected; the lists default to empty when omitted. Deserialization checks only the types: the semantic checks (ranges, units, budgets, geometry) are those of cfd-craft check, which reports coded diagnostics with field paths.

Unknown fields are rejected.

FieldTypeRequiredDescription
boundariesBoundariesrequired
building_roughness_mnumber or nulloptionalOptional aerodynamic roughness of building walls in meters, independent of cell width. Omission reproduces the legacy wall recipe (CFD-E085).
constituentsarray of Constituentdefault []Passive gases transported by the flow. Default: empty, which solves the flow only.
domainDomainrequired
flowFlowrequired
geometryarray of Blockdefault []Axis-aligned solid boxes (buildings, obstacles). A cell is solid when its center lies inside a box. Not allowed with prescribed_uniform flow (CFD-E013). Optional footprint_m selects polygon prisms. Masked multigrid is supported. Default: empty.
geometry_min_passage_cellsinteger or null (>= 0)optionalWarn if a represented street between solids is narrower than this number of horizontal cells. Omitted for legacy cases (CFD-W011).
gridGridSpecrequired
initial_conditionsarray of Initialdefault []Initial concentration fields, at most one per constituent (CFD-E018); a constituent without one starts at zero. Default: empty.
moving_wallsarray of MovingWalldefault []Tangentially moving wall faces of the domain, such as a cavity lid; laminar flow only (CFD-E021). Default: empty.
namestringrequiredNonempty experiment label (CFD-E002), copied into the result. It is excluded from the physics hash, so renaming keeps checkpoints compatible.
numericsNumericsrequired
outputOutputrequired
receptorsarray of Receptordefault []Named concentration samples, reported for every constituent in the result’s receptors_kg_m3 and in probes.csv. Default: empty.
runRunrequired
schema_versionstringrequiredContract version; must be cfd-craft.case/0.1 (CFD-E001).
sourcesarray of Sourcedefault []Continuous emissions into the constituents. Default: empty.
vegetationarray of VegetationoptionalOpt-in porous canopy boxes; zero leaf density has no numerical effect.

Advection

Advection scheme of the constituents. linear_upwind is first-order upwind; it is linear in the concentrations, so responses to sources superpose exactly in a fixed flow. muscl adds a second-order slope with the bounded monotonized-central limiter; it is nonlinear, so superposition is not exact.

Allowed values: linear_upwind, muscl.

Block

An axis-aligned solid box. Cells whose centers lie inside it (lower bound inclusive, upper bound exclusive) are solid; boxes may overlap. The bounds must increase on every axis and lie inside the domain (CFD-E014), and the box must contain at least one cell center (CFD-E028). Fewer than ten cells across its height draws warning CFD-W001.

Unknown fields are rejected.

FieldTypeRequiredDescription
footprint_marray or nulloptionalOptional simple footprint polygon in local x/y meters. With this field the shape is a prism between min_m[2] and max_m[2]; the other bounds must equal the footprint bounds. Holes and self-intersections are rejected (CFD-E084). Omission selects the original box.
idstringrequiredUnique nonempty ID (CFD-E014); the key of the box’s cell count in geometry.json.
max_marray of 3 numberrequiredUpper corner [x, y, z] in meters.
min_marray of 3 numberrequiredLower corner [x, y, z] in meters.

Boundaries

Boundary conditions of the domain: x, y and z each set the condition of the two domain faces normal to that axis (west and east, south and north, ground and top).

Unknown fields are rejected.

FieldTypeRequiredDescription
xBoundaryrequired
yBoundaryrequired
zBoundaryrequired

Boundary

Boundary condition of the pair of domain faces normal to one axis. periodic identifies the two faces. open lets flow in or out: each face is an inlet or an outlet by the sign of the case flow’s normal velocity there; inlets prescribe that velocity and a zero concentration increment, outlets fix the pressure level, and faces without normal flow are slip faces. wall is impermeable and no-slip (a rough wall with neutral_rans). slip is impermeable and stress-free. ground_open_top (z only, CFD-E005) is a rough ground with a top that applies the boundary-layer shear stress; neutral_rans requires it (CFD-E011) and laminar flow may not use it (CFD-E023).

Allowed values: periodic, open, wall, slip, ground_open_top.

CanopyClosure

Published canopy source-coefficient set; the ambient k-epsilon constants are unchanged. Both alternatives are unvalidated in this urban solver.

ValueDescription
green1992Green (1992): beta_p=1, beta_d=4, C_e4=C_e5=1.5.
sanz2003Sanz/Katul: beta_p=1, beta_d=5.1, C_e4=C_e5=0.9.

Constituent

A passive gas: transported and diffused by the flow without affecting it. Concentrations are in kg/m3.

Unknown fields are rejected.

FieldTypeRequiredDescription
diffusivity_m2_snumberrequiredMolecular diffusivity in m2/s, finite and nonnegative (CFD-E015). With neutral_rans the turbulent diffusivity nu_t/Sc_t is added.
idstringrequiredUnique nonempty ID (CFD-E015), referenced by sources and initial conditions and used in the result.
particleParticleBin or nulloptionalOptional spherical aerosol bin. Omitted for gases, preserving old hashes.

Domain

Physical extent of the domain: a box from the origin to size_m.

Unknown fields are rejected.

FieldTypeRequiredDescription
size_marray of 3 numberrequiredLengths along x (east), y (north) and z (up) in meters, each finite and within 1e-6..1e9 (CFD-E003).

Flow

Flow model, selected by kind: prescribed_uniform (a fixed uniform velocity; only the constituents are solved), laminar (incompressible flow with constant viscosity) or neutral_rans (a neutral atmospheric boundary layer with the k-epsilon model). The numeric fields are checked as CFD-E012.

Flow, kind prescribed_uniform

A fixed uniform velocity with no flow solve. Its normal component must be zero at impermeable boundaries (CFD-E024), and solid boxes are not allowed (CFD-E013).

Unknown fields are rejected.

FieldTypeRequiredDescription
kindprescribed_uniformrequired
velocity_m_sarray of 3 numberrequiredVelocity [u, v, w] in m/s, finite.

Flow, kind laminar

Incompressible laminar flow with constant kinematic viscosity, started from a uniform velocity.

Unknown fields are rejected.

FieldTypeRequiredDescription
acceleration_m_s2array of 3 numberdefault [0.0, 0.0, 0.0]Uniform body acceleration [x, y, z] in m/s2, for example the pressure-gradient drive of a periodic channel. Default: zero.
initial_velocity_m_sarray of 3 numberrequiredUniform initial velocity [u, v, w] in m/s, finite. It also sets the velocity of open inlet faces and decides which open faces are inlets or outlets.
kindlaminarrequired
viscosity_m2_snumberrequiredKinematic viscosity in m2/s, finite and positive.

Flow, kind neutral_rans

Neutral atmospheric boundary layer with the k-epsilon model (C_mu 0.09, C_epsilon1 1.44, C_epsilon2 1.92, kappa 0.4). Inflow and initial fields are the logarithmic equilibrium profiles U = u*/kappa ln((z + z0)/z0), k = u*^2/sqrt(C_mu) and epsilon = u*^3/(kappa (z + z0)), with u* set by speed_m_s at reference_height_m. Requires boundaries.z = ground_open_top (CFD-E011).

Unknown fields are rejected.

FieldTypeRequiredDescription
direction_deg_fromnumberrequiredMeteorological wind direction in degrees: where the wind blows from, clockwise from north. 270 blows toward +x (east), 180 toward +y (north). Finite; any value is accepted.
kindneutral_ransrequired
reference_height_mnumberrequiredHeight of speed_m_s above the ground in meters, positive and not above the domain top. It is also the length scale of the normalized checks.
roughness_mnumberrequiredAerodynamic roughness length z0 of the ground in meters, positive. Building and other wall faces use min(z0, 0.001 cell width), which ties that wall roughness to the grid (see the flow model card).
speed_m_snumberrequiredMean wind speed at reference_height_m in m/s, finite and positive. It is also the velocity scale of the normalized checks.
turbulent_schmidtnumberrequiredTurbulent Schmidt number Sc_t, positive: constituents diffuse with their molecular diffusivity plus nu_t / Sc_t.
viscosity_m2_snumberrequiredMolecular kinematic viscosity in m2/s, positive; the eddy viscosity C_mu k^2/epsilon is added to it.

GridSpec

Uniform Cartesian grid: the cell size along an axis is the domain length divided by the cell count.

Unknown fields are rejected.

FieldTypeRequiredDescription
cellsarray of 3 integer (>= 0)requiredCell counts along x, y and z: 2..4096 per axis, or 1..4096 on a periodic axis, which makes a two-dimensional run (CFD-E004). The total enters the memory estimate and may not exceed 1e8 cells (CFD-E006).

Initial

Initial concentration of one constituent, selected by kind. Each constituent has at most one (CFD-E018); without one it starts at zero. Solid cells always hold zero.

Initial, kind uniform

The same concentration in every fluid cell.

Unknown fields are rejected.

FieldTypeRequiredDescription
concentration_kg_m3numberrequiredConcentration in kg/m3, finite and nonnegative (CFD-E025).
constituentstringrequiredID of the initialized constituent.
kinduniformrequired

Initial, kind periodic_gaussian

A Gaussian puff, periodized over the domain, integrated per cell and scaled to exactly total_mass_kg of fluid mass. Needs periodic boundaries on all three axes (CFD-E026); used by the transport verification fixtures.

Unknown fields are rejected.

FieldTypeRequiredDescription
center_marray of 3 numberrequiredCenter [x, y, z] in meters, inside the domain.
constituentstringrequiredID of the initialized constituent.
kindperiodic_gaussianrequired
sigma_marray of 3 numberrequiredStandard deviations along x, y and z in meters, each positive and at most twice the domain length.
total_mass_kgnumberrequiredMass of the puff in kg, positive.

Mode

Run mode. steady iterates in pseudo-time until every steady check passes; run.end_time_s does not bound it. transient integrates the physical interval up to run.end_time_s.

Allowed values: steady, transient.

MomentumAdvection

Momentum advection on the staggered grid. Donor-cell (advective form) is the default; the others are conservative flux forms with an upwind-biased reconstruction of the transported component (van Leer’s MUSCL in Sweby’s notation).

ValueDescription
donor_cellFirst-order donor-cell upwind in advective form (default).
second_order_upwindUnlimited second-order upwind: face value 1.5 phi_U - 0.5 phi_UU. Not bounded.
limited_upwindSecond-order upwind with the limiter in numerics.momentum_limiter.

MomentumLimiter

Limiter of limited_upwind momentum advection, in Sweby’s notation s(a, b) with a and b the upwind and downwind differences: van_albada s = ab(a + b)/(a^2 + b^2), van_leer s = 2ab/(a + b), or monotonized_central s = sign(b) min(2|a|, |a + b|/2, 2|b|). Each is zero where a and b differ in sign.

Allowed values: van_albada, van_leer, monotonized_central.

MovingWall

A tangential velocity of one wall face of the domain, such as a cavity lid. Laminar flow only, at most one per face, and the velocity component normal to the wall must be zero (CFD-E021).

Unknown fields are rejected.

FieldTypeRequiredDescription
axisinteger (>= 0)requiredAxis normal to the wall: 0 (x), 1 (y) or 2 (z). That axis must have wall boundaries.
upperbooleanrequiredTrue for the face at the upper end of the axis (for example z = Lz), false for the face at 0.
velocity_m_sarray of 3 numberrequiredWall velocity [u, v, w] in m/s, finite; the component along axis must be zero.

Numerics

Discretization choices, tolerances and the steady monitor window. The optional selections pressure_preconditioner, momentum_advection, momentum_limiter and steady_algorithm are left out of the normalized case when they have their default, so cases written before they existed keep their case and physics hashes.

Unknown fields are rejected.

FieldTypeRequiredDescription
advective_cfl_maxnumberrequiredStability factor of explicit steps, 0 < CFL <= 0.45 (CFD-E010): with the explicit algorithm and for constituent sub-steps, dt = CFL / (sum of max|u|/dx + 2 D sum of 1/dx^2), D the largest viscosity or diffusivity. implicit_viscous applies it to advection only; implicit_projection uses its own CFL ramp for the flow.
max_time_step_snumberrequiredUpper bound of the time step in seconds, finite and positive (CFD-E009). The step is the smaller of this and the stability limit; in transient mode the last step is clipped to end at run.end_time_s.
momentum_advectionMomentumAdvectionoptionalMomentum advection: donor_cell (default), second_order_upwind or limited_upwind. Omitted from the normalized case when donor_cell, which keeps existing case and checkpoint hashes.
momentum_limiterMomentumLimiter or nulloptionalLimiter of limited_upwind: required with it and rejected otherwise (CFD-E037). Omitted when absent.
monitor_windowinteger (>= 0)requiredSteps per monitor window, 2..100000 (CFD-E008). A steady run assesses its checks every monitor_window steps and needs three full windows before monitor_stability can pass.
pressure_max_iterationsinteger (>= 0)requiredPCG iteration limit of each pressure solve, nonzero (CFD-E008). Reaching it fails the step with CFD-E033.
pressure_preconditionerPressurePreconditioneroptionalPreconditioner of the pressure solve: ic0 (default) or multigrid. Omitted from the normalized case when ic0, which keeps existing case and checkpoint hashes.
pressure_relative_tolerancenumberrequiredRelative residual target of each pressure solve, finite and positive (CFD-E009). A solve is accepted when the recomputed residual is within 10 times this plus 1e-12. A loose value changes the path to a steady state, not the steady checks.
steady_algorithmSteadyAlgorithmoptionalPseudo-time algorithm of steady runs: explicit (default), implicit_viscous (laminar only) or implicit_projection (laminar or neutral_rans). The implicit options need run.mode = steady (CFD-E045) and a solved flow (CFD-E047). Omitted from the normalized case when explicit, which keeps existing hashes.
steady_monitor_tolerancenumberrequiredThreshold of monitor_stability, the largest relative change between the means of three successive monitor windows; finite and positive (CFD-E009). Steady mode only.
steady_residual_tolerancenumberrequiredThreshold of the normalized steady equation residuals (momentum, turbulence and each constituent), finite and positive (CFD-E009). Steady mode only.
transportAdvectionrequired

Output

Which optional artifacts a run archive keeps, and its output budget.

Unknown fields are rejected.

FieldTypeRequiredDescription
checkpointbooleanrequiredWrite checkpoint.json, a checksummed restart state.
fieldsbooleanrequiredWrite fields.json, the full final state including the native face velocities.
max_total_mibinteger (>= 0)requiredBudget for all artifacts in MiB. The preflight estimate must fit (CFD-E007); at publication, fields and checkpoint are omitted and listed in the manifest when they would exceed it (CFD-E061).

ParticleBin

Dilute spherical particle bin, with no feedback, chemistry or resuspension. The declared deposition velocities exclude gravitational settling, which is added separately on upward-facing ground and roofs.

Unknown fields are rejected.

FieldTypeRequiredDescription
density_kg_m3numberrequiredParticle material density in kg/m3, above the reference air density.
diameter_mnumberrequiredGeometric diameter in meters (1e-8..1e-4).
ground_deposition_velocity_m_snumberdefault 0.0Additional ground deposition speed, in m/s, excluding settling.
roof_deposition_velocity_m_snumberdefault 0.0Additional roof deposition speed, in m/s, excluding settling.
settling_velocity_m_snumber or nulloptionalDirect nonnegative settling speed, bypassing the Stokes validity gate.

PressurePreconditioner

Preconditioner of the pressure PCG solve. ic0 (the default) is an incomplete Cholesky factor built once per grid and works on every grid. multigrid is a fixed symmetric multigrid cycle. On an unmasked grid it is geometric, and strongly anisotropic spacings select line or plane smoothing. With geometry it aggregates connected fluid cells and uses point smoothing only, so strong anisotropy can make it slower than ic0. Strong anisotropy draws warning CFD-W004 in both cases. Both preconditioners solve the same equation to the same tolerance and recomputed residual.

Allowed values: ic0, multigrid.

Receptor

A named concentration sample, selected by kind and reported in kg/m3 for every constituent (receptors_kg_m3 of the result, probes.csv). IDs are unique and nonempty (CFD-E019); the support is nondegenerate and inside the domain (CFD-E027) and may not sample a solid cell (CFD-E042).

Receptor, kind point

Trilinear interpolation between the eight surrounding cell centers, clamped at the domain boundary.

Unknown fields are rejected.

FieldTypeRequiredDescription
idstringrequiredUnique nonempty receptor ID (CFD-E019).
kindpointrequired
point_marray of 3 numberrequiredPosition [x, y, z] in meters, inside the domain.

Receptor, kind volume_average

The average over a box, weighted by the exact overlap of each cell with the box. Not a point sample or a peak bound.

Unknown fields are rejected.

FieldTypeRequiredDescription
idstringrequiredUnique nonempty receptor ID (CFD-E019).
kindvolume_averagerequired
max_marray of 3 numberrequiredUpper corner [x, y, z] in meters; every bound above min_m and inside the domain.
min_marray of 3 numberrequiredLower corner [x, y, z] in meters.

Receptor, kind path

Polyline sampling at a constant height. Samples are equally spaced in arc length, including both endpoints, with spacing at most the declared maximum. The receptor mean is normalized trapezoidal quadrature.

Unknown fields are rejected.

FieldTypeRequiredDescription
height_mnumberrequiredConstant sample height above flat ground, in meters.
idstringrequiredUnique nonempty receptor ID (CFD-E019).
kindpathrequired
polyline_marray of array of 2 numberrequiredLocal metric x/y vertices; 2..4097, without repeated neighbors.
sample_spacing_mnumberrequiredPositive finite maximum arc-length spacing, in meters.

Run

Mode, endpoint and execution budgets. The whole group is excluded from the physics hash, so budgets can change between a run and its restart.

Unknown fields are rejected.

FieldTypeRequiredDescription
end_time_snumberrequiredPhysical end time of a transient run in seconds: finite, positive and at most 1e12 (CFD-E009, CFD-E022). It does not bound a steady run.
max_stepsinteger (>= 0)requiredMaximum number of retained steps (outer iterations with an implicit steady algorithm), counted from the cold start including the steps of a restart checkpoint; nonzero (CFD-E008). Reaching it ends the run as iteration_limit.
memory_limit_mibinteger (>= 0)requiredMemory budget in MiB for the preflight estimate (CFD-E006); a restart checkpoint may be at most half of it (CFD-E065). An estimate check, not an enforced process limit.
modeModerequired
threadsinteger (>= 0)requiredWorker threads, 1..64 (CFD-E008). The CLI and the Python binding solve on a pool of this size; the Rust library does not create one.
wall_time_limit_snumberrequiredWall-time allowance in seconds: finite, positive and at most seven days (CFD-E009, CFD-E022). The CLI and the Python binding enforce it; a Rust caller passes it, or its own limit, to Control::new.

Source

A continuous emission into one constituent, selected by kind. Rates are finite and nonnegative (CFD-E016); the support is nondegenerate and inside the domain (CFD-E017). The integrated rate is distributed over the cells the support covers. Support touching a solid cell is rejected (CFD-E040), as is a steady source in a fluid region without an outlet (CFD-E043, and CFD-E020 when no boundary is open).

Source, kind point

A point emission, deposited in the cell that contains the point.

Unknown fields are rejected.

FieldTypeRequiredDescription
constituentstringrequiredID of the emitted constituent (CFD-E016).
idstringrequiredUnique nonempty source ID (CFD-E016).
kindpointrequired
point_marray of 3 numberrequiredPosition [x, y, z] in meters, inside the domain (each coordinate at least 0 and below the domain length).
rate_kg_snumberrequiredEmission rate in kg/s.

Source, kind line

A straight line emission. The integrated rate is rate_kg_s_m times the line length, distributed over the cells the segment crosses in proportion to its length in each.

Unknown fields are rejected.

FieldTypeRequiredDescription
constituentstringrequiredID of the emitted constituent (CFD-E016).
from_marray of 3 numberrequiredStart point [x, y, z] in meters, inside the domain.
idstringrequiredUnique nonempty source ID (CFD-E016).
kindlinerequired
rate_kg_s_mnumberrequiredEmission rate per meter of line, kg/(s m).
to_marray of 3 numberrequiredEnd point [x, y, z] in meters, inside the domain and different from from_m.

Source, kind volume

A uniform emission over a box. The integrated rate is rate_kg_s_m3 times the box volume, distributed over the cells by their exact overlap with the box.

Unknown fields are rejected.

FieldTypeRequiredDescription
constituentstringrequiredID of the emitted constituent (CFD-E016).
idstringrequiredUnique nonempty source ID (CFD-E016).
kindvolumerequired
max_marray of 3 numberrequiredUpper corner [x, y, z] in meters; every bound above min_m and inside the domain.
min_marray of 3 numberrequiredLower corner [x, y, z] in meters.
rate_kg_s_m3numberrequiredEmission rate per cubic meter, kg/(s m3).

SteadyAlgorithm

Steady pseudo-time algorithm. explicit is the SSPRK2 march of the earlier release. The implicit options solve for a correction driven by the full steady residual (delta form), so they share its fixed point.

ValueDescription
explicitSSPRK2 pseudo-time steps with a projection per stage, limited by advection and diffusion together (default).
implicit_viscousSSPRK2 stages with an implicit viscous term: (I − Δτ L_ν) δ = Δτ R.
implicit_projectionOne implicit correction per outer iteration, A δ = R with a Picard first-order upwind and viscous Jacobian and a CFL ramp, followed by a projection at the pseudo-time step (a SIMPLEC-type coupling).

Vegetation

Flat-ground porous vegetation volume. Box membership uses cell centers, lower-inclusive and upper-exclusive, exactly as building masks.

Unknown fields are rejected.

FieldTypeRequiredDescription
drag_coefficientnumberrequiredDimensionless form-drag coefficient.
idstringrequiredUnique nonempty volume ID.
leaf_area_density_m2_m3numberrequiredLeaf area per air volume, in m2/m3 (inverse meters).
leaf_deposition_velocity_m_snumberdefault 0.0Particle collection velocity per leaf area, m/s; excludes settling.
max_marray of 3 numberrequiredBox upper corner in meters.
min_marray of 3 numberrequiredBox lower corner in meters.
turbulence_closureCanopyClosuredefault "green1992"Canopy k-epsilon source coefficient set.

Result schema

This page lists the fields of summary.json and of the phase profile. It is generated from the result_schema and phase_profile_schema fields of cfd-craft describe. What the files mean and which checks report repeats is in the result contract. A field without a default that is not required may be absent; null means unavailable, not zero.

Summary

The result of one native run (schema cfd-craft.result/0.1), written as summary.json: identities, the stopping reason and numerical verdict, work counters, geometry, the recomputed checks and per-constituent evidence. termination says why execution stopped; assessment says what the checks support; experimental validation is a separate question. Null means unavailable in the stated context, not zero.

Unknown fields are rejected.

FieldTypeRequiredDescription
assessmentstringrequiredNumerical verdict: steady_discrete_solution or transient_interval_completed (completed with every check passed), failed_checks (completed, some check failed) or incomplete (any other termination). Never upgraded because the last state looks reasonable.
build_versionstringrequiredPackage version and compiler of the producing build, as <version>; <rustc version>.
case_sha256stringrequiredSHA-256 of the consumed, normalized case as compact JSON.
checksarray of CheckrequiredEvery recomputed check of the returned state.
constituentsarray of ScalarEvidencerequiredEvidence for each constituent, in case order.
elapsed_snumberrequiredWall seconds of this invocation, from the creation of its control.
errorstring or nulloptionalThe failure that stopped the run, usually with its code (for example CFD-E033: pressure iteration limit 100), or cancelled / wall_time_limit when the stop came inside a step; null otherwise.
estimated_peak_mibnumberrequiredThe preflight memory estimate of the case check, in MiB.
experimental_validationstringrequiredAlways not_validated; see validation/data-inventory.json: numerical acceptance is not experimental validation.
fluid_cellsinteger (>= 0)requiredNumber of fluid cells.
fluid_componentsinteger (>= 0)requiredNumber of face-connected fluid regions, each with its own pressure gauge unless it touches an outlet.
frozen_flowFrozenFlowEvidence or nulloptionalOptional verified fixed-flow initialization and zero-flow-update evidence. Ordinary coupled runs omit this field.
initial_state_sha256stringrequiredSHA-256 of the starting state (cold or restored), so restarts from different states stay distinguishable.
mask_sha256stringrequiredSHA-256 of the cell mask, one byte per cell (1 fluid, 0 solid) in cell order; also in geometry.json.
model_scopestringrequiredModel label: incompressible_laminar, prescribed_flow_passive_transport or neutral_k_epsilon_rough_wall; the CLI prefixes preview: for a coarsened preview.
momentum_residualnumber or nulloptionalLargest normalized momentum residual, null for prescribed flow.
momentum_solver_iterationsinteger or null (>= 0)optionalInner iterations of implicit momentum-correction solves, when selected.
namestringrequiredThe case name.
particulate_matterobject with string keys and values of ParticulateEvidenceoptionalPM2.5/PM10 airborne mass and receptor sums for spherical particle bins. No interpolation within a bin: its representative aerodynamic diameter is either below the cutoff or excluded. Omitted without particles.
physical_time_snumberrequiredTime covered in seconds; pseudo-time in steady mode.
physics_sha256stringrequiredPhysics hash of the case: the case without name, run and output. Checkpoints are compatible across cases with the same value.
pressure_iterationsinteger (>= 0)requiredCumulative pressure PCG iterations of the retained steps.
receptor_relative_changenumber or nulloptionalLargest relative change between the means of three successive monitor windows over all monitor columns (flow norm, constituent masses, receptor values and, with neutral_rans, mean k and epsilon); null before three full windows. The monitor_stability value of steady runs.
schema_versionstringrequiredAlways cfd-craft.result/0.1.
solid_cellsinteger (>= 0)requiredNumber of solid cells.
source_sha256stringrequiredSource fingerprint of the producing build. A library run reports the core crate’s; the CLI and the Python binding combine it with their own.
stepsinteger (>= 0)requiredRetained steps (outer iterations with an implicit steady algorithm), cumulative across restarts.
terminationstringrequiredWhy execution stopped: completed, iteration_limit (step budget), wall_time_limit, cancelled or diverged (a failed step, recorded in error).
threadsinteger (>= 0)requiredThe case’s declared run.threads, not a measurement of the pool.
turbulence_residualnumber or nulloptionalLargest normalized k or epsilon residual, neutral_rans only.
turbulent_floor_eventsinteger (>= 0)requiredTurbulence updates that hit the k or epsilon floor; any event fails the turbulence checks.
vegetationEvidence or nulloptionalRecomputed porous canopy drag/coverage, absent without nonzero LAD.
velocity_max_m_snumberrequiredLargest absolute face velocity in m/s.

Check

One numerical check, recomputed by the solver from the current fields. A check passes when its value is finite and at most its threshold. Continuity and residual values are normalized with the case’s velocity and length scales (neutral_rans: speed_m_s and reference_height_m; otherwise the reference speed, at least 1 m/s, and the shortest domain side).

Unknown fields are rejected.

FieldTypeRequiredDescription
methodstringrequiredHow the value was obtained, for example application recomputation from current fields.
namestringrequiredWhat is checked: local_continuity, boundary_volume_balance, steady_momentum_equations, steady_turbulence_equations, turbulence_floor_events, monitor_stability, or per constituent <id>.mass_budget, <id>.negative_mass, <id>.steady_equation and <id>.steady_mass_balance. The steady checks appear in steady mode only, the turbulence checks with neutral_rans only.
passedbooleanrequiredWhether the value is finite and at most the threshold.
thresholdnumberrequiredLargest accepted value, a fixed gate or the tolerance from the case.
valuenumber or nulloptionalThe measured value, or null when it is not finite or not available, such as monitor_stability before three full monitor windows. A null value fails.

Evidence

Instantaneous canopy evidence; integrated drag is per unit air density.

Unknown fields are rejected.

FieldTypeRequiredDescription
drag_power_per_density_m5_s3numberrequiredPositive rate of work against canopy drag, divided by density (m5/s3).
drag_quadraturestringrequiredQuadrature of the actual staggered momentum sink over active face dual volumes (area times face gradient distance).
integrated_drag_acceleration_m4_s2array of 3 numberrequiredIntegral of drag acceleration over fluid volume (m4/s2), with its sign.
validationstringrequiredThe model remains numerically verified and physically unvalidated.
volume_fluid_cellsobject with string keys and values of integer (>= 0)requiredNumber of represented fluid cells per vegetation ID; overlaps count twice.

FrozenFlowEvidence

Provenance for scalar responses on one accepted, immutable flow state.

Unknown fields are rejected.

FieldTypeRequiredDescription
assessmentstringrequiredSource flow assessment; only steady_discrete_solution is accepted.
flow_physics_sha256stringrequiredPhysics hash of the source flow-only case.
flow_state_sha256stringrequiredSHA-256 of length-prefixed little-endian f64 velocity,p,k,epsilon arrays.
initializationstringrequiredThe transport starts from the declared (required zero) concentration field.
native_flow_solvesinteger (>= 0)requiredNumber of nonprescribed native flow solves: 0 for analytic prescribed flow,1 otherwise.
preparation_stepsinteger (>= 0)requiredCoupled flow steps used in the preparation, counted separately.
response_flow_updatesinteger (>= 0)requiredFlow updates during this scalar response; always zero.
source_sha256stringrequiredSource implementation of the accepted flow preparation.

ParticulateEvidence

Sum over particle bins passing an aerodynamic-size cutoff.

Unknown fields are rejected.

FieldTypeRequiredDescription
mass_kgnumberrequiredIntegrated airborne mass, in kg.
receptors_kg_m3object with string keys and values of numberrequiredLocal-source concentration increments at receptors, in kg/m3.

PathEvidence

A path receptor sampled from one constituent’s returned concentration field.

Unknown fields are rejected.

FieldTypeRequiredDescription
concentrations_kg_m3array of numberrequiredLinear-interpolated concentration increments, in kg/m3.
distance_marray of numberrequiredArc length from the first route vertex, in meters.
mean_kg_m3numberrequiredArc-length trapezoidal mean, also in receptors_kg_m3 for this ID.
points_marray of array of 3 numberrequiredLocal east/north/up positions in meters, in route order.

ScalarEvidence

Evidence for one constituent at the returned state: mass budget, extrema, the steady residual, instantaneous rates and receptor values. Cumulative quantities are in kg, rates in kg/s, concentrations in kg/m3.

Unknown fields are rejected.

FieldTypeRequiredDescription
aerodynamic_diameter_mnumber or nulloptionalUnit-density equivalent aerodynamic diameter used for PM sums.
boundary_inflow_rate_kg_snumberrequiredCurrent rate of mass entering through boundary faces.
boundary_outflow_rate_kg_snumberrequiredCurrent rate of mass leaving through boundary faces.
budget_defect_kgnumberrequiredmass_kg minus initial, emitted and inflow mass plus outflow mass.
deposited_kgobject with string keys and values of numberoptionalCumulative particle deposition by surface class, in kg.
deposition_rate_kg_sobject with string keys and values of numberoptionalCurrent deposition rate by surface class, in kg/s.
emitted_kgnumberrequiredCumulative mass emitted by the sources.
idstringrequiredThe constituent ID.
inflow_kgnumberrequiredCumulative mass that entered through boundary faces.
mass_kgnumberrequiredMass in the domain, the sum of concentration times cell volume.
maximum_kg_m3numberrequiredLargest concentration over all cells, at least 0.
minimum_kg_m3numberrequiredSmallest concentration over the fluid cells.
negative_mass_kgnumberrequiredMass of the negative concentrations, as a positive number; never clipped.
outflow_kgnumberrequiredCumulative mass that left through boundary faces.
pathsobject with string keys and values of PathEvidenceoptionalOrdered path samples and their arc-length means, keyed by path ID. Omitted when no path receptor is declared, preserving legacy output bytes.
receptors_kg_m3object with string keys and values of numberrequiredConcentration at each receptor, keyed by receptor ID. JSON maps are sorted lexically (R10 before R2), so look values up by ID.
relative_budget_defectnumberrequiredAbsolute budget defect over the sum of initial, emitted, inflow and outflow mass; the mass_budget check requires at most 1e-9.
settling_velocity_m_snumber or nulloptionalResolved particle settling speed; omitted for gases.
source_rate_kg_snumberrequiredEmission rate of the represented sources.
steady_residualnumberrequiredLargest steady-equation residual |dc/dt| over the cells, normalized by the velocity scale, the length scale and maximum_kg_m3.

The phase profile is the timing field of the profile.json that cfd-craft profile writes.

Profile

A phase profile (schema cfd-craft.phase-profile/0.1): wall time and work per solver phase. Only exclusive times may be added. Work includes failed attempts, so it can exceed the counters of the retained state.

Unknown fields are rejected.

FieldTypeRequiredDescription
accounted_exclusive_snumberrequiredSum of the exclusive seconds of all phases.
elapsed_snumberrequiredWall seconds since the control was created, at the snapshot.
phasesobject with string keys and values of PhaseTimingrequiredTiming of each phase that ran, keyed by its snake_case phase name.
schema_versionstringrequiredAlways cfd-craft.phase-profile/0.1.
unattributed_snumberrequiredElapsed minus exclusive phases for a single serial invocation. Parallel callers may have aggregate phase time exceeding elapsed wall time.

MultigridWork

Attempted work, accumulated locally without timers or locks inside PCG. Hierarchy dimensions/storage are maxima, not sums over repeated solves.

Unknown fields are rejected.

FieldTypeRequiredDescription
block_level_cell_visitsinteger (>= 0)optionalCells of the block-smoothed levels per visit; omitted when zero. Then smoothing = 4 x residual - 2 x block visits.
block_smoothing_cell_updatesinteger (>= 0)optionalCell updates of block sweeps; omitted when zero. Twice the block level visits.
block_solvesinteger (>= 0)optionalExact line or plane block solves; omitted when zero.
coarse_solvesinteger (>= 0)requiredDense direct solves on the coarsest level, one per cycle.
cyclesinteger (>= 0)requiredV-cycles applied, one per preconditioner application.
hierarchy_buildsinteger (>= 0)requiredHierarchy constructions (0 when a cached hierarchy was reused).
hierarchy_bytesinteger (>= 0)requiredRetained hierarchy storage in bytes (maximum over the merged solves).
hierarchy_cellsinteger (>= 0)requiredUnknowns over all levels (maximum over the merged solves).
hierarchy_levelsinteger (>= 0)requiredNumber of levels (maximum over the merged solves).
hierarchy_nonzerosinteger (>= 0)requiredStored matrix entries over all levels (maximum over the merged solves).
prolongation_cell_updatesinteger (>= 0)requiredCell updates of prolongations; equal to the residual updates.
residual_cell_updatesinteger (>= 0)requiredCell updates of residual evaluations, one per cell and nonterminal level visit.
restriction_cell_updatesinteger (>= 0)requiredCell updates of restrictions; equal to the residual updates.
smoothing_cell_updatesinteger (>= 0)requiredCell updates of all smoothing sweeps, point and block.

PhaseTiming

Accumulated time and work of one phase over all its calls.

Unknown fields are rejected.

FieldTypeRequiredDescription
callsinteger (>= 0)requiredNumber of finished spans of this phase.
exclusive_snumberrequiredWall seconds excluding nested phases; these add up to accounted_exclusive_s.
inclusive_snumberrequiredWall seconds including nested phases. Do not add these up.
multigridMultigridWork or nulloptionalMultilevel work of pressure_solve with the multigrid preconditioner; omitted otherwise.
operator_applicationsinteger (>= 0)requiredOperator products: the compact pressure products plus the independent true-residual products of pressure_solve, and one (CG) or two (BiCGStab) per inner iteration of the implicit solves.
preconditioner_applicationsinteger (>= 0)requiredApplications of the selected preconditioner.
true_residual_checksinteger (>= 0)requiredIndependent face-by-face residual recomputations of pressure_solve.
work_unitsinteger (>= 0)requiredAttempted inner iterations: PCG for pressure_solve, the implicit correction solves for momentum_solve and turbulence_solve; zero for other phases.

Case, result and provenance

The public schemas are generated from the actual types by cfd-craft describe. Case version is cfd-craft.case/0.1. Result version is cfd-craft.result/0.1. Unknown fields, unsupported variants and duplicate object fields are rejected by the typed parser; semantic checks enforce physical values, geometry and budgets.

The illustrative JSON in the earlier planning document was a draft. Use the canonical files in cases/ and the current describe output. This release fixes uniform grids and passive mass in its type definitions instead of accepting unused kind tags.

Status

Termination describes why execution stopped. Assessment describes what its numerical checks support. Experimental validation is a separate label/report.

SituationTerminationAssessment
Steady criteria all metcompletedsteady_discrete_solution
Requested physical interval completed, checks metcompletedtransient_interval_completed
Budget or cancellation before completioniteration_limit / wall_time_limit / cancelledincomplete
Complete execution with failed checkscompletedfailed_checks
Failed numerical stepdivergedincomplete

A failed step is not committed. The saved state is the last accepted state and the error records the attempted-step failure. Passing checks on that earlier state does not promote an incomplete run.

Files

Source identity is package-safe: each crate fingerprints its Rust sources, manifest and build script, plus the root workspace manifest and lockfile in a checkout or its own lockfile when packaged; the CLI combines its fingerprint with the core’s. A direct library call identifies the core, while the Python binding also identifies its native wrapper. Cargo normalizes packaged manifests and lockfiles, so registry and checkout builds can have different fingerprints. These are distribution identities, not a guarantee that a downstream consumer resolved exactly that lockfile. Applications embedding the library should also record their own resolved Cargo.lock and application build identity.

  • case.json: normalized consumed case.
  • summary.json: actual stopping reason, checks, physical scales, work and receptor values.
  • geometry.json: cell counts, connected components, mask hash and the cells of each box.
  • probes.csv: final receptor values in kg/m3.
  • fields.json: optional state archive including native face velocities.
  • checkpoint.json: optional restart wrapper with payload checksum and physics identity.
  • manifest.json: file hashes, artifacts omitted for the output budget, the input case file hash, source/executable/build identity, initial-state hash and platform/thread scope.
  • complete.json: manifest checksum, written last.

The manifest identifies the actual initial state as well as the case. Two restarts of the same case from different accepted states therefore remain distinguishable. Keep parent checkpoints when their initial states must be reproduced.

Checkpoint compatibility excludes name, output and the whole run section (mode, horizon, budgets, threads) from the physics hash. Changing the requested endpoint can change the last clipped timestep; exact step-for-step restart comparisons interrupt a run by its work budget while preserving the same physical endpoint. Reject checkpoints beyond the new requested horizon.

The run directory is created before the solve: a missing parent (CFD-E063) or an existing destination (CFD-E062) fails at once. The output estimate in the check report bounds what a run writes: the fields and checkpoint, the monitor history they carry, and the case, summary and probe text, which grow with the receptors, boxes and sources. A run that passed the check therefore does not normally omit anything. Files use atomic temporary-write/rename publication. If fields or the checkpoint would exceed the output budget, they are omitted and listed in the manifest under omitted; the small artifacts are still written and the run exits 2. Complete files can describe a numerically incomplete run.

report rejects an archive with CFD-E064 when the completion marker or manifest is missing or altered, a listed artifact changed, an entry is not listed, a file is not a regular file, an artifact the case requested is missing without being listed as omitted, summary.json does not describe case.json, the manifest and summary disagree on the source or initial state, or the manifest has an unsupported schema, lacks a required small artifact or lists an unknown artifact name. For an archive whose manifest lists omitted artifacts it prints the summary, repeats CFD-E061 with the omitted names on stderr, and exits 0. Unkeyed hashes do not stop someone from rewriting and rehashing an archive on purpose; validation/check_fields.py recomputes the physics checks for that reason.

With an implicit numerics.steady_algorithm, summary.json also reports momentum_solver_iterations, the cumulative inner iterations of the implicit momentum-correction solves; steps then counts outer iterations. The field is omitted for the explicit default, as is the matching checkpoint field, so existing results and checkpoints are unchanged. With constituents, the archived state (fields and checkpoint) also carries scalar_time_s, the pseudo-time the constituents covered: an implicit algorithm advances them in at most 16 explicit stable sub-steps per outer iteration, so it can be less than time_s, and emitted mass equals the source rate times it. Explicit runs omit it (it equals time_s there).

Numerical check scope

Current steady targets are normalized local continuity 1e-4, net boundary balance 1e-5, physical equation residual from the case, and three stable monitor windows. Scalar cumulative relative budget defect is bounded by 1e-9, with tighter results observed on analytic fixtures. Floor events are forbidden for accepted turbulence runs.

Steady scalar acceptance additionally requires instantaneous source plus inflow to balance outflow within 1e-6 of a declared flux scale. Initial mass supplies a fixed absolute scale for source-free decay. A growing concentration cannot pass merely by making its relative equation residual small. Steady source support in an unanchored fluid component is rejected before time stepping.

The turbulence-floor counter refers to state updates. The separate wall algebraic epsilon minimum is part of the documented prototype wall model; it is not an additional independent acceptance certificate.

The Rust application recomputes checks from the fields. The Python checker separately reconstructs current continuity, mass, source-rate/time accounting and the recorded cumulative-budget equation. Full time-history flux reconstruction and independent turbulent-equation evaluation are not claimed.

Missing/unavailable numeric values are JSON null with an explicit context. Compare them as unavailable values, not zero. Numerical repeatability is scoped to a tested executable/platform/work budget. Wall-time-limited iteration counts are not reproducibility targets.

Command line reference

One section per command of the cfd-craft binary. The usage list and the exit codes are generated from the binary by scripts/generate_reference.py; the rest is written by hand and checked against the source of the command line.

Setup

Commands run from the root of a checkout with target/release on PATH. Fields of a case are in the case schema, files of a run in the result contract, codes in diagnostics.

Usage

  • cfd-craft describe
  • cfd-craft check CASE
  • cfd-craft run CASE --output NEW_DIR [--restart CHECKPOINT]
  • cfd-craft profile CASE --output NEW_DIR [--restart CHECKPOINT]
  • cfd-craft preview CASE --output NEW_DIR [--factor N]
  • cfd-craft report DIR
  • cfd-craft verify CASE

help and --help print this text as {"usage": ...}. --output, --restart and --factor take one value each and may appear once; anything else is an unknown or duplicate option. The thread count, budgets and wall-time limit are case fields (run.*), not options.

Exit codes

ExitMeaning
0success: valid case, passed numerical assessment or verified archive
1invalid input or an execution/I/O error; check reports are printed on stdout
2completed execution with incomplete or failed numerical evidence

Errors that are not check reports go to stderr as {"error": "..."} with exit 1, as does a missing case or directory argument. Exit 0 from report does not mean the run converged: read termination and assessment.

describe

Prints the build and schema description as JSON. No options. Fields include case_schema, result_schema, phase_profile_schema, exit_codes, the names and defaults of the physics and numerics, coordinates, pressure_units, experimental_validation and limitations.

check

check CASE parses and checks a case without solving. Stdout is {"check": REPORT, "geometry": EVIDENCE}: valid, diagnostics (code, severity, path, message), the estimated memory and the cell count. geometry is present when the grid could be built. Exit 0 when valid, 1 when not; warnings do not invalidate.

python -c "import json; c=json.load(open('cases/verification/periodic-tracer.json')); c['name']=''; json.dump(c, open('bad.json', 'w'))"
cfd-craft check bad.json > bad.out || echo "exit $?"
python -c "import json; d=json.load(open('bad.out'))['check']['diagnostics'][0]; print(d['code'], d['path'])"
exit 1
CFD-E002 name

run

run CASE --output NEW_DIR [--restart CHECKPOINT] checks the case, solves it and writes a native archive. NEW_DIR must not exist and its parent must (CFD-E062, CFD-E063). An invalid case, or an estimated peak above 80 percent of the available memory (CFD-E070), prints the check report and exits 1 before anything is created. Stdout is the summary.json content. Exit 0 when assessment is steady_discrete_solution or transient_interval_completed and nothing was omitted; exit 2 otherwise, including artifacts omitted over the output budget (CFD-E061 on stderr). SIGINT and SIGTERM stop the run: it ends cancelled and incomplete, writes its archive and exits 2. --restart continues from a checkpoint.json with the same physics (CFD-E050, E060, E065, E066); the case sets the new endpoint.

cfd-craft run cases/verification/periodic-tracer.json --output runs/a > runs/a.json; echo "exit $?"
cfd-craft run cases/verification/periodic-tracer.json --output runs/a > /dev/null 2>&1 || echo "exit $?"
python -c "import json; s=json.load(open('runs/a.json')); print(s['termination'], s['assessment'])"
exit 0
exit 1
completed transient_interval_completed

profile

profile CASE --output NEW_DIR [--restart CHECKPOINT] runs like run and times the solver phases. NEW_DIR holds profile.json and the ordinary archive in run/. Stdout is the profile envelope cfd-craft.native-profile/0.1: passed, error, the identities, summary and timing (the Profile table of the result schema). physical_qualification is always false. Exit codes are those of run; if the solve fails, profile.json is still written with passed false and the exit is 1.

preview

preview CASE --output NEW_DIR [--factor N] runs the case on a coarser grid. Each axis keeps cells / N cells, at least 2; an axis of one cell stays at one. N is an integer of at least 2 (default 2). The name gets the suffix -preview and model_scope starts with preview:. With geometry, a preview is rejected when coarsening changes the solid volume by more than 20 percent or the fluid components (CFD-E072), or when the original mask cannot be counted (CFD-E073). Output and exit codes are those of run.

report

report DIR verifies a native archive (manifest, file hashes, completion marker, no unlisted entries) and prints its summary.json. Exit 0 for an intact archive whatever its assessment; 1 with CFD-E064 when verification fails. Omitted artifacts exit 0 and repeat CFD-E061 as a warning on stderr. It reads native archives only, not OpenFOAM ones.

cfd-craft run cases/verification/periodic-tracer.json --output runs/a > /dev/null
cfd-craft report runs/a | python -c "import json,sys; print(json.load(sys.stdin)['assessment'])"
transient_interval_completed

verify

verify CASE runs the pressure fixture on the grid of the case and prints fixture, passed, iterations, residual and error. Exit 0 when passed, 2 when not, 1 for an invalid case. It tests the pressure solver, not an archive.

Python API

This page is generated from the docstrings of python/cfd_craft/__init__.py and python/cfd_craft/__main__.py. Examples are in guide chapter 11, the chapter on the Python binding.

Module cfd_craft

In-process, bounded CFD summaries; native CLI for fields and archives.

cfd_craft.__version__ is the installed distribution version.

CfdError

Subclass of ValueError.

Rejected input, including the shared native diagnostic report when present.

Attributes: diagnostics, report.

case_bytes(case)

Preserve raw JSON bytes for native duplicate/unknown-field validation.

describe()

Return native schemas, supported interface operations and build identity.

check(case)

Return the native preflight report: validity and coded diagnostics.

The checks are the CLI’s (strict parsing, geometry, sources, receptors and the host-memory estimate); the report omits the CLI’s geometry evidence and its {“check”: …} wrapper.

simulate(case, *, cancel_file=None)

Run in-process without the GIL and return a native summary dictionary.

Inspect termination, assessment, checks and experimental_validation before using receptor values. Incomplete runs remain results, not successes. Creating cancel_file stops cooperatively. Ctrl-C raises KeyboardInterrupt after the worker has stopped. Each call has its own bounded Rayon pool.

Console script

Summary-only Python CLI; the native CLI owns field/restart archives.

Run it as python -m cfd_craft COMMAND.

Options before the command: --version (prints the version).

CommandArguments
checkcase (Path)
describenone
simulatecase (Path); --cancel-file (Path)

Diagnostics

Every diagnostic has a code, and the family of the code says which part reported it.

CodesReported bySection
CFD-E, CFD-WThe native solver: check, run, preview, profile, reportNative case checks and run errors
CFD-X, CFD-DThe OpenFOAM adapter and the reference dataExternal backend and reference data
CFD-PThe Python packageTools, examples and scripts
CFD-U, CFD-T, CFD-RExample programs, optimization lessons, release and documentation toolsTools, examples and scripts
CFD-MThe map and street converters, the ride tool and the mobile studyCity blocks and mobile measurements
CFD-BPerformance probes, comparisons and sweepsTools, examples and scripts; Native profiling and accuracy-sweep diagnostics

Tools, examples and scripts

The guide’s example programs (examples/manual/, crates/cfd-craft/examples/) and validation/manual_examples.py use CFD-U001 manual.<field> for missing/unavailable inputs, occupied example output paths, failed process/schema expectations, unaccepted example results, incorrect source units or source-response scaling, and checkpoint/archive replays that disagree. These are example/API checks, not new solver numerical tolerances. Rust library solver failures retain their existing diagnostics; the OpenFOAM example retains the adapter’s external codes.

The optimization lessons (tutorials/optimization) use CFD-T001 optimization.<field> when a lesson check fails: an unaccepted response, replay or held-out solve (the path names the solve or arm), a native LP/MIP status, primal or integrality check, an LP that disagrees with the independent vertex reference, a superposition replay outside its tolerance, an incomplete or failed GP job, inconsistent evaluation accounting, or a velocity field whose length does not match the grid’s faces. These are lesson checks, not new solver tolerances; F3’s fidelity gate is reported per design, not as a diagnostic.

The Python package reports CFD-P001 python.<field>: python.case for a dictionary that strict JSON cannot represent (NaN, infinity, unsupported types), python.worker when the solver thread panicked or ended without a result (the panic message is included), and python.<command> for console-script failures outside the native report. Native rejections keep their own codes and paths. The release scripts (scripts/package_version.py, scripts/check_release.py) and the installed-package acceptance (validation/check_installed.py) report CFD-R001 release.<field>: inconsistent versions, crate metadata or lockfiles, and failed installed checks. Neither family is a solver tolerance.

The reference generator (scripts/generate_reference.py) reports CFD-R002 reference.<field>: reference.binary when the native binary cannot be run or prints no usable JSON, reference.cli.markers when cli.md lacks a generated-block marker, reference.python-api for a public Python definition without a docstring, reference.<page> (for example reference.case-schema) when --check finds a committed page that differs from the current build, and reference.diagnostics when --check finds a CFD- code in the Rust or Python sources that this page does not list.

The documentation check (scripts/check_docs.py) reports CFD-R003 docs.<field>: PAGE:LINE: message for a page whose code blocks do not hold: docs.fence for a block without a known info string or without an end, docs.marker for an unknown, misplaced, malformed or repeated <!-- check: ... --> or <!-- file: ... --> comment, a tolerance above 1e-4, a timeout that is not a positive number of seconds or a missing tolerance sentence, docs.setup when ## Setup is not the first section, docs.python and docs.bash for a block that raises, exits non-zero, has a syntax error, names a script that is not in the checkout or does not end in time, docs.text when the output of the block before it differs from the shown text (floats within the tolerance the page declares, everything else exactly) or when a text block shows a float on a page without a tolerance, docs.json for JSON that is not strict, a case that cfd-craft check rejects or a block that differs from the committed file it names, docs.sh, docs.toml and docs.rust for a block that does not parse or is not found in the file it is bound to, docs.binary when cfd-craft cannot be run, docs.counts when a page has fewer blocks of a class than its entry in docs/check-counts.json, has no entry, or (for the default set) an entry names a page that is not checked, docs.page for an unreadable page and docs.arguments for invalid options. The line is the line of the opening fence, or of the differing output line; it is 0 for docs.counts. These are checks of the documentation, not solver tolerances.

The documentation site tools (scripts/mdbook_links.py, the mdBook preprocessor, and scripts/check_site.py, the check of the built book/ directory) report CFD-R004 site.<field>: site.link for a link in a page under docs/ whose target does not exist or leaves the repository, site.book or site.protocol for input that mdBook should not send, site.directory for a missing or empty site directory, site.reference for an internal href or src in the built HTML that resolves to no file, and site.anchor for a fragment that names no id on the target page. These are checks of the documentation site, not solver tolerances.

Native performance probes use CFD-B001 benchmark.<field> for invalid probe arguments, case or output, missing input files, nonfinite or null results, repetitions that disagree, changed binary/case/producer identities, a child that did not perform the requested work, unequal work or fields, missing or malformed report fields and timing samples, and failed, cancelled or timed-out benchmark children. The same-host backend comparison uses CFD-B002 comparison.<field> for invalid limits or inputs, a run that is not accepted or misses the 0.06 Ghia screen, an ambiguous solver record, work, profiles or producers that differ between rounds, and inputs changed during the comparison. These research measurements are not CFD numerical-acceptance or physical-qualification verdicts.

Native case checks and run errors

cfd-craft check CASE prints a cfd-craft.check/0.1 report on stdout. Each diagnostic has a code, a severity, a JSON path into the case (for example geometry[1], sources[0].rate_kg_s_m, numerics.advective_cfl_max) and a message. Errors make the case invalid; warnings do not. run, profile and preview print the same report and exit 1 when the case is invalid, before any output directory is created. preview checks the coarsened case it runs, then compares it with the original’s cell mask, which it counts without building the original grid.

The grid, source and receptor checks need the built grid. When the estimated peak does not fit this host (CFD-W070), they are skipped, so a check never allocates more than the host can hold. They also run only when the case has no other error, and a file that does not parse is reported alone (CFD-E000): check again after each fix.

CodeSeverityMeaning
CFD-E000errorThe file is not a valid case: unknown or duplicate field, wrong type, trailing data. The path points at the element
CFD-E001errorUnsupported schema_version
CFD-E002errorEmpty name
CFD-E003errorA domain length outside 1e-6..1e9 m
CFD-E004errorAn axis with fewer than 2 (1 on a periodic axis) or more than 4096 cells
CFD-E005errorground_open_top on x or y
CFD-E006errorEstimated peak memory above run.memory_limit_mib, or more than 1e8 cells
CFD-E007errorEstimated artifacts above output.max_total_mib
CFD-E008errorThreads, step budget, pressure iterations or monitor window out of range
CFD-E009errorA time, tolerance or step limit that is not finite and positive
CFD-E010erroradvective_cfl_max outside 0..0.45
CFD-E011errorNeutral RANS without ground_open_top
CFD-E012errorInvalid flow parameters
CFD-E013errorObstacles with prescribed uniform flow
CFD-E014errorBox ID missing or repeated, or bounds not increasing inside the domain
CFD-E015errorConstituent ID or diffusivity invalid
CFD-E016errorSource ID, constituent or declared rate invalid
CFD-E017errorSource support degenerate or outside the domain
CFD-E018errorMore than one initial condition per constituent, or an undeclared one
CFD-E019errorReceptor ID missing or repeated
CFD-E020errorSteady sources without an open boundary to remove their mass; a particle source also passes with a declared ground, roof or leaf deposition candidate
CFD-E021errorInvalid moving wall
CFD-E022errorWall-time limit above seven days or physical horizon above 1e12 s
CFD-E023errorLaminar flow with ground_open_top; its open top exists only in the RANS closure
CFD-E024errorPrescribed velocity with a normal component at an impermeable boundary
CFD-E025errorNegative or nonfinite initial concentration
CFD-E026errorInvalid periodic Gaussian initial condition
CFD-E027errorReceptor support degenerate or outside the domain
CFD-E028errorA box or polygon prism contains no cell center, so the grid would not represent it; the path names the shape
CFD-E030errorThe geometry leaves no fluid cells
CFD-E034errornumerics.pressure_preconditioner: multigrid on a grid without fluid components, or with nonpositive/nonfinite pressure weights. A geometry mask and several fluid components are supported and do not raise it
CFD-E036errornumerics.pressure_preconditioner: a principal line-block Cholesky pivot is nonpositive/nonfinite; no diagonal repair or fallback
CFD-E035errornumerics.pressure_preconditioner: the multigrid coarse Cholesky factor is not positive definite (on a masked grid, the factor of one fluid component), or masked aggregation could not reduce a connected component; no diagonal repair or hidden fallback is applied
CFD-E037errornumerics.momentum_limiter: limited_upwind without a limiter, or a limiter with another momentum scheme
CFD-E045errornumerics.steady_algorithm: an implicit pseudo-time algorithm in transient mode
CFD-E047errornumerics.steady_algorithm: an implicit pseudo-time algorithm with prescribed flow, or implicit_viscous with neutral_rans
CFD-E040errorA source intersects a solid cell
CFD-E041errorA source has no support on the grid
CFD-E042errorA receptor is empty or samples a solid cell
CFD-E043errorA steady source in a fluid component without an outlet; a particle source also passes with a represented ground, roof or leaf deposition sink in that component
CFD-E044errorThe represented source density is not finite
CFD-E070errorrun, profile and preview: the estimated peak exceeds 80 % of this host’s available memory
CFD-E072errorpreview only: coarsening changes the solid volume by more than 20 % or the number of fluid components
CFD-E073errorpreview only: the original cell mask cannot be counted (more than 1e8 cells, or its 4 bytes per cell do not fit this host), so the preview cannot be compared with it
CFD-W001warningA box spans fewer than 10 vertical cells: too coarse for physical interpretation
CFD-W002warningRANS blockage ratio above the COST 732 recommendation of 3 %
CFD-W003warningRANS domain clearance below the COST 732 recommendation (about 5 H_max upstream, at the sides and above; 15 H_max downstream). Every open, slip or wall side is checked; periodic sides are not
CFD-W004warningnumerics.pressure_preconditioner: pressure weights select symmetric line/small-plane blocks and semicoarsening (ratio above 25, including stiff two-cell axes). Setup and memory increase; compare total cost with IC(0), especially for extreme stretching. Weak two-cell spans alone do not trigger this policy. With geometry the same weight ratio draws the warning, but the masked path has no line blocks: it keeps point smoothing and can need more iterations and time than IC(0). See the pressure guide and anisotropy results
CFD-W070warningcheck only: the estimated peak exceeds 80 % of this host’s available memory; the grid checks are skipped

W002 and W003 encode the COST 732 best-practice guideline (Franke et al., 2007) as summarized by secondary sources that cite it. The primary document was not retrieved from its distribution share; validation/data-inventory.json records that. They are warnings because best-practice distances depend on the scenario: a wind-tunnel reproduction may use the tunnel’s own dimensions.

Codes from a run, a restart or report, reported in summary.json error or on stderr:

CodeMeaning
CFD-E031Closed fluid component with an incompatible net flux
CFD-E032Pressure CG lost positive definiteness
CFD-E033Pressure iteration limit reached
CFD-E050Checkpoint dimensions do not match the case
CFD-E051Nonfinite or invalid state, including concentration in a solid cell
CFD-E052Velocity divergence
CFD-E053Negative concentration beyond round-off; no clipping is applied
CFD-E054Eddy viscosity outside the declared numerical regime
CFD-E055The time step is not finite and positive
CFD-E056An implicit momentum-correction system is nonfinite or singular, or its CG lost positive definiteness
CFD-E057An implicit k or ε correction system is nonfinite or singular
CFD-E060Checkpoint identity or checksum mismatch
CFD-E061Fields or checkpoint omitted because they would exceed the output budget; the manifest lists them under omitted and the run exits 2. report repeats the code on stderr for such an archive and exits 0
CFD-E062The output directory already exists
CFD-E063The output directory cannot be created, for example because its parent does not exist
CFD-E064report rejects the archive; the message names the failed check
CFD-E065The restart checkpoint cannot be read or parsed, or is larger than half of run.memory_limit_mib
CFD-E066The restart checkpoint lies beyond run.max_steps, or in transient mode beyond run.end_time_s, of the case

External backend and reference data

These Python diagnostics carry the code and offending field in the error text. They belong to the separate external artifact schema. E062/E063 are also used for occupied/unavailable external output paths. The external tools exit 0 for an accepted result, 2 for a completed, stopped or verified run without accepted evidence, and 1 for a failed execution or invalid input (backend guide).

CodeMeaning
CFD-X001Invalid external case/input identity or execution-limit field, including an iteration limit without a divisor between 50 and 250 (iterations)
CFD-X002Missing/unsupported runtime, version, package identity or installer dependency
CFD-X003A child command exited unsuccessfully; the actual return code and log are retained
CFD-X004External execution wall deadline reached
CFD-X005External output/per-file budget reached
CFD-X006Invalid mesh, returned field, sample, numerical record or archive checksum
CFD-X007A completed external solve did not reach its convergence/continuity gate
CFD-X008External execution cancelled; process group stopped
CFD-X009A cross-solver comparison exceeds its frozen target
CFD-X010The solver log shows a numerical breakdown: execution.solve.residual for a NaN/Inf residual or continuity value, execution.solve.continuity for a reported mean continuity error (sum local, in units of U_ref/H) of at least 1. The process group is stopped and the failure archive retained
CFD-X011The independent Cartesian audit rejects mesh.* (points, faces, owner/neighbour order and orientation, boundary ranges, volume, first-cell heights), fields.phi.* or wallShearStress.* (missing, malformed, nonfinite, or zero traction on a wall); run.numerical marks an archive without a final field, which is not assessed
CFD-X012initial_state.*: an ineligible or changed restart source (source.*), a receipt that is incomplete or disagrees with the consumed inputs (fields, fixed inputs, metadata, controls, field header times), a runtime or rebuilt mesh that differs from the source (runtime, mesh.*), a stored face flux that fails the independent local gate (phi.local_continuity), or a stage input that cannot be written (inputs)
CFD-X013comparison.*: a restart comparison of two archives from different cases, recipes, meshes or runtimes, or without final fields; an invalid mode or missing data; a run of the fixed-work driver (source, split, continuous) that did not complete with a final field
CFD-D001Reference/protocol hash, measurement identity, pairing or metric input invalid
CFD-X014mapping.*: in a coarse-to-fine preparation, solve or archive, an unsupported source, level or initialization; changed source bytes or a broken source chain (source.*); failed source acceptance or audit; invalid mapped fields; consumed values that no single nearby source cell supplies in every field (mapper.values) or replay statistics that differ from the receipt (mapper.replay); utility arguments or logs that differ from the receipt (mapper.*, commands); changed generated boundaries or controls; missing, malformed or unreadable evidence; an exceeded output budget (output); or a runtime or rebuilt mesh that differs (runtime, mesh.*)
CFD-X015refinement.*: unsupported campaign limits; an output inside the source or the reverse (output); an unreadable, unaccepted, non-cold or unsupported coarse source, or one that fails its audit or measurement screen (source, source.*); a source changed during its checked snapshot or a copy that is not the archive the plan froze (source.copy.*, source.inventory, source.manifest); a changed or incorrectly bound retained parent (stages[N].parent.*); a failed archive checkpoint (archives.*, preserving the underlying diagnostic), including an archive changed after its first checkpoint, a sealed summary that differs from the returned record (stages[N].summary.*) or a stage or producer that is not the frozen implementation (stages[N].implementation.*, plan.implementation.*); incompatible mesh-pair inputs, runtimes or observable identities (pair.*); or a symlink rejected before CI archive serialization (archive.*). No archive is repaired or resealed

Native profiling and accuracy-sweep diagnostics

CodeMeaning
CFD-B003profile.*: an active or incorrectly nested phase snapshot (active, nesting), an unwritable profile report (output), or a profile/archive identity, time-accounting or attempted-work mismatch named by its field path.
CFD-B004sweep.*: invalid grid/limit/target/row fields, changed inputs (inputs), inconsistent repeated accepted work/fields/producer (repeat.*), a failed bounded child (native.execution, openfoam.execution), an occupied process-log destination (process.output), or an evidence zip that cannot be written, contains a symlink or an unsafe member, or holds an archive of unknown schema (archive.*). Unaccepted numerical rows remain recorded separately.

CFD-B005 pressure_benchmark.<field> identifies invalid pressure-comparison inputs, changed producers, failed or malformed child measurements, missing returned arrays, inconsistent work or repeats, failed independent recovery, cavity numerical/archive/reference gates or pressure/velocity equivalence. Rows retain the original measurement when a later check rejects them. Cold setup, reused pressure time, accepted solver time and workflow time are separate scopes.

CFD-B004 sweep.process.namespace reports unavailable or invalid Linux procfs PID/group namespace metadata. Process cleanup uses local IDs from NSpid/NSpgid and checks namespace identity, rather than comparing ancestor procfs IDs with local killpg IDs.

CFD-B006 pressure_suite.<field> covers the shared rough-pressure probe and anisotropy campaign: invalid arguments/limits/cases, occupied or failed output, nonfinite data, changed inputs/producers, inconsistent work/repetitions and invalid result identities. A valid pressure-limit failure or missed independent recovery bound remains a nonqualifying measurement, with no speedup ratio.

CFD-B007 momentum.<field> identifies a failed momentum verification fixture: invalid/empty/nonfinite norms or order inputs (norms, orders.*), seed or generated-checkpoint shape (<trial>.seed, <trial>.initial), a vortex solve, actual timestep count or time-refinement failure (<trial>.run, <trial>.steps, temporal), an invalid 1000-step stability control (stability.run), changed default artifacts or work (defaults.<filename>, defaults.pressure_iterations), an invalid self-reference/profile (self.*), or output/argument errors (output, arguments), and a failed predeclared second-order gate (gates). An intentional stability iteration limit is recorded separately from numerical acceptance. CFD-B008 steady.<field> identifies a failed implicit steady-algorithm campaign (validation/steady_algorithms.py): a run that misses the unchanged gates (<run name>), fields of different shape or a zero canyon reference field (fields), a failed fixed-point shrink gate (fixed_point), unknown schemes (schemes), any other campaign failure (campaign) or output errors (output), for the cavity and for the --case canyon campaign. Explicit cavity grid selectors use CFD-X001 recipe.cavity_grid; shared sweep grids use CFD-B004 sweep.grids.

CFD-B004 sweep.collection.<run_directory> rejects an archive that passed its measurement-time checks but fails revalidation after all child runs. The row retains accepted_at_measurement, gains collection_verified=false and is excluded from qualifying costs. sweep.collection.manifest identifies a changed sealed manifest. Collection does not repair files or relax archive checks.

CFD-E080 constituents[i].particle.<field> rejects a nonfinite or out-of-range spherical aerosol diameter (1e-8..1e-4 m), density (above reference air and at most 30000 kg/m3), or settling/deposition speed (0..10 m/s). CFD-E081 constituents[i].particle.settling_velocity_m_s rejects a computed Stokes–Cunningham speed outside its creeping-flow range (particle Reynolds number above 0.1). A separately justified direct speed bypasses that formula; it does not validate the particle physics.

CFD-E082 vegetation[i].<field> rejects a duplicate/empty canopy ID, an invalid box, or nonfinite/out-of-range canopy parameters: LAD 0..100 m2/m3, drag coefficient 0..10, leaf collection velocity 0..10 m/s. CFD-E083 vegetation[i].drag_coefficient rejects positive drag with a prescribed velocity, because no momentum response would be solved. Use zero drag for a prescribed-flow leaf-collection study, or solve laminar/RANS flow.

City blocks and mobile measurements

CodePathMeaning
CFD-E084geometry[i].footprint_m, geometry_min_passage_cellsInvalid/self-intersecting polygon, mismatched footprint bounds or nonpositive passage-resolution request
CFD-E085building_roughness_mBuilding roughness must be finite, positive and used with neutral RANS
CFD-W011geometry_min_passage_cellsA represented horizontal street between solids has fewer cells than requested, or the request was not evaluated because the grid has more than 10000000 cells (the message says which; geometry.json still records the passage of every shape)
CFD-M001mapConverter rejected source geometry, coordinates, elevation range, provenance or native case check; the message names the reason

The wind-direction campaign (validation/urban_campaign.py) has no code of its own. It refuses invalid budgets or a case without neutral_rans flow with a Python ValueError, and each direction that fails keeps a row with accepted: false and an error text such as campaign_budget_exhausted, worker_watchdog_timeout, worker_failed or no_native_archive.

CFD-E028 is an error also when a polygon prism contains no cell center: a warning must never silently remove a building from the physics.

For particle bins, CFD-E020 run.mode admits a closed-air source only with a declared removal candidate, and CFD-E043 sources[i] then requires an actual positive represented ground/roof/leaf removal mechanism in the same fluid component as each source support cell. A sink in another component or a canopy volume that misses all fluid-cell centers does not qualify. Passive gases keep the original outlet requirement. Admissibility does not establish convergence.

CFD-M002 covers the optional supplied-street emission converter. Paths identify rates.columns, rates.rows[CSV line].<field>, streets.crs, streets.features[i].<field>, streets['ID'].segments[i], map_provenance.<field>, height_m, case.sources, native_check or output. It rejects missing/nonfinite/negative rates, missing or mismatched kg/s/m units, duplicate/unknown IDs, invalid coordinates or map transforms, continuous building intersections and failed native case preflight. Intersecting sources are never relocated; positive-rate omissions from clipping and unrated streets remain explicit in the provenance. See the traffic converter.

CFD-E086 receptors[i].polyline_m, .height_m or .sample_spacing_m rejects an invalid path receptor: 2..4097 finite in-domain vertices, positive segment lengths, in-domain height and finite positive spacing are required. CFD-E087 receptors[i] rejects any path segment that enters a represented solid cell, even between generated samples, or any sample interpolation stencil with positive solid support. CFD-E088 receptors[i].sample_spacing_m rejects more than 20001 generated samples per path; CFD-E088 receptors rejects more than 50000 across a case. Both limits apply before sample allocation.

CFD-M004 virtual_ride identifies invalid/nonfinite speed, interval, response time or sensor series, an unaccepted/non-steady source field, consumed archive checksum problems, a missing route/constituent, a ride exceeding 200000 samples, or an existing/unwritable result file. The tool’s output is an idealized pass through a steady mean local increment, not time-resolved atmospheric validation.

CFD-E089 mobile_response.case rejects nonlinear transport, nonzero initial scalar conditions, a non-steady run or changed frozen-flow physics/controls. mobile_response.flow rejects an incomplete/unaccepted, mismatched or changed flow preparation; identities and actual field gates are recomputed. A retained flow/diffusivity allocation exceeding run.memory_limit_mib is also rejected. The ordinary run and restart contracts are unchanged.

CFD-M003 mobile_inference covers invalid matrix/observation identities, nonfinite values, noise/pass assumptions, malformed study inputs, unsafe IDs, duplicate training/held-out identities and execution/output errors in the optional mobile study driver. Bounded native or integer-solver failures remain in the report, and the study then does not pass.

Units and conventions

Every quantity has one unit, carried by its field name (velocity_m_s). Nothing is converted silently. Time is in seconds.

Setup

Commands run from the root of a checkout with target/release on PATH.

Units

QuantityUnit or convention
Position and domain sizemeters; x east, y north, z up (local coordinates)
Velocitym/s
Pressurekinematic pressure, m2/s2; with RANS the isotropic part 2k/3 is absorbed
k and epsilonm2/s2 and m2/s3
Concentrationkg/m3; multiply by 1e9 for micrograms/m3
Source ratekg/s (point), kg/(s m) (line), kg/(s m3) (volume)
Diffusivity and viscositym2/s
Particle diameter and densitymeters (diameter_m: 1e-6 is one micrometer, allowed 1e-8 to 1e-4) and kg/m3 (density_kg_m3, the density of the particle material)
Settling and deposition velocitym/s, positive downward or onto the surface (0 to 10)
Deposited mass and deposition ratekg and kg/s per surface class: ground, roof, vegetation
Leaf area density and drag coefficientm2 of leaf area per m3 of canopy (leaf_area_density_m2_m3, 0 to 100); dimensionless (0 to 10)
Roughness lengthmeters (flow.roughness_m for the ground, building_roughness_m for building walls)
Path receptorcorners as east and north in meters, one height_m above the ground; distance_m is the length along the route from its first corner
Street emission ratekg/(s m): rate_kg_s_m of a line source; the street CSV requires units to be exactly kg/s/m

A point (a point source, an end of a line source, a point receptor) is inside the domain when 0 <= coordinate < size on every axis, so a point on an upper domain face is outside (CFD-E017, CFD-E027). A box may reach the faces.

describe states the coordinates and the pressure unit itself:

cfd-craft describe | python -c "import json,sys; d=json.load(sys.stdin); print(d['coordinates']); print(d['pressure_units'])"
local east, north, up; meteorological wind direction from
kinematic m2/s2; RANS isotropic 2k/3 absorbed

Wind direction

Wind direction is the meteorological direction the wind comes from, in degrees clockwise from north (flow.direction_deg_from of a neutral_rans case). A wind from 270 degrees travels in positive x; from 225 degrees, toward positive x and y. Native gas inflows carry a zero concentration increment; an ambient background is a separate physical interpretation, not a hidden source.

Particles

A particle bin has one diameter and one density. Its settling speed is the Stokes speed with the Cunningham slip correction in air at 293.15 K and 101325 Pa (density 1.204 kg/m3, viscosity 1.81e-5 Pa s, mean free path 6.6e-8 m, gravity 9.80665 m/s2), unless the case gives settling_velocity_m_s. The result reports the speed used (settling_velocity_m_s) and the aerodynamic diameter (aerodynamic_diameter_m): the diameter of a sphere of density 1000 kg/m3 with the same settling speed. particulate_matter has the entries PM2.5 and PM10: sums over the bins whose aerodynamic diameter is at most 2.5e-6 m or 1e-5 m. A deposition velocity in the case is added to the settling speed on ground and roofs; it does not include settling.

Maps and rotated frames

The map converter works in a projected coordinate system in meters and rotates the buildings clockwise by rotation_deg about the center of the crop. The case is in the rotated model frame: model direction = map direction

  • rotation_deg (modulo 360), and map-provenance.json keeps both. A path receptor and a line source are given in the model frame; the street converter applies the recorded rotation and translation for you.

Sensor rides

A virtual ride uses seconds for time, the reading interval and the response time, m/s for the riding speed and kg/m3 for the field and the sensor reading. Response-matrix columns are in kg/m3 per unit multiplier of a source group; the reference rate of a group is in kg/s.

Array ordering

Concentration, pressure, k and epsilon are cell values; velocity components live on faces. For cells = [nx, ny, nz]:

  • Cells are x-fastest: cell (i, j, k) has index (k*ny + j)*nx + i.
  • Face arrays are concatenated by component (x, y, z), each x-fastest, with one additional face along its own axis when that axis is not periodic (periodic arrays wrap and do not repeat an end face).
nx, ny, i, j, k = 4, 3, 1, 2, 1
print((k * ny + j) * nx + i)
21

Prefer the VTK exporter (see scripts) to hand-written reshaping.

Scripts

The Python tools a user calls. Each runs from the root of a checkout as python PATH. This list comes from their argument parsers and exit statements. Several write files: give each a new --output, and read the source of a script before running it with other arguments.

Setup

Native scripts need the release binary (cargo build --release -p cfd-craft-cli). The scripts find it at target/release/cfd-craft; --binary overrides that. OpenFOAM scripts need --foam-root, the Foundation 13 runtime that integrations/install_openfoam13.py stages. The map and street converters need Shapely (integrations/requirements-urban.txt). The mobile study needs the packages of integrations/requirements-mobile.txt and the example binary target/release/examples/mobile_response (cargo build --release --locked -p cfd-craft --example mobile_response).

Exit codes

A script exits 0 when its checks passed and 1 when they did not or its input was invalid, unless the table says otherwise. Exit 2 means the work completed without accepted evidence (the convention of the native CLI). Failures carry a code from diagnostics. No exit code sets physical qualification.

Inspect and export a run

ScriptArgumentsResult
validation/export_vtk.py--run DIR --output FILE.vtr [--max-mib 64]ParaView rectilinear file from a verified archive with fields. Exits 1 if FILE exists or the archive fails the field checks
validation/check_profile.pyDIRChecks a cfd-craft profile directory against its archive; prints the findings
validation/profile_case.py--binary PATH --case CASE --output DIRChild-process resource use (KiB, Linux) of one command
cfd-craft run cases/verification/periodic-tracer.json --output runs/a > /dev/null
python validation/export_vtk.py --run runs/a --output runs/a.vtr | python -c "import json,sys; print(json.load(sys.stdin)['cells'])"
3456

Verification and acceptance

ScriptArgumentsResult
validation/run_suite.py--output DIR [--binary PATH] [--preset smoke|study] [--pressure-preconditioner ic0|multigrid] [--abl-numerics JSON] [--abl-steady]Analytic cases against frozen targets, with a report under --output
validation/cavity.py--output DIR [--binary PATH]Lid-driven cavity against the Ghia reference; a numerical benchmark, not urban validation
validation/manual_examples.py--output DIR [--binary PATH] [--example-dir DIR] [--foam-root ROOT]Runs the native examples; with --foam-root also the OpenFOAM ones
validation/check_installed.py--output FILE [--binary PATH]Installed-wheel acceptance; run it with python -I outside the checkout

Measurement

ScriptArgumentsResult
validation/benchmark_native.py--baseline PATH --candidate PATH --case CASE --mode setup|pressure|momentum|production|transport|steps --output DIR [--rounds 5] [--inner 4] [--steps 8] [--threads 1] [--timeout-s 180]Alternating paired probes of two binaries at fixed work
validation/compare_backends.py--foam-root ROOT --output DIR [--binary PATH] [--repeats 1] [--timeout-s 180] [--grid-sweep ...]Same-host cavity timing, native against OpenFOAM. Exit 2 in sweep mode when the workflow is valid but a gate failed

--grid-sweep adds --levels, --grids, --sweep-rounds, --accuracy-target, --native-wall-s, --native-max-steps, --native-pressure-preconditioner, --native-numerics, --native-span and --foam-iterations; read validation/compare_backends.py for their defaults.

Tutorials

ScriptArgumentsResult
tutorials/canyon_study.py--output DIR [--binary PATH] [--preset smoke|sensitivity|study]Canyon wind, grid, domain and Schmidt sensitivity; failed rows are kept
tutorials/source_inference.py--output DIR [--binary PATH] [--preset smoke|study]Three-source inverse problem with held-out sensors
tutorials/external_cfd.py--foam-root ROOT --output DIR [--binary PATH] [--data PATH] [--preset cavity|smoke|study] [--timeout-s 600]Both backends and a measurement comparison. Exit 2 for recorded unaccepted evidence, 1 for a workflow error
tutorials/backstep_resolution.py--foam-root ROOT --output DIR [--data PATH] [--preset smoke|controls|study] [--timeout-s 900] [--iterations 6000] [--max-stages 1]Convergence and mesh-resolution study. Exit codes as above

City blocks and mobile measurements

Guide chapters 22, 23 and 24 use these scripts. Each --output must not exist yet.

ScriptArgumentsResult
integrations/urban_map.pySOURCE --output DIR --crop XMIN YMIN XMAX YMAX --cell-m M --coordinate-system TEXT --license TEXT --attribution TEXT [--template CASE] [--rotation-deg DEG] [--height-attribute height] [--max-ground-range-m 0.5] [--ensemble-clearance] [--binary PATH]Input: building footprints as GeoJSON polygons or CityJSON solids in projected meters. Output: case.json with polygon prisms, check.json (the report of cfd-craft check) and map-provenance.json (input hash, license, crop, rotation, assumed heights, dropped buildings). --template (default cases/canyon/wh1-wind270.json) supplies flow, numerics and budgets. Exit 1 with CFD-M001
integrations/traffic_sources.py--case CASE --map-provenance FILE --streets GEOJSON --rates CSV --height-m M --output DIR [--binary PATH] [--street-id-property id] [--street-license TEXT] [--street-attribution TEXT] [--rates-description TEXT]Input: a converted case with its provenance, street centerlines in the same coordinates and a CSV with street_id, constituent, rate_kg_s_m, units. Output: case.json with added line sources, traffic-provenance.json, check.json, check.stderr. Exit 1 with CFD-M002 and a diagnostic.json (input contract)
validation/urban_campaign.py runCASE --output DIR [--binary PATH] [--run-budget-s 120] [--campaign-budget-s 1200] [--threads 1] [--workers 2] [--map-provenance FILE] [--runner PATH]Input: a neutral_rans case. Runs the wind directions 0, 30, …, 330 degrees from cold starts. Output: campaign-plan.json (written first), one folder wind-DDD per direction with the consumed case, the run archive, the independent field check and result.json, then results.json and report.json. Exit 0 when all twelve are accepted within the campaign budget, 2 otherwise. --runner sends the directions through optimization-run
validation/urban_campaign.py workerJOB [--binary PATH]Runs the one direction that a job.json of the campaign describes. The campaign and the job launcher integrations/launch_urban_command.py call it
integrations/virtual_ride.pyRUN_DIR --constituent ID --path ID --speed-m-s V --sampling-interval-s S --output FILE [--response-time-s 0] [--initial-kg-m3 C]Input: an accepted steady run archive with a path receptor. Output: a JSON file (cfd-craft.virtual-ride/0.1) with times, positions, the field along the ride and the reading of a first-order sensor; prints the number of readings. Exit 1 with CFD-M004
tutorials/mobile_measurements.py run--output DIR [--preset source-response|canyon] [--config PLAN.json] [--binary PATH]Runs a source-inference study: per wind one flow, one frozen-flow transport run per source group and one reference run; then the ride response matrix, the fit, pass planning and route selection. Output: frozen-study-plan.json (written first), the archives per wind, mobile-response-matrix.json, virtual-observations.csv, report.json. Exit 0 when every check of the plan passes, 2 otherwise, 1 with CFD-M003 for invalid input. --binary is the mobile_response example
tutorials/mobile_measurements.py fitMATRIX CSV --train RIDE [RIDE ...] --heldout RIDE [RIDE ...] --output FILEInput: a response matrix of run and a CSV with wind,ride,sample_index,concentration_kg_m3. Output: fitted multipliers, rank and ambiguous combinations, held-out error and the hashes of both inputs. Exit 1 with CFD-M003
validation/summarize_urban.pyEVIDENCE_DIR --output FILESummarizes the directory layout of the urban evidence record: paired default and multigrid runs, district campaigns, failed rows included

integrations/mobile_inference.py is a module, not a command: identifiability, infer_sources, required_passes, route_information and select_routes are the functions behind chapter 24. integrations/urban_job.py stages the campaign directions as jobs of optimization-run (chapter 14).

OpenFOAM backend

python integrations/openfoam_backend.py COMMAND:

CommandArgumentsExit
prepare--case cavity|backstep --output DIR [--level 1] [--cavity-grid N] [--iterations 3000] [--data PATH] [--mesh-family legacy|wall-resolved] [--solver-profile legacy|simplec|simple]0, or 1 for an invalid request
prepare-restart--source DIR --output DIR [--iterations 6000]0, or 1 for an ineligible source
prepare-mapped--source DIR --level N --output DIR --foam-root ROOT [--iterations 6000] [--data PATH] [--timeout-s 300] [--output-mib 512] [--memory-mib 2048]as prepare-restart
run--case CASE --output DIR --foam-root ROOT [--timeout-s 600] [--output-mib 256] [--memory-mib 2048]0 accepted; 2 completed, timed out or canceled without accepted evidence; 1 execution failed
reportDIRas run for the archived result; 1 if verification fails
ScriptArgumentsResult
integrations/install_openfoam13.py--output DIR [--package-file DEB]Stages the pinned package without root; 1 on failure
integrations/run_jobs.py--runner PATH --output DIR [--binary PATH] [--worker PATH]Runs a CFD command and scalar application profiles on a foreground node

Release tools

ScriptArgumentsResult
scripts/package_version.pynonePrints the release version; fails when the three version sources disagree
scripts/check_release.pynoneChecks crate metadata, licenses and lockfiles before packaging
scripts/generate_reference.py[--binary PATH] [--check]Writes the generated pages of this section; --check writes nothing and fails when one differs
scripts/generate_cases.pynoneRewrites the committed cases under cases/; do not run it casually

Model cards

  • Flow: pressure projection, laminar and neutral k–epsilon package.
  • Transport: conservative gas balance, sources, receptors and response matrices.
  • Evidence and restart: the meaning and provenance of a result.
  • OpenFOAM backend: external execution, numerical comparison and preliminary experimental assessment.

Each card states a supported scope, discretization and verification evidence. An implemented equation and a converged solution do not establish experimental validation.

Flow model 0.1

Scope

Constant-density incompressible flow, flat ground, uniform Cartesian cells, box and optional polygon-prism masks, CPU f64. Face velocities and cell pressure share the same divergence/gradient definition. Local coordinates are east/north/up. Pressure is kinematic pressure in m2/s2; the isotropic 2k/3 contribution is absorbed in RANS pressure.

Within one face evaluation, the advective samples and the viscous coefficients use the same staggered neighbor faces: wall ghosts at wall and blocked faces, periodic wrapping and outlet sampling.

By default the momentum predictor uses first-order donor-cell advection of each staggered velocity component and an explicit variable-viscosity stencil. The extra variable-viscosity symmetric-stress contribution is reconstructed from cell gradients under the incompressibility assumption. It is not a claim of globally second-order momentum accuracy.

numerics.momentum_advection selects, opt-in, a conservative flux form of the advective term instead (Harlow and Welch, 1965; Morinishi, Lund, Vasilyev and Moin, 1998; Ferziger, Perić and Street, ch. 7):

  • each momentum control volume is centered on its face; the advecting velocity on a control-volume face is the MAC average of the two face velocities that meet there;
  • the transported component is reconstructed upwind, φ_f = φ_U + ½·s(a, b) with a = φ_U − φ_UU and b = φ_D − φ_U (van Leer, 1974, in Sweby’s 1984 notation), division-free;
  • second_order_upwind uses s = a (unlimited, not bounded). limited_upwind with numerics.momentum_limiter uses van Albada (van Albada, van Leer and Roberts, 1982), van Leer, or monotonized central (van Leer, 1977);
  • every control-volume face carries one flux shared by its two momentum cells, so momentum is conserved to round-off in a periodic box;
  • the near samples at walls and solids use the same ghost values as the viscous term. Where the far-upwind sample is not an interior face, that face falls back to s = 0 (first order), so no stencil reaches through a solid.

At an open boundary (stage P3b) the outer half of an outlet’s momentum cell advects with the outlet face velocity and a zero-gradient value (s = 0); its tangential faces extrapolate the inside cell’s advecting velocity. Inflow faces are prescribed. With neutral_rans the near-wall samples use the wall-function ghosts as before, and the k and ε equations keep their first-order upwind transport. These closures passed the empty-ABL check with unchanged gates and the development canyon with zero floor events for all four schemes before neutral_rans was allowed. Donor-cell remains the default, and default runs are byte-identical to the earlier release. Time integration (SSPRK2 with a projection per stage) and the CFL cap are unchanged. The second-order momentum results record operator orders of 2.06 (unlimited) and 1.92–1.95 mean L1 (limited), translating-vortex orders of 2.0–2.3, momentum conservation to 1e-16, bounded limited schemes, and a steady Re=100 cavity Ghia error of 0.005–0.006 at 24², against 0.028 for donor-cell.

An incremental projection is applied to each SSPRK2 velocity stage. Tests recover second-order decay for periodic viscous shear. General unsteady open-boundary pressure order is not established by that fixture. The intended urban use is a checked steady solution.

Steady pseudo-time algorithms

In steady mode, numerics.steady_algorithm selects how pseudo-time advances. All options are written in delta form: they solve for a correction δ driven by the full steady residual R(u, p) = momentum_rhs(u) − G p, which is exactly what assess recomputes. Inexact inner solves, approximate Jacobians and the pseudo-time step change only the path; at a fixed point δ = 0 and the pressure correction is zero (Beam and Warming, 1978; Ferziger, Perić and Street, ch. 8).

  • explicit (default): SSPRK2 with a projection per stage, Δτ limited by advection and diffusion together. Unchanged from the earlier release.

  • implicit_viscous (stage P4): the same SSPRK2 stages, each solving (I − Δτ·ν·L) δ = Δτ·R with the existing viscous stencil (wall ghosts are affine, so δ obeys the homogeneous ghost relation). Δτ follows the advective limit only. Jacobi-preconditioned CG from δ = 0, relative tolerance 1e-3, at most 50 iterations per solve.

  • implicit_projection (stage P5a): one outer iteration solves A δ = R with A = I/Δτ + first-order upwind advection with advecting velocities frozen at uⁿ (Picard) − ν·L. The second-order part of the advection enters only through R (deferred correction: Khosla and Rubin, 1974; Hayase, Humphrey and Greif, 1992). Then u* = uⁿ + δ is projected at scale Δτ and the pressure correction is added in full. With a uniform Δτ, a_P − Σ a_nb = 1/Δτ away from walls, the consistent SIMPLEC coefficient (Van Doormaal and Raithby, 1984), so this is a SIMPLEC-type coupling. A is diagonally dominant with nonpositive couplings. The inner solve is Jacobi-preconditioned BiCGStab (van der Vorst, 1992) from δ = 0 to a relative residual of 0.1, at most 50 iterations, selected by a predeclared pilot against symmetric Gauss–Seidel. Pseudo-time follows a deterministic CFL ramp CFL_n = min(5, 1.0·1.2ⁿ), Δτ = CFL_n / Σ_a max|u_a|/h_a, capped by max_time_step_s; restarts need no extra state. The cap of 5 was chosen on the development cases (24² and 48² cavities, development canyon); before it the ramp grew to 1e6 and only max_time_step_s bounded it. Each projection is a correction: at a fixed point it requires div u = 0 whatever its inner tolerance, so a relTol-style pressure_relative_tolerance of 0.1 changes the path, not the steady state. The recommended implicit recipe is that tolerance with a non-binding max_time_step_s (100) so the ramp sets the step (performance results).

  • implicit_projection with neutral_rans (stage P5c): A uses the face viscosities of the momentum right-hand side (ν + ν_t, averaged with an interior neighbor), and wall-function ghosts are linearized with ν_t and the cell velocities lagged at uⁿ, because the wall functions are nonlinear. The variable-viscosity cross term stays explicit. After the momentum–pressure update, segregated implicit k and ε steps in delta form follow (see the turbulence package).

  • Constituents (stage P5d) advance in explicit SSPRK2 sub-steps within each outer iteration of either implicit algorithm: the fewest equal sub-steps of at most the explicit stable step (the explicit algorithm’s step formula at the new velocity), capped at 16 steps of that size. The transport scheme, budgets, positivity and receptors are those of the explicit step; only the pseudo-time the constituents cover per outer iteration changes, and with it the path, not the steady state.

The implicit options run in steady mode only (CFD-E045). Prescribed flow, and implicit_viscous with RANS, are rejected (CFD-E047). A singular or nonfinite correction system stops the run with CFD-E056 (momentum) or CFD-E057 (k, ε). steps counts outer iterations, physical_time_s accumulates pseudo-time, and momentum_solver_iterations the inner iterations. Acceptance, the monitor window and all thresholds are unchanged. See the implicit steady results: on the Re=100 cavity, implicit_projection reaches the unchanged gates in 180–300 outer iterations, 18–40× faster than the explicit mode at the same accuracy. With RANS and a tracer (P5c/P5d results) it keeps the explicit fixed point (round-off pair to 1.5e-10), the empty-ABL check and zero floor events, and accepts the 27k and 93k canyons; the predeclared tightening statistic fails for U on one decade, where the difference is the explicit run’s own convergence error.

Stage V adds momentum verification without changing these equations. Eight shifted periodic Taylor–Green operator tests and a translating-vortex refinement measure donor-cell’s first-order advection, with separate time refinement. The periodic vortex also records mean-momentum drift: the default donor-cell advective form is not a conservative shared momentum-flux scheme (the opt-in flux form above is). The 1000-step transverse-step fixture measures extrema at the existing CFL cap; its intentional work limit is not numerical acceptance. These are analytic verification fixtures, not experimental validation.

Pressure

The matrix-free operator is minus divergence times gradient. Internal faces have one shared flux. On a periodic axis with one cell (a two-dimensional run) a face joins a cell to itself; it carries no pressure difference, and the IC(0) factor skips it. Pressure-outlet correction is zero; fixed normal-velocity faces use a homogeneous correction derivative. A closed fluid component has a mean-zero gauge and a compatibility check.

By default PCG uses a cached incomplete Cholesky factor with zero fill. A tiny shift regularizes only the preconditioner, not the solved operator. Recomputed residuals use the compatible mean-zero right-hand side in closed components. The nominal recurrent tolerance is checked against an independently formed operator residual, allowing a documented round-off margin of ten times the target plus 1e-12.

The IC(0) factor is stored as contiguous row offsets, column indices and values. Construction sums duplicate periodic edges in face order, sorts each row and intersects sorted rows without per-row allocations. Each solve builds a compact list of interior and outlet face weights in face order for its PCG products; the list is local to the solve, so changed grid coefficients take effect at the next solve, and the final residual check uses the face-by-face operator instead. PCG keeps the preconditioned residual in one buffer, so nothing is allocated per iteration. The memory estimate includes 112 bytes per cell for factor construction and the face list, before its 25% margin.

Projection forms its right-hand side and the per-cell round-off scale in one cell pass, in the axis order of the divergence, and applies the correction gradient directly to the faces. Performance results give paired timings of these kernels at fixed work.

Projection residuals, actual face-flux continuity and boundary balance are separate checks. An opt-in symmetric multigrid preconditioner supports unmasked grids with Galerkin coarse operators and a direct coarse solve. The fine equation, projection and residual gates are unchanged; masks still use IC(0). Strong unequal spacings select symmetric principal line/small-plane blocks and semicoarsening, with a setup/memory warning; see the measured anisotropy coverage. Component-preserving masked multigrid, general sparse direct factorization and MPI remain open. Experimental model qualification is unchanged.

Neutral turbulence package

The closure is nu_t = C_mu k² / epsilon. Constants are:

ConstantValue
C_mu0.09
C_epsilon11.44
C_epsilon21.92
sigma_k1
kappa0.4
sigma_epsilonkappa² / ((C_epsilon2-C_epsilon1) sqrt(C_mu)) = 1.111111…

This coefficient choice supports the high-Re neutral log-layer equilibrium, rather than mixing an inlet profile with unrelated standard coefficients.

The inlet profiles are U = u_star/kappa log((z+z0)/z0), k = u_star²/sqrt(C_mu), and epsilon = u_star³/(kappa(z+z0)). Wind direction is meteorological direction from, so horizontal components are [-U sin(theta), -U cos(theta)].

Ground momentum uses a log-law stress based on adjacent tangential velocity. Wall dissipation follows C_mu^(3/4) k^(3/2)/(kappa distance), which remains meaningful at stagnation cells. Wall production uses the stress and k-derived friction scale. A cell with several wall faces, such as a canyon floor cell between two buildings, uses the mean of the wall production and of the wall dissipation over those faces, with equal weights. Omitting building_roughness_m preserves the legacy small effective non-ground wall roughness min(inlet z0, 0.001 cell width). Supplying it uses that positive physical z0 for non-ground wall stress, production and dissipation, independent of cell width. Ground z0 is unchanged. Neither wall option has independent urban-wall validation yet.

That building-wall adaptation depends on cell width. A future qualification study must replace it with an explicit physical wall parameterization before treating refinement as a pure discretization study. The current canyon grid experiments combine numerical and wall-model sensitivity.

The upper boundary has zero normal velocity, the equilibrium tangential stress and reference k/epsilon diffusion treatment. That stress closure is what makes ground_open_top an open top, so laminar cases may not use it (CFD-E023): without the closure the top would act as a no-slip lid. This is a particular neutral-domain closure, not a reproduction of an arbitrary tunnel ceiling. Side faces are classified from the prescribed wind as inlet, pressure outlet or impermeable slip.

Production and the variable-viscosity cross terms look up the six cell neighbors once per cell and use them for every tensor component; a missing neighbor at a blocked or boundary face falls back to the cell itself. A regression test pins the bit patterns of the momentum, production and turbulence-step results on an open and a periodic canyon grid.

Turbulence destruction terms use positive implicit denominators. Wall epsilon is an explicit algebraic constraint; tiny k/epsilon floors are counted. Any floor event prevents numerical acceptance. Excessive eddy viscosity causes a reported divergence instead of silent clipping.

With steady_algorithm = implicit_projection (stage P5c), each outer iteration solves, after the momentum–pressure update, (I/Δτ − T_k + ε/k) δk = T_k(k) + P − ε and (I/Δτ − T_ε + C_ε2 ε/k) δε = T_ε(ε) + C_ε1 P ε/k − C_ε2 ε²/k. T is the first-order upwind transport of the explicit step (its linear part, including the upper-boundary diffusion term); P, the diffusivities, ε/k and the wall functions are lagged at the start of the iteration, and the implicit destruction terms are the explicit step’s. Wall-function cells keep the algebraic ε, as identity rows δε = ε_wall − ε. Each solve is Jacobi-preconditioned BiCGStab from δ = 0 to a relative residual of 0.1, at most 50 iterations, profiled as turbulence_solve. Floors are counted as in the explicit step. At a fixed point δ = 0, so the explicit step’s residuals are zero there too; the steady residual is measured with the explicit step size for every algorithm.

The counter covers state-update floors. The wall algebraic relation itself has a minimum epsilon of 1e-14 and is not separately counted by that field; its activity must be treated as an additional regime check before physical qualification.

Evidence and limitations

Verification covers Poisson/projection identities, gauges, analytic channels, Couette flow, periodic viscous shear and the Re=100 lid cavity. The empty-ABL test compares near-outlet U/k/epsilon to the inlet at heights H..5H under frozen tolerances. It is a consistency check for this setup. The suite also reports, without a gate, the drift below H. There the cell-centered velocity gradient of the second cell overestimates the logarithmic gradient, so production and epsilon run high: on the canonical empty-ABL grid epsilon is up to 16 % above the inlet profile below H (U 4 %, k 4 %), and more on coarser vertical grids. A log-consistent near-wall gradient is an open improvement.

The illustrative canyon examples are not exact CODASC geometry/inflow reproductions. Their coarse-grid numerical convergence does not validate urban dispersion. Fine-grid pressure/explicit-time throughput is an open performance gate. No buoyancy, stratification, traffic turbulence, chemistry or unsteady turbulent statistics are represented. Opt-in vegetation (below) and opt-in particles (transport model card) have their own numerical verification and no experimental validation.

Method references: Richards and Hoxey (1993), Richards and Norris (2011), and Hargreaves and Wright, “On the use of the k–ε model in commercial CFD software to model the neutral atmospheric boundary layer”, J. Wind Eng. Ind. Aerodyn. 95 (2007) 355–369. No OpenFOAM source code is included or was consulted for these methods.

Porous vegetation

vegetation contains axis-aligned volumes with id, min_m, max_m, leaf_area_density_m2_m3 (LAD, inverse meters), drag_coefficient (Cd), optional leaf_deposition_velocity_m_s, and turbulence_closure. Membership uses fluid-cell centers; overlapping boxes add their coefficients. Buildings keep their existing impermeable mask. Vegetation changes momentum, turbulence and particle transport; it does not change the pressure equation.

The momentum acceleration is (-C_d,\mathrm{LAD}|U|U_i). At staggered faces, the nonnegative cell coefficient (C_d,\mathrm{LAD}|U|) is averaged from adjacent fluid cells and multiplies the native face component. It enters both the full nonlinear residual and a frozen implicit diagonal. The explicit-pseudo-time path uses a positive semi-implicit drag correction; implicit-viscous and implicit-projection paths include it in their correction matrices. All have the same steady fixed point. The transient canopy drag fixture verifies first-order time convergence for this semi-implicit treatment. The gas SSPRK2 second-order claim does not apply to canopy momentum. General unsteady urban canopy accuracy remains unvalidated.

The canopy contributions are

[ S_k=C_d,\mathrm{LAD}(\beta_p |U|^3-\beta_d |U|k),\qquad S_\epsilon=C_d,\mathrm{LAD}(C_{\epsilon4}\beta_p|U|^3\epsilon/k -C_{\epsilon5}\beta_d|U|\epsilon). ]

Source coefficient setbeta_pbeta_dC_e4C_e5
green1992 (default)141.51.5
sanz200315.10.90.9

The equations and coefficient convention are documented by Viana Parente Lopes, Palma and Silva Lopes (2021), equations 1.1–1.3 and table 1. green1992 is the set of Green (1992) in that table. sanz2003 is the set of Sanz (2003) as tabulated there, where it is listed under Katul et al. (2004). Only canopy source coefficients switch; the existing ambient k-epsilon constants, wall functions and upper-boundary treatment remain fixed. This is a model-range comparison within the existing closure, not a reproduction of all settings used by those publications. Both explicit and implicit turbulence updates retain canopy destruction implicitly and evaluate the same residual. Algebraic epsilon wall cells keep the established wall condition.

Particle leaf removal is (\mathrm{LAD},v_{leaf},c), integrated in the same SSPRK2 budget as settling; the CFL allowance includes this loss rate. Removed mass is deposited_kg.vegetation, with its current rate reported per bin. Gases have no leaf sink. A prescribed-flow study must set Cd=0; positive canopy drag is rejected rather than silently ignored.

With zero LAD, all additional operators return before changing arithmetic; whole returned state bytes, including k/epsilon and counters, match a case without vegetation. The empty-ABL zero-LAD fixture checks this explicitly. Nonzero-LAD fixtures verify uniform force/drag equilibrium, pressure-drop/integrated-drag balance, prescribed-flow exponential leaf decay, leaf-block spatial attenuation/refinement and both published source formulas. summary.vegetation stores current drag power per unit density (m5/s3), volume integrated drag acceleration (m4/s2), represented cells and an explicit verified_numerics_unvalidated_physics label. It is an instantaneous work rate, not a reconstructed history of cumulative mechanical work. The independent checker recomputes these from the archived face velocities and canopy boxes. Drag power uses the actual staggered momentum sink, summed over active face dual volumes (face area times pressure-gradient distance), including half volumes at outlets. drag_quadrature identifies this convention; the power is the exact discrete sink work in that face inner product, rather than a separate cell-centered estimate.

No heat, cooling, radiation, seasonal leaf dynamics, leaf-size dependence, wake-resolved flow or experimental urban-canopy qualification is claimed.

Passive transport 0.1

Solve a cell-integrated advection–diffusion balance using the projected face fluxes. One internal face contributes equal and opposite flux to its adjacent fluid cells. Molecular diffusivity is nonnegative; RANS adds nu_t/Sc_t. The canyon cases use a molecular value for a trace gas (1.5e-5 m2/s), so the turbulent Schmidt number controls the mixing; a large constant would dominate nu_t/Sc_t in the canyon and mask it.

The linear reference uses donor-cell upwind and the higher-order option monotonized-central MUSCL reconstruction; both advance with SSPRK2. Timestep restrictions account for advective and diffusive rates, and cap the combined allowance at 0.45. Observed convergence is measured; limiter behavior can reduce order for other fields.

With an implicit steady flow algorithm (numerics.steady_algorithm, stage P5d), the same SSPRK2 step runs in sub-steps within each outer iteration: the fewest equal sub-steps of at most the explicit stable step, capped at 16 such steps (solver::SCALAR_SUBSTEPS_MAX). Every sub-step keeps the explicit step’s stability limits, budgets and positivity, so the steady state, its mass balance and the receptors do not depend on the pseudo-time step; only the number of outer iterations to reach them does. When the cap binds the constituents cover less pseudo-time than the flow; the state records theirs as scalar_time_s, and the emitted mass is the source rate times it.

Domain walls/slip faces and masked solids have no scalar flux. Inlets use zero local-increment concentration, including scalar backflow values. Pressure outlets have zero diffusive gradient. Background concentration is a separately interpreted physical contribution.

Point sources use the containing cell. Lines are split at exact grid crossings and normalized by physical length. Volumes use Cartesian overlap and the declared volumetric rate. Source support intersecting a solid is rejected; there is no silent redistribution or clipping.

Point receptors use multilinear cell-center interpolation, clamped to the nearest center at the outer boundary. Any positive-weight solid cell invalidates the stencil. Volume receptors use exact overlap weights and reject solid intersections.

Stored evidence separates initial, emitted, boundary-in, boundary-out and remaining mass. The final difference is audited without treating numerical correction as a physical sink. Negative concentrations beyond round-off stop the run; concentrations are never clipped to conceal failure.

The archived-field checker recomputes every receptor value from the stored concentration field with these weights. Transport never changes a solid cell, so its concentration stays exactly zero; the checker requires that, and a restart checkpoint with mass in a solid cell is rejected (CFD-E051).

For exact response matrices, use fixed flow/diffusivity and linear_upwind. A nonlinear limiter invalidates exact superposition. The source-inference tutorial verifies combined versus separate sources, holds out receptors, includes an unidentifiable matrix and repeats observations with changed inflow/grid.

The independent SciPy reference assembles the steady uniform-flow matrix and compares the full concentration field with a direct sparse solve. This is numerical verification, not measured atmospheric validation.

A step builds its candidate state separately, from only the fields it changes, and replaces the state only after the state, velocity and positivity checks pass; the monitor history is checked in place and moved over last. A pressure failure, a cancellation or a late check failure leaves the whole state unchanged, and constituents without a supplied source array keep their values.

Particle bins

A constituent may declare particle with diameter_m, density_kg_m3, an optional settling_velocity_m_s, and optional ground_deposition_velocity_m_s and roof_deposition_velocity_m_s (both zero by default). Absence of particle preserves the gas equation and its serialized case/state bytes. No feedback on air, chemistry, agglomeration, resuspension or non-spherical shape correction is represented.

Computed settling uses the Stokes–Cunningham spherical terminal speed

[ w_s = \frac{(\rho_p-\rho_a) g d^2 C_c}{18\mu},\quad C_c=1+\mathrm{Kn}(1.257+0.4e^{-1.1/\mathrm{Kn}}),\quad \mathrm{Kn}=2\lambda/d. ]

The reference atmosphere is fixed and explicit: 293.15 K, 101325 Pa, (\rho_a=1.204,\mathrm{kg/m^3}), (\mu=1.81\times10^{-5},\mathrm{Pa,s}), (\lambda=66,\mathrm{nm}), and (g=9.80665,\mathrm{m/s^2}). Formula evaluation requires particle Reynolds number at most 0.1. Higher-Re particles need a user-supplied terminal speed; that choice and the fixed atmosphere are assumptions, especially at altitude. The formula and its limits follow the primary model description in AerSett v1.0, Mailler et al. (2023).

Settling adds a conservative first-order vertical donor flux to the existing advection–diffusion operator. It is first order even when gas advection uses MUSCL. Its outgoing rate enters the same positivity CFL limit as advection, diffusion and surface removal. Settling leaves through an open lower boundary; the incoming increment at an open top is zero. Impermeable upward-facing ground and roofs absorb at ((w_s+v_d)c); the separately specified (v_d) excludes settling. Vertical walls have no particle deposition.

The SSPRK2-integrated cumulative budget is initial + emitted + boundary-in = airborne + boundary-out + deposited. Ground and roof deposits are separate surface classes in the checkpoint and summary. The independent archived-field checker recomputes current surface fluxes, settling, aerodynamic classification, airborne mass, cumulative accounting and receptor sums. Cumulative deposited mass is the time-integrated ledger; a final airborne field alone cannot reconstruct its time history.

particulate_matter.PM2.5 and .PM10 sum only spherical bins whose representative unit-density aerodynamic diameter passes the cutoff, with slip correction in the diameter conversion. A bin crossing a cutoff is not fractionally split. These are local-source concentration increments, with no regional background, not regulatory sample predictions. Numerical fixtures cover a descending layer, absorbing ground, roof flux, periodic settling refinement and superposition, Stokes units and validity, and the exponential interior settling–diffusion operator balance. The exponential fixture tests the interior operator; it does not claim that an absorbing column with no supply has a nonzero steady state. Experimental aerosol/urban-deposition validation remains open.

Complete steady settling–diffusion column

The source-free interior exponential check is complemented by cases/verification/particle-steady-column.json: a closed-air column of height L=1 m, with a uniform volumetric source q=4e-6 kg/(m3 s) above z_s=0.75 m, settling w=0.2 m/s, diffusivity D=0.1 m2/s, additional bottom deposition v_d=0.1 m/s and zero total flux at the top. The bottom is absorbing with J(0)=(w+v_d) C(0), where downward total flux J=wC+D C’.

Below the source, Q=q(L-z_s), C_0=Q/(w+v_d) and

[ C(z)=Q/w+(C_0-Q/w)\exp(-wz/D). ]

Within the source layer, (C_p(z)=q(L-z)/w+qD/w^2) and (C(z)=C_p(z)+[C(z_s)-C_p(z_s)]\exp[-w(z-z_s)/D]). This solution satisfies J(L)=0 and continuity of concentration and flux at z_s. The finite-volume deposition law samples the adjacent cell center rather than an extrapolated surface value, so first-order boundary convergence is expected. Cold-start 16/32/64-cell runs compare the complete returned steady profile with this analytic solution, and verify source/deposition equality, mass conservation and positivity under frozen error/refinement gates.

Steady particles may use a deposition/leaf sink in place of an air outlet. The case-level screen requires a relevant declared sink candidate; source preflight then requires a represented positive sink in every source-bearing fluid component. Connectivity is necessary, not a proof of reachability or convergence, and the numerical steady-equation and mass gates still apply. A passive gas retains the original outlet requirements (CFD-E020/CFD-E043).

Path receptors and an idealized moving sensor

Receptor::Path adds linear observation weights to the returned concentration field; it changes no transport or flow equation. A local x/y polyline at a constant height is sampled at equal arc-length intervals, including endpoints. Normalized trapezoidal sample weights define the path mean. All individual samples and their mean remain linear in the field; source superposition still requires the existing fixed-flow, fixed-diffusivity, linear-upwind conditions. Complete segments may not enter represented solids, and interpolation may not use positive-weight solid cells. No silent clipping/relocation is performed. The independent checker rebuilds the geometry and observation weights.

The separate virtual-ride tool interpolates these samples in arc length, assumes a constant riding speed, and integrates a declared first-order sensor response exactly for that piecewise-linear input. Its output is an idealized pass through a steady mean local increment. Temporal turbulence, intermittent emissions, a regional background and sensor-specific calibration remain outside this observation model. See the mobile-path guide.

Frozen-flow source responses

The opt-in mobile_response::PreparedFlow API accepts only completed steady flow with matching case/physics/current-source identity and recomputed native state gates. It freezes velocity, pressure, k and epsilon, initializes each scalar column at zero, and reuses the existing linear-upwind SSPRK2 operator, stable step and full transport/flow acceptance gates. No flow updates are performed during a column. This is a declared initialization path, not a neighboring-wind restart. The summary stores its flow hash and work counts; the independent checker recomputes the hash from archived flow arrays. Nonlinear MUSCL and nonzero scalar initial conditions are rejected. Species diffusivity, particle deposition and leaf sinks remain fixed in each response. The implementation rejects any negative returned candidate concentration.

The mobile study verifies native combined truth against separate columns, then applies a shared linear virtual-sensor operator with zero initial sensor value. Rank, ambiguity and held-out recovery are conditional numerical evidence. Noise/scatter and required-pass estimates are assumptions, with no simulated atmospheric variability. See the inference guide.

External backend: OpenFOAM Foundation 13

Purpose and supported scope

An external execution backend for reproducible numerical comparisons and experimental assessment. It complements the native Rust solver. Their result schemas, turbulence packages and scientific claims remain separate.

The tested build is Foundation 13 package 20260407, 13-441953dfbb42, Ubuntu 24.04 x86_64, double precision, 32-bit labels, serial Pstream. Other forks, versions, MPI decompositions and architectures are not qualified by these tests. The adapter checks the executable’s own version and records executable and solver-library hashes. The package installer verifies a frozen 118586852-byte SHA-256 before extraction. OpenFOAM is licensed under the GNU GPL, version 3 or later. CFD-craft runs it as separate programs and neither links nor imports it; no OpenFOAM source or executable is part of this repository. The generated case dictionaries and the Python adapter are original CFD-craft code.

Numerical comparison: cavity

The cavity is a unit square, lid speed 1 m/s, nu=0.01 m2/s, Re=100. OpenFOAM uses x/y coordinates with an empty span; the native case uses x/z with an invariant periodic span. There is no open-boundary mass flux. Both profiles are compared at the existing Ghia stations with a maximum error target of 0.06 lid-speed units, and against each other with the same target.

OpenFOAM solves the steady equations; the native case advances to 30 s. The report retains this distinction. Ghia is a numerical reference, not a physical experiment. Code agreement is not experimental validation.

On this cavity, timed on the same machine with one thread each, OpenFOAM’s steady workflow is 4.7–5.5 times faster than the native steady mode and closer to Ghia (0.0090 against 0.0276); its solver process is about 9 times faster than the native solver. The native method needs about three times as many explicit pseudo-time steps as OpenFOAM needs SIMPLE iterations, on twice the cells. See the backend comparison; it is not a fixed operation count or a ranking for other problems.

Experimental comparison: Driver–Seegmiller backstep

The reference is the zero-angle configuration in Driver and Seegmiller (1985), DOI 10.2514/3.8890, distributed by the TMR dataset owner. The corrected reference Reynolds number is approximately 36000 based on step height. The reported reattachment is 6.26 +/-0.10 H.

The generated domain is x/H=-4..50, y/H=0..9; the upstream floor is y/H=1 and the downstream floor is y/H=0. H=1 m and Uref=1 m/s are incompressible similarity scales; nu=1/36000 m2/s. A 0.1H empty span makes a two-dimensional calculation. This is a short-inlet reconstruction using measured upstream data, rather than TMR’s long developing-plate inflow construction. It assumes that compressibility at the experiment’s approximately Mach 0.128 is negligible.

The closure is Foundation 13 kOmegaSST, with kqRWallFunction, omegaWallFunction and nutkWallFunction, using its default coefficients. The inlet U is linearly interpolated from the x/H=-4 profile. That profile is an input and is excluded from downstream scoring. Mean transverse velocity is set to zero. The unmeasured spanwise variance is assumed equal to vv, giving k=(uu+2vv)/2000 in the table’s units. Omega follows a mixing length of 0.07*1.5H. No-slip endpoint values at y/H=1,9 and tiny positive turbulence endpoint values are assumptions. None of these parameters is calibrated to downstream data.

The mesh has 22656, 90624 or 203904 cells at levels 1,2,3. The channel above y/H=1 is graded toward its walls. The block below the step is uniform in y, with 24 cells per H at level 1, so the first cell center sits at H/48. With wall functions this places the first lower-wall cell in the buffer layer in the scored region, where the k-based wall function switches near y+ 11; refinement moves it lower, so a mesh series also changes the wall treatment. Each comparison report estimates the first-cell y+ from the sampled wall stress. Momentum advection uses bounded linear upwind; k/omega use upwind. Pressure uses GAMG and SIMPLEC; the linear systems use absolute 1e-11 and relative 0.001 stopping targets in the backstep. A separate nonlinear gate requires each final initial residual <=1e-7, explicit solver convergence, local reported continuity <=1e-6, and stored boundary-flux imbalance <=1e-6. Final cell fields are checked for finiteness, nonnegative k and nut, and positive omega. The summary also records a residual trend: the median first-solve residual of each field over the last tenth of the iterations and over the tenth before it. A ratio near one at a high level is a stall, which more iterations do not cure. Reported turbulence bounding messages are counted; they are not independently instrumented floor events like the native solver’s counter.

The protocol (validation/protocols/backstep-v1.json, whose hash the comparison checks) sets the targets: each station’s U/Uref RMSE <=0.10, lower-wall Cf RMSE <=0.001, and reattachment error <=0.75 H. These are project screening choices, not derived from measurement uncertainty. To show how much they discriminate, each station also reports its RMSE below and above y/H=2 and the RMSE of a predictor that ignores the step (the inlet profile above y/H=1, zero below), and the friction comparison reports the RMSE of Cf=0. The measured Cf file’s error column is retained without asserting an undocumented 95% confidence level. The U profile file supplies no uncertainty interval. Cf uses the signed kinematic wall traction, Cf=-2*tau_x/Uref^2, at the lower wall. All downstream velocity sample identities are paired exactly; Cf interpolation cannot extrapolate.

Wall-resolved recipes

The legacy dictionaries remain the default. Explicit backstep-only options select mesh_family=legacy|wall-resolved and solver_profile=legacy|simplec|simple:

ProfilePressure couplingRelaxation p / U, k, omegaOther settings
legacySIMPLEC0.2 / 0.5as described above
simplecSIMPLEC1 / 0.7as described above
simpleSIMPLE0.3 / 0.5; on the wall-resolved mesh 0.1 / 0.1on the wall-resolved mesh: PCG/DIC pressure (absolute 1e-12, relative 0, at most 5000 iterations), bounded first-order upwind momentum, cell-limited gradients, zero initial interior U

On the wall-resolved mesh, GAMG uses a DICGaussSeidel smoother with two pre- and post-sweeps and a direct solve on its coarsest level. The tutorial’s wall-resolved reference recipe is wall-resolved/simplec, with second-order bounded linear-upwind momentum. The first-order simple profile is a stability reference, not an accuracy reference.

The wall-resolved mesh has 48896, 195584 and 440064 cells at levels 1, 2, 3. In y, the channel above y/H=1 is graded toward both walls (first cell 1.18e-3 H at level 1) and the block below the step is graded toward both the floor and the shear-layer line y/H=1 (first cell 9.15e-4 H). In x, both sides of the step plane start from the step wall’s 0.002 H first cell (at level 1). Widths grow by 10% per cell downstream, with an 11% step into a uniform 0.1 H over the scored region 1 < x/H < 12, then to 0.31 H at the outlet, and by 15% per cell upstream to 0.18 H at the inlet. At level 1, neighboring cell widths differ by at most a factor 1.15 in x and 1.32 in y, also across block interfaces; finer levels keep these bounds. Tests check these widths against blockMesh’s grading rules and against the actual Foundation-13 blockMesh output. An earlier streamwise spacing with a 140:1 width jump at the step plane diverged in every run (results).

SST keeps its default coefficients. k is fixed to zero at walls, nutLowReWallFunction imposes zero wall eddy viscosity, and omegaWallFunction takes its viscous-sublayer value while the k-based y+ is below its switch point (about 11.5 in Foundation 13). This is a low-Re near-wall package, not a change to the bulk Reynolds number. The inlet and its assumptions are unchanged; its near-wall velocity is a linear ramp to the first measured point, which is not an inner-layer profile.

The separate Cartesian auditor has its own readers for the polyMesh files, the stored face flux phi and the wall traction; it uses the adapter only to verify the archive’s seal. It checks the point, face, owner and neighbour lists, the owner-below-neighbour order, face orientation (area vectors point from owner to neighbour and out of the domain), patch ranges and the represented volume. From the stored phi it reconstructs each cell’s divergence, with the target max(abs(div(phi)))*H/U <=1e-4. That measure grows like H/dx for a given relative flux error, so it tightens as cells shrink; the per-cell relative imbalance abs(sum phi)/(sum abs(phi)/2) is reported beside it, ungated. A stored phi is conservative to the pressure-solver tolerance by construction, so this gate tests the linear solve and the file’s integrity, not nonlinear convergence.

For the wall-resolved package the auditor also checks the first-cell distance on all four walls against the generated heights, and max(y+) <=1 on each wall from the tangential part of the stored wall traction, reporting where the maximum lies. A wall whose traction is zero everywhere was not sampled and is rejected. Its report separates its own checks from the adapter’s numerical verdict. It does not reconstruct momentum/turbulence residuals or validate SST against nature.

Measurement screening of the wall-resolved package additionally requires this independent audit. A failed numerical/independent gate leaves the screen not assessed. Refinement skips finer cases after a coarse case is not accepted. The tutorial and results retain those failures.

Bounded steady field continuation

prepare-restart copies the final U/p/phi and, for SST, k/omega/nut of a completed same-mesh run into a fresh local pseudo-time zero. Failed, timed-out or canceled runs are ineligible. A completed but unconverged stage is eligible when its final fields are finite and its stored face flux passes the auditor’s independent local gate, max abs(div(phi))*H/U <=1e-4. That gate follows the last pressure solve’s relative tolerance and tightens like H/dx with refinement, so early stages of the GAMG profiles fail it (0.0048 at iteration 500 of the reference recipe, 2.7e-9 at 6000). The final stage is accepted only with the unchanged nonlinear, independent and measurement gates.

The sealed initial-state receipt records the parent manifest and case hashes, source acceptance and work, the source metadata and controls, exact fields including phi, fixed physics inputs, actual mesh files and runtime identity. The rebuilt mesh and exact runtime must match before solving. The stage’s controls may differ from the source’s only in endTime and writeInterval, and each copied field must carry the source time in its header. The archive verifier rechecks the receipt and, for a stage that solved, its runtime and mesh; a rejected initialization is recorded as a failed archive. Retain parent archives to inspect the chain; unkeyed checksums do not establish authenticity.

Restarting resets the solver’s residual history. In the laminar cavity a split stage reproduces the uninterrupted run to round-off. In the SST backstep the restarted iteration’s residuals differ by about 1e-4 relative, consistent with turbulence-model state that the fields do not carry. After a further 250 iterations of the simple profile the fields agree to about 1e-6 of their magnitudes; a converged staged solve of the reference recipe reproduces the converged single run.

The resolution tutorial can continue up to --max-stages 8 (default 1) with unchanged per-stage limits. It stops at numerical acceptance, at a converged but unaccepted stage, at a stopped execution, at a source that fails the flux gate and at the stage limit, and records the reason; the wall-y+ and measurement gates still decide final acceptance. Every stage is retained, and the report keeps the final stage’s iterations apart from cumulative work.

A run that stops at its iteration limit writes a final field only when the limit is a multiple of the write cadence. Preparation uses the largest divisor of the limit up to 250, and rejects limits without a divisor between 50 and 250; 6000 and 20000 keep cadence 250. See the guide and continuation results.

Coarse-to-fine volume initialization

prepare-mapped maps an accepted run to the next finer existing level of the same generated case, mesh family and solver profile. The source must be a cold-generated case built by the current generator, numerically accepted and passing the independent audit; restarted and mapped sources are not accepted. Its inputs must equal the generator’s, including the measured inlet and the controls.

The separately licensed Foundation-13 mapFields utility runs on checked copies with mapNearest. Only internal U and p and, for SST, k, omega and nut are imported; the generated target boundary dictionaries, dimensions and controls are kept exactly. Nearest-cell initialization is not conservative interpolation and makes no accuracy claim. Coarse phi and wall stress are not transferred: the target solver builds a new phi from its U and corrects it as usual. Preparation establishes no initial conservation, fine-grid convergence or measurement screen.

The mesh_initialization receipt (schema 0.2) binds the source case, manifest, summary, audit, fields and work, the target metadata, templates, mapper output and mesh, the utility arguments and logs, and the runtime identity; it records the mapFields hash at preparation. Validation, before every solve and when an archive is verified, rechecks that chain and replays the mapping with the independent mesh reader: each consumed cell value must come, in every field, from one source cell among the 27 with the nearest centers. On the uniformly refined cavity that is always the nearest cell; on the graded backstep meshes Foundation 13 takes another nearby cell for some cells, and the replay reports how many and how far. Solved runs also require the recorded runtime and the identical rebuilt mesh. Unkeyed hashes remain consistency checks, not authenticity of an untrusted case. The runtime programs remain external GPL executables; no implementation code is copied into the MIT core.

After a mapped solve completes, same-mesh continuation uses its actual final fields and phi under the existing gate. The new stage’s receipt names the mapped parent and replaces the mapping receipt; source-grid work is not fine-grid work. No source-flux, final nonlinear, wall-y+ or measurement threshold changes. See the guide, plan and results. The cavity comparison is numerical verification, the SST mapping check uses synthetic fields, and no accepted fine backstep is claimed.

Bounded mapped refinement campaign

The campaign driver snapshots an accepted cold source that passes its audit and measurement screen, freezes producer identities and limits, maps to the next level once, and continues eligible completed stages on that same fine mesh. After each stage and at final collection it rechecks the complete retained source and parent chain, requires every archive to keep its first checkpoint’s manifest and every sealed summary to match what its run returned, and checks the producers against the plan. A changed archive stops the workflow; no repair or reseal is attempted. The exact stop and per-stage numerical, independent-audit and measurement verdicts are retained. Source work and fine work are separate, and cancellation overrides campaign acceptance.

Only numerically accepted and independently audited coarse/fine fields enter the descriptive observable comparison. Velocity sample identities match exactly; Cf uses common experimental locations without extrapolation. mesh_sensitivity.passed means both original numerical/audit/reference gates pass. It does not bound the inter-grid change or certify mesh independence. Two grids do not give a GCI, and physical qualification remains false. The results record the declared level-2 backstep campaign: three audited 4000-iteration stages that ended at the stage limit, with the final Uy (1.8e-7) and k (1.05e-7) residuals above the 1e-7 gate, so no accepted fine backstep is claimed. The campaign changes no native solver, SST, mapping, restart or measurement gate.

Interpretation and open gates (all packages)

Execution, numerical convergence, measurement screening and physical qualification have separate fields. A zero exit cannot make a nonconverged solve acceptable. When the numerical gate fails, the comparison still reports the metrics of the final iterate, each marked within or outside its target, but the measurement screen is not assessed (measurement_screen_passed is null). The physical-qualification status remains preliminary even if all development metrics pass: inlet uncertainty, near-wall resolution, mesh sensitivity and model-form sensitivity require work. Failed meshes remain in the report and are excluded from converged mesh pairs. No GCI is manufactured from an incomplete or non-asymptotic series.

There are no passive-scalar measurements in this benchmark. These comparisons therefore do not validate gas dispersion, particles, the native RANS package or a street canyon. CODASC and the native building-wall/throughput gates remain open. See the recorded external results.

Execution limits

The backend executes only trusted generated dictionaries in a copied fresh directory. Input hashes detect changes; they are not a signature authorizing untrusted OpenFOAM code. OpenFOAM itself can load user code, so do not substitute unreviewed case directories. The adapter never shells out to construct commands.

The runtime is serial. Each child gets a fixed environment (the runtime paths, single-threaded BLAS/OpenMP and HOME=/nonexistent, nothing inherited from OpenFOAM settings of the caller), a hard address-space limit and a per-file size limit; the host’s hard limits are checked first. The overall output budget and wall time are polled every 50 ms. There can be a small polling overshoot and manifests add metadata overhead. SIGTERM/SIGINT and deadline expiry terminate the process group, with a forced kill after one second if necessary. The log and failure archive are retained. Hashing/manifest creation and the bounded runtime preflight add overhead outside the child solve.

The solver log is read incrementally, each line once. A NaN/Inf residual or continuity value, or a reported mean continuity error (“sum local”, in units of U_ref/H because the cases are scaled to U_ref = H = 1 with deltaT 1) of at least 1, stops the process group with CFD-X010, also when the child exits zero. Converged and stalled runs stay below 3e-4, including their first iterations; the recorded diverging runs crossed 1 at iterations 7 to 154, well before their last logged iteration (38 to 700). The actual log, return code and progress are retained. Earlier saved snapshots are not promoted to final solutions.

report verifies an archive’s consistency: file hashes, the consumed inputs and that the case holds nothing else besides solver outputs, the numerical summary recomputed from the returned log and fields, status and error codes, command return codes, the Foundation-13 runtime and log identity, progress and samples. Unkeyed hashes are not tamper-evidence: a consistent rewrite of log, fields and summary cannot be detected this way.

About the evidence

Version 0.2.0 is a research prototype. A numerically accepted run is not an experimentally validated prediction.

These pages are the committed records of measurements: what was run, on which code and machine, what came out, and what failed. Pages elsewhere quote their numbers with a link to the record.

What counts as evidence here

  • A record names the commands, the code revision or source fingerprint, the machine and, where it has one, the CI run. Numbers come from the returned reports, never from a hand estimate.
  • Failed, incomplete and rejected rows stay in the record. A later record adds rows; it does not rewrite earlier ones.
  • Termination (did a run complete), numerical assessment (is a result accepted) and experimental validation (does a model match measurements) are separate. No record here validates a model against measurements of the use case: the street-canyon data could not be obtained.

What does not count: a wall time read as a target on another machine, a same-grid speed ratio read as cost at matched accuracy, an iterate of a solve that did not pass its numerical gate, and a comparison with a numerical reference (the Ghia et al. cavity) read as a comparison with an experiment. The Driver and Seegmiller backstep measurements are the one experimental data set, and only the OpenFOAM backend is compared with them.

The records

Each line gives the date the record states. “Current” means no later record replaces its rows; a later record that adds to it is named.

Native verification

  • Native verification: analytic orders, transport, cavity, empty ABL, coarse canyons, memory; the record gives no date. Current; its canyon timings use default numerics (opt-in timings in implicit RANS).
  • Momentum verification: donor-cell order and the paired cavity baseline; 1 November 2026. Current as the default-numerics baseline; its stage table is the plan as recorded.

Native numerics campaigns

Native against OpenFOAM (Re = 100 cavity only)

  • Backend comparison: default numerics, OpenFOAM faster and closer to the reference; the record gives no date. Current for default numerics; opt-in numerics in matched accuracy.
  • Gap baseline: same-host accuracy, cost and phase attribution; 31 October 2026. A baseline; the later state is in performance gap status.
  • Matched accuracy: both backends at the 0.01 target with opt-in numerics; 1 November 2026. Current, with a later run added in the record itself.
  • Performance gap status: dated sections, newest first; latest 1 November 2026. Current summary.

OpenFOAM backend campaigns

  • External backend: cavity against the reference, legacy backstep (stalled, not accepted); the record gives no date. Current for the cavity; the wall-resolved recipe is in backstep resolution.
  • Backstep resolution: wall-resolved level-1 backstep accepted on one mesh; the record gives no date. Current.
  • Steady continuation: a staged solve equals one uninterrupted run; the record gives no date. Current.
  • Mesh initialization: mapped against cold starts, no accepted level 2; the record gives no date. Current.
  • Refinement campaign: three stages, stage_limit, no accepted fine grid; 31 October 2026. Current.

Optimization lessons

  • Optimization lessons: F1 to F3, including the failed fidelity gate of F3; the record gives no date. Current.

City blocks and mobile measurements

  • Urban features: multigrid with buildings, polygon prisms, particles, vegetation, the rotated canyon (not passed) and the Delft district campaign (no direction converged); 14 November 2026. Current, with the measurements of the code review added in the record itself.
  • Mobile measurements: path receptors, virtual rides, street sources, and inference and route selection on two synthetic studies; 14 November 2026. Current.

The runs behind these two records are attached to the GitHub release v0.2.0 as cfd-craft-0.2.0-evidence.zip: complete archives with fields for the mobile studies; cases, summaries, profiles and manifests without the field files for the urban runs. Both records say how to reproduce them.

Open gates

  • Measured canyon data. The raw wind-tunnel files and their terms were not obtained (data inventory); no canyon result is experimentally validated.
  • Grid study. The native canyon is not grid-converged, and the OpenFOAM backstep has no accepted pair of meshes, so there is no grid-convergence index for either.
  • Same-case comparison. There is no OpenFOAM canyon recipe, so no canyon comparison between the two solvers exists.
  • Multigrid with buildings. It cuts pressure iterations but gives no consistent end-to-end gain on the measured cases, and it is slower on a strongly stretched grid (urban features).
  • Grid orientation. The canyon rotated by 45 degrees did not pass its frozen study (urban features).
  • District runs. No direction of the Delft demonstration converged within its short budget (urban features).
  • Mobile inference. It is verified on synthetic data of the same model only; no measured ride has been used (mobile measurements).
  • Particles and vegetation. Verified against analytic fixtures; no measured deposition or canopy data has been compared.

Recorded verification results

The source fingerprint quoted below uses the definition before 0.1.0, which hashed the Rust/TOML files under crates/ and the root manifest and lockfile; 0.1.0 fingerprints each package instead (see the result contract), so current builds report a different value for the same numerical code.

These numbers were produced by the commands given with each table, from the source fingerprint f2286e5db2c3b5ca627409b85fca94d42e17f4469372abecf08b3794e9606644 (cfd-craft describe), built with rustc 1.97.0 on the machine described under Measured resources, Python 3.13, NumPy 2.5.3 and SciPy 1.18.1. Rerun the commands and read the reports rather than treating these values as targets; wall times depend on the machine.

This is a tested research prototype. Experimental urban validation is blocked by data access, and the canyon resolution study does not finish within its budgets (see the last section).

Checks and numerical verification

CheckResultCommand
Rust regressions32 passed (rustc 1.97 here; CI runs 1.88.0 and stable)cargo test --release --workspace --locked
CLI, launcher and independent-checker boundaries35 passed, also under python -Opython validation/test_cli.py
Periodic shear spatial / temporal order1.9972 / 2.0102python validation/flow_accuracy.py
3D Gaussian transport, relative L2 errors at 24, 36, 48 cells0.0595233, 0.0265493, 0.0136076; order 2.32 for the finest pair (gate: at least 1.8)python validation/run_suite.py
The same at 48, 72, 96 cells0.0136076, 0.0054900, 0.0030418; order 2.05python validation/run_suite.py --preset study
Poiseuille maximum speed error, 16 wall-normal cells0.00488 m/spython validation/run_suite.py
Empty ABL drift of U / k / epsilon at heights H..5H (gated)0.23 % / 0.94 % / 2.68 % (gates 2 % / 5 % / 5 %)python validation/run_suite.py
Empty ABL drift below H (reported, not gated)4.0 % / 3.6 % / 16.2 % over 8 cellspython validation/run_suite.py
Re=100 lid cavity, maximum centerline difference from Ghia et al.0.0275 lid-speed units (gate 0.06)python validation/cavity.py
Steady transport against an independent SciPy sparse solve6.08e-13 relative L2python validation/scipy_reference.py
Exact-source superposition defect3.9e-16python tutorials/source_inference.py
Bounded 2 % observation-noise rate error2.01 %python tutorials/source_inference.py
Changed-inflow inverse rate error5.90 %python tutorials/source_inference.py
Changed-inflow and changed-grid inverse rate error5.16 %python tutorials/source_inference.py --preset study

Coarse finite-canyon cases

python tutorials/canyon_study.py --preset sensitivity runs the three canonical cases in cases/canyon and three variants of the W/H = 1 case. --preset smoke runs only the first three; their rows are identical.

All six reached a steady discrete solution, passed the independent archived-field checks and had no turbulence-floor events. The grid has 18x16x12 cells of 1 m x 1 m x 0.5 m: each building is one cell wide and two cells high, and the W/H = 1 street is one column of cells. These cases exercise the coupled flow and gas workflow; they cannot resolve a canyon vortex and support no physical claim.

CaseStepsPseudo-time (s)Momentum residualSensors 0-3 (µg/m³)
canyon-wh1-wind2703800122.018.1e-1196.5, 230.7, 97.1, 141.0
canyon-wh2-wind2703800121.891.6e-0848.0, 124.7, 47.7, 77.1
canyon-wh1-wind225180058.534.5e-0728.5, 60.1, 93.7, 19.4
schmidt-0.54200110.572.5e-1086.1, 189.0, 86.5, 112.0
schmidt-0.93500128.004.5e-11103.3, 261.2, 104.0, 163.7
extended-outlet3900125.225.9e-1196.5, 230.8, 97.1, 141.1

Steady acceptance compares three successive 100-step monitor windows, so the step counts are multiples of 100. The tracer has a molecular diffusivity of 1.5e-5 m²/s, so the turbulent Schmidt number controls the mixing: from Sc_t = 0.5 to 0.9 the sensor-1 concentration rises from 189 to 261 µg/m³.

Measured resources

Measured on a cloud virtual machine with two cores of an Intel Xeon processor (no further model information exposed), 8 GB of memory, Linux x86_64. Peak memory is the maximum resident set size of a 30-step run (ru_maxrss); the estimate is estimated_peak_mib from check.

CaseCellsPeak memory (MiB)Estimate (MiB)
periodic tracer 24x12x123,45622.529.6
lid cavity 24x2x241,15220.627.1
empty ABL 16x4x48, four threads3,07222.930.8
canyon 18x16x123,45623.529.6
canyon 36x32x2427,64852.454.7
canyon 54x48x3693,31287.3122.8
canyon 100x100x100, three steps1,000,000851.71063.6

At one million cells the measured inventory is 0.89 kB (893 bytes) per cell. The three steps took 121 s of wall time, mostly on one core, including grid construction and the first pressure factorization.

The steady canyon cases on 18x16x12 take 17–63 s of wall time each when the sensitivity preset runs two two-thread solves at a time (wall_s in the report). Each run directory, with fields and checkpoint, holds about 1.1 MiB; the extended-outlet case holds 1.4 MiB.

Optimizer integration

python integrations/run_jobs.py --runner optimization-run with optimization-run built from optimization-jobs cc6b03d. A rerun after the adapter’s pins moved to fcmaes-rust f764a75 and optimization-jobs 12f9d57, with optimization-run built at 12f9d57, gave the same objective values. Evaluate, BiteOpt retry and the experimental GP surrogate completed through the application worker. Retry and GP each used 24 new CFD evaluations and one recheck, with no failed or cancelled evaluations.

The baseline objective was 1.8682465; the selected BiteOpt and GP values were 1.8657713 and 1.6799143. Values are the maximum receptor concentration divided by 1e-8 kg/m³. One small deterministic experiment does not rank optimizers.

Open gates

python tutorials/canyon_study.py --preset study adds the W/H = 1 case on finer grids. Neither finished within its 300-second budget, so there is no grid-convergence result or GCI. The script runs two two-thread solves at a time, so on this two-core machine the two grids shared the cores; the steps reached depend on the machine:

GridCellsSteps reachedPseudo-time reached (s)Momentum residual
36x32x2427,328 fluid157115.204.4e-03
54x48x3692,232 fluid3041.420.14

The coarse grid needed about 120 s of pseudo-time to reach a steady state. The roadmap lists the throughput work this requires.

The building-wall roughness adaptation depends on the cell width, so a refinement series also changes the wall model; an explicit physical wall parameterization is needed before refinement can isolate discretization error.

Raw CODASC files and the required metadata and terms were not obtained; validation/data-inventory.json records what was tried. The experimental evaluator refuses an unfrozen protocol. A matched OpenFOAM run and an external domain review remain future evidence.

Native CPU performance: results

Measured against merged main 402a15036636d8f48591a2d9b5f4ed203cb5ab91, as declared in the plan. The changes reduce the cost of the native pressure solve, the RANS and momentum stencils and the step’s state handling. Equations, tolerances, initial fields, stopping rules and acceptance gates are unchanged, and the results are bit-identical to the previous implementation on every workload compared. The measurements support cost claims for the listed workloads; they are not physical validation or an accepted fine-grid study.

Changes and their measured effect

Each row was measured against the preceding row on the first host below (single thread, fixed work). The eight increments are not eight independent speedups: three are neutral or slower on their own workload, and only the pressure-solve and stencil changes give a clear gain.

IncrementImplementationMeasured against the preceding increment
07One preconditioned-residual buffer per PCG solvepressure solve 1.023×, ranges overlap: no clear gain
08IC(0) factor in contiguous row arrays; flat triangular sweepspressure solve 1.243×
09Factor assembled directly into the flat arrayspressure solve 0.944× and first (cold) solve 0.982×, both slower; probe peak RSS 61.6 → 58.8 MiB
10Per-solve compact list of face weights for the PCG productspressure solve 1.640×; probe peak RSS 58.8 → 67.9 MiB
11Projection right-hand side and correction without temporary arrays27k coupled steps 0.956×, slower
12Cell neighbors looked up once in RANS production and cross stressproduction 1.180×, momentum 1.092×
13Staggered neighbor faces shared by advection and viscosityRANS momentum 1.216×, cavity momentum 1.298×
14Candidate state built from only the fields a step changes27k coupled steps 0.961×, slower; periodic steps 1.030×

The unchanged control kernels (scalar transport and grid setup) ranged from 0.947× to 1.084× in the same measurements, so differences of a few percent, including the 1.092× of increment 12’s momentum kernel, are within the noise of that host. In time saved per pressure solve, increments 08 and 10 contribute most.

Equivalence

  • Paired runs. Every timed comparison compares the complete result of both builds: work counts exactly, floating-point values within 1e-13 absolute plus 1e-11 relative, and the result hash. All comparisons on both hosts were exact.
  • Verification suites. The flow-accuracy, analytic, cavity, SciPy-reference, source-inference and coarse-canyon suites were run with both builds on the second host. Their fields and reports are identical (about 630,000 compared values); the only differences are the memory estimate and the hashes of the summary files that contain it.
  • Tests. A dense IC(0) reference checks the flat factor on duplicate periodic edges, odd cycles and masked, closed and outlet grids. The compact face list must equal the face-by-face operator bit for bit, also on unequal spacing. The projection’s right-hand side and round-off scale are checked against their definitions. The bit patterns of the momentum, production and turbulence-step results on an open and a periodic canyon grid were recorded from 402a150 and are pinned. Step tests cover cancellation inside the pressure solve, invalid history, a late positivity failure, unsupplied constituents and the step counters.

Measurement protocol

crates/cfd-craft/examples/performance_probe.rs runs one kernel or a batch of coupled steps a fixed number of times on a frozen case and reports the timings, the work counts and the full result. Every repetition repeats the same work from the same input and must return the same result. In pressure and step modes the first repetition is cold (it builds the cached factor) and is excluded from the warm median. Timings exclude JSON output and hashing.

validation/benchmark_native.py runs a baseline and a candidate probe as fresh child processes: one unscored warmup pair, then five pairs in alternating order (three baseline-first, two candidate-first). It checks the binaries, the case and itself before and after every child, requires each child to report the requested work, rejects failed, timed-out or cancelled children and records per-child CPU time and peak RSS. speedup is the ratio of the medians of the per-round warm medians; paired_speedup_median is the median of the per-round ratios. The baseline probe is the same example file built against the base sources. The frozen cases are in cases/performance/.

First host

AMD EPYC 9V74 (8 CPU quota, 8 GiB), Linux x86_64, rustc 1.99.1, thin LTO, debug = 1. Grids: canyon 27,648 cells [36,32,24], canyon 93,312 [54,48,36], periodic 27,648 [48,24,24], cavity 4,608 [48,2,48]. Step batches: 8 steps (27k), 4 (93k), 20 (cavity). Seconds are the median of the per-round warm medians, with the range.

MeasurementThreadsBase seconds (range)Current seconds (range)Ratio of mediansPaired median
Pressure solve, 93k10.827566 (0.795666–0.889123)0.393146 (0.383360–0.407823)2.105×2.105×
Coupled steps, 27k11.923034 (1.831214–2.074935)1.418245 (1.360255–1.527298)1.356×1.356×
Coupled steps, 93k16.895446 (6.613648–7.243533)3.697075 (3.500438–3.950186)1.865×1.827×
Coupled steps, 27k41.860154 (1.824871–1.897006)1.219921 (1.190750–1.244716)1.525×1.520×
Cavity steps10.711224 (0.680099–0.798692)0.520557 (0.498224–0.562699)1.366×1.347×
RANS momentum, 93k10.039268 (0.037651–0.040835)0.031472 (0.030745–0.033244)1.248×1.196×
RANS momentum, 93k40.016792 (0.016663–0.017377)0.013269 (0.012132–0.013671)1.265×1.260×
Production, 93k10.004408 (0.004363–0.005795)0.003767 (0.003603–0.003835)1.170×1.197×
Transport (control), 27k10.001179 (0.001104–0.001218)0.001145 (0.001093–0.001329)1.030×0.985×
Transport (control), 27k40.001191 (0.001136–0.001779)0.001258 (0.001138–0.001853)0.947×0.987×
Grid setup (control), 93k10.024547 (0.022512–0.026668)0.022653 (0.022164–0.030408)1.084×1.016×

Setup mode compares only the cell and face counts. Four threads are reported, not presumed beneficial: the pressure solve and several stencil stages are serial. The optimizer worker uses prescribed flow, so it does not receive the pressure-solve gain; no optimization-campaign speedup was measured.

Full command-line runs at fixed work (warmup plus five pairs, one thread, setup, cold factorization, solve and output included): canyon 27k with 30 steps, canyon 93k with 10, periodic 27k with 30. All end at their step limit (exit 2, iteration_limit, assessment incomplete) as intended; their fields, budgets and histories are identical and pass the independent mass, positivity, receptor and continuity checks. These are not times to an accepted steady state. They were measured with a separate harness that is not part of the repository; the second host repeats them with plain cfd-craft run commands.

RunBase seconds (range)Current seconds (range)RatioBase / current RSS MiB
Canyon 27k, 30 steps7.037264 (6.934881–7.336335)4.929432 (4.878793–5.180386)1.428×47.8 / 47.4
Canyon 93k, 10 steps16.516343 (16.115981–17.369829)9.295386 (9.040095–9.497321)1.777×79.9 / 77.5
Periodic 27k, 30 steps0.164736 (0.164686–0.215004)0.165001 (0.164537–0.214932)0.998×35.7 / 35.4

Second host

A 2-vCPU Intel Xeon virtual machine, Linux x86_64, rustc 1.97.0, Python 3.13, same build profile and frozen cases, one thread, nothing else running. Both probes were built from the same example source.

MeasurementBase seconds (range)Current seconds (range)Ratio of mediansPaired median
Pressure solve, 93k0.476113 (0.473162–0.479557)0.326266 (0.322278–0.330026)1.459×1.468×
Coupled steps, 27k1.577008 (1.556403–1.583522)1.077420 (1.072821–1.098611)1.464×1.448×
Coupled steps, 93k4.040266 (3.996620–4.069136)2.857895 (2.838412–2.907191)1.414×1.414×
Cavity steps0.543029 (0.523197–0.590023)0.376625 (0.376356–0.397618)1.442×1.443×
RANS momentum, 93k0.026979 (0.026858–0.027269)0.021527 (0.021392–0.021570)1.253×1.258×
Production, 93k0.002734 (0.002713–0.002902)0.002274 (0.002242–0.002338)1.202×1.205×
Transport (control), 27k0.001058 (0.001042–0.001615)0.001061 (0.001043–0.001665)0.998×1.005×
Grid setup (control), 93k0.012031 (0.011492–0.012770)0.012132 (0.011653–0.013764)0.992×0.992×

Full command-line runs on the same cases, timed as alternating cfd-craft run processes (warmup plus five pairs). In every round the two builds wrote byte-identical fields, checkpoint, geometry, case and probe files and the same summary apart from the memory estimate, elapsed time and source identity; validation/check_fields.py passes on the archives of both builds.

RunBase seconds (range)Current seconds (range)Ratio of mediansBase / current RSS MiB
Canyon 27k, 30 steps5.747947 (5.729801–6.025189)4.000546 (3.937259–4.041992)1.437×52.3 / 51.7
Canyon 93k, 10 steps10.171532 (10.021527–10.196703)7.235306 (7.166604–7.266669)1.406×87.3 / 85.0
Periodic 27k, 30 steps0.156923 (0.151550–0.164198)0.156661 (0.149262–0.173452)1.002×35.0 / 34.5

The gains carry over, but their size depends on the machine: the pressure solve is 1.46× faster here against 2.1× on the first host, the 93k step batch 1.41× against 1.87× and the 93k command-line run 1.41× against 1.78×. The periodic run uses prescribed flow and has no pressure solve, so it does not change.

Memory

Measured with an allocator count on a 48³ grid, in bytes per cell:

BaseCurrent
Factor kept after construction9664
Peak while building the factor (first solve)12088
Working set of a pressure solve56144
Working set of a projection72160

The face list (32 bytes per entry, about three faces per cell) outweighs the smaller factor, so peak memory rises by about 56 bytes per cell. The preflight estimate adds 112 bytes per cell before its 25% margin, which is conservative. Cases close to their declared memory allowance can therefore be rejected where they were accepted before: a one-million-cell periodic tracer is now estimated at 1190 MiB instead of 1056 MiB. Nothing is allocated per PCG iteration.

One three-step, one-million-cell CLI pair (one thread, 170 s solver budgets, fields and checkpoint disabled) was declared before execution on the first host as a resource sample. It is a single sample, not a speed claim and not a steady or physical validation.

Three-step million-cell sampleBaseCurrent
Wall seconds130.77778.060
Peak resident MiB778.836822.914 (+5.7%)
Estimated peak MiB1062.5981196.113
Completed steps33
Pressure iterations23092309

Validation

Current build. Both hosts give these values, and on the second host the base build gives them too.

CheckResult
Rust release workspace7 pressure unit tests, 18 numerical tests, 21 regression tests pass
Static checkscargo fmt, clippy on all targets with -D warnings, Ruff format and lint
Python suites, normal and -Obenchmark runner 28, CLI 35, OpenFOAM backend 38, resolution 41, continuation 54, mapping 58, refinement 68
Periodic shear spatial / temporal order1.997159 / 2.010160 (gates 1.8 / 1.8)
MUSCL Gaussian spatial order2.323308 (gate 1.8)
Poiseuille maximum speed error0.00488276293 m/s
Empty ABL U / k / epsilon drift, H to 5H0.2341% / 0.9405% / 2.6754% (gates 2% / 5% / 5%)
Lid cavity maximum centerline error0.02754881 (gate 0.06)
Independent SciPy field / assembled residual6.08427e-13 / 8.22817e-13
Exact source superposition / held-out defect3.86113e-16 / 3.9386e-16
Coarse canyonsall three accepted; independent mass and continuity checks pass; no floor events
Coarse canyonStepsPressure iterationsAssessment
canyon-wh1-wind2703800398027steady_discrete_solution
canyon-wh2-wind2703800394667steady_discrete_solution
canyon-wh1-wind2251800171079steady_discrete_solution

The 93k manufactured pressure problem takes 166 iterations in both builds, with a recomputed relative residual of 6.9540e-12 and an RMS error of 3.1094e-12. The below-H empty-ABL epsilon drift is still about 16.16% and is reported, not gated. The external OpenFOAM backend does not use the native solver and is unchanged.

Reproduce

cargo build --release --locked --example performance_probe --bin cfd-craft
git worktree add ../cfd-craft-base 402a15036636d8f48591a2d9b5f4ed203cb5ab91
mkdir -p ../cfd-craft-base/crates/cfd-craft/examples
cp crates/cfd-craft/examples/performance_probe.rs ../cfd-craft-base/crates/cfd-craft/examples/
(cd ../cfd-craft-base && cargo build --release --locked --example performance_probe --bin cfd-craft)
python validation/benchmark_native.py \
  --baseline ../cfd-craft-base/target/release/examples/performance_probe \
  --candidate target/release/examples/performance_probe \
  --case cases/performance/canyon-93k.json --mode pressure --rounds 5 \
  --inner 4 --steps 8 --threads 1 --output runs/pressure-comparison

The other rows use modes steps, momentum, production, transport and setup with the inner repetitions and step counts given above (20 inner repetitions for the kernels, 2 for step batches). Copy only the probe example into the base checkout, never optimized core files, and keep builds and other work off the machine while measuring.

Open performance and scientific gates

At the time of this record, the pressure solve ran serial PCG at every projection; a verified multigrid preconditioner was the larger algorithmic opportunity, and explicit diffusion and advection limited the time step. (Opt-in multigrid and implicit steady algorithms followed; see the gap status.) These results do not establish accepted fine canyon throughput, asymptotic grid convergence, a mesh-independent building-wall law, experimental urban validation or calibrated uncertainty. The external fine-backstep acceptance gate and the source-flux decision from PR #5 remain open.

Pressure multigrid results

This is the historical P1 point-smoother/full-coarsening campaign, including the shape sweep added in merged PR #13. Its rows are retained unchanged. The subsequent line/small-plane and semicoarsening implementation has separate anisotropy results and a fresh native/OpenFOAM gap assessment.

Scope and protocol

Baseline: main bbd191b (merged PRs #11 and #12), measured 2026-10-31. Opt-in tensor-linear symmetric geometric multigrid versus the unchanged default IC(0), solving the same fine pressure equation. No scientific gate was relaxed. One solver thread on AMD EPYC 9V74; Rust 1.88.0, locked dependencies; the host exposed 9 CPUs with an 8-CPU quota and 8 GiB memory limit. Native source fingerprint: d246dc36db0681182f74601a8bd8c87932283769bc836ea566d0e2a4ea6592d9.

One warmup and three alternating timed pairs per configuration. Repeated work and returned fields match for each method. Kernel results below come from the isolated campaign, with one cold solve and three reused solves per child; reused time is the median within a child, then across timed children.

Manufactured pressure kernels

All 40 child records passed the independent manufactured-field and true-residual bounds. Boundary conditions are wall x/z and periodic y; the cavity retains two span cells. Nominal tolerance is 1e-11, independent RMS recovery bound 1e-8 and final true-relative-residual bound 1.01e-10. The table reports milliseconds.

GridIC(0) / MG iterationsCold IC(0)Cold MGReused IC(0)Reused MGReused speedup
cavity2453 / 61.4374.6391.2920.9281.39×
cavity48102 / 612.94223.46813.0073.6463.57×
cavity96193 / 6100.655118.179102.41016.8646.07×
cube2461 / 722.338161.03619.56513.0591.50×
cube48113 / 7413.9641995.427390.576152.0882.57×

Cold multigrid is slower on every tested kernel. Reuse amortizes hierarchy construction; a single small solve is not a reason to select it. The observed 6/7 iterations belong to this RHS and are not a general iteration bound.

Accepted coupled cavity

Both methods keep the canonical numerics, 20000-step/600-second resource bounds, independent archived-field audit and frozen 0.06 Ghia centerline screen. All 16 child records passed, including warmups. Solver time includes setup and actual stepping; workflow time additionally includes process/output/checking work.

Flow-plane gridSteps (both)IC(0) PCG workMG PCG workIC(0) solver sMG solver sSolver speedupGhia error (both)
24²2010204,85024,1207.3555.4121.36×0.02756134
48²63901,262,03576,680180.66574.1082.44×0.01695144

Maximum returned-field differences over the pairs: velocity 2.22e-16 m/s; pressure 2.22e-15 m²/s², with the same gauge. Predeclared bounds were 1e-8 and 1e-7 respectively. The 0.01 development accuracy target remains unmet; pressure acceleration does not change donor-cell momentum error. No fresh OpenFOAM speed ratio or matched-accuracy comparison is claimed.

Hosted reproduction

The manual external=pressure job ran the same campaign on a GitHub runner (AMD EPYC 7763, 4 CPUs, ubuntu-24.04; run 41235330963) on the code of commit 646dda3, which differs from the recorded measurements by the CFD-W004 check and an exact (rather than hashed) hierarchy reuse check. All rows passed; iterations, steps and Ghia errors equal the recorded ones.

ConfigurationIC(0) / MG iterationsIC(0)MGSpeedup
kernel cavity24, reused ms53 / 61.6320.9281.76×
kernel cavity48, reused ms102 / 613.1034.0513.24×
kernel cavity96, reused ms193 / 6102.4416.0876.37×
kernel cube24, reused ms61 / 722.91914.1031.63×
kernel cube48, reused ms113 / 7378.06130.762.89×
accepted cavity 24², solver s204,850 / 24,1207.9655.5261.44×
accepted cavity 48², solver s1,262,035 / 76,680185.3373.972.51×

Cold multigrid solves were again slower than IC(0) on every kernel (0.14–0.84×). The evidence zip kept its directory entries; all 16 sealed archives verified in its extracted copy.

Shape sweep: where multigrid is slower

The kernels above use a smooth manufactured right-hand side on near-isotropic grids. A separate sweep on another host solved a rough compatible right-hand side (sin(0.618 i), centered) to a relative tolerance of 1e-10, timing the second solve, so the hierarchy is reused. One thread. Face weights are 1/dx² per axis; the ratio is taken between axes of more than two cells, and CFD-W004 marks ratios above 25.

CellsDomain, mWeights x/y/zRatioW004IC(0) it / msMG it / ms
96×2×244×0.1×1576/400/5761no106 / 9.710 / 5.0
48×48×481×1×0.22304/2304/5760025no132 / 379.619 / 304.4
64×2×641×0.1×0.24096/400/10240025no96 / 15.717 / 15.9
128×2×16100×1×12/4/256128yes212 / 17.042 / 16.9
64×64×81×1×0.014096/4096/640000156yes199 / 153.540 / 154.3
64×2×641×0.1×0.14096/400/409600100yes85 / 13.934 / 30.9
64×2×641×0.1×0.054096/400/1638400400yes82 / 13.568 / 61.0
48×48×481×1×0.12304/2304/230400100yes151 / 436.836 / 569.3
32×32×161×1×0.051024/1024/102400100yes127 / 44.037 / 71.5
64×8×641×1×14096/64/409664yes109 / 87.036 / 148.7
64×16×641×4×14096/16/4096256yes162 / 278.970 / 644.5
64×8×641×1×0.24096/64/1024001600yes136 / 108.6121 / 505.8
64×8×641×1×0.14096/64/4096006400yes147 / 116.0231 / 935.9

With a rough right-hand side, one cycle costs roughly as much as 5–10 IC(0) applications. Multigrid was faster only on the near-isotropic shapes; above a ratio of 25 it was as fast or slower, sometimes with more iterations. In a separate review test (64×8×64, domain 1×1×0.02 m, x/z ratio 2500), multigrid exceeded the case default of 1200 PCG iterations and stopped with CFD-E033, where IC(0) converged in about 200. check reports CFD-W004 for such cases; semicoarsening or line smoothing is the remedy, and part of the next pressure work.

Memory and work attribution

GNU time 1.9 reports the maximum individual process RSS, including waited descendants, rather than simultaneous aggregate memory. Peak columns below are maxima across timed children. Hierarchy storage counts retained numeric/index vector capacities and level records, excluding reporting/cache handles, allocator overhead, the grid, outer PCG vectors and construction temporaries.

KernelIC(0) peak MiBMG peak MiBMG retained MiBGrid complexityOperator complexity
cavity243.073.500.481.3282.267
cavity485.326.952.061.3322.450
cavity9615.1621.588.541.3332.553
cube2411.7717.316.311.1432.443
cube4880.14123.7052.681.1432.601

The 48² accepted-run peaks were 21.03 MiB (IC(0)) and 22.70 MiB (MG). The preflight hierarchy/construction allowance is 1024 additional bytes per cell before the existing 25% margin; it is a conservative budget rather than RSS.

Additional 100-step 48² phase profiles are explicitly incomplete steady runs. They pass archive/profile/independent checks and compare equivalent fields, but are not accepted-solution timings. IC(0) used 19162 PCG iterations and MG 1200, with 200 independent true-residual checks each. MG built one five-level hierarchy (6138 cells/78084 stored entries across levels), made 1200 cycles and coarse solves, and recorded 29376000 smoothing cell updates. Pressure projection occupied about 85.0% of the IC(0) profile and 67.2% of the MG profile.

Verification and reproducibility

  • Clean Rust 1.88 release workspace tests: 65 passed; fmt and clippy with warnings denied passed.
  • Python suites pass normally and with -O, including strict profile fault injection, field equivalence/repetition rejection, and process cleanup.
  • Independent dense Galerkin matrices, the entire small preconditioner on the compatible subspace, manufactured/continuous Poisson and projection checks pass.
  • Changed public face coefficients rebuild the hierarchy; masks fail explicitly. Cancellation and pressure limits preserve the entire prior state.
  • Default IC(0) fields/checkpoints/probes match the merged binary bitwise on cavity and masked canyon controls, including legacy checkpoint replay. Multigrid restart matches uninterrupted fields/checkpoints/probes bitwise.
  • Gaussian refinement, Poiseuille and empty-ABL checks pass with multigrid. Empty-ABL U/k/epsilon drift above H is 0.2341%/0.9405%/2.6754%, below the unchanged 2%/5%/5% gates. Its known below-H epsilon drift remains about 16.2%.

The measurements froze their observer before the later PID-namespace cleanup fix. This host exposes ancestor procfs IDs; cleanup now uses namespace-local NSpid/NSpgid and checks namespace identity. The pre-fix observer and original failed tests are retained in raw evidence. Measured native executables launch no subprocesses; kernel and solver timers are internal and unchanged by that post-child enumeration fix. Raw workflow times retain their original observer identity. A separate final-observer control validates the complete measurement path, without replacing the three-pair headline measurements.

Use the guide and validation/benchmark_pressure.py to reproduce. The recorded evidence was archived with validation/archive_evidence.py, which keeps directory entries rather than copying only files; all 69 sealed archives verify in its extracted copy.

Remaining work

IC(0) remains default. Masked topology/component-preserving coarsening, robust anisotropy, cheaper hierarchy construction and coarse operator complexity are next pressure work. Better momentum accuracy and an implicit/steady flow algorithm remain separate gap-closing steps. (Since then anisotropic smoothing followed in P2a, and P3a and P5a closed the cavity gap at matched accuracy; see the gap status. Masked coarsening P2b and the hierarchy cost P2c remain.) The canyon experimental-data gate, and the native physical-qualification status, are unchanged.

Anisotropic pressure multigrid results

Scope and frozen protocol

Measured 2026-10-31 on one AMD EPYC 9V74 solver thread; host exposes 9 CPUs, 8-CPU quota and 8 GiB memory limit. Both cores use Rust stable 1.99.1 and locked dependencies. Baseline core is merged PR #13, main 2ddf17d. The old point core has only two measurement overlays: the identical shared pressure_probe.rs and an unused empty multigrid/line.rs source-fingerprint marker; its algorithm is unchanged. The candidate adds symmetric line/small-plane relaxation and semicoarsening; IC(0) remains default. See the plan and algorithm and API.

Rough exact pressure is sin(0.73*i) + 0.3*cos(0.17*i), centered in closed domains; the fine operator generates its RHS. NumPy independently checks the returned vector, with separate dense operator/Galerkin/block references in the Rust tests. Each of 18 shapes has one warmup plus three balanced timed triplets (IC(0), merged point MG, candidate MG). Each child makes one cold and one cached solve. All use tolerance 1e-14, maximum 1200 iterations, independent RMS recovery <=1e-8 and true relative residual <=1.1e-12. Repeated work and result/source signatures must agree. These are pressure fixtures, not accepted flow or experimental validation.

All 216 child records (432 successful pressure solves) passed. Maximum independent recovery error across all methods was 1.844e-10; maximum true relative residual was 1.036e-14. No gate was relaxed. An initial pilot at 1e-12 failed the recovery bound on the most stretched grid for IC(0) and the candidate; its rows are retained separately and excluded from this campaign. Tightening the common solver tolerance preceded the formal measurements.

Cached pressure solves

Times are medians in milliseconds, excluding output and hashing. A speedup greater than one favors the candidate. Iterations are IC(0)/point/candidate. The first three rows keep point arithmetic and have bit-identical point and candidate pressure vectors. Short timing samples can vary substantially.

ShapeIterationsIC(0) msPoint msCandidate msPoint/candidateIC(0)/candidate
isotropic60 / 8 / 81.5571.0291.0840.95×1.44×
near-isotropic122 / 13 / 1314.8497.29413.6190.54×1.09×
threshold25108 / 24 / 2423.69227.68925.2781.10×0.94×
thin10092 / 45 / 521.11348.4115.6948.50×3.71×
thin40086 / 83 / 518.59887.4346.23014.03×2.99×
cube100147 / 46 / 5504.977881.392141.5816.23×3.57×
slab100118 / 51 / 648.116106.36015.5206.85×3.10×
plate64126 / 49 / 11109.486211.56152.7954.01×2.07×
plate256199 / 94 / 12378.140997.147144.4996.90×2.62×
thin1600152 / 150 / 19143.281664.697149.8414.44×0.96×
thin6400162 / 278 / 18147.7851313.360136.8729.60×1.08×
review-stretched161 / 1169 / 17146.1095245.237137.49938.15×1.06×
odd87 / 108 / 145.82836.6455.3736.82×1.08×
periodic145 / 257 / 78.77381.9552.80729.19×3.13×
outlet92 / 102 / 136.34934.0824.4207.71×1.44×
stiff-two-cell95 / 50 / 94.48111.9231.7146.96×2.61×
long-domain220 / 54 / 2326.07927.40612.0052.28×2.17×
short-stiff-axis204 / 57 / 6174.028244.17832.0477.62×5.43×

On the 15 block-selected shapes, cached solves are 2.28–38.15× faster than merged point MG. Against IC(0), the range is 0.96–5.43×: at thin1600 IC(0) is about 4.6% faster; on review-stretched, the large point-MG improvement buys only about 6% over IC(0). Fewer iterations alone do not establish a useful speedup. Near-isotropic’s initial short samples have large spread (candidate 7.25–16.53 ms), despite unchanged arithmetic and field hashes; do not interpret that row as an algorithmic isotropic gain.

A follow-up investigated this spread without replacing any original row: one warmup plus five timed triplets on the three point controls, unchanged binaries/fields/gates (54 more child records, all accepted). Point/candidate cached medians were 1.081/1.086 ms isotropic, 7.763/7.692 ms near-isotropic, and 24.985/25.871 ms at threshold25. The point/candidate ratios were 1.00/1.01/0.97 respectively. This supports treating the large initial near-isotropic difference as timing variation; no isotropic speedup is claimed.

Cold cost and memory

Cold time includes setup and solve. Hierarchy MiB counts retained numeric/index vector capacities and level records, excluding the exact face signature, reporting handles, grid, outer PCG vectors, allocator and construction temporary storage. Peak RSS is the complete candidate child, including JSON output; it is not a hierarchy-only memory number. Preflight adds a further 512 bytes per cell to the existing 1024-byte MG allowance, before its 25% margin, when the block policy is selected.

ShapeCold IC(0) msCold point msCold candidate msPoint hierarchy MiBCandidate hierarchy MiBCandidate peak RSS MiB
isotropic1.6834.5984.3490.480.483.39
near-isotropic14.99428.20427.5802.042.046.96
threshold2525.70262.80465.6513.263.2610.69
thin10021.19490.09729.5073.266.2613.68
thin40019.831142.24037.6773.266.2613.71
cube100575.6532659.865651.83252.6895.23169.95
slab10050.982296.26265.7907.1012.5025.37
plate64111.984551.616288.29814.0924.6548.56
plate256396.8391997.226651.08429.8849.3194.73
thin1600135.0501046.937273.98914.0928.3151.71
thin6400165.3411622.962256.80414.0928.3151.67
review-stretched141.5635725.831274.64914.0928.3151.75
odd6.24656.79715.1031.402.576.49
periodic9.08399.55111.8221.372.426.15
outlet6.62056.99013.7501.402.576.52
stiff-two-cell4.77218.4819.7360.781.254.77
long-domain25.22643.39423.5621.542.897.62
short-stiff-axis182.163517.239146.81113.5223.2046.79

Cold candidate solves are often slower than IC(0). Retaining weak-axis modes also retains larger coarse grids and operators. Setup and operator complexity remain explicit P2c work; this implementation does not claim universal cold or low-memory superiority.

Shape definitions

All meshes are uniform within each axis. Grid counts and domain lengths are separate; this is not support for graded/nonuniform meshes. Wall fixtures use wall x/z, periodic y and no moving wall; periodic uses periodic x/y and wall z; outlet uses open x, periodic y, wall z and imposed initial x velocity. Every exact input JSON is retained. Labels are mnemonics, not acceptance gates.

ShapeCells x,y,zDomain m x,y,zx boundary
isotropic24, 2, 241.0, 1.0, 1.0wall
near-isotropic96, 2, 244.0, 0.1, 1.0wall
threshold2564, 2, 641.0, 0.1, 0.2wall
thin10064, 2, 641.0, 0.1, 0.1wall
thin40064, 2, 641.0, 0.1, 0.05wall
cube10048, 48, 481.0, 1.0, 0.1wall
slab10032, 32, 161.0, 1.0, 0.05wall
plate6464, 8, 641.0, 1.0, 1.0wall
plate25664, 16, 641.0, 4.0, 1.0wall
thin160064, 8, 641.0, 1.0, 0.2wall
thin640064, 8, 641.0, 1.0, 0.1wall
review-stretched64, 8, 641.0, 1.0, 0.02wall
odd33, 5, 171.0, 1.0, 0.1wall
periodic31, 5, 170.05, 1.0, 1.0periodic
outlet33, 5, 171.0, 1.0, 0.1open
stiff-two-cell32, 2, 321.0, 0.001, 1.0wall
long-domain128, 2, 16100.0, 1.0, 1.0wall
short-stiff-axis64, 64, 81.0, 1.0, 0.01wall

Accepted coupled anisotropic flow

Square-domain Re=100 cavity, 64x2x12, canonical flow numerics; one warmup and three alternating timed IC(0)/MG pairs per mode. Limits are 600 s/20000 steps. Archive integrity and independent field audits must pass. The steady row also retains the existing 0.06 Ghia screen. The transient row means completion to 1 s, not convergence to steady flow. Both methods repeat their work and fields. All 16 child records pass. Total solver time includes setup; workflow time also includes launch, archive and checking work.

ModeSteps bothIC(0)/MG PCG workSolver IC(0)/MG sSolver speedupWorkflow IC(0)/MG sWorkflow speedupGhia error
steady4950477,555 / 59,31523.632 / 16.7511.41×23.722 / 16.8431.41×0.04298755
transient29728,846 / 3,4791.546 / 0.9421.64×1.642 / 1.0481.57×not steady

Maximum pairwise velocity difference is 2.22e-16 m/s and pressure difference 5.01e-15 m²/s²; predeclared bounds are 1e-8 and 1e-7 with the same gauge. Steady stopping steps are unchanged. This throughput fixture’s 0.04299 Ghia error does not reach the 0.01 accuracy objective; it is not a matched-accuracy OpenFOAM comparison. It compares the candidate with IC(0), while the isolated pressure suite additionally compares the merged point algorithm.

Hosted reproduction

The manual external=anisotropy job ran both campaigns on a GitHub runner (AMD EPYC 7763, 4 CPUs, ubuntu-24.04; run 41268224744) at commit 8ebee01, whose solver code is the code measured above. The job builds the merged point core from main 2ddf17d with the same two measurement overlays. All kernel and flow records passed, and all 16 flow archives verified after a zip round trip.

Every shape repeated the recorded iteration counts for all three methods, and the coupled runs repeated the recorded steps, PCG work and Ghia error. Reused kernel times (medians, ms) and speedups of the candidate:

ShapeIC(0)PointCandidatePoint/candidateIC(0)/candidate
isotropic1.9141.2211.2031.01×1.59×
near-isotropic16.3018.2398.2711.00×1.97×
threshold2525.20026.99827.1660.99×0.93×
thin10021.60649.9346.3977.81×3.38×
thin40020.31391.6086.42514.26×3.16×
cube100494.481847.348117.4167.22×4.21×
slab10053.578113.89815.2767.46×3.51×
plate64119.990222.67847.2554.71×2.54×
plate256392.266935.114113.8988.21×3.44×
thin1600144.321682.025113.4706.01×1.27×
thin6400153.7921332.020112.21311.87×1.37×
review-stretched153.5595373.320108.43849.55×1.42×
odd6.77740.3605.9216.82×1.14×
periodic10.56891.2852.89831.50×3.65×
outlet6.76435.9495.1217.02×1.32×
stiff-two-cell5.41413.1131.9806.62×2.73×
long-domain26.19228.79212.5492.29×2.09×
short-stiff-axis199.073251.83830.4838.26×6.53×

On this runner the candidate’s cached solves beat IC(0) on all 15 block-selected shapes (1.14–6.53×), including thin1600, where IC(0) was faster on the recording host. Against merged point MG the range is 2.29–49.55×.

ModeSteps bothIC(0)/MG PCG workSolver IC(0)/MG sSolver speedupWorkflow IC(0)/MG sWorkflow speedupGhia error
steady4950477,555 / 59,31526.861 / 19.1071.41×26.941 / 19.2181.40×0.04298755
transient29728,846 / 3,4791.600 / 1.1281.42×1.706 / 1.2061.42×not steady

The opt-in multigrid cavity accuracy sweep (external=accuracy with native_pressure=multigrid, AMD EPYC 9V74, 4 CPUs; run 41267955525) accepted all 20 records with unchanged Ghia errors. Native/OpenFOAM solver time was 6.85× at 24² and 10.99× at 48² (workflow 3.60× and 9.79×), close to the same-host comparison. Native still misses the 0.01 target through 48², so no equal-accuracy ratio exists.

Identity, reproduction and limits

Shared-probe source fingerprints (different scope from the CLI build SHA):

  • point_mg: 694a65b070e537d1026368517e9d0ffdea6621bef04a293e562ffe0f4571677e.
  • candidate_mg: a00c21b56c2ba635d9888da064309c8dc65c47966dc816c0337ba1b71451cfd1.

The raw evidence records executable/input/producer SHA-256 values, compiler, host limits, every child, returned pressure vectors, hierarchy dimensions, block bandwidth/storage, work, RSS, repeated profiles and complete native flow archives. The guide gives local and opt-in CI commands. The tables above come from the recording host; the hosted reproduction above ran on a GitHub runner.

Verification passes 75 Rust release tests on minimum 1.88.0 and stable 1.99.1, with all-target Clippy warnings denied, plus 396 distinct Python tests per normal/optimized mode across 16 suites. The 23 runtime-dependent tests were rerun with the pinned real backend, with no skips. The existing scalar/flow verification, Poiseuille, empty-ABL, manual examples and masked SciPy reference pass. A block-selected 12x4x12 checkpoint replay produces bit-identical fields to the uninterrupted run; a forced one-iteration pressure failure retains the whole initial state, with attempted work visible in the validated profile.

Mask support, component-preserving transfers, narrow passages and the 27k/93k canyon gate are still open. Anisotropy selection is a fixed spacing heuristic, not a guarantee for every aspect ratio or arbitrary modified face matrix. No OpenFOAM code is copied. No flow/transport/turbulence model or scientific tolerance changes. The fresh overall gap and remaining stages keep pressure throughput, accuracy and physical qualification distinct.

Stage V: momentum verification and donor-cell baseline

Measured 1 November 2026 against main f358be6 (merged PR #14). Stage V changes verification and measurement only. Production Rust numerics, default serialization, physical models and acceptance thresholds are unchanged. See the protocol, full accuracy/steady plan and machine-readable reduced evidence.

Analytic verification

The production donor-cell operator has mean L1 order 0.99723 over eight prescribed phase offsets and grids 32/64/128/256. The test-only helper zeros viscosity/forcing after grid construction; production arithmetic is not refactored. The solid-barrier insulation test and near-side sensitivity control pass.

PhaseL1 orderL2 orderL∞ order
10.997810.997950.99793
20.997480.997910.99808
30.996800.997780.99722
40.996930.997790.99757
50.997750.997980.99777
60.997070.997640.99752
70.996440.997660.99642
80.997550.997880.99817

The translating Taylor–Green vortex, with nonzero uniform drift, recovers L1/L2/L∞ orders 0.97390 / 0.97475 / 0.95906. Time refinement gives order 2.00022; its last L1 difference is 4.95e-06 of the grid-64 spatial error (gate 0.01). The fixture therefore exposes advection’s first-order error independently of the existing second-order viscous-shear test.

GridVelocity L1 errorL2 errorL∞ errorLargest normalized component-momentum drift, 100 steps
16²0.004709470.005838710.012943040.0018038913
32²0.002414710.002990920.006741350.00096546842
64²0.001220740.001511680.003424710.00049480891

Momentum drift is a recorded baseline, not a newly weakened conservation gate. The current advective donor-cell form is not conservative; P3a’s shared fluxes must meet its separate 1e-13-per-100-step gate. The transverse step has no new extrema after 1000 steps at CFL cap 0.45; final range is [0.42350959, 0.57649041]. Its deliberate iteration limit is recorded as incomplete numerical acceptance, rather than called an accepted transient interval.

Paired backend sweep

AMD EPYC 9V74, 8-CPU cgroup, one solver thread; Rust 1.88.0, Python 3.12.14, pinned OpenFOAM Foundation 13 package from the existing adapter. One warmup plus three alternating timed pairs per grid. Native multigrid, 600 s/20000 steps; OpenFOAM 180 s/3000 iterations. The recorded run used a fresh temporary directory, started after all builds and the 96² reference had finished, and recorded filesystem events and process snapshots. All 32 rows pass final collection, and its evidence archive verifies 51/51 sealed archives after a zip round trip, including the analytic fixtures, default controls and the accepted 96² reference. Default controls retain IC(0). These medians are not a speedup comparison with earlier hosts or compiler versions.

GridNative Ghia errorOpenFOAM Ghia errorNative steps / OpenFOAM iterationsNative solver sOpenFOAM solver sNative/OpenFOAM
16²0.038024530.018753671020 / 3751.0700.3143.41×
24²0.027561340.008966322010 / 6965.2020.7267.16×
32²0.023514480.008703803240 / 110215.0391.49310.07×
48²0.016951440.007079986390 / 213271.6136.17911.59×

Native computes two span cells, OpenFOAM one. Native elapsed_s excludes startup/output; OpenFOAM’s solver-process time includes its startup/output. The native and SIMPLEC stopping norms also differ. These are configured same-flow-plane-grid ratios, not equal-work or equal-accuracy ratios.

OpenFOAM reaches 0.01 on 24²; native misses it on every grid in the paired list. The paired report’s native_over_openfoam_at_target remains null.

Native 96² self-reference and the first observed target crossing

A separately budgeted native 96² cold solve reached the steady checks at 21390 steps, residual 9.9253791e-06, after 1074.45 s of solver work. It then exited 1 writing executable identity, because an active executable had been replaced during a build. Its directory remains unsealed; no manifest or completion marker was manufactured.

A fresh run used that unchanged checksummed checkpoint through the public restart contract and the fixed candidate executable. It recomputed acceptance, passed the independent archive/field audit and finished at 21420 steps, residual 9.7918938e-06, Ghia error 0.00920541. The normal restart advances to the next monitor window: 30 extra steps, 360 pressure iterations and 1.574 s. The predecessor/continuation byte comparison failed and is retained: maximum velocity change 2.31e-07, pressure change 6.59e-08. These are different-work states; this is not claimed as a same-step restart-identity pass. Default same-work controls below are unchanged and pass.

Thus native can reach the 0.01 objective at 96², with approximately 1076.02 s (17.9 minutes) of accumulated solver work in this diagnostic chain. OpenFOAM’s qualifying 24² median is 0.726 s. On the GitHub runner a cold 96² solve, with no restart, was accepted after 825.9 s (see Hosted reproduction). This exposes a very large accuracy-per-cost deficit, but a failed cold archive plus one continuation is not a repeated matched-accuracy benchmark. The 96² reference is excluded from the paired cost-at-target calculation; its 1.574-second continuation timer must never be presented as the full solve cost.

Against this accepted same-scheme 96² centerline on 257 fixed stations, descriptive L1/L2/L∞ slopes over 16/24/32/48 are 1.28448 / 1.27649 / 1.35582. A finite reference and this interpolation-based observable do not establish asymptotic order or a GCI.

Controls, checks and retained failures

Default steady cavity24, transient Poiseuille and a three-step masked canyon match unmodified main byte for byte in fields, checkpoints, probes, geometry and consumed case, with identical steps and pressure work (2010/204850, 2/0, and 3/365 respectively). The canyon work limit is not called convergence. Rust 1.88.0 and 1.99.1 each pass all 77 release workspace tests, fmt and strict all-target clippy. All 17 Python suites pass in normal and optimized mode (411 tests per mode). Ruff passes formatting and lint.

Two partial sweeps were invalidated by changed frozen inputs and retained. A complete sweep failed an OpenFOAM warmup progress check. A complete repeat initially passed all 32 rows, but later checks rejected three of its OpenFOAM archives: purged snapshots/directories no longer matched their seals. Those initial passes are not presented as the final trustworthy baseline.

A new post-campaign collection guard rechecks the manifest and native/external archive after all child runs, retains accepted_at_measurement, and invalidates late changes before calculating qualifying costs. Two regression tests cover changed manifests and late archive rejection; the final accuracy-sweep suite and comparator suites cover them in both Python modes. The subsequent sequential reproduction still failed (two rows at collection, further changes at packaging), and remains failed. The older cloud archive investigation already describes this anomaly; its underlying cause remains unknown.

The recorded campaign used the identical numerical and timing protocol in a fresh temporary directory. It passed collection and the zip round trip there, and its archive was rechecked after copying (51/51 sealed archives, identical bytes and CRCs). Filesystem events, process snapshots, the reproduction driver and the failed attempts are kept with the evidence. This containment is not a repair of old archives or a diagnosis. No verifier or scientific tolerance was relaxed. The cold-reference and different-work byte comparison failures remain recorded above.

Hosted reproduction

Ordinary Rust CI includes the operator and insulation tests; numerical CI runs validation/momentum_accuracy.py. The manual external=momentum job runs the whole protocol on a GitHub runner: fixtures, the paired sweep, the 96² reference and the default byte controls against main (f358be6 for this run; the job now builds 6d33850). It ran on the code of commit 9fdc961 (AMD EPYC 9V74, 4 CPUs, ubuntu-24.04; run 41302658721), whose solver and fixture code is the code measured above. Every step passed.

  • Fixtures: identical to the recorded values: vortex orders 0.97390 / 0.97475 / 0.95906, time-difference order 2.0002 at 4.95e-6 of the spatial error, the same momentum drift and no new extrema in the transverse step.
  • Paired sweep: all 32 rows accepted, the workflow valid, and no row rejected at final collection. Ghia errors equal the recorded ones; native still misses 0.01 on every paired grid, so the ratio at target stays null.
GridNative solver sOpenFOAM solver sNative/OpenFOAMNative workflow sOpenFOAM workflow s
16²0.9240.2643.50×0.9930.841
24²4.3910.6296.98×4.4541.250
32²12.9371.4508.92×13.0302.061
48²59.5515.41710.99×59.6576.146
  • 96² reference: a cold solve accepted at 21390 steps after 825.9 s of solver time, Ghia error 0.00920562, with no restart. This is the clean counterpart of the recorded checkpoint continuation (21420 steps, 0.00920541). It is still a single diagnostic, not a repeated cost-at-target sample: about 1,300 times OpenFOAM’s 0.629 s at 24².
  • Self-convergence: descriptive L1/L2/L∞ slopes 1.2845 / 1.2765 / 1.3558 against the cold reference, equal to the recorded ones to four digits.
  • Default controls: steady cavity24, transient Poiseuille and the three-step masked canyon are byte-identical to main with identical work (2010/204850, 2/0, 3/365).
  • Evidence archive: 51/51 sealed archives verified after the zip round trip; no archive records a time directory without files.

Remaining stages

Stage V provides verification fixtures and a baseline; it delivers no numerical speedup. Each following stage may require more than one PR. Done since (1 November 2026): P3a, P3b, P4, P5a, P5c, P5d and M; P5b was not needed; P2b and P2c remain open (gap status). The table is the plan as recorded.

StageRemaining implementation and exit evidence
P3a — nextOpt-in conservative second-order laminar advection; unlimited and limited candidates; operator/vortex order, conservation, extrema/stability, wall/solid closure, default/restart controls and accepted cavity sweep. Keep only schemes that pass.
P4Delta-form implicit viscous correction in steady pseudo-time; same fixed point under stricter residual checks, unchanged acceptance, restart and complete-run cost.
P5aUniform-step implicit steady momentum/projection; choose inner solver by predeclared pilot. Must reduce solver time by at least 2× versus the better explicit/P4 method with selected P3a advection.
P5b — conditionalConsistent local pseudo-time and face-weighted projection only if P5a misses its cost gate; independent pressure-operator and nullspace tests.
P3b + P5cOpen-boundary closures and RANS, empty-ABL check, same fixed point, zero floor events, accepted 27k/93k canyons and updated model card.
P5dScalar transport with implicit flow: declared substeps, implicit transport or a verified frozen-flow workflow; mass, positivity, units and refinement checks.
M — after each stageRepeated same-host cost at the declared error, both backends on the shared list, unchanged checks and all failures retained; add a qualifying native grid to the paired protocol when needed.
Separate pressure workP2b masked multigrid and P2c setup/hierarchy costs. They do not block P3a.

Second-order momentum advection (stage P3a): results

Date: 1 November 2026. Plan and predeclared gates: accuracy and steady-solver plan, stage P3a. Base: main at 6d33850 (merged PR #15).

What changed

numerics.momentum_advection selects, opt-in, a conservative flux form of the momentum advection on the staggered grid with an upwind-biased reconstruction (second_order_upwind, or limited_upwind with numerics.momentum_limiter = van_albada, van_leer or monotonized_central). Donor-cell stays the default. The method and its sources are in the flow model card. Stage P3b, at the end of this document, adds the open-boundary closure and allows neutral_rans.

Gates

All gates were declared in the plan before the scheme existed. All schemes pass all gates.

1. Operator order

tests/momentum.rs, second_order_schemes_meet_the_predeclared_operator_orders: the production momentum_rhs with viscosity and forcing zeroed, on the shifted periodic Taylor–Green field at the 8 predeclared phases, N = 32, 64, 128, 256. Least-squares slopes of the error norms:

SchemeL1 meanL1 minL2 meanL2 minMax meanMax minGate
second_order_upwind2.0572.0492.0882.0852.2072.204every phase ≥ 1.9 in all norms: pass
van_albada1.9161.8871.5001.4130.9970.783L1 mean ≥ 1.8, every phase ≥ 1.6: pass
van_leer1.9211.8351.4941.3190.9990.702pass
monotonized_central1.9481.7461.4911.0451.0140.430pass

The plan’s NumPy model of the operator predicted 2.05 for the unlimited scheme and L1 minima/means of 1.87/1.93 (van Albada), 1.78/1.96 (van Leer) and 1.77/2.13 (monotonized central). As expected, the limiters fall back to first order in strips around smooth extrema, so their L2 and max-norm slopes are lower; those norms are reported, not gated. Donor-cell’s mean L1 slope is 0.997.

2. Translating Taylor–Green

validation/momentum_accuracy.py --scheme NAME: periodic x and z, offset velocity (0.7, 0.2, 0.3), grids 16, 32, 64 at a fixed step of 0.0005 s, with a separate time refinement.

SchemeL1 orderL2 orderMax orderTime / spatial error at 64²Gate (L1 ≥ 1.7)
donor_cell (Stage V baseline)0.9740.9750.9595.0e-6—
second_order_upwind1.9992.0082.0279.4e-5pass
van_albada2.0441.9011.5851.6e-4pass
van_leer2.1592.0621.7602.0e-4pass
monotonized_central2.3202.3212.1392.7e-4pass

The 64² L1 velocity errors are 6.6e-5, 4.1e-5, 3.1e-5 and 2.3e-5 for the four schemes. Time errors stay below 0.03 % of the spatial errors.

3. Conservation

Total momentum change of each component, normalized by Σ|u_a|·V, per 100 steps, largest over all vortex runs: 4.2e-17 (unlimited), 2.5e-17, 5.7e-17 and 5.8e-17 (limited), against the 1e-13 gate. Donor-cell drifts by 1.8e-3 per 100 steps at 16². The Rust test flux_form_advection_conserves_periodic_momentum checks the operator alone on a field that is not divergence-free.

4. Boundedness and stability

The transverse step v(x) carried by a uniform flow, 1,000 steps at advective_cfl_max 0.45:

SchemeFinal range (initial 0–1)New extremaGate
donor_cell0.42–0.58 (smeared)0—
second_order_upwind−0.226–1.2260.226 (reported)no growth from step 500 (0.2277) to 1000 (0.2257): pass
van_albada0.0076–0.99240≤ 1e-12: pass
van_leer0.0009–0.99910pass
monotonized_central0.0000–1.00000pass

The cap of 0.45 was not lowered for any scheme.

5. Insulation

second_order_schemes_keep_a_solid_barrier_insulating: perturbing the far side of a two-cell barrier leaves the near-side right-hand side bit-identical for every scheme, and a near-side perturbation does change it.

6. Controls

  • Default byte identity: the steady cavity, a transient Poiseuille run and a masked canyon (3 steps), built from this branch and from main (6d33850), have byte-identical fields.json, checkpoint.json, probes.csv, geometry.json and case.json, with identical work: 2010 steps and 204,850 pressure iterations, 2/0 and 3/365.
  • Shear flows: on Poiseuille and Couette fields u(z), the advective contribution of every scheme is exactly zero, and the right-hand side equals donor-cell’s to 1e-14.
  • Independent reference: flux_form_matches_an_independent_periodic_reference compares all five reconstructions, including the s = 0 control, with a separate plain-array implementation on a 6×5×7 periodic grid with three spacings, to 1e-12.
  • Restart: a 12² steady cavity run for 6 steps equals 3 steps plus a resumed 3, bit for bit, for every scheme.
  • Diagnostics: CFD-E037 (limiter rules) carries the field path; default numerics are not serialized. P3a also rejected open boundaries and RANS (CFD-E038, CFD-E039); stage P3b retired both codes after its gates passed.

7. Cavity sweep

Steady Re=100 lid-driven cavity, native only, opt-in multigrid pressure, one thread, this host (2-vCPU Intel Xeon VM), budgets 20,000 steps and 600 s. Every row reached the unchanged steady gates. Donor-cell’s hosted errors on the same grids are 0.0380, 0.0276, 0.0235 and 0.0170 (Stage V).

GridSchemeStepsSolver sGhia error
16²second_order_upwind1,3202.240.0230
16²van_albada1,3202.080.0257
16²van_leer1,3202.270.0243
16²monotonized_central1,3201.930.0225
24²donor_cell2,0104.980.0276
24²second_order_upwind2,49010.140.00578
24²van_albada2,4609.950.00589
24²van_leer2,4609.430.00544
24²monotonized_central2,4909.740.00494
32²second_order_upwind3,87028.50.00733
32²van_albada3,84028.60.00332
32²van_leer3,84029.10.00365
32²monotonized_central3,84028.90.00400
48²second_order_upwind7,230123.90.00660
48²van_albada7,230125.50.00487
48²van_leer7,230123.40.00500
48²monotonized_central7,230124.20.00515

The 24² times are medians of three rounds (donor 4.59–5.07 s; unlimited 9.58–10.35; van Albada 9.94–10.49; van Leer 9.28–9.81; monotonized central 9.51–9.83). The other rows are single runs, measured while the host also built code, so they are approximate.

Every second-order scheme reaches the 0.01 target at 24², the same grid as OpenFOAM (whose hosted error there is 0.0090). Donor-cell reaches it only at 96². The Ghia error is near its floor: it does not fall monotonically with the grid, which is why the plan adds a self-convergence measurement.

Self-convergence (selected scheme)

Van Leer at 96² as a same-scheme reference (22,830 steps, 1,742 s, accepted, Ghia error 0.00504), and the mean absolute centerline difference at 257 stations for the shared grids:

GridL1 difference to 96²
16²0.00920
24²0.00406
32²0.00198
48²0.00062

Least-squares order 2.45, against 1.28 for donor-cell with the same method in Stage V. A finite reference inflates the order as the grids approach it, so this is a descriptive difference, not an exact error or a grid-convergence index.

Selection

Predeclared rule: among passing schemes, the lowest native solver time on the coarsest grid that reaches 0.01; prefer a limited scheme over the unlimited one within timing noise. The coarsest grid is 24² for all four. limited_upwind with van_leer has the lowest median there (9.43 s); monotonized central (9.74 s) overlaps it within noise. All four schemes stay selectable.

Cost

The flux form costs about 3.8 ms per step at 24² against 2.5 ms for donor-cell, and needs 22% more steps (2,460 against 2,010) because the steady monitors settle later. Cost at the target on this host is therefore 9.4 s for native against 0.63 s for OpenFOAM on the hosted runner: roughly 15×, where before P3a native needed 96² and about 826 s (roughly 1,300×). The hosts differ, so the hosted stage M measurement gives the actual ratio. Steps to a steady state (P4, P5a) and the cost per step are the remaining levers.

Stage P3b: open boundaries and RANS

Outlet closure

The outer half of an outlet’s momentum cell advects with the outlet face velocity and a zero-gradient value (s = 0), and its tangential faces extrapolate the inside cell’s advecting velocity; inflow faces are prescribed. Tests (tests/momentum.rs):

  • uniform flow through an open channel has an advective contribution of at most 1e-14 on every face, including the outlets, for all four schemes;
  • the open channel (10×2×6, inflow 0.4 m/s) reaches the unchanged steady gates with every scheme, in the explicit mode and with implicit_projection.

While adding this, a defect in the P5a matrix showed up: at an outlet, the indices of its advecting velocities fell back to cell 0 and to the outlet’s own face for a missing cell, so the Jacobian rows of outlet faces depended on unrelated velocities. The delta form kept the fixed point, but the path was wrong. implicit_matrix_rows_at_an_outlet_use_only_adjacent_velocities fails without the fix; the rows now use the same zero-gradient closure.

RANS

Predeclared conditions for allowing the schemes with neutral_rans: the empty-ABL check with unchanged gates (2% U, 5% k and ε in H..5H), and the development canyon (W/H = 1, 270°, 18×16×12) reaching the steady gates with zero floor events. Both were run with a build that only lifted the rejection:

SchemeABL drift U / k / εABL floorsCanyon stepsCanyon solver sCanyon floorsCanyon gates
donor_cell (control)0.23% / 0.94% / 2.68%03,80042.10pass
second_order_upwind0.22% / 0.92% / 2.70%05,10070.60pass
van_albada0.23% / 0.88% / 2.72%03,10045.40pass
van_leer0.23% / 0.88% / 2.69%03,10046.80pass
monotonized_central0.22% / 0.89% / 2.66%03,00043.50pass

All conditions hold, so neutral_rans is allowed with every scheme. run_suite.py --abl-numerics '{"momentum_advection": ...}' reproduces the ABL check; with van Leer the whole verification suite passes (drifts 0.22%, 0.88%, 2.69%). The k and ε equations keep their first-order upwind transport.

The canyon’s receptor concentrations depend on the momentum scheme: sensor0 is 9.6e-8 kg/m³ with donor-cell, 7.4e-8 with van Leer and 1.4e-7 with the unlimited scheme. That is numerical sensitivity on a coarse development grid, not a validation statement; the canyon validation gate is unchanged.

Implicit steady pseudo-time (stages P4 and P5a): results

Date: 1 November 2026. Plan and predeclared gates: accuracy and steady-solver plan, stages P4 and P5a. Method: flow model card, “Steady pseudo-time algorithms”. Campaign script: validation/steady_algorithms.py (its cavity default is implicit_viscous; P5a uses --algorithm implicit_projection).

All measurements: steady Re=100 lid-driven cavity, opt-in multigrid pressure, one solver thread, a 2-vCPU Intel Xeon VM that also ran other work, so timings are approximate. Hosted reproduction is stage M.

Summary

StageGateResult
P4 implicit_viscoussame fixed point (mode difference shrinks ≥ 5× per 10× tightening)failed (see below); the round-off pair agrees to 1e-12
P4unchanged acceptancepass
P4restart identitypass
P4cost1.5–2.2× faster than explicit
P5a implicit_projectionsame fixed pointpass: 7.8–13.5× per decade
P5aunchanged acceptancepass
P5arestart identitypass
P5acost: ≥ 2× below the better of explicit and P4 at 24² and 48²pass: 13× and 18× below P4

P5a passed its cost gate, so the conditional stage P5b (local pseudo-time steps with a face-weighted projection) is not built.

Fixed point

Predeclared test: the 24² cavity in the explicit mode and the candidate mode at the case tolerances (steady residual 1e-5, monitor 1e-3) and with both tightened 10× and 100×; the maximum face-velocity difference between the modes must shrink at least 5× per decade. One pair is converged near round-off (residual 1e-11, monitor 1e-9). “To reference” is each mode’s distance to the round-off explicit solution, reported, not gated.

P4 implicit_viscous

SchemeTighteningSteps explicit / P4Mode differenceTo reference: explicit / P4
donor_cell1×2010 / 11701.29e-61.34e-5 / 1.21e-5
donor_cell10×2490 / 14402.98e-81.33e-6 / 1.30e-6
donor_cell100×2970 / 17107.48e-91.31e-7 / 1.39e-7
van_leer1×2460 / 14403.38e-71.83e-5 / 1.80e-5
van_leer10×3060 / 18001.02e-71.81e-6 / 1.71e-6
van_leer100×3660 / 21601.67e-81.79e-7 / 1.62e-7

Shrink per decade: donor-cell 43.2× and 4.0×, van Leer 3.3× and 6.1×. The gate fails for both schemes, and the failure is kept. The round-off pairs differ by 3.6e-13 (donor) and 1.0e-12 (van Leer). Each mode’s own distance to the round-off solution falls exactly 10× per decade, so both converge to the same fixed point; the two modes follow nearly the same path, and their small mutual difference depends on where in a 30-step monitor window each one stops. The gate measures that difference, so it fluctuates. It is not changed after the fact. P4 stays an opt-in option with this recorded failure; P5a, which passes the same gate, is the recommended implicit mode.

P5a implicit_projection

SchemeTighteningSteps explicit / P5aMode differenceTo reference: explicit / P5a
donor_cell1×2010 / 1801.06e-51.34e-5 / 2.79e-6
donor_cell10×2490 / 2109.13e-71.33e-6 / 4.13e-7
donor_cell100×2970 / 2407.02e-81.31e-7 / 6.09e-8
van_leer1×2460 / 2101.17e-51.83e-5 / 6.62e-6
van_leer10×3060 / 2701.50e-61.81e-6 / 3.15e-7
van_leer100×3660 / 3001.10e-71.79e-7 / 6.86e-8

Shrink per decade: donor-cell 11.6× and 13.0×, van Leer 7.8× and 13.5×: pass. The round-off pairs differ by 1.0e-11 (donor, 4860 explicit steps against 390 outer iterations) and 9.8e-12 (van Leer, 6060 against 480). At each tolerance P5a is closer to the converged solution than the explicit mode.

Acceptance and restart

Every run of both campaigns reached the unchanged steady gates: the fixed-point runs above, plus Poiseuille, Couette and the 24² cavity with donor-cell, van Leer and the unlimited scheme. Rust tests (tests/implicit.rs) check restart bit identity after 3 of 6 outer iterations for both algorithms and two schemes, the CFL ramp, and that explicit runs do no and report no inner work.

Operators

tests/implicit.rs also checks:

  • the P4 stencil is the linear part of the production viscous right-hand side, to 1e-12, on a cavity, a masked cavity, an open channel, a slip lid, Couette and Poiseuille, and is symmetric and negative definite;
  • the P5a matrix equals an independent plain-array assembly of I/Δτ + frozen-flux first-order upwind − ν·L on a periodic grid, to 1e-10;
  • constants are in its advective and viscous kernel for a divergence-free field, it has nonpositive couplings and dominance by 1/Δτ, also with walls;
  • the inner solve reaches its relative tolerance.

Inner-solver pilot (P5a)

Declared before running: van Leer, 24² and 48², two runs each; candidates symmetric Gauss–Seidel with 2 or 4 sweeps, and Jacobi-preconditioned BiCGStab to a relative residual of 0.1 (cap 50); select the lowest sum of mean solver times among candidates accepted on both grids.

Candidate24² iterations24² s48² iterations48² sSum s
SGS, 2 sweeps2400.5733903.954.52
SGS, 4 sweeps2100.4833003.083.57
BiCGStab2100.5062702.813.32

All runs were accepted with Ghia errors 0.00543 (24²) and 0.00501–0.00502 (48²). BiCGStab was selected; the margin over four SGS sweeps (7%) is within this host’s timing noise.

Cost

Van Leer, solver seconds to the unchanged gates:

GridExplicitP4P5aP5a speed-up over explicitGhia error
24²9.43 (2460 steps)6.13 (1440)0.51 (210)18×0.00543
48²123.4 (7230)55.5 (3120)3.06 (270)40×0.00500–0.00502

Donor-cell with P5a: 0.26 s at 24² (180 iterations) and 1.75 s at 48² (270), Ghia errors unchanged at 0.0276 and 0.0169. The cost at the 0.01 target is now about 0.5 s for native at 24² on this host, where OpenFOAM’s hosted solver time at 24² is 0.63 s; the hosted stage M measurement compares both on one runner.

The flux form makes an outer iteration about 1.7× as costly as with donor-cell (11 against 6.5 ms at 48²); the advective kernel is the next performance target.

Implicit steady iteration with RANS and constituents (stages P5c and P5d): results

Date: 1 November 2026. Plan and predeclared gates: accuracy and steady-solver plan, stages P5c and P5d. Method: flow model card (“Steady pseudo-time algorithms” and “Neutral turbulence package”) and transport model card. Campaign script: validation/steady_algorithms.py --case canyon --output DIR (the candidate defaults to implicit_projection for the canyon).

All measurements: one solver thread on a 2-vCPU Intel Xeon VM (2.1 GHz) that also ran other work, so timings are approximate. The P5c/P5d code is commit 2ffedec; the recipe rows at the end use the performance iterations (validation/PERFORMANCE_ITERATIONS_RESULTS.md).

Summary

StageGateResult
P5csame fixed point as the explicit mode on the development canyon, with the tightening test (mode differences of U, k and ε shrink ≥ 5× per decade)failed for U on the second decade (2.9×); k and ε pass; the round-off pair agrees to 1.5e-10
P5cempty-ABL check with unchanged gates (2% U, 5% k and ε in H..5H)pass, in steady mode: drifts 0.26% / 0.81% / 3.44%, equal to the explicit steady run’s
P5czero floor eventspass in every run
P5ccanyon 27k and 93k acceptedpass
P5cmodel card updateddone
P5dmass budget, negative mass, positivitypass: relative budget defects ≤ 3.1e-13, no negative mass
P5dunit normalization and superpositionpass: doubling the emission doubles every concentration to 1e-12 (Rust test, both implicit algorithms)
P5dsteady mass balance, receptorspass: receptors equal the explicit mode’s to 2.2e-7 (development canyon) and 5e-7 (27k)
P5drefinementthe discrete steady state is the explicit mode’s at every grid; the canyon itself is not grid-converged (below)

Fixed point (P5c)

The development canyon (cases/canyon/wh1-wind270.json, 18×16×12, open sides, ground_open_top) without its tracer, explicit and implicit_projection, at the case tolerances (steady residual 1e-5, monitor 1e-3) and with both tightened 10× and 100×. Differences are maxima over the field, relative to the explicit field’s maximum. “To reference” is each run’s distance to the round-off explicit solution (reported, not gated).

TighteningSteps explicit / implicitSolver sU differencek differenceε differenceTo reference, U: explicit / implicit
11000 / 50011.8 / 4.01.69e-53.40e-53.47e-51.7e-5 / 1.4e-6
101200 / 50014.1 / 4.02.10e-64.74e-63.24e-63.4e-6 / 1.4e-6
1001400 / 70015.2 / 5.27.28e-77.17e-75.22e-79.0e-7 / 1.7e-7

Shrink per decade: U 8.1 and 2.9, k 7.2 and 6.6, ε 10.7 and 6.2. The U gate fails on the second decade and is recorded as failed. The last column shows why: at 100× the mode difference is the explicit run’s own distance to the converged solution (9.0e-7), while the implicit run is five times closer.

Round-off pair: the turbulence-residual probe of assess has a floor near 1.8e-10 on this case in both modes (it differences k over one 1e-6-scaled explicit step), so the cavity’s 1e-11 tolerance is unreachable; the campaign uses 1e-9 for the residual and the monitor. Explicit 2,600 steps (31.1 s), implicit 1,000 (7.5 s); differences U 1.5e-10, k 1.0e-10, ε 6.1e-11. A separate pair run to the iteration limit (residual tolerance 1e-11, 140,642 explicit and 200,000 implicit steps, momentum residuals 3.2e-15 and 8.6e-16, both stopped by the same 1.805e-10 turbulence floor) differs by 1.2e-14 (U), 7.3e-15 (k) and 9.8e-15 (ε): the two modes have the same fixed point.

Empty ABL (P5c)

The empty-ABL check is transient in run_suite.py; the implicit algorithms run in steady mode only, so the check ran in steady mode for both (new option run_suite.py --abl-steady, gates unchanged; the implicit rows add --abl-numerics '{"steady_algorithm": "implicit_projection"}', and the recipe row also "pressure_relative_tolerance": 0.1, "max_time_step_s": 100):

ModeStepsSolver sDrift U / k / ε (H..5H)Floors
explicit270027.20.262% / 0.810% / 3.427%0
implicit_projection4005.00.263% / 0.806% / 3.437%0
implicit_projection, recipe, final code (run_suite.py --abl-steady)3001.40.263% / 0.806% / 3.437%0

Tracer and grids (P5c, P5d)

Development canyon with its line-source tracer, case settings:

ModeStepsSolver sRelative budget defectMax receptor difference
explicit380042.07.5e-16—
implicit_projection130010.96.1e-142.2e-7

Performance canyons (cases/performance/canyon-27k.json, 36×32×24, and canyon-93k.json, 54×48×36), with the tracer:

GridMode, numericsStepsSolver sAcceptedFloorsBudget defect
27kexplicit, case settings14,4002974yes (needs more than the case’s 7,000 steps)02.3e-15
27kimplicit, case settings1,400180*yes01.9e-13
27kimplicit recipe1,00070.7yes01.1e-13
93kimplicit, case settings2,5001772*yes09.0e-14
93kimplicit recipe2,500684yes03.1e-13
27kimplicit recipe, final code (d7a9a31)1,00057.6yes01.1e-13
93kimplicit recipe, final code2,500615yes03.1e-13

* two runs shared the two cores. Implicit recipe: implicit_projection, pressure_relative_tolerance 0.1 and max_time_step_s 100, with the CFL cap of performance iteration 7 (commit 5d08fc5). At 27k the implicit receptors equal the explicit ones to 5e-7 (case settings) and 1.2e-6 (recipe), within the steady tolerances. Within the case’s own budgets (7,000 steps, 240 s) the explicit mode does not finish the 27k canyon; the implicit mode does.

Refinement: the sensor1 receptor is 2.31e-7 kg/m³ on the development grid, 5.29e-7 at 27k and 6.75e-7 at 93k in both modes. The sub-stepping changes the path, not the discrete steady state, so the refinement behavior is the explicit mode’s; the canyon is not grid-converged on these grids, which remains the open fine-grid gate of the model card.

Choices made on the development cases

  • Scalar sub-step cap 16 (solver::SCALAR_SUBSTEPS_MAX): with the final recipe, caps 4, 8, 16 and 32 reach the development canyon’s gates in 1000, 600, 400 and 400 outer iterations (4.5, 2.8, 2.4 and 3.6 s).
  • The turbulence inner solves use the momentum correction’s predeclared BiCGStab tolerance and cap (0.1, 50); one iteration per solve sufficed in most outer iterations.

Ten performance iterations after P5d: results

Date: 1 November 2026. Goal: close the remaining cost gap to OpenFOAM at matched accuracy (stage M measures it on the cavity) and make the steady RANS canyon with its tracer, the case of the dust study, cheaper. No OpenFOAM source was read or copied; the levers are standard steady-solver practice (inexact inner pressure solves, a bounded pseudo-time ramp, one cell on the homogeneous axis of a two-dimensional problem) and plain kernel work.

How the iterations were checked

  • Bit identity. Iterations 1–3, 5 and 8–10 do not change any result. A new regression (kernels_keep_their_recorded_bits, recorded at 2ffedec before the first iteration) pins the bits of the momentum right-hand side for all five momentum schemes, the laminar and RANS implicit matrices and their product, an implicit k–ε step and both scalar transport schemes, on a cavity, a masked cavity, an open channel and an open and a periodic RANS canyon. It passed unchanged after each of these iterations, as did rans_stencils_keep_their_recorded_bits, and the archived fields of the benchmark runs kept their SHA-256.
  • Changed paths. Iterations 4, 6 and 7 change the path to the steady state (or, for 6, the grid), not the steady state; their evidence is acceptance under the unchanged gates and unchanged accuracy.
  • Timing. The 2-vCPU VM is noisy (±10–50% between identical runs), so timings are medians of 3–5 alternating rounds, and kernel iterations are also compared by instruction counts of fixed-work runs (valgrind cachegrind; about a third of each count is the SHA-256 of the executable, which valgrind runs in software, and is constant).

The iterations

#CommitChangeIdentityEvidence
18334d31Flux-form momentum advection: each control-volume face flux evaluated once (center fluxes per cell, edge fluxes per face) instead of from both momentum cellsbit-identical48² cavity¹: 2.92 → 2.41 s
2ac5e33eCached same-axis neighbor faces of every face (Grid::neighbor_faces)bit-identical2.41 → 2.30 s
3874bd8cAllocation-free k and ε transport operator in the implicit turbulence solvesbit-identicalno measurable change; the turbulence step’s cost is in its residual terms
4090676bInexact inner projections for implicit_projection (recipe: pressure_relative_tolerance 0.1; the sweep accepts 0.1 or 0.01)same fixed point48² cavity: 1,536 → 270 multigrid PCG iterations, Ghia error 0.0050161 unchanged to 1e-9; development canyon: 26,947 → 3,690 IC(0) iterations in the same 500 outer iterations
5222a3c8Edge-flux faces from cached tables (Grid::edge_faces); laminar momentum skips the eddy-viscosity face meansbit-identical48² cavity, tolerance 0.1: 1.67 → 1.35 s
6906fdd4One cell on a periodic axis: two-dimensional runs; fixes the IC(0) factor for faces that join a cell to itselfspan 1 = span 2 to 1e-1024² cavity: 0.272 → 0.191 s, same 210 iterations and Ghia error
75d08fc5CFL ramp capped at 5 (was 1e6, so only max_time_step_s bounded it); recipe: non-binding max_time_step_s 100same fixed pointdevelopment canyon with tracer: 1,300 → 400 outer iterations
8875819dGhost probes evaluate a boundary branch once for both values; eddy-viscosity face means computed once per callbit-identicalcanyon, 40 iterations: 3.175e9 → 3.065e9 instructions
97f148b1Scalar transport sub-steps reuse their buffers; one division per facebit-identicaltracer recipe, 60 iterations: 5.718e9 → 5.452e9
10d7a9a31Fixed scalar transport faces gathered once per outer iteration (transport::FixedRhs)bit-identical5.452e9 → 4.994e9

¹ van Leer, implicit_projection, multigrid, 3 alternating rounds on a loaded host. Rejected on the way: a compact face-kind array (slightly more instructions); scalar sub-step caps other than 16 and CFL caps other than 5 (see the P5c/P5d results and the commit messages).

Iteration 6 found a real defect: for a face that joins a cell to itself, the IC(0) factor added a diagonal term and a self off-diagonal entry, so the preconditioner was wrong on such grids. The dense IC(0) reference test with [3, 1, 4] and [1, 3, 1] grids failed before the fix. Grids with at least two cells per axis have no such faces, so nothing else changed.

Before and after

Solver seconds on this host, medians of 3–5 alternating rounds. “Before” is 2ffedec (P5d, before iteration 1) with the stage M recipe for the cavity (van Leer, implicit_projection, multigrid, two span cells) and the case settings for the canyon (implicit_projection, pressure tolerance 1e-10, max_time_step_s 0.1). “Final” is d7a9a31 with the final recipe: pressure tolerance 0.1, max_time_step_s 100 and, for the cavity, one span cell.

CaseBeforeFinal, same settingsFinal recipeSpeed-upAccuracy
24² cavity0.47 s (210 it.)0.33 s0.069 s (180 it.)6.8×Ghia 0.005433 → 0.005427
48² cavity2.84 s (270 it.)2.29 s (300 it.)²0.49 s (300 it.)5.8×Ghia 0.005016 → 0.005012
Development canyon, flow3.69 s (500 it.)3.55 s1.55 s (400 it.)2.4×—
Development canyon, tracer10.7 s (1,300 it.)9.8 s1.99 s (400 it.)5.4×receptors to 2e-7
27k canyon, tracer180 s³ (1,400 it.)—57.6 s (1,000 it.)3.1×receptors to 1.2e-6 of explicit
93k canyon, tracer1772 s³ (2,500 it.)—615 s (2,500 it.)2.9×receptors to 1.6e-7 of the case-settings run

² The CFL cap changes the 48² path (300 instead of 270 iterations). ³ Two runs shared the two cores.

Against the explicit steady mode, which the dust study used before P5c: the development canyon with its tracer takes 42 s explicit and 2.0 s with the final recipe (21×); the 27k canyon 2,974 s and 57.6 s (52×), and the explicit mode needs twice the case’s step budget.

On this host the final recipe makes the 24² cavity 6.8× cheaper than the stage M recipe, which had a hosted native/OpenFOAM solver ratio of 0.74×; the hosted reproduction below measures 0.111×.

Hosted reproduction

Run 41361132558 (external=momentum) on branch head 639b331: GitHub runner, AMD EPYC 9V74, 4 CPUs, one solver thread per backend, the unchanged stage M protocol (shared grids 16, 24, 32, 48; one warmup and three alternating timed rounds; the OpenFOAM recipe, the audits and the screens unchanged). Native inputs: momentum_scheme=van_leer, native_span=1, native_numerics={"momentum_advection": "limited_upwind", "momentum_limiter": "van_leer", "steady_algorithm": "implicit_projection", "pressure_relative_tolerance": 0.1, "max_time_step_s": 100.0}, multigrid pressure. All rows were accepted, and the evidence archive verified all 51 sealed archives after the zip round trip.

GridNative solver sOpenFOAM solver sNative/OpenFOAMNative Ghia errorOpenFOAM Ghia error
16²0.02440.2640.092×0.02430.0188
24²0.06980.6280.111×0.005430.00897
32²0.1421.3990.101×0.003660.00870
48²0.4395.4150.081×0.005010.00708

Workflow medians (with meshing, sampling and audits): 0.091/0.842, 0.142/1.200, 0.345/2.013 and 0.551/6.095 s. At the 0.01 target (24² for both) native takes 0.111× OpenFOAM’s solver time and 0.119× its workflow time, against 0.74× and 0.45× in the stage M run with the earlier recipe and code (another runner model; each ratio is a same-runner pairing). The native 96² reference with the same numerics was accepted after 570 outer iterations and 3.39 s (48.5 s before), Ghia error 0.00505, self-convergence orders 2.46 (L1), 2.42 (L2) and 2.21 (max). The default controls (cavity, transient Poiseuille, masked canyon) are byte-identical to main (6d33850) with identical work, and the van Leer momentum fixtures repeat the stage V values.

Scope as in stage M: a laminar two-dimensional cavity; both backends now compute one span cell; the stopping rules differ (native: the unchanged assess gates; OpenFOAM: residualControl 1e-7). The canyon has no OpenFOAM counterpart in this repository.

Native solver and OpenFOAM on the lid-driven cavity: measured cost

Both backends solve the supported Re=100 lid-driven cavity on the same machine, one solver thread each, on two hosts. The first host ran an earlier script of the same procedure; the second, a GitHub runner, ran validation/compare_backends.py with the current repository. This compares configured, accepted workflows; it is not a fixed operation count or a ranking of Rust against C++.

Result

On this case OpenFOAM is faster and closer to the Ghia reference. Native steady mode costs about half as much as the native transient run to 30 s, but OpenFOAM’s whole workflow is still 4.7–5.5 times faster than native steady mode on the two hosts, and its solver process about 9 times faster than the native steady solver.

First host: AMD EPYC 9V74 virtual machine, Linux x86_64, Python 3.12. One warmup per method, then the six orders of the three methods once each.

ConfigurationWorkflow median (range), sSolver median, sSteps or iterationsCellsMaximum centerline u error / lid speed
OpenFOAM steady SIMPLE/GAMG1.2622 (1.2091–1.5991)0.77646965760.00896632
Native steady6.9443 (6.8714–7.0333)6.9060201011520.02756134
Native transient to 30 s13.9984 (13.7937–14.0767)13.9303409311520.02754881
Native / OpenFOAMWorkflow, ratio of mediansWorkflow, median within roundsSolver, ratio of medians
Native steady5.5025.4558.895
Native transient11.09010.98917.942

GitHub runner: AMD EPYC 9V45, 4 CPUs, ubuntu-24.04, Python 3.12, workflow run 41195406078. One warmup per method, then the six orders twice (12 rounds).

ConfigurationWorkflow median (range), sSolver median, sSteps or iterationsCellsMaximum centerline u error / lid speed
OpenFOAM steady SIMPLE/GAMG0.89909 (0.89281–1.0084)0.472096965760.00896632
Native steady4.2183 (4.1309–4.3696)4.1921201011520.0275613
Native transient to 30 s8.7101 (8.4174–8.8005)8.6833409311520.0275488
Native / OpenFOAMWorkflow, ratio of mediansWorkflow, median within roundsSolver, ratio of medians
Native steady4.6924.6758.88
Native transient9.6889.54918.39

The solver ratios agree closely between the hosts (8.9 and 8.9 for steady, 17.9 and 18.4 for transient). The workflow ratios differ more (5.5 and 4.7), because OpenFOAM’s fixed workflow overhead, about 0.4–0.5 s, is a larger share of its shorter workflow.

All runs on both hosts passed their numerical checks, their independent audits and the frozen 0.06 Ghia screen, and each method repeated its work count and sampled profile exactly in every round. The first host’s native build has a different source identity from the current repository, but its native fields are byte-identical to those of the current build (checked separately on a third machine), so both hosts measure the same native numerics.

What is held fixed and what differs

Both solve a unit square cavity with lid speed 1 m/s, viscosity 0.01 m²/s (Re=100), zero initial velocity and 24×24 cells in the flow plane. The native case is x/z with two periodic span cells (24×2×24, 1152 cells), because native validation then rejected a one-cell axis (periodic axes accept one cell since performance iteration 6; compare_backends.py --grid-sweep --native-span 1); OpenFOAM uses one empty span cell (24×24×1, 576 cells, 0.1 m deep). Both are nominally two-dimensional, but the native solver computes both span layers.

OpenFOAMNative steadyNative transient
Casegenerated cavity recipe, unchangedcases/verification/lid-cavity.json, one thread, run.mode = steadythe same case, one thread
Algorithmsteady SIMPLE (consistent), GAMG pressure, bounded linear-upwind momentumexplicit SSPRK2 pseudo-time steps with two pressure projections per step (PCG with IC(0)), donor-cell momentumthe same steps, in physical time
Stopping1e-7 initial residuals plus independent stored-flux checksthe existing momentum and monitor gates (momentum residual 8.85e-6 at 2010 steps, pseudo-time 14.81 s)the end time of 30 s (momentum residual 3.88e-10)
Ghia error0.00900.02760.0275

The residual definitions of the two backends are not interchangeable. The Ghia profile is a numerical reference, not an experiment, and the error is one sampled velocity component, not a full-field assessment.

Where the time goes

Per cell and step, native costs about 1.5 times as much as OpenFOAM per cell and SIMPLE iteration on both hosts. Most of the factor of about 9 comes from how many steps the native method needs and from its second span layer:

Solver timeFirst hostGitHub runner
OpenFOAM, per SIMPLE iteration1.12 ms0.68 ms
Native steady, per step3.44 ms2.09 ms
OpenFOAM, per cell and iteration1.94 µs1.18 µs
Native steady, per cell and step2.98 µs1.81 µs

Native steady takes 2.9 times as many steps as OpenFOAM takes SIMPLE iterations, on twice the cells, and each native step runs about 102 PCG iterations in its two projections (204,850 over 2010 steps). The OpenFOAM time includes process start-up and file input and output, so its per-iteration cost is overstated here. This decomposition explains the measured numbers on this case; it is not a measured attribution of what a different algorithm would save.

Timing definitions

  • Workflow time encloses case preparation, the solve, the independent audit and the centerline evaluation. For OpenFOAM that includes copying the case, the runtime check (which hashes the runtime’s binaries and libraries), blockMesh, checkMesh, foamRun, sampling and archive verification, each child polled every 50 ms. For native it includes writing the case, the CLI run and its output, check_fields.py and reading the fields. Installation and compilation are excluded.
  • Solver time is the foamRun process for OpenFOAM and the native solver’s own timer (elapsed_s, without process start) for native. The two are similar in scope but not identical.
  • One unscored warmup per method precedes the timed rounds; every order of the three methods is used, so each method runs first, second and last equally often. The runs are serial with one solver thread and BLAS and OpenMP limited to one thread. No CPU frequency pinning or host isolation was established.

Consequences

  1. There is no measured native speed advantage over OpenFOAM on this shared case. The native performance results compare the native solver with its own previous version, not with OpenFOAM.
  2. The native cost is dominated by the number of explicit pseudo-time steps and by the pressure solve in each. A steady algorithm and a multigrid pressure solver or preconditioner are the natural next native experiments; this comparison does not measure what they would save.
  3. Ranking the backends for the urban canyon needs the same 3D canyon with compatible physical assumptions, accepted fields, cost at comparable observable error and complete campaigns. The backstep and native canyon results solve different problems and cannot supply that ranking.
  4. Large-case scaling and memory are not measured head to head. OpenFOAM supports MPI domain decomposition, but the CFD-craft adapter runs it serially; the native solver uses shared-memory threads on uniform grids. Nothing about multi-core speedups follows from these single-thread runs.

Reproduce

With the pinned runtime installed as in guide chapter 15 and a release build:

cargo build --release --locked
python validation/compare_backends.py --foam-root ROOT --output runs/backend-comparison

--repeats N runs the six orders N times (default 1). A manual CI dispatch with external=comparison runs two passes on a GitHub runner, publishes the medians and ratios as notices and uploads the report. Exit 0 means every run passed and the comparison completed; any failed run, changed input or unrepeated result exits 1 with a coded CFD-B002 comparison.<field> error.

Native/OpenFOAM gap-closing baseline

Measured 31 October 2026 on the code of 6759996 plus the profiling and sweep tools. The native numerics measured are IC(0)-PCG pressure, donor-cell momentum and SSPRK2 steps; profiling leaves their results unchanged.

Protocol

One hosted Linux machine, AMD EPYC 9V74 80-Core Processor (full hardware/cgroup record retained), rustc 1.99.1, Python 3.12.14, Foundation-13 package 20260407. Each solve uses one thread. The container exposes 9 logical CPUs with an 8-CPU quota and 8 GiB memory limit. Runs are serial; affinity and CPU frequency are not pinned. Compilation/installation are excluded.

The accuracy sweep uses one unscored warmup and three timed repetitions per configuration, alternating backend order within each shared-grid block. Native 12² is a diagnostic block. Native has two periodic span cells; OpenFOAM has one empty span cell. The same Ghia stations and existing 0.06 screen are retained. The 0.01 development target is additional. Every row, including a separate deliberately incomplete campaign, is retained.

Same-host accuracy and cost

MethodFlow-plane gridSolver median, sWorkflow median, sSteps / outer iterationsGhia errorAll timed rows accepted
native-steady12²0.31640.38256300.05968212True
native-steady24²7.24197.316520100.02756134True
openfoam-steady24²0.77801.48916960.00896632True
native-steady48²172.7545172.839063900.01695144True
openfoam-steady48²5.88806.790821320.00707998True

OpenFOAM reaches error ≤0.01 at 24². Native does not reach it on the tested 12²/24²/48² grids. Its cost at the target and the cross-backend equal-accuracy ratio are therefore unavailable. No target crossing is extrapolated. The cavity is a numerical reference, not an experimental validation of urban dispersion.

Workflow time includes preparation, a bounded child process, archive checks and centerline sampling. Native solver time is its elapsed_s; OpenFOAM solver time encloses foamRun startup, case I/O and solve. GNU-time RSS means maximum individual process RSS including waited descendants, not simultaneous aggregate memory. Complete timers, ranges, RSS, order, inputs and producer hashes accompany the report.

The original three-method comparator was also rerun:

MethodWorkflow median, sSolver median, sWork
openfoam-steady1.29110.7289696
native-steady7.35977.31642010
native-transient14.732614.68804093

That experiment has one warmup per method and all six method orders once. Its workflow timer has a different scope from the new sweep, so use each named experiment within its own protocol.

Hosted reproduction

The manual external=accuracy job ran the same sweep on a GitHub runner (AMD EPYC 9V74, 4 CPUs, ubuntu-24.04). Every Ghia error equals the recorded value above. With the recorded 180 s native budget (run 41216664708), native 48² stopped at the wall-time limit in all three timed rounds; those rows are retained as unaccepted. The job therefore declares 600 s per native run, with unchanged gates (run 41218093307); all 20 rows were accepted:

MethodGridSolver median, sWorkflow median, sGhia error
native-steady12²0.38800.48360.0596821
native-steady24²8.26158.35960.0275613
openfoam-steady24²0.83951.54760.00896632
native-steady48²200.27200.360.0169514
openfoam-steady48²7.01497.95680.00707998

The conclusion is the same: OpenFOAM reaches 0.01 at 24² and native does not on the tested grids. The uploaded evidence zip kept its directory entries, and all 20 archives verified in its extracted copy.

Actual phase attribution

The following are medians of per-run wall-time fractions over the profiled timed controls. Pressure projection includes its linear solve/setup subphases; it is not added to those subphases again.

CasePressure projection shareMomentum RHS shareScalar transport share
cavity2477.92%19.75%0.00%
scalar27k0.00%0.00%62.19%
canyon27k84.34%10.91%0.70%

One separately profiled 48² run retained 6390 steps and 1262035 pressure iterations, with assessment steady_discrete_solution. Its pressure-projection share was 88.34%; attempted PCG work was 1262035, and the profiler recorded 1274815 fine-operator applications, including 12780 independent true-residual checks. This one phase observation is not a repeated timing estimate.

Instrumentation cost and exact-state checks

The merged baseline, candidate plain command and candidate profile command were run in recorded orders: one warmup per mode, five timed rounds for the cavity and two timed rounds for each fixed-work control. Every returned state was byte-identical across all three builds/modes within each case; independent field audits passed. There is no performance threshold or solver-speedup claim.

CaseProfile/plain solver ratio, paired medianCandidate plain/baseline solver ratio, paired medianProfile/plain process ratio, paired median
cavity240.97771.03130.9808
scalar27k0.93721.11290.9995
canyon27k1.00021.02081.0049

The scalar and canyon controls use fixed work and can end at their iteration limits; their independent audit is distinct from steady convergence. GNU time was unavailable on this host, so RSS is retained as null rather than estimated from other runs. Ratios above 1 mean the numerator cost more. They include timing noise and order/host effects; inspect the retained ranges. Short prescribed-flow controls are particularly sensitive to fixed process overhead. Profiling near a deadline can change the final retained step.

Incomplete and rejected observations

A deliberate one-step native / 50-iteration OpenFOAM sweep completed with unaccepted rows and exit 2. Its numerical, independent-check and reference statuses remain separate, and no configuration is promoted into cost-at-target results. A failed-pressure test records attempted work even though no step commits.

The final sweep freezes and checks its input/producer identities before and after each row. A development campaign with a changed producer was rejected; its report is retained separately and supplies no timing claim here.

Archives with an empty recorded time directory

In three of the four 48² OpenFOAM runs (the timed rounds, not the warmup), the summary written at sealing lists an old time directory, 250 or 500, that holds no files; the final fields are at iteration 2132 in every run. This is the anomaly described in the archive investigation. The sweep verified each archive on the measuring host, where the directory existed. The evidence copy kept files only, so these three archives fail openfoam_backend.py report after restoration and verify again once the empty directories are recreated. All 72 native archives, the other 15 OpenFOAM archives and the 13 profile envelopes in the evidence verify as copied. The timing and Ghia-error results of the three runs come from their final fields and are unaffected. Use validation/archive_evidence.py to transfer such evidence with its directory entries.

Next numerical iteration

(P1 and the later stages are done since; see the gap status.) At the time: proceed to P1: a fixed linear symmetric multigrid preconditioner for the unchanged pressure equation, initially on supported unmasked grids. Retain IC(0), fine-operator/true-residual checks and independent topology/projection references. Measure setup, repeated solves, memory and accepted-workflow cost. Momentum accuracy remains a separate high-priority stage because pressure throughput alone cannot establish the missing 0.01 accuracy target.

See the profiling guide, iteration plan and earlier backend comparison.

Matched-accuracy measurement against OpenFOAM (stage M)

Date: 1 November 2026. Protocol: stage M of the accuracy and steady-solver plan, run through the external=momentum CI selection, which was declared for Stage V and extended with the native_numerics and momentum_scheme inputs.

Hosted run

Run 41345659321 on branch head 4973d3c: GitHub runner, Intel Xeon Platinum 8370C, 4 CPUs, one solver thread for both backends. Inputs: momentum_scheme=van_leer, native_numerics={"momentum_advection": "limited_upwind", "momentum_limiter": "van_leer", "steady_algorithm": "implicit_projection"}. Unchanged from Stage V: the shared grids 16, 24, 32 and 48 for both backends, one warmup plus three timed rounds alternating the backends, native budgets 600 s and 20,000 steps, native multigrid pressure, the OpenFOAM recipe (3,000 iterations, 180 s), the archive and field audits, the 0.06 Ghia screen and the 0.01 target.

All 32 rows were accepted, and the evidence archive verified all 51 sealed archives after the zip round trip.

GridNative solver sOpenFOAM solver sNative/OpenFOAMNative Ghia errorOpenFOAM Ghia error
16²0.2360.3200.74×0.02430.0188
24²0.5490.7430.74×0.005430.00897
32²0.9671.6120.60×0.003650.00870
48²3.0416.0020.51×0.005020.00708

Medians of three rounds. Workflow medians (including meshing, sampling and audits) are 0.348/0.994 s, 0.654/1.453 s, 1.060/2.316 s and 3.180/6.808 s.

Both backends first reach the 0.01 target at 24². There the native solver takes 0.74× OpenFOAM’s solver time and 0.45× its workflow time (native_over_openfoam_at_target), and is more accurate (0.0054 against 0.0090). On every grid from 24² up, native is both faster and more accurate. At 16² native is faster but less accurate than OpenFOAM, and neither reaches the target.

How the gap closed

The same protocol with the earlier default numerics (Stage V, hosted run 41302658721, another runner) gave a native/OpenFOAM solver ratio of 6.98× at 24² with native missing the target on every shared grid; native needed 96² and about 826 s to reach 0.01. The changes, each opt-in:

ChangeEffect on the 24² cavity (local host)
P3a: limited_upwind/van_leer momentum advectionGhia error 0.0276 → 0.0054; the target is reached at 24² instead of 96²
P5a: implicit_projection steady algorithm2,460 explicit steps → 210 outer iterations; solver time 9.4 → 0.51 s

The explicit mode with the same scheme isolates the two levers. In the accuracy sweep of run 41346827479 (external=accuracy, native_numerics={"momentum_advection": "limited_upwind", "momentum_limiter": "van_leer"}, branch head 4973d3c, AMD EPYC 7763, 4 CPUs, three rounds), van Leer with the explicit steady mode also first reaches the target at 24² (Ghia error 0.00544, OpenFOAM 0.00897), but its solver time there is 11.19 s against OpenFOAM’s 0.844 s, 13.25× (workflow 7.47×). At 48² it takes 136.5 s against 6.48 s. So P3a moves the target to the coarse grid, and P5a removes the cost of the explicit pseudo-time on it.

After the performance iterations

Run 41361132558 repeats the protocol with the final implicit recipe (pressure tolerance 0.1, non-binding max_time_step_s, one span cell; see the performance iterations) on an AMD EPYC 9V74 runner. All rows were accepted. At 24² native takes 0.0698 s against OpenFOAM’s 0.628 s (0.111×), workflow 0.119×, with Ghia error 0.00543 against 0.00897; 0.092×, 0.101× and 0.081× at 16², 32² and 48². The 96² reference took 570 outer iterations and 3.39 s. Default controls stayed byte-identical to main.

Other results of the run

  • Momentum fixtures (van Leer): translating-vortex orders 2.159 / 2.062 / 1.761 (L1 / L2 / max), momentum drift at most 5.7e-17 per run, time difference 2.0e-4 of the spatial error, transverse step range 0.0009–0.9991 with no new extrema. These equal the local values.
  • 96² reference with the same numerics: accepted after 990 outer iterations and 48.5 s (the explicit van Leer reference needed 22,830 steps and 1,742 s locally), Ghia error 0.00505. Self-convergence orders against it: 2.45 (L1), 2.42 (L2), 2.21 (max).
  • Default controls: the cavity, a transient Poiseuille run and a masked canyon are byte-identical to main (6d33850) with identical work.

Scope

The cavity is laminar and two-dimensional. The ratio describes this case, these recipes and this runner: in run 41345659321 native computed two span cells and OpenFOAM one (in run 41361132558 both compute one), and the two stopping rules differ (native: the unchanged assess gates with three stable monitor windows; OpenFOAM: residualControl 1e-7). It does not transfer to the RANS canyon: implicit_projection now runs it (results), but there is no OpenFOAM canyon recipe to compare with. Defaults are unchanged: donor-cell and the explicit mode remain the default numerics until a separate, announced decision.

Performance gap: current state and remaining stages

Masked multigrid (P2b) is implemented and its setup and reuse costs are recorded (P2c), with independent topology/nullspace/SPD/reference tests. The coupled urban throughput gate remains open; see the urban features record. Historical measurements below retain their original implementation and scope.

After P5c, P5d and ten performance iterations (1 November 2026)

The hosted paired sweep with the final implicit recipe (run 41361132558, performance iterations) accepted every row. At the 0.01 Ghia target (24² for both) native takes 0.111× OpenFOAM’s solver time (0.0698 against 0.628 s) and 0.119× its workflow time, with error 0.0054 against 0.0090; on every shared grid from 16² to 48² native solves in 0.08–0.11× OpenFOAM’s time. The steady RANS canyon with its tracer now runs with implicit_projection (P5c, P5d; results): the 27k canyon in 57.6 s on one 2.1 GHz thread, 52× faster than the explicit mode, and the 93k canyon in 615 s. There is no OpenFOAM canyon recipe to compare it with.

Open: defaults remain donor-cell and explicit until an announced decision; the predeclared P5c tightening statistic failed for U on one decade (recorded); the canyon is not grid-converged at 93k; masked multigrid (P2b) would cut the canyon’s remaining IC(0) pressure work.

Matched accuracy after P3a and P5a (1 November 2026)

With opt-in limited_upwind/van_leer momentum advection (P3a) and the implicit_projection steady algorithm (P5a), the hosted paired sweep (matched-accuracy results, run 41345659321) accepted all 32 rows. Both backends first reach 0.01 Ghia error at 24², where native takes 0.74× OpenFOAM’s solver time (0.549 against 0.743 s) and 0.45× its workflow time, with error 0.0054 against 0.0090. From 24² up native is faster and more accurate on every shared grid (0.51× solver time at 48²). Before these stages, native needed 96² and about 826 s to reach the target.

Defaults are unchanged. Open work at that time: the implicit algorithm for RANS (P5c) and scalar transport (P5d), which the canyon needs (both done since; see the section above), and a decision on defaults. Details: second-order momentum and implicit steady results.

Stage V accuracy baseline (1 November 2026)

Stage V, the first stage of the accuracy/steady-solver plan, adds verification without changing production numerics. Read the Stage V results for the exact protocol and retained failures. The recorded 16/24/32/48 sweep passed all 32 rows at final collection, and its evidence archive verified all 51 sealed archives after a zip round trip. The hosted reproduction repeated the sweep on a GitHub runner with the same errors and all rows accepted, at native/OpenFOAM solver ratios of 3.50–10.99×.

GridNative Ghia errorOpenFOAM Ghia errorNative steps / OpenFOAM iterationsNative solver sOpenFOAM solver sNative/OpenFOAM
16²0.038024530.018753671020 / 3751.0700.3143.41×
24²0.027561340.008966322010 / 6965.2020.7267.16×
32²0.023514480.008703803240 / 110215.0391.49310.07×
48²0.016951440.007079986390 / 213271.6136.17911.59×

These configured-recipe timings (recording host, Rust 1.88.0) do not measure a change in solver performance. The donor-cell operator order is 0.997; the translating vortex L1 order is 0.974, with independently negligible time error.

A separately budgeted 96² same-scheme reference reaches Ghia error 0.00921. On the GitHub runner a cold solve was accepted at 21390 steps after 825.9 s of solver time. On the recording host the cold solve converged but failed during archive writing, and an accepted checkpoint continuation supplied the reference after about 1076 s of accumulated solver work; both are documented. Neither is a repeated cost-at-target timing sample. The shared paired sweep still has no native qualifying grid, so its formal native_over_openfoam_at_target remains null. Native reaches the accuracy objective in this diagnostic, but the cost deficit remains very large.

Next: P3a conservative second-order laminar advection, then P4 implicit viscous correction and P5a implicit steady projection. P5b is conditional; P3b/P5c extend open boundaries/RANS and P5d adds scalar transport. M repeats matched-accuracy measurement after each stage. P2b/P2c remain separate pressure work. No defensible percentage of the full gap closed follows from this verification-only stage.

Pressure stage P2a

Stage P2a, anisotropic unmasked pressure multigrid, builds on main 2ddf17d (merged PR #13). Fixed symmetric principal line/small-plane solves and stiff-axis semicoarsening replace point smoothing only where the spacing policy selects them. Default IC(0), isotropic point arithmetic, the fine pressure operator and independent numerical gates are retained. See the implementation design, plan and measured anisotropy results.

Pressure acceleration reduces cost per projection. It does not improve the donor-cell momentum discretization, increase the explicit stability limit, reduce the number of pseudo-time steps by design, or establish physical model validity. The prescribed-flow optimization worker bypasses pressure, so its fitness evaluations gain nothing directly from this change.

Same-host comparison, 31 October 2026

Fresh same-host, one-thread comparison of opt-in native multigrid and the pinned OpenFOAM Foundation 13 SIMPLEC/GAMG cavity recipe, measured 2026-10-31. One warmup plus three alternating timed pairs at 24²/48²; a native 12² diagnostic is retained. All 20 child records passed numerical/archive/field checks and the existing 0.06 Ghia screen. This screen is distinct from the 0.01 accuracy objective. Native limits are 600 s/20000 steps; OpenFOAM limits are 3000 iterations/180 s. Rust stable 1.99.1; AMD EPYC 9V74, one solver thread, 8-CPU/8-GiB cgroup. Native phase profiling is enabled. Pressure uses its unchanged case tolerance (1e-10); the 1e-14 kernel tolerance is not imposed on flow cases.

Flow-plane gridNative solver sOpenFOAM solver sNative/OpenFOAM solverNative workflow sOpenFOAM workflow sNative/OpenFOAM workflow
24²4.7320.7276.51×4.7991.3433.57×
48²65.0035.57011.67×65.1066.33610.28×

These are configured-recipe ratios on the same flow-plane grid, not identical algorithms/cell counts or matched-accuracy results. Native retains two span cells (1152/4608 total); OpenFOAM’s 2D empty-boundary recipe has one (576/2304). Native solver time is elapsed_s; OpenFOAM solver time is the recorded solver process wall time. Workflow includes startup, preparation/output and independent checking. Native stores and evolves the extra span layer. Memory medians are about 20.8/25.3 MiB native versus 115.1/116.4 MiB OpenFOAM at 24²/48², complete process RSS measured by GNU time; these are neither peak campaign memory nor identical-mesh memory ratios.

Flow-plane gridNative Ghia errorOpenFOAM Ghia errorNative steps / OpenFOAM iterationsReaches 0.01: native / OpenFOAM
24²0.027561340.008966322010 / 696no / yes
48²0.016951440.007079986390 / 2132no / yes

Error is the frozen maximum absolute centerline-velocity difference at Ghia Re=100 stations, normalized by lid speed. OpenFOAM reaches 0.01 already at 24² (0.727 s solver, 1.343 s workflow). Native has not reached it through 48². Therefore the report’s native_over_openfoam_at_target is null, and a finite equal-accuracy speed ratio cannot be claimed.

The standard 24²/48² cavities retain point arithmetic and the previous errors and stopping steps. P2a does not close their isotropic gap; its benefit is the newly supported anisotropic pressure regime. In the separate 64x2x12 anisotropic coupled test, the candidate is 1.41× faster than IC(0) for accepted steady convergence (23.632 -> 16.751 s), and 1.64× for transient interval completion (1.546 -> 0.942 s). That coarse vertical grid misses the 0.01 target too. Kernel gains of up to 38.15× over old point MG must not be presented as whole-simulator or OpenFOAM speedups.

To reproduce, build release/locked and run python validation/compare_backends.py --grid-sweep --native-pressure-preconditioner multigrid --levels 1 2 --sweep-rounds 3 --native-wall-s 600 --native-max-steps 20000 --foam-iterations 3000 --timeout-s 180 --accuracy-target 0.01 --foam-root PATH --output NEW_DIR. The raw report stores the frozen plan, exact inputs, builds, runtime/executable identities, all rows and profiles. Foundation package openfoam13_20260407_amd64.deb has SHA-256 9a491909372dd3de79d6fa8980d7fe6c9c1624da49cd14d61675ecacf4fdbcc2.

These are work packages; each may take several changes. P0 instrumentation, P1 isotropic multigrid, P2a, P3 (P3a/P3b), P4, P5 (P5a, P5c, P5d; P5b was not needed) and the matched-accuracy measurement M are complete; their rows are kept below as the record of what was asked. Open: P2b, P2c, P6 and a decision on defaults.

Next stageScopeEvidence required before calling it complete
P2b: masked multigridComponent-preserving aggregation/interpolation; one nullspace/gauge per sealed component; anchored components; thin passages and disconnected pockets. Extend the current rejection only with verified supportIndependent masked -DG/Galerkin/reference solves; full preconditioner symmetry/positive-energy tests; no merging across solid barriers; changed coefficients/topology/cancellation/restart controls. Accepted 27k/93k canyon comparisons, field equivalence and an actual coupled benefit; preserve budget failures
P2c: setup and hierarchy costProfile cold hierarchy construction and coarse operator growth. Reduce assembly/scratch/transfer overhead where measured, retaining the fixed SPD cycleCold/reused work and memory, operator/grid complexity, exact field/reference controls. Require an end-to-end gain for representative repeated and one-off workloads; iteration counts alone are insufficient
P3: momentum accuracy per cost (done)Independently verified higher-order momentum advection with explicit boundary/conservation treatment. Keep a selectable baseline and frozen physical modelManufactured spatial/temporal order, periodic and wall/outlet conservation, bounded stability regime, Ghia cost-versus-error refinement. A native run must actually reach the declared 0.01 target before a matched-accuracy ratio can be reported
P4: implicit diffusion decision (done)Bounded laminar implicit momentum diffusion trial after profiling its attainable benefit. Treat turbulent/scalar extensions separatelyIndependent diffusion/time-order tests, boundary and energy checks, linear-solver residuals, accepted coupled cost at equal error. The earlier approximately 1.68 stability-headroom estimate is a ceiling under assumptions, not a promised speedup; stop if overhead removes the benefit
P5: a dedicated steady algorithm (done)Reduce explicit pseudo-time work with a documented steady momentum/pressure coupling; maintain a consistent residual and fixed pointIndependent steady equation residuals, conservation and gauge checks, baseline-equivalent converged fields, cavity grid/error sweep and masked/RANS controls. Compare complete convergence, not cost per outer iteration
P6: canyon and optimization payoffReplay representative canyon and optimizer campaigns using experiment-craft/optimization-jobs, frozen budgets, cached converged flows and held-out scenarios where appropriateAccepted 27k/93k refinement, model-card and empty-ABL gates, reproducible worker/job identities and failed jobs, budget-matched best-so-far outcomes and fine-grid replay. Experimental-data acquisition/model qualification remains a separate prerequisite for physical claims

P3–P5 were done before P2b, as recommended, because the accuracy deficit was visible on unmasked cavities; the cost-at-equal-accuracy comparison is now reported. The recommended next pressure stage is P2b.

All listed CPU implementation and small/medium validation work can run in cloud CI; many-core and GPU studies remain lower priority. The opt-in external=anisotropy selector runs the hosted anisotropy campaign; its GitHub run is recorded in the anisotropy results.

What parity would mean

Use the same physical problem, domain, boundary conditions and declared error objective; independently accepted fields; repeatable complete-run time and memory on the same host. Report setup, solver and outer workflow separately. The native steady algorithm (explicit SSPRK2 by default, opt-in implicit_projection) and the pinned OpenFOAM Foundation 13 SIMPLEC/GAMG recipe use different discrete schemes and stopping norms. A same-grid configured timing ratio describes those recipes. A matched-accuracy ratio additionally requires both methods to reach the error target. Neither is experimental validation of urban dispersion.

Repeated matched-accuracy costs on the cavity now exist (runs 41345659321 and 41361132558); they describe the laminar cavity and these recipes, not the canyon, for which there is no OpenFOAM recipe. Pressure-kernel speedups and coarse-grid throughput retain their own scope.

Recorded external-backend results

These numbers were produced by the commands below. The implementation files had the SHA-256 identities listed at the end. The run used OpenFOAM Foundation 13 package 20260407 (build 13-441953dfbb42, serial, f64, 32-bit labels) on a GitHub-hosted ubuntu-24.04 runner with four cores of an AMD EPYC 9V45, using Python 3.12. The external-backend job of the CI workflow runs exactly these commands on manual dispatch. Rerun them and read the reports rather than treating these values as targets; wall times and the iterations reached within a time budget depend on the machine.

The cavity comparison passes. The backstep does not pass its numerical gate: the coarse solve stalls, and the finer meshes time out. Its measurement screen is therefore not assessed. Nothing here qualifies the native canyon model or passive-gas transport.

python integrations/install_openfoam13.py --output runs/openfoam13
python tutorials/external_cfd.py --preset study --timeout-s 300 \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 \
  --output runs/external-study

Cavity: native and OpenFOAM against Ghia

Re=100. The native case advances to 30 s; OpenFOAM solves the steady equations and converged in 696 iterations. Ghia et al. is a numerical reference, not an experiment. OpenFOAM’s vertical axis is y, the native one z.

ComparisonMaximum error / lid speedTarget
Native versus Ghia0.02754880.06
OpenFOAM versus Ghia0.008966320.06
Native versus OpenFOAM at the Ghia stations0.03117050.06

Backstep: OpenFOAM against Driver–Seegmiller measurements

The raw TMR measurements are fetched with frozen SHA-256 identities. The x/H=-4 profile defines the inlet; the 112 downstream velocity samples and 17 lower-wall Cf values are evaluation data. No case parameter is fitted to them.

Numerical status, level 1 (22,656 cells): all 6000 iterations ran in 165 s, with no convergence report. The final pressure initial residual is 1.19e-3, against the gate of 1e-7. Over the last 600 iterations its median is 1.492e-3, against 1.488e-3 over the 600 before: the solve is stalled, not slowly converging. Local continuity and the stored boundary-flux imbalance are small, but every pressure solve makes them small, so they do not show a steady solution.

The first lower-wall cell centre lies at y+ 13 (median; range 2.4–16.7) in the scored region 1 < x/H < 12. That is the buffer layer, where the k-based wall function switches.

Metrics at the final iterate. These describe one iterate of a stalled solve, not a solution. They carry no evidential weight, and the measurement screen is not assessed.

x/HSamplesRMSE U/UrefBelow y/H=2Maximum errorNo-step predictor RMSETarget
1280.04670.05710.1390.06750.10
4280.06540.08040.1430.1790.10
6280.09270.1150.1710.2370.10
10280.09220.1130.1800.3220.10

The no-step predictor is the inlet profile above y/H=1 and zero below. At x/H=1 it scores 0.0675, inside the 0.10 target, so that target does not discriminate there. Below y/H=2, the shear layer and recovery region, the errors at x/H=6 and 10 exceed the target; the outer flow, which is easy to match, lowers the full-profile RMSE.

Lower-wall Cf RMSE is 0.000491 against a target of 0.001; Cf=0 everywhere would score 0.00145. Predicted reattachment is 6.4505 H against a measured 6.26 ± 0.10 H. The 0.19 H error is inside the 0.75 H screening target but outside the reported experimental uncertainty. The profile file supplies no mean-U uncertainty.

Mesh levels

LevelCellsExecutionIterations started in 300 sNumerically accepted
122,656completed6000no (stalled)
290,624timeout2192no
3203,904timeout854no

Levels 2 and 3 reached about 24 % and 9 % of their 6000 iterations; finishing them needs roughly 20 and 55 minutes of serial time. Their final iteration was not written, so they are marked not evaluable rather than given a score. With no two accepted levels there is no mesh sensitivity and no GCI.

Since refinement moves the first cell toward y+ 1–10, a converged series would also cross wall-treatment regimes. A wall-resolved or wall-function-consistent mesh is needed before the series can be interpreted; the wall-resolved results record such a recipe.

Earlier configurations, all failed

Before the recorded configuration, the level-1 backstep was run with four recipes. All ended without numerical acceptance:

RecipeIterationsFinal p residualOutcome
130006.0e-3gate not reached (CFD-X007)
260001.25e-3gate not reached (CFD-X007)
3, first-order momentum advection——timeout at 600 s (CFD-X004)
4, the recorded configuration60001.19e-3gate not reached (CFD-X007)

Earlier runs of the recorded configuration gave the same level-1 metrics and cavity errors to the digits shown here; how far levels 2 and 3 get in 300 s depends on the runner. At revisions of the backend and case generator that generate the same dictionaries, they reached 1418/554, 1456/572 and 1443/568 iterations on runners with an AMD EPYC 7763 (level 1 in 265, 260 and 266 s) and 1672/663 on an AMD EPYC 9V74 (224 s); still earlier runs, on another EPYC 7763 runner and on an eight-core cloud machine, reached 1458/570 and 1406/522.

What is needed next

The legacy stall persists with SIMPLEC pressure relaxation 1 as well as 0.2; in that control its largest late changes lie in wall-function cells near the switch point, y+ about 11 (wall-resolved results). A wall-resolved recipe converges at level 1 there. The next steps are:

  • an accepted mesh series of the wall-resolved recipe;
  • a continuous wall-function package as a one-change test of the legacy stall;
  • inlet-turbulence, inlet-profile and model sensitivity;
  • justified screening targets.

The native wall roughness and throughput tasks, measured canyon concentrations and an external passive-scalar comparison are separate work. No general urban-model validation or Rust performance advantage is claimed.

Reproduction: guide chapter 16. Assumptions: external model card.

Implementation identities (SHA-256)

FileSHA-256
integrations/openfoam_backend.py1f733f86f08acfe5d87b514678c67ec718ce7b72cb3019779ded7405a7c91969
integrations/openfoam_cases.pyf0e79c2e8054884c56e38e740b8dcc5708134fb44fbbe379ca6ed22ec6a38860
validation/backstep_data.py736281b80881ffb8c3773fb54b0288245d6a92352bcd42ecd1eac376754d964d
validation/compare_backstep.py5141c2e7e9b22850e6a7143dab21dcb28002c527740257c1097c569e0d9a4a3e
validation/audit_openfoam_mesh.py9274c2151328ea0fbde8b083eb184b4d2b36767f4d5d514907735678b0d77cd1
tutorials/external_cfd.py63512ea458ba17d09791e80886a25f52bd54749236d4cccb0914c08a38b63a6e

Recorded wall-resolved backstep results

These results cover the wall-resolved Driver–Seegmiller backstep recipes and the independent Cartesian audit. The external results record the legacy recipe; the plan states the targets and the model card the recipes. Rerun the commands and read the reports rather than treating these values as targets: wall times and the iterations reached within a budget depend on the machine.

Result

The wall-resolved/simplec recipe at level 1 (48896 cells) is the first backstep calculation here to pass the nonlinear gate: it converged after 18412 iterations, with every final initial residual <=1e-7 and the solver’s own convergence report. It passes the independent audit, so its measurement screen is assessed, and the screen passes. This is one mesh: there is no mesh pair, no GCI and no physical qualification, and the screening targets are broad (a predictor that ignores the step scores 0.067 at x/H=1, inside the 0.10 target). An earlier wall-resolved spacing, with a cell-width jump at the step plane, diverged in every run; the legacy wall-function recipe still stalls.

Recorded run

python tutorials/backstep_resolution.py --preset smoke --iterations 20000 \
  --timeout-s 3500 --data runs/external-study/measurements \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 --output runs/resolution-study

The study exited 0: one requested case, accepted and passed. Execution completed in 3037.4 s of the 3500 s budget, including mesh generation and postprocessing. The final initial residual of p is 1.19776e-8; its median over the last tenth of the iterations is 1.449e-8, against 2.527e-8 over the tenth before. The development run of the same dictionaries (below) stopped at the same iteration with the same p residual; its final Ux, Uy, k and omega residuals are 1.00e-7, 6.0e-8, 3.6e-8 and 4.5e-11.

Reruns at later revisions. The external-resolution CI job ran the same study three more times, on runners with four cores of an AMD EPYC 9V45, an AMD EPYC 7763 and an Intel Xeon Platinum 8370C. Each converged at iteration 18412 and reproduces every number of this section to the digits shown, apart from the wall time: 1984.6 s, 2982 s and 3161.4 s of execution. The same job continued the recipe in stages, compared in the continuation results, and started level 2 from it, reported in the mapping results.

Independent audit. Maximum local divergence 6.38e-11 H/U against 1e-4 (maximum relative cell imbalance 2.4e-7). Largest first-cell y+ per wall, from the tangential stored traction, against the limit of 1:

WallMaximum y+Where (x/H, y/H)Median y+
step0.9630, 0.9995: just below the lip0.123
upstream floor0.877-0.001, 1: just before the lip0.799
upper0.65849.84, 9: outlet0.559
lower0.48449.84, 0: outlet0.431

The comparison’s own estimate of the lower-wall first-cell y+ over the scored region 1 < x/H < 12 has median 0.34 (range 0.02–0.41).

Measurement screen (frozen protocol; targets in the last column):

x/HRMSE U/UrefBelow y/H=2Maximum errorNo-step predictor RMSETarget
10.04490.05510.1520.06750.10
40.06460.07930.1480.1790.10
60.09310.1150.1720.2370.10
100.09120.1120.1780.3220.10

Lower-wall Cf RMSE is 0.000417 against 0.001 (Cf=0 everywhere scores 0.00145). Predicted reattachment is 6.7064 H against a measured 6.26 +/-0.10 H: the 0.45 H error is inside the 0.75 H screening target but outside the reported experimental uncertainty. As in the legacy record, the errors below y/H=2 at x/H=6 and 10 exceed 0.10; the outer flow lowers the full-profile RMSE. The stalled legacy iterate reattaches at 6.45 H; its metrics carry no weight.

Development runs on the same dictionaries

Before the recorded run, the three solver profiles ran on the wall-resolved level-1 mesh with the same backend (openfoam_backend.py as below) and byte-identical generated dictionaries, each on a GitHub-hosted ubuntu-24.04 runner with four cores (CPU model in the table). Their audits used an earlier revision of the auditor with the same continuity and y+ computations. They are development evidence, not the record.

ProfileIterationsWall timeRunner CPUFinal initial residuals p / Ux / kAudit: max div(phi)*H/U; max y+ lower / upstream / upper / stepReattachmentCf RMSEProfile RMSE at x/H=1 / 4 / 6 / 10
legacy6000509 sAMD EPYC 9V452.07e-4 / 2.34e-5 / 2.90e-53.4e-7; 0.48 / 0.88 / 0.64 / 0.966.775 H4.17e-40.045 / 0.064 / 0.095 / 0.086
legacy200001742 sAMD EPYC 9V456.95e-7 / 1.31e-6 / 2.44e-61.7e-9; 0.48 / 0.88 / 0.66 / 0.966.706 H4.18e-40.045 / 0.065 / 0.093 / 0.091
simplec6000981 sIntel Xeon 8370C7.76e-7 / 5.33e-6 / 1.53e-52.7e-9; 0.48 / 0.88 / 0.66 / 0.966.706 H4.22e-40.045 / 0.065 / 0.093 / 0.091
simplec18412, converged2979 sAMD EPYC 77631.20e-8 / 1.00e-7 / 3.56e-86.4e-11; 0.48 / 0.88 / 0.66 / 0.966.706 H4.17e-40.045 / 0.065 / 0.093 / 0.091
simple60001953 sIntel Xeon 6973P-C2.12e-3 / 2.53e-5 / 4.79e-52.8e-12; 0.60 / 0.90 / 0.77 / 0.995.179 H9.74e-40.049 / 0.056 / 0.085 / 0.152

The long SIMPLEC run is the only one that reached the nonlinear gate: every final initial residual <=1e-7, with the solver’s own convergence report, at iteration 18412. Its independent audit and measurement screen passed. The other runs stopped at their iteration limit; their screens are not assessed and their metrics describe final iterates only. No run diverged. The residual medians over the last tenth of the iterations are below those of the tenth before for every field, by 17–51% for the GAMG profiles; the simple profile’s k residual fell only 2.5%. The mean continuity error stayed below 1e-4 (legacy, simplec) and 1e-11 (simple). Between 6000 and 20000 iterations the legacy profile’s reattachment moved from 6.775 to 6.706 H, the value of the converged SIMPLEC solution; its other metrics agree with it to one unit in the last digit shown. The first-order simple profile converged slowest and its final iterate differs most from the measurements.

The largest y+ is on the step wall, 0.96–0.99 at level 1, followed by the upstream wall near the step lip, 0.88–0.90. Both are close to the y+ <=1 gate; their first cells halve at level 2.

Earlier streamwise spacing

The earlier wall-resolved spacing kept the legacy upstream grading (32 cells per level, last width 0.064 H) next to a 4.6e-4 H first downstream cell: a 140:1 width jump along the whole step plane, plus 2.4:1 jumps at x/H=1 and 12. Foundation-13 checkMesh does not test width ratios and reported no error. All nine level-1 runs on that spacing, eight development variants (the simplec and simple profiles, GAMG and PCG pressure, tighter linear solves, first-order momentum, a cold start, gradient limiting and a steeper wall grading) and a recorded simple run, diverged. Their mean continuity error grew roughly exponentially and passed 1 (in units of U_ref/H) at iterations 7 to 154, before their last started iteration (39 to 700). Eight then logged NaN/Inf residuals; the first, run before the NaN guard existed, timed out after 900 s. The recorded simple run logged NaN/Inf at started iteration 700, after 322.10 s of a 420 s budget; in its last saved field (iteration 500) the velocity exceeded 1e15 everywhere and the k and omega maxima lay in the last cell before the step plane. These runs used an unspecified Ubuntu 24.04 x86_64 cloud machine.

The two spacings generate identical dictionaries apart from blockMeshDict. With that single difference, the simple profile diverged on the earlier spacing and stayed stable for 6000 iterations on the current one: the streamwise spacing, whose largest defect was the step-plane jump, caused the divergence, not the solver profile. The current guard stops such a run when its continuity error passes 1 (CFD-X010).

Legacy mesh, SIMPLEC control

On the legacy wall-function mesh (22656 cells), the simplec profile ran 6000 iterations in 277.45 s on the same unspecified cloud machine without numerical acceptance. Its final pressure initial residual is 0.00168726, and the medians over the last two tenths of its iterations are about 0.001758 for p, 0.000195 for k and 0.000237 for omega in both windows: the same stall as the legacy profile (external results), although the pressure relaxation changed from 0.2 to 1 and the transport relaxation from 0.5 to 0.7. Its relative boundary-flux imbalance is 4.9021e-10 and its independent local divergence 3.54708e-5, below 1e-4: small mass errors do not establish momentum/turbulence convergence. Between its saved iterations 4250 and 6000 the largest velocity change (3.2e-3 U_ref) lies in the first cells above the upstream floor near the inlet, a row whose k-based y+ spans 6 to 14, and 34 first cells under the upper wall cross the wall functions’ switch point (about 11.5) between the two snapshots.

Independent audit checks

Starting from an actual returned cavity archive (576 cells, converged at iteration 696, local divergence 4.05294e-9), add 0.01 m3/s to its first internal face flux and recompute the archive’s checksums and completion marker. The global boundary budget is unchanged and the archive verifier still passes. The independent auditor rejects the altered field: its maximum local normalized divergence is 57.6, against 1e-4. This deliberate synthetic corruption shows what the local check adds; it is not a physical-validation result. The real runtime tests repeat it on GitHub.

On the actual Foundation-13 blockMesh output of the wall-resolved level-1 recipe, the real runtime tests check the first-cell distance on all four walls, the represented volume of 48.2 m3, and that every cell width equals the tested grading model, with neighbouring widths within a factor 1.2 in x and 1.35 in y.

Implementation and machine

The recorded run used OpenFOAM Foundation 13 package 20260407 (build 13-441953dfbb42, serial, f64, 32-bit labels) with Python 3.12 on a GitHub-hosted ubuntu-24.04 runner with four cores of an AMD EPYC 7763. The implementation files had the SHA-256 identities in the first column; the development runs used the same openfoam_backend.py and generated the same dictionaries. The last rerun used the second column, which generates byte-identical dictionaries for this recipe.

FileRecorded runLast rerun
tutorials/backstep_resolution.pydbe4a43014df73ebb02558c232bd3c6c370dfc68a0371e6ad86211eb79e80f1597fd503e8f54102cf2936a8cefdd673e90f6e26fd93eb966061537c5a1d93fe5
integrations/openfoam_backend.py801f7e2a444b6212f92638b8ca1cbe0e7269485a239bf03ba948f2d15aca8d381f733f86f08acfe5d87b514678c67ec718ce7b72cb3019779ded7405a7c91969
integrations/openfoam_cases.py07c4b8a92f4c943f9a58846e44a506b1280bc3b921dcd667db6bab3788f4fbedf0e79c2e8054884c56e38e740b8dcc5708134fb44fbbe379ca6ed22ec6a38860
integrations/openfoam_restart.py—202d4605ca82f4625b5bd24b49af046de64ff534c0d7597f566862d9abe31a35
validation/audit_openfoam_mesh.pya0b1695599bfff99f35417d9b9351e48704b6237dddb0d2e518b4d7ace12c7b79274c2151328ea0fbde8b083eb184b4d2b36767f4d5d514907735678b0d77cd1
validation/compare_backstep.py5141c2e7e9b22850e6a7143dab21dcb28002c527740257c1097c569e0d9a4a3esame
validation/backstep_data.py736281b80881ffb8c3773fb54b0288245d6a92352bcd42ecd1eac376754d964dsame

The two earlier reruns used openfoam_backend.py 5c75ea48aae2fd8ffb7339182c918c10ea0c8da4f310a666b8fdef3c03e1ec98 and earlier revisions of openfoam_restart.py, which the single run does not call.

Software verification

At the recorded implementation, in CI with the pinned runtime and locally without it:

  • Rust formatting, Clippy with warnings denied and the 32 release tests pass.
  • Ruff formatting and lint checks pass.
  • The 35 native CLI tests, the 38 external-backend tests and the 41 resolution tests pass in normal and optimized Python. The resolution tests fail when any one of 30 deliberate reversions of their checks is applied (the mesh spacing, the log scan, the auditor’s gates and readers, the tutorial’s acceptance and error handling, the comparison’s audit gate). Synthetic fixtures remain labeled as such; the real-runtime tests check the actual blockMesh output and a corrupted returned flux.

Reproduce

python integrations/install_openfoam13.py --output runs/openfoam13
python tutorials/external_cfd.py --preset study --timeout-s 300 \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 --output runs/external-study
python tutorials/backstep_resolution.py --preset smoke --iterations 20000 \
  --timeout-s 3500 --data runs/external-study/measurements \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 --output runs/resolution-study

The external-backend and external-resolution jobs of the CI workflow run these commands on manual dispatch and publish the numbers as notices. For one profile on its own:

python integrations/openfoam_backend.py prepare --case backstep --level 1 \
  --iterations 20000 --mesh-family wall-resolved --solver-profile legacy \
  --data runs/external-study/measurements --output runs/wall-legacy-input
python integrations/openfoam_backend.py run --case runs/wall-legacy-input \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 --timeout-s 3500 \
  --memory-mib 2048 --output-mib 512 --output runs/wall-legacy
python validation/audit_openfoam_mesh.py --run runs/wall-legacy --output runs/wall-legacy-audit.json
python validation/compare_backstep.py --run runs/wall-legacy \
  --data runs/external-study/measurements --output runs/wall-legacy-comparison

The controls preset (--preset controls) runs the 2x2 mesh/profile design at level 1; the cavity corruption check is test_returned_internal_flux_corruption_is_detected in validation/test_resolution.py, which runs when CFD_OPENFOAM_ROOT is set.

Open questions

  • Mesh sensitivity. A level-2 case has four times the cells of the level-1 solve, which took about 50 minutes, and more iterations would be expected; it is not expected to finish within the 3600 s per-case limit. Same-mesh continuation (continuation results) lets it run in bounded stages, each of which must pass the source flux gate. A nearest-cell start from the coarse solution now exists (prepare-mapped, mapping results); the declared refinement campaign has not yet produced an accepted level 2 (refinement results), and conservative interpolation is not implemented. No GCI or mesh-independent claim is made.
  • Near-wall resolution margin. The step wall’s largest y+ (0.96) and the upstream wall’s near the lip (0.88) are close to the y+ <=1 gate at level 1.
  • Inlet. The inlet velocity falls linearly from the first measured point to zero at each wall, about 140 wall units on the lower wall, and the inlet omega near the walls is far below its viscous value. A composite inner-layer profile matched to the measured outer profile, or a developing inflow, is the next sensitivity to examine; the over-predicted reattachment (0.45 H, outside the 0.10 H experimental uncertainty) may depend on it.
  • Legacy stall. A continuous wall-function package on the legacy mesh (blended omegaWallFunction with nutUSpaldingWallFunction) is a one-change test of the buffer-layer explanation.
  • Outlet. U, k and omega use zeroGradient at the outlet; inletOutlet would prevent backflow during a cold start.
  • Flux gate. The gated measure tightens as cells shrink; the relative cell imbalance is reported beside it for comparison across levels.

Physical qualification stays open: inlet uncertainty, mesh sensitivity and model-form sensitivity are separate gates, and there are no scalar measurements. Nothing here qualifies the native canyon model.

Recorded steady-continuation results

These results cover same-mesh steady field continuation of the OpenFOAM backend (guide, plan). The resolution results record the wall-resolved reference recipe solved in one run. Rerun the commands and read the reports rather than treating these values as targets; wall times depend on the machine.

Result

Continued in stages, the wall-resolved/simplec level-1 backstep reaches the same converged solution as one uninterrupted run. Four stages (6000, 6000, 6000 and 412 iterations) converge after 18412 cumulative iterations, the iteration at which the single run converges. Both pass the nonlinear gate, the independent audit and the measurement screen, and the final fields differ by about 2e-12 in U, far inside every preregistered bound. Short fixed-work comparisons of the cavity and of the backstep’s simple profile meet their equivalence bounds. The source flux gate stops early simplec sources; whether that gate suits continuation is an open decision (below). This is one coarse mesh: nothing here is a mesh pair, a GCI or physical qualification.

Staged solve of the wall-resolved reference

The external-resolution CI job ran the single control and then the staged chain on the same runner, and compared them with compare_restart.py --mode converged. The bounds were declared before either result was read.

QuantityStaged chainSingle runBoundCheck
Completed iterations18412 (4 stages)18412within 5%pass
Numerical gate, audit, screenpassedpassedboth passpass
Reattachment6.7063877 H6.7063877 H0.01 Hpass
Lower-wall Cf RMSE4.171678e-44.171678e-41e-5pass
Profile RMSE at x/H=1 / 4 / 6 / 100.044934662 / 0.064592104 / 0.093141628 / 0.091193745same1e-4 eachpass
Max y+ lower / upstream / upper / step0.484081 / 0.877159 / 0.658362 / 0.962831same0.01 eachpass
Max abs U difference1.94e-12 m/s1e-3pass
Max abs p difference2.73e-13 m2/s21e-3pass
k / omega / nut: max difference over control max1.9e-12 / 5.7e-15 / 1.3e-101e-3pass

The stages took 599.9, 638.8, 648.2 and 46.0 s (1933 s in total) and the single run 1984.6 s, each against a 3500 s budget. Stages 1 to 3 ended at their iteration limit without numerical acceptance; each then seeded the next stage, so each passed the source flux gate. Stage 4 stopped at numerical acceptance (numerically_accepted). The final p initial residual is 1.19776e-8 on both paths. The audits give max abs(div(phi))*H/U 6.39e-11 for the chain and 6.38e-11 for the single run.

The single run reproduces the recorded resolution result to all digits shown there, apart from the wall time. A development run of the same comparison, on a runner with an AMD EPYC 7763 and an earlier source check that is not adopted (see below), gave the same differences to all digits shown; its stages took 940.7, 969.0, 1002.5 and 70.7 s and its single run 2982 s.

The receipt resets the local pseudo-time and the solver history, so a converged chain is not expected to be bitwise identical to the single run; here the largest relative difference in any cell is 3.0e-7 in p.

Fixed-work comparisons

A fixed-work comparison continues FIRST iterations for SECOND and compares the final fields with an uninterrupted FIRST + SECOND run of the same recipe. Its bounds were declared before the comparisons: 1e-6 in U and p for the cavity, 1e-5 for the backstep, and 1e-5 for k/omega/nut relative to the control’s largest magnitude. Neither path needs to converge, and no measurement screen follows from a pass.

CaseSplitMax abs U differenceMax abs p differenceTurbulence: max difference over control maxResult
cavity, real-runtime test400 + 200 against 600<1e-6<1e-6—pass
backstep wall-resolved simple, level 1250 + 250 against 5001.54519e-6 m/s2.88676e-7 m2/s21.82e-6 (nut; k 1.10e-6, omega 1.46e-8)pass

The cavity test asserts the bounds and does not print the differences; the cloud run below measured them at round-off. The backstep comparison ran twice, on runners with four cores of an AMD EPYC 7763 and of an AMD EPYC 9V74, with the same differences to all digits shown. The second run, with the final version of compare_restart.py, also gated both final face fluxes: max abs(div(phi))*H/U is 1.28e-11 for the continued run and 1.24e-11 for the control, against 1e-4. The p difference is gated without removing a constant offset. The largest cell- relative differences, reported but not gated, are 0.0136 in U and 0.0074 in p; they lie in cells where the control’s value is below 4e-4 of its largest magnitude. Each path did 500 iterations, and neither reached the nonlinear gate. The source, the continued stage and the control took 112.6, 114.1 and 219.7 s on the EPYC 7763 and 100.1, 100.7 and 196.0 s on the EPYC 9V74, against 600 s limits. These early fields are equivalence fixtures: on the cloud machine their wall-resolution audit failed (step-wall first-cell y+ 1.41 at the end, 3.25 in the source).

Earlier evidence

The comparisons below ran on a cloud machine (Ubuntu 24.04.3, AMD EPYC 9V74, eight-core quota, Python 3.12.14) with the same runtime and an earlier revision of the receipt, the stage loop and the cadence rule, which generates the same dictionaries for these recipes. The archives are not part of the repository.

ComparisonResult
Cavity 400 + 200 against 600max U difference 1.03e-15 m/s, p 6.6e-16 m2/s2 after removing a constant offset (bounds 1e-6)
Cavity: restart from iteration 400 until convergenceconverged after 296 more iterations, 696 in total, passing the nonlinear gate and the audit; its fields equal those of a cold run converged at 696 to 1.0e-15 in U and 2.0e-15 in p
Backstep simple, 250 + 250 against 500the U, k, omega and nut differences of the CI comparison above, to the digits shown; p 2.63e-7 after removing a 2.55e-8 offset; 111.8, 114.0 and 219.5 s
Backstep simplec, source at 500 iterationsrejected by the source flux gate: max abs(div(phi))*H/U 0.00483124 against 1e-4, although mean continuity is 3.56e-8 and the boundary imbalance 8.6e-9; no stage input created
Staged study, two 500-iteration simplec stagesone completed, unaccepted stage, stop at the source gate, levels 2 and 3 not started, exit 2

One earlier run of that staged study was found, after the workflow had sealed its first stage, to contain an additional case/250 time directory; its comparison was rejected (CFD-X006 archive.progress). The cause is unknown. The verifier caught it, and the archive was not resealed to accept it.

Source eligibility: an open decision

A completed stage seeds the next only if its stored face flux passes the auditor’s local gate, max abs(div(phi))*H/U <=1e-4, as preregistered. The evidence collected here bears on whether that gate suits its role; it has not been changed:

  • The measure follows the last pressure solve’s relative tolerance. The simple profile (PCG, relative tolerance 0) scores 1.5e-11 at iteration 250; the reference simplec profile (GAMG, relative tolerance 1e-3) scores 0.0048 at iteration 500, 2.7e-9 at 6000 and 6.6e-10 at 10000. The cold start every run begins from scores 5.6.
  • It tightens like H/dx with refinement, which is where continuation is needed.
  • An uninterrupted run continues from exactly the state the gate rejects.
  • A development run on GitHub, with a scale-free source check (net cell flux over U_refdzsqrt(dx*dy) <=1e-2) in place of the gate, continued the rejected 500-iteration simplec source for 500 iterations. Against the uninterrupted 1000 iterations the fields differ by 7.25e-5 in U, 3.36e-5 in p and up to 4.2e-4 of the largest nut, beyond the 1e-5 equivalence bounds. Early simplec restarts therefore perturb the trajectory more than simple ones, although converged staged solves agree with the single run.
  • That scale-free check is a plausibility check, not an integrity check: an all-zero or uniformly scaled phi passes, and so do about a quarter of single-face sign flips on low-flux faces of the 500-iteration source.

Implementation and machine

The CI runs used OpenFOAM Foundation 13 package 20260407 (build 13-441953dfbb42, serial, f64, 32-bit labels) with Python 3.12 on GitHub-hosted ubuntu-24.04 runners with four cores: an AMD EPYC 9V45 for the staged chain and its single-run control, which ran one after the other in the same job, and an AMD EPYC 7763 and an AMD EPYC 9V74 for the two fixed-work runs. The implementation files had these SHA-256 identities:

FileSHA-256
integrations/openfoam_restart.py97d4ef6bfbf1a19b674c5b7ff04fce1e27daafb16e0006aa36904d001b4febb6
integrations/openfoam_backend.py5c75ea48aae2fd8ffb7339182c918c10ea0c8da4f310a666b8fdef3c03e1ec98
integrations/openfoam_cases.pyf0e79c2e8054884c56e38e740b8dcc5708134fb44fbbe379ca6ed22ec6a38860
tutorials/backstep_resolution.py97fd503e8f54102cf2936a8cefdd673e90f6e26fd93eb966061537c5a1d93fe5
validation/compare_restart.pya183c4876c24ee11017cb9e1ed2b9903ab79af5b3d57a2d00e69857fa1cd295b; the converged comparison and the first fixed-work run used 7e7eb7beff9dec4d007481a7da27f19e75ab78b405d2cb2ea599036a1eceb744, which differs only by that gate and its docstring
validation/restart_equivalence.py77a282e03a11919fcaa159c00c60df791a2afaeac0e8659b79a6424ac2c7ecec
validation/audit_openfoam_mesh.py9274c2151328ea0fbde8b083eb184b4d2b36767f4d5d514907735678b0d77cd1
validation/compare_backstep.py5141c2e7e9b22850e6a7143dab21dcb28002c527740257c1097c569e0d9a4a3e
validation/backstep_data.py736281b80881ffb8c3773fb54b0288245d6a92352bcd42ecd1eac376754d964d

Software verification

At the recorded implementation, in CI with the pinned runtime and locally without it:

  • Rust formatting, Clippy with warnings denied and the 32 release tests pass on stable Rust and on 1.88.0.
  • Ruff formatting and lint checks pass.
  • The 35 native CLI tests, the 38 external-backend tests, the 41 resolution tests and the 54 continuation tests pass in normal and optimized Python. Seven continuation tests need the runtime and run in the external-backend job: cavity fixed-work and converged-chain comparisons, a restart to the unchanged numerical gate, runtime and mesh mismatches that stop before foamRun and leave a verifiable failure, and a corrupted or resealed bad-flux source that is rejected before any input is created.
  • Each of 51 deliberate reversions of the receipt checks, the stage loop, the cadence rule and the comparison tools, and of two more of the fixed-work flux gate, makes at least one continuation test fail.

Reproduce

python integrations/install_openfoam13.py --output runs/openfoam13
python validation/backstep_data.py --output runs/measurements
python tutorials/backstep_resolution.py --preset smoke --iterations 20000 \
  --timeout-s 3500 --data runs/measurements \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 --output runs/resolution-study
python tutorials/backstep_resolution.py --preset smoke --iterations 6000 \
  --max-stages 4 --timeout-s 3500 --data runs/measurements \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 --output runs/resolution-staged
python validation/compare_restart.py --mode converged --data runs/measurements \
  --run runs/resolution-staged/wall-resolved-simplec-level1-stage4 \
  --control runs/resolution-study/wall-resolved-simplec-level1 \
  --output runs/staged-comparison.json
python validation/restart_equivalence.py --case backstep --solver-profile simple \
  --first 250 --second 250 --timeout-s 600 --data runs/measurements \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 --output runs/equivalence-simple
python validation/restart_equivalence.py --case cavity --first 400 --second 200 \
  --timeout-s 60 --foam-root runs/openfoam13/runtime/opt/openfoam13 \
  --output runs/equivalence-cavity

The external-backend and external-resolution jobs of the CI workflow run these comparisons on manual dispatch (the cavity ones as real-runtime tests in validation/test_restart.py) and publish their numbers as notices. The stage directory in the comparison command is the chain’s last stage, which the study report names.

Open questions

  • The source eligibility decision above, and stage lengths for level 2, where the gate is about twice as strict and a 3500 s stage holds roughly 4500 iterations.
  • Which turbulence-model state a restart does not carry in the SST backstep (the restarted iteration’s residuals differ by about 1e-4 relative); one hypothesis is that nut is recomputed from k and omega at start-up.
  • The cause of the extra time directory in the earlier staged study; the mapping results record a second occurrence.
  • A fine-mesh campaign from a coarse-to-fine start (see the mapping results); refinement_campaign.py now runs one, but no accepted level 2 exists yet (refinement results); then mesh, inlet and model sensitivity. Nothing here qualifies the native canyon model or passive-gas transport.

Recorded coarse-to-fine initialization results

These results cover one-level mesh initialization of the OpenFOAM backend (guide, plan). The continuation results and the resolution results record the accepted level-1 backstep that the backstep starts below use as their source. Rerun the commands and read the reports rather than treating these values as targets; wall times depend on the machine.

Result

A coarse result initializes the next finer level as intended, and the receipt binds the consumed fields to it. A mapped and a cold level-2 cavity converge to the same fields (5.1e-9 in U) and pass every declared check. On the wall-resolved backstep the path works from the accepted level-1 solution: after 3000 level-2 iterations the mapped start’s pressure residual is 1.1e-6, against 6.4e-5 for a cold start with the same limits. Neither start reached the nonlinear gate, so there is no accepted level-2 backstep, no mesh pair, no GCI and no physical qualification.

Cavity: mapped against cold

validation/mapping_equivalence.py solves the 24x24 Re=100 cavity (level 1), maps it to a new 48x48 case (level 2) and solves that, and solves a cold 48x48 case with the same settings. The bounds were declared before the runs.

CheckMapped / cold level 2Declared bound
Final numerical gatepassed / passedboth pass
Iterations to convergence1356 / 2132reported only
Maximum U difference5.11115e-9 m/s<=1e-4
Maximum p difference, no offset removed2.4529e-9 m2/s2<=1e-4
Maximum local div(phi)*H/U, independent audit1.67052e-9 / 1.67193e-9<=1e-4 each
Ghia centerline error0.00707999 / 0.00707998<=0.06 each

The source converged after 696 iterations. The run wall times, including mesh generation, checks and postprocessing, were 0.89 s for the source, 0.65 s for the preparation, 2.94 s for the mapped run and 4.24 s for the cold run. One run supports no speed claim, and the source and preparation work come on top of the mapped run’s. The Ghia profile is a numerical reference: the report sets physical_qualification to false.

The replay found the nearest source cell for every one of the 2304 cells, and the actual-runtime tests check every mapped value against the coarse cell that contains the fine cell’s centre, the target boundary dictionaries against the generated ones, and a same-mesh continuation of the mapped result.

mapNearest on the backstep meshes

An actual-runtime test generates the wall-resolved level-1 (48896 cells) and level-2 (195584 cells) backstep meshes with blockMesh, writes distinct smooth synthetic values of U, p, k, omega and nut on level 1 and maps them with mapFields -consistent -mapMethod mapNearest. Every level-2 cell takes all five values from one level-1 cell. For 185984 cells that is the cell with the nearest centre; for the other 9600 it is another nearby cell, at most the fourth nearest and at most 1.16 times as far as the nearest centre. The replay accepts any of the 27 nearest cells, in every field at once, and records these counts; 27 was set before these statistics were known. The fields are synthetic: this is a check of the utility and of the replay, not a turbulent solve.

Backstep level 2: mapped and cold starts

validation/mapped_start.py started level 2 (195584 cells) of the wall-resolved simplec recipe twice, with the same iteration limit (3000), budget (3500 s, 1024 MiB output) and runner: once mapped from the accepted single level-1 run (18412 iterations), once cold. It is a report: no gate was declared, and neither run is numerically accepted, so the measurement screen is not assessed. The metrics describe each final iterate only.

Quantity after 3000 iterationsMapped startCold start
Executioncompleted, not convergedcompleted, not converged
Final initial residual p / Ux / Uy1.06e-6 / 3.6e-7 / 1.1e-56.4e-5 / 5.4e-5 / 6.8e-4
Final initial residual k / omega1.0e-6 / 2.2e-91.7e-4 / 5.9e-8
p residual median, last / previous tenth1.10e-6 / 1.14e-66.8e-5 / 8.9e-5
Independent auditpassedpassed
Max abs(div(phi))*H/U1.3e-85.4e-6
Max y+ lower / upstream / upper / step0.25 / 0.47 / 0.34 / 0.520.29 / 0.49 / 0.33 / 0.53
Reattachment, final iterate6.686 H5.579 H
Cf RMSE, final iterate3.9e-44.9e-4
Profile RMSE at x/H=1 / 4 / 6 / 10, final iterate0.045 / 0.065 / 0.094 / 0.0910.038 / 0.038 / 0.034 / 0.049
Run wall time2201.7 s2111.2 s

Preparation took 38.5 s and the source run 3161.4 s; those are additional to the mapped start. The replay statistics of the real fields equal those of the synthetic fields above (185984 nearest, 9600 other nearby cells, rank at most 4), as expected, since the addressing depends on the meshes only. All maximum y+ values are about half the level-1 values, as the wall spacing halves.

The mapped iterate is still close to the level-1 solution (reattachment 6.686 H against 6.706 H) and its pressure residual falls slowly, by 4% over the last tenth of the run, so these numbers do not predict the converged level-2 answer or when it is reached. The cold iterate is far from converged; its closer profile errors carry no weight.

Earlier evidence

The cavity comparison also ran on a cloud machine (AMD EPYC, eight-core quota, Python 3.12.14) with the same runtime and an earlier revision of the mapping code without the replay. It gave the same iterations, differences, local continuity and Ghia errors to all digits shown above. One earlier run of the same experiment there was rejected when its archives were verified (CFD-X006 archive.progress): a time directory that the solver had removed was present again after the archive was sealed, although the manifests list only the initial and final times. No archive was resealed to accept it; the continuation results record a similar occurrence on that machine. It has not occurred in any GitHub run. The archives are not part of the repository.

Implementation and machine

The GitHub runs used OpenFOAM Foundation 13 package 20260407 (build 13-441953dfbb42, serial, f64, 32-bit labels) with Python 3.12 on GitHub-hosted ubuntu-24.04 runners with four cores: an AMD EPYC 9V45 for the tests and the cavity experiment, and an Intel Xeon Platinum 8370C for the level-1 solve and the level-2 starts. The implementation files had these SHA-256 identities:

FileSHA-256
integrations/openfoam_mapping.pyb2360565ff3fbbecfb01490763d8e888e704410bf4d48c7e1f708b2ddc78fadb
integrations/openfoam_backend.py1f733f86f08acfe5d87b514678c67ec718ce7b72cb3019779ded7405a7c91969
integrations/openfoam_restart.py202d4605ca82f4625b5bd24b49af046de64ff534c0d7597f566862d9abe31a35
integrations/openfoam_cases.pyf0e79c2e8054884c56e38e740b8dcc5708134fb44fbbe379ca6ed22ec6a38860
validation/mapping_equivalence.pyf017ef254219d9ba497b0a41c9a9ba53d22c23ea1c909e8df10aa24c6eeabd76
validation/mapped_start.py689cc37f98227be8fad1a0a9f6cfb4a961fdec652c9f0a8a750e08839baea1d3
validation/audit_openfoam_mesh.py9274c2151328ea0fbde8b083eb184b4d2b36767f4d5d514907735678b0d77cd1
validation/compare_restart.pya183c4876c24ee11017cb9e1ed2b9903ab79af5b3d57a2d00e69857fa1cd295b
validation/compare_backstep.py5141c2e7e9b22850e6a7143dab21dcb28002c527740257c1097c569e0d9a4a3e
tutorials/backstep_resolution.py97fd503e8f54102cf2936a8cefdd673e90f6e26fd93eb966061537c5a1d93fe5

Software verification

At the recorded implementation, in CI with the pinned runtime and locally without it:

  • Rust formatting, Clippy with warnings denied and the 32 release tests pass on stable Rust and on 1.88.0.
  • Ruff formatting and lint checks pass.
  • The 35 native CLI, 38 external-backend, 41 resolution, 54 continuation and 58 mapping tests pass in normal and optimized Python. Eight mapping tests need the runtime: the cavity’s nearest cells and boundaries, a mapped run that converges and is continued on its mesh, occupied outputs and unaccepted sources, a source-copy race, deadline and cancellation, runtime and rebuilt mesh mismatches that stop before the solve, and the backstep mapping check above. The others use real-format square meshes with distinct values, stand-ins for the utilities and mocked runs; they change each receipt, evidence and preparation check in turn, resealed consistently.
  • Each of 72 disabled require checks of openfoam_mapping.py, one at a time, and each of 24 further deliberate reversions (the replay, the receipt values, the field reader, the failure record, the drivers) makes at least one test fail.

Reproduce

python integrations/install_openfoam13.py --output runs/openfoam13
CFD_OPENFOAM_ROOT="$PWD/runs/openfoam13/runtime/opt/openfoam13" \
  python validation/test_mapping.py -v
python validation/mapping_equivalence.py \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 --timeout-s 180 \
  --output runs/mapping-cavity
python validation/backstep_data.py --output runs/measurements
python tutorials/backstep_resolution.py --preset smoke --iterations 20000 \
  --timeout-s 3500 --data runs/measurements \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 --output runs/resolution-study
python validation/mapped_start.py \
  --source runs/resolution-study/wall-resolved-simplec-level1 --iterations 3000 \
  --timeout-s 3500 --data runs/measurements \
  --foam-root runs/openfoam13/runtime/opt/openfoam13 --output runs/mapped-start

The external-backend job of the CI workflow runs the tests and the cavity experiment; the external-resolution job, dispatched with mapping or all, runs the single level-1 solve and the level-2 starts. Both publish their numbers as notices.

Open questions

  • A level-2 campaign: stage lengths, and whether the source flux gate suits continuation, an open decision in the continuation results.
  • Sources from a continued or mapped chain, conservative interpolation, and a check of the stored templates against the generator at verification (it needs the measurement files for the backstep).
  • Restart comparisons (compare_restart.py) count only fine-grid work and do not report a mapped initialization.
  • The cause of the reappearing time directory on the cloud machine.

Bounded mapped refinement: results

The declared level-2 backstep campaign of the plan, run on a GitHub-hosted runner on 31 October 2026 from commit e7b095277ac1346806984ae4070bc18ac1e9aefe. The campaign code of that commit is the current code; later commits change tests, notices and documentation only.

Outcome

The campaign did not produce an accepted fine grid. All three declared stages of 4000 iterations completed, and the stop reason is stage_limit. Every stage passed the independent audit (local flux and wall y+), but none passed the numerical gate: after 12000 fine iterations the final initial residuals of Uy (1.81e-7) and k (1.05e-7) are still above 1e-7, and the solver did not report convergence. The two-grid comparison was therefore not assessed. Physical qualification remains false.

The residuals fell steadily through all three stages. The Uy residual, which had seemed to level off near 1e-5 in shorter runs, fell by a factor of about 7 per stage. Whether one more stage would pass the gate is an extrapolation; this campaign does not show it.

ItemValue
Workflow run41151497327, dispatch input external=refinement
RunnerGitHub-hosted ubuntu-24.04, AMD EPYC 9V45, 4 CPUs (serial solve)
Evidenceartifact resolution-evidence (13026704954, 139081798 bytes, sha256:c05c07f37b68e395801a43a3fa8fd708170dd476bf8825a4a81c9ef70c440f72), containing runs/refinement-campaign/report.json and runs/refinement-campaign-evidence.zip
Workflow completed / passedTrue / False
Stop reasonstage_limit
Completed / started fine iterations12000 / 12000
Source iterations (separate)18412
Archive checkpoints5 (source snapshot, three returned stages, final collection)
Campaign wall time5507.2 s, of which preparation 23.5 s
refinement_campaign.py6173411c59ed07a83c4d5f42836dbedb117507eb3bd07733f11825d2ce707b02

Source and declared work

The same job first ran the wall-resolved SIMPLEC level-1 backstep cold, in one run with a 20000-iteration budget (backstep_resolution.py --preset smoke). It converged at 18412 iterations in 1988.2 s, with a final pressure residual of 1.20e-8. It passed the independent audit (max abs(div(phi))·H/U 6.4e-11, highest wall y+ 0.963 on the step wall) and the measurement screen:

Source observableValueScreen target
U profile RMSE x/H = 1, 4, 6, 100.0449, 0.0646, 0.0931, 0.0912≤ 0.10 each
Signed Cf RMSE (17 points)4.17e-4≤ 1e-3
Reattachment6.706 Hwithin 0.75 H of 6.26 H

The campaign took this archive (48896 cells) as its source and mapped it once to level 2 (195584 cells). The declared limits, frozen before mapping, were three stages of at most 4000 iterations, 3500 s per solve, 900 s for preparation, 1024 MiB output and 4096 MiB child address space per stage. The mapping replay matched the earlier runs exactly: 185984 cells took their nearest source cell and 9600 another of the 27 nearest (largest rank 4, largest distance ratio 1.1601).

Stages

StageIterationsWall sConvergedNumericalAuditMeasurement screen
140001800.4nofailpassnot assessed
240001778.8nofailpassnot assessed
340001737.7nofailpassnot assessed

Final initial residual of each stage; the gate is ≤ 1e-7 for every field:

FieldStage 1Stage 2Stage 3Reduction per stage
Ux2.92e-71.22e-77.72e-82.4, 1.6
Uy9.06e-61.19e-61.81e-77.6, 6.6
p8.06e-71.03e-71.56e-87.8, 6.6
k6.93e-72.55e-71.05e-72.7, 2.4
omega1.60e-95.73e-102.46e-102.8, 2.3

Bold values meet the gate. The pressure residual’s median over the last tenth of each stage, against the tenth before, was 8.5e-7 / 9.7e-7, 1.13e-7 / 1.42e-7 and 1.72e-8 / 2.11e-8.

Each stage ran at about 0.44 s per iteration. The level-1 source ran at about 0.11 s per iteration with a quarter of the cells.

Independent audit of the fine stages

Stagemax abs(div(phi))·H/UMax relative cell imbalance
11.29e-83.5e-6
28.8e-103.5e-8
32.4e-101.1e-7

The local-flux target is ≤ 1e-4. Maximum y+ at stage 3: lower wall 0.253, upstream wall 0.473, upper wall 0.343, step wall 0.515 (target ≤ 1; the same to three digits in every stage). A passing audit of conservation and wall sampling does not establish nonlinear convergence.

Final-iterate observables

These are metrics of fields that are not numerically accepted. The measurement screen was not assessed, and the differences from the source are not a mesh sensitivity.

ObservableSource (level 1, accepted)Stage 1Stage 2Stage 3
U profile RMSE x/H = 10.044930.045070.045080.04508
U profile RMSE x/H = 40.064590.064990.065010.06502
U profile RMSE x/H = 60.093140.093600.093790.09380
U profile RMSE x/H = 100.091190.091850.091910.09188
Signed Cf RMSE4.172e-43.918e-43.927e-43.929e-4
Reattachment x/H6.70646.67886.68116.6805

Between stages 2 and 3 the reattachment length moved by 0.0006 H and the profile errors by at most 3e-5.

Two-grid comparison

Not assessed: it requires both final numerical assessments and independent audits to pass. When assessed, velocity samples are paired by station, sample ID and physical y/H, and Cf is compared at common positive measured x/H positions without extrapolation. mesh_sensitivity.passed means both grids pass the original gates, not that their difference is below a threshold. Two grids do not give a GCI.

Integrity

Every checkpoint passed: the copied source had the manifest the plan froze; each stage’s receipt bound its parent’s manifest, final time, fields, mesh, runtime and cumulative fine work; every archive kept the manifest of its first checkpoint; each sealed summary stated what its run returned; and the producing files kept the hashes the plan froze. The CI step zipped the complete campaign directory, including empty directories, and rejected symlinks.

Reproduce

On a runner with the pinned Foundation-13 runtime, dispatch the CI workflow with external=refinement, or run:

python validation/backstep_data.py --output runs/measurements
python tutorials/backstep_resolution.py --preset smoke --iterations 20000 \
  --timeout-s 3500 --data runs/measurements --foam-root ROOT \
  --output runs/resolution-study
python validation/refinement_campaign.py \
  --source runs/resolution-study/wall-resolved-simplec-level1 \
  --iterations 4000 --max-stages 3 --timeout-s 3500 --preparation-s 900 \
  --data runs/measurements --foam-root ROOT --output runs/refinement-campaign

Exit code 2 means a completed campaign with unaccepted evidence, as here.

Earlier executions

These preceded the declared campaign. None supplied a source for it.

  • Reduced run (workflow check). Two stages of 400 iterations, 450 s per solve and 180 s preparation, on a cloud machine. It reused the accepted level-1 archive of workflow run 41106074755 (artifact 13008679534, SHA-256 34ff3df6f86741413aed94a4ffd5c34498de1bba8ce47f2191553d8445931322, source manifest d90c70c78997c3de30b658cea631fd873fcbad5f2f02ea8793def42750c5284a). It stopped at stage_limit after 800 fine iterations, with Uy at 1.04e-5 and p at 2.6e-6; all audits passed. Its limits were frozen in its report before it started, but the plan was changed to declare it only afterwards.
  • Runs that ended early. A prototype was cancelled at started iteration 238 to correct the cancellation rule. Two runs of the declared campaign on the same cloud machine ended at started iterations 1457 and 1193 without a returned solver record or seal, for unknown reasons. Their records were kept; nothing from them was continued.
  • Cavity proof. A real Foundation-13 cavity campaign passes: the cold level-1 source converged in 696 iterations; the mapped level-2 chain took 1356 iterations in stages of 400, 400, 400 and 156. Both grids pass their numerical, independent and Ghia-reference checks (maximum Ghia errors 0.00897 and 0.00708 against 0.06), and the largest centerline change between the grids is 0.0075 lid-speed units. This is numerical verification, not physical validation.
  • Reappearing directory. On the same cloud machine, a sealed cavity source later showed an empty old time directory while every file still matched its manifest. The archive checks rejected it; the cause is unproven. See the investigation. It has not occurred on GitHub.

Tests

The campaign tests run in normal and optimized Python. Without the runtime they cover limits, the source snapshot, observations, the two-grid comparison, lineage, checkpoints, stopping, cancellation, the command line and the CI notices. With CFD_OPENFOAM_ROOT set, five more tests run real cavity campaigns, including an archive changed after sealing and a reappearing empty directory; they passed on GitHub in run 41151500191.

Open questions

  • Another declared trial. The stage-3 fields are retained and pass the audit. An accepted level-2 backstep needs a new declared campaign with more fine work, for example four or five stages of 4000 iterations, within the 360-minute job. The number must be declared before it runs; this result does not justify a smaller gate.
  • Mesh sensitivity. An accepted level-2 grid gives a two-grid comparison, not a GCI. A third level requires chained mapping provenance, which the campaign does not support.
  • Other uncertainty. Inlet and near-wall reconstruction, turbulence-model form and measurement uncertainty remain open. The benchmark has no passive-gas data.
  • Native gates. Native canyon throughput, building-wall treatment and measured canyon and gas qualification are separate and unchanged.

The guide and the tutorial prompt describe the workflow and the meaning of its verdicts.

Validation record

F1–F3 use the existing numerical solvers, the native LP/MIP API, native BiteOpt and the CFD GP worker; no transport, pressure or physical model is changed by them. results/verified.json holds the numbers below for one complete smoke and one complete study run of the committed lessons. record.py writes it from the runs’ summaries and refuses incomplete or failed runs:

python tutorials/optimization/record.py --smoke SMOKE_DIR --study STUDY_DIR \
  --output tutorials/optimization/results/verified.json
CheckResult (smoke and study)
F1 native LP versus independent vertex enumerationAgree; normalized optimum 1.6662105873
F1 fresh full-field superposition replayLargest normalized receptor difference 1.1e-15 to 1.8e-15 for all three arms
F1 BiteOpt and native GP (seed 601 each)Completed with fresh and changed-wind replays; not a solver-superiority claim
F2 native MIP versus all 20 three-sensor subsetsBoth MIP and greedy cover weight 24, the optimum
F2 coverage-optimal subsets35 subsets of at most three sensors reach 24 (2 single sensors, 13 pairs, all 20 triples); 15 are rank deficient, the full-rank ones have condition numbers 2.0 to 259
F2 held-out inversionMIP: one sensor, rank 1; greedy: three sensors, rank 3, condition 2.0
F3 numerical and workflow checksEvery native solve accepted (45 smoke, 149 study) and independently checked
F3 fidelity gate (10% change in mean squared speed)Zero supported designs; smoke 32% (all three arms at lid speed 1.0), study 12.1% (fixed), 10.4% (sampling), 10.6% (BiteOpt)
Eight Python unit and negative checksPass normally and under python -O

F2 cannot separate the MIP from greedy: two single receptors already detect all twelve scenarios, so every three-sensor subset is coverage-optimal, and the rank contrast between the two answers comes from the solver’s and greedy’s tie order, not from the objective. That is the lesson’s point: coverage optimality says nothing about identifiability. A rank-deficient inverse reports its nullity and a null full-inverse condition number, separately from the condition number of its observed subspace.

F3 measures mean squared speed as the trapezoid volume mean of the staggered face velocities. Its study designs miss the 10% screen by 0.4 to 2.1 points; the gate is not relaxed. The withheld viscosity is a convergence check only. In smoke, sampling and BiteOpt return the fixed lid speed, so the three arms are one design.

F1 uses serial prescribed transport; only F3 exercises coupled pressure and momentum. F1’s GP work counters are separate from its full-field solve counts. Timings depend on host load and establish no performance ranking. F2 keeps the same small exact scenario design in both presets.

The F3 negative result is part of the lesson. Accepted discrete solutions, two-grid agreement and physical validation are distinct. These fixtures do not qualify canyon/RANS predictions, masked multigrid, a coupled-flow worker or real-world sensor placement. A refinement study must retain the current failures and predeclare its next resolution and criteria.

Urban features: verification, measured failures and open gates

Summary. Polygon-prism buildings, building-wall roughness, pressure multigrid with buildings, particle size classes, porous vegetation, the map converter and the wind-direction campaign pass their numerical verification fixtures. None of them is experimentally validated. Four results of this record are failures or open questions, and they stay in it:

  • Multigrid with buildings needs fewer pressure iterations but gives no consistent gain in run time (ratio of default to multigrid time 1.05, 0.94 and 0.91 on three accepted pairs). The default preconditioner did not change.
  • The canyon rotated by 45 degrees did not pass its frozen grid study: one case was rejected and two timed out. No rotation error is known.
  • In the Delft district demonstration none of the twelve wind directions converged within its 45 s budget, and the refined run stopped after 5 steps.
  • No urban comparison with OpenFOAM and no comparison with measured urban data exists.

The guide for these features is chapter 22.

Names used in this record

The work followed a plan whose stage and gate names appear below.

NameMeaning
U0 to U7Stages of the plan: U0 throughput target, U1 multigrid with buildings (masked multigrid), U2 decision on defaults, U3 polygon prisms and wall roughness, U4 map converter, U5 particle size classes, U6 vegetation, U7 one district with twelve wind directions
U8A conditional GPU experiment; not started
P2b, P2cNames of masked multigrid and of the measurement of its setup cost in the performance gap status
G0Gate after U0: a declared throughput target and a measured baseline
G1Gate after U1: equivalent accepted fields and a measured end-to-end gain of multigrid on the 27k and 93k canyons
G3Gate after U3: a canyon rotated by 45 degrees reproduces the grid-aligned receptor values within a tolerance declared before the run, at two resolutions, with a shrinking difference
G7Gate after U7: every direction of the district campaign is accepted or kept as a failed row within a declared budget
V1, V2Validation tracks: V1 the same canyon in OpenFOAM, V2 measured data
M5a, M5bRoadmap milestones for particle settling and for vegetation (roadmap)
R1 to R3, GRStages and gate of the mobile-measurement work (mobile record)

Where the run archives are

The run records behind this page are not in the repository. They are attached to the GitHub release v0.2.0 as the asset cfd-craft-0.2.0-evidence.zip (3.5 MB): folder urban/ for this record and mobile/ for the mobile record, with a README, SHA256SUMS.json and DATA-LICENSE.txt, which holds the CC BY 4.0 attribution of the inputs derived from 3DBAG for the Delft district. The raw map is not included.

The urban field files are not in the asset and were not kept. For each urban run the asset has the consumed case, summary.json, the profile, the manifest, the record of the independent field check and the logs, but not fields.json and checkpoint.json (38 field files, 711 MB). The manifests and urban/evidence-summary.json record their SHA-256 hashes. So the pass or fail of each independent field check and the field differences of the multigrid pairs below are values recorded by the runs that had the fields; they cannot be recomputed from the asset, only by running the cases again. The mobile archives are complete, with fields.

The archives were produced before the code review of this release, on the source tree that each archive records. They are records of past runs. A run with the current code has another source fingerprint, and its timings depend on the host.

To reproduce a run of the pressure or rotation comparisons, take its consumed case urban/NAME.json from the asset, run cfd-craft profile urban/NAME.json --output NEW_DIR and audit the result with python validation/check_fields.py NEW_DIR/run. python validation/summarize_urban.py DIR --output FILE builds the summary of the pairs from run directories that contain their fields; run on the urban/ folder of the asset it marks every row as not accepted, because the fields are missing. For the district, download the 3DBAG tile named below, convert it with integrations/urban_map.py and run validation/urban_campaign.py run with the budgets stated below (chapter 22). The verification fixtures are tests of the repository (cargo test --release --workspace --locked and validation/test_urban_*.py).

Source and measurement scope

Base: 7d8d70a864383e92f431d8afdacd15864e6c1c54 (0.1.1, latest main when checked out). An isolated clean build independently confirmed the original IC0 producer source fingerprint ce85729bc3564d2658ce6894e232e69da981a07ac36fde4512c5468ba05866fc. The archived runs record four source fingerprints, because the source tree grew while the stages ran: the IC0 rows record the one above, the multigrid rows a64798247531f1b67e0ef264bd6b87440fd4b2cb9585f9aaed3f87ba9fb8776b, the rotation study and the district ensemble 5067dfcb11cd8b0dbc7e322cc8ed8b22d418986d6029dab5a8623aa275ca9e33, and the refined district run 786eb87c9f81b86fd1f8aa8aa947d090524abeedd5d6de3ef0eb2daceba30a72. An IC0 row and its multigrid row therefore come from different builds. The later R1–R3 producer and its separate synthetic gate are recorded in mobile evidence; these earlier experiments were not silently relabeled as runs of that implementation. Compiler: rustc 1.100.0, x86_64 Linux. Each numerical run requests one thread; the district campaign uses two concurrent workers. Timings are one cold run per recipe on a shared cloud host, with complete setup/phase profiles. They are exploratory measurements, not a repeated statistical speed ranking.

The provisional G0 target is an accepted one-million-cell steady district run within two hours on one CPU thread, with a 6144 MiB preflight budget and independent field audit. This target is declared for future qualification, not achieved by the present short-budget experiment. The synthetic block has 20 buildings, a 200 m × 200 m × 60 m domain and 5H/15H/5H clearances for its declared prevailing wind. The 4 m grid has 37,500 cells; the 2 m grid has 300,000.

Pressure multigrid with buildings: no consistent gain

Solver elapsed time below includes native setup/solve scope; launcher and archive overheads are retained separately in the detailed records.

CaseIC0 secondsMultigrid secondsOuter steps eachIndependent fieldsIC0/MG time
Synthetic block, 37,500 cells30.451933.5757400Both pass0.907
Canyon, 27,648 cells66.474863.44731100Both pass1.048
Canyon, 93,312 cells816.9110869.20233000Both pass0.940
Synthetic block, 300,000 cells60.271160.511950/54Both incomplete; continuity audit failsNo ratio

The accepted field comparisons use bounds declared before comparison: maximum velocity difference 1e-4 m/s, pressure difference 1e-3 m2/s2, and receptor relative difference 1%. Actual velocity/pressure differences are about 1e-15 on both canyon grids; receptor differences are 4.43e-10 and 3.27e-11 relative. Both methods solve the unchanged fine equation to the existing native and independent archived-field checks. There is no accuracy-for-speed trade.

The 27k gain is small and absent on 93k and the block. Therefore G1’s coupled gain requirement is not met (gate G1 remains open), and U2 keeps donor-cell/explicit/IC0 defaults. The opt-in implicit recipe remains available as an explicit case copy.

Setup and pressure work of multigrid (U1, P2c)

CaseMG setup secondsIC0 pressure iterationsMG pressure iterations
37,500-cell block0.039232794510
27k canyon0.00685558902019
93k canyon0.07484128274231

Each hierarchy builds once and is reused. Fewer PCG iterations do not imply lower coupled cost. Masked connected-aggregate verification covers exact Galerkin products, full-cycle symmetry/positive energy, independent pivoted dense reference solutions, sealed/anchored/singleton components, barriers, passages, cache rebuilding, projection and transactional cancellation.

The original sequential campaign recorded RUSAGE_CHILDREN.ru_maxrss, a cumulative maximum over all preceding children. Its later rows must not be read as per-case RSS. The durable 93k replays independently sampled 245,300 KiB (IC0) and 273,484 KiB (MG). Profiles/fields identify every producer. An initial IC0 session interruption is retained separately; the bounded replay supplies the completed 93k result.

Geometry and the rotated canyon (gate G3 not passed)

Boxes, simple concave prisms, equivalent 0°/90° masks, exact shape volumes, represented volume errors, adjacent passage resolution, diagnostic paths and empty-ABL roughness controls pass. The independent checker rebuilds polygon masks, shape counts/volumes/passages and rejects forged geometry evidence. A positive optional non-ground wall roughness is independent of cell width; omission preserves the legacy wall recipe.

The frozen 45° study uses 32×32×12 and 64×64×24 grids, 90 s per run, receptor relative bounds 35%/25%, and requires shrinking error. It does not pass:

GridAligned45°
12,288 cellsAccepted in 10.153 s, 400 stepsRejected: receptor stencil crosses a stair-stepped solid (CFD-E042)
98,304 cells90.092 s timeout, 285 steps90.111 s timeout, 260 steps

No rotation accuracy ratio is reported for rejected/incomplete pairs. The strict interpolation rule is preserved. Wider passages, sufficiently resolved sampling and a complete frozen refinement study are needed before claiming orientation independence; improved wall treatment remains a possible follow-up.

Particle and vegetation verification

FixtureResult
Falling layer cumulative mass budgetRelative defect 3.47e-16
Periodic settling L1, 32/64/128 cells0.0053689/0.0027203/0.0013672
Wind-plume centroid(0.390000000000005, 0.539999999999995), analytic (0.39, 0.54)
Complete steady settling–diffusion/source column, 16/32/64Relative RMS 1.760%/0.894%/0.451%; first-order boundary/spatial refinement
Column steady source/deposition ratesAgree within frozen 1.1e-6; maximum cumulative mass defect 1.08e-13
Uniform-force canopy speedMatches sqrt(0.08) with zero measured error
Porous-block pressure drop0.799999999965 versus integrated drag 0.800000000000
Uniform leaf decayRelative error 1.07e-6, mass defect 1.47e-15
Leaf-block refinementRelative errors 3.26e-4/8.10e-5/2.05e-5
Active-canopy transient momentumVerified first-order time convergence
Zero leaf area densityEntire numerical State bytes and empty-ABL terms unchanged

The complete column supplements the earlier interior manufactured exponential residual test. It starts cold, includes its top-layer source and boundary balance, and permits steady particle sources only when a represented removal path exists in their fluid component. Gas outlet rules are preserved. Other regressions cover one-cell periodic drift, periodic roof deposition, near-buoyant aerodynamic diameter, positivity, units, superposition and exact checkpoint continuation. Instantaneous discrete canopy work is recomputed from staggered face fields; cumulative deposited mass is checkpointed.

Case/physics identities record declared zero-LAD input, so identity fields and full archives differ; byte identity applies to the complete numerical State. No gas, particle or canopy field is experimentally validated by these tests.

Delft district: the campaign keeps every row, no direction converged (gate G7)

Data: 3DBAG v2025.09.03, tile 9-284-556, EPSG 7415, CC BY 4.0; credit © 3DBAG by tudelft3d and 3DGI. Source: download, license. No user site was supplied; this is a public demonstration crop in Delft. The converter records 21 input objects, retains 5 prisms at 3 m, and records 16 below-two-cell omissions. Ground elevation range 0.413 m is within the declared 0.5 m screen. Buildings are cropped/rotated/simplified and terrain flattened; 15H clearances are used on all horizontal sides. Source emission 1e-7 kg/s and one porous canopy are synthetic additions, not measured traffic or vegetation. The raw map is not committed.

The 183,260-cell ensemble has twelve cold local directions 0, 30, …, 330°, 45 s per run, one thread each, two concurrent workers and 720 s total budget. All twelve rows are retained; all twelve are incomplete timeouts. Workflow elapsed 296.18 s is inside the budget. These are failed study rows, not concentration predictions. Their incomplete local continuity audits also fail where recorded; mass closure alone does not make them accepted.

The same physical footprints, source, canopy and domain were refined to 1,466,080 cells on local 270° (geographic 247° after 23° map rotation). With a 45 s solver budget and 6,144 MiB preflight budget it reached 5 steps in 46.83 s and remained incomplete. Observed peak RSS was 3,844,560 KiB. The raw fine job omitted its map rotation metadata and initially labeled geographic 270°; a declared derived metadata correction sets 247° without changing native input or fields. No grid-convergence conclusion is available from these incomplete runs.

The fine profile gives pressure solve 5.34 s (11.4%) and scalar transport 11.89 s (25.4%) of 46.83 s; setup is separate. Coarse district profiles put pressure near 5–6% and scalar transport near 40%. These are partial-run profiles.

A separate one-second orchestration smoke repeated all twelve directions through the pinned optimization-jobs trusted-command runner. All twelve failed rows, native archive ZIPs and verified runner manifests were retained in 39.26 s. This verifies orchestration/failure preservation, not convergence. An initial command-output cap error was fixed to the runner’s 64 MiB limit and its twelve rejected rows were kept. app.cfd.wind-direction also completed one actual SDK evaluation with zero failed/cancelled evaluations.

Validation and GPU decisions (U8, V1, V2)

U8 is not triggered: pressure is not the dominant measured cost, including the million-cell sensitivity run. No GPU backend or speed/parity claim is added. V1’s urban OpenFOAM translator/comparison remains pending; this host has no OpenFOAM installation, and the existing backend still supports its earlier two cases. V2 remains blocked on measured urban data/terms; no contact or agreement was made. Existing data inventory and CODASC protocol remain authoritative. The published backstep evidence does not validate urban PM or vegetation.

The next useful performance work follows the measured coupled profile: scalar substeps/canopy coefficient reuse, momentum residual and turbulence work. Re-run the same accepted 27k/93k fields and the frozen district/rotation gates before changing defaults or recommending district optimization campaigns.

Measurements of the code review

The code review of this release (14 November 2026; 2-CPU host, rustc 1.97, one thread, fixed numbers of steps, so these are not accepted steady runs) measured multigrid against the default ic0 preconditioner again:

CaseMultigrid pressure iterationsic0 pressure iterationsMultigrid pressure timeic0 pressure time
Canyon, 27,648 cells160461923.5 s4.2 s
Canyon, 93,312 cells70331595.9 s8.3 s
Canyon, 1,000,000 cells, 3 steps387230958 s114 s
Canyon 18x16x96, weight ratio 256, 10 steps223616954.48 s1.15 s

On the three grids with equal cell widths multigrid needs 3.9 to 6.0 times fewer iterations. On the stretched grid it is slower, because the path for grids with buildings has point smoothing only; the warning CFD-W004 now says so for a case with geometry. Setup at one million cells took 0.8 s and 170 bytes per cell. These rows do not change the conclusion above: no consistent end-to-end gain, default unchanged.

The review also corrected the rule for a cell center exactly on a slanted polygon edge that two footprints share. An archive produced before that correction whose polygons have such a center no longer passes validation/check_fields.py; none of the committed cases is affected.

Mobile measurements: numerical evidence on synthetic data

Summary. Path receptors, the virtual ride, line sources from supplied street rates, frozen-flow source responses, the fit of emission rates and the route selection pass their numerical checks on two synthetic studies. In both studies the data were produced by the same model that is fitted, so a recovered rate tests the workflow, not the atmosphere. No measured ride, traffic count or calibrated sensor has been used; nothing here is experimentally validated. The open questions of the urban record (rotation, district budget, no consistent multigrid gain) apply unchanged to any matrix built on a district flow.

The guides are chapters 23 and 24.

Names used in this record

NameMeaning
R1Stage of the plan: path receptors and virtual rides
R2Stage: line sources from street data
R3Stage: source inference and route selection from rides
GRGate after R3: on a synthetic truth, street emission rates inferred from virtual rides are recovered on held-out rides within an error declared beforehand, and source combinations that the rides cannot separate are reported
V1, V2Validation tracks: V1 the same canyon in OpenFOAM, V2 measured data. Both are open

Where the run archives are

The run archives of both studies are not in the repository, because field files are large. They are attached to the GitHub release v0.2.0 as the asset cfd-craft-0.2.0-evidence.zip (3.5 MB), folder mobile/, beside the folder urban/ of the urban record, a README, SHA256SUMS.json and DATA-LICENSE.txt. They were produced before the code review of this release, on the source tree that each archive records. They are records of past runs.

To reproduce the studies with the current code, build the mobile_response example and run

python tutorials/mobile_measurements.py run --preset source-response --output NEW_DIR_1
python tutorials/mobile_measurements.py run --preset canyon --output NEW_DIR_2

(chapter 24). The new reports carry the fingerprints of the current source; the documentation check runs the first preset on every change.

Identity and frozen gates

Base commit: 7d8d70a864383e92f431d8afdacd15864e6c1c54 (0.1.1). Native mobile producer source SHA-256: bb0a97221837bafb1fc82e6c4f29c7f0a8bcf60e5fc5e21b4bfebebcfd75c845. Each report records the native example-driver, request and immutable-flow hashes. The matrix additionally records its frozen study-plan and Python driver hashes, complete sensor parameters and per-wind producer identities. No raw map or measured ride dataset is needed for these synthetic fixtures.

Before execution, tutorials/mobile_measurements.py writes the plan and gates: relative rate and held-out errors at most 1e-3, relative superposition defect at most 1e-4, full training rank, disclosed alias ambiguity, and a certified integer solution within 2e-6 normalized defect of exhaustive enumeration. Thresholds were not relaxed after observing results.

Both studies use three source groups, multipliers [0.7,1.3,0.4], two winds, two training and two held-out routes. Each wind executes one native flow preparation, three scalar columns and one separate combined-truth scalar solve, with zero flow updates during responses. All 20 final archives across the two studies pass the independent stored-field audit, including every path sample/mean, mass, represented geometry and frozen-flow fingerprint. The independent combined truth is not formed by multiplying A by the truth.

Path and supplied-street verification

The native Gaussian path interpolation fixture’s relative RMS errors at 16/32/64/128 cells are 0.01173618/0.00291733/0.000728648/0.000199703. A shrinking straight path versus its thin volume average gives differences 0.00492794/0.00123327/0.000308397, consistent with second-order convergence. Other fixtures cover reversed samples, exact linearity, corner geometry, continuous solid crossing between samples, solid interpolation support and bounded sample allocation. Actual returned field samples and path means agree with independent reconstruction. The first-order sensor reproduces analytic step and ramp responses, preserves the exact final timestamp without duplicates, and handles a zero response time.

The supplied-street converter fixture preserves multisegment lengths and adds exactly 3.7e-6 kg/s from the supplied synthetic CSV. Tests include native emitted-mass normalization, 90° map rotation, crop/domain clipping, an intermediate thin-building intersection, positive-rate omissions, unknown IDs, wrong units, malformed geometry and native coarse-mask rejection. The tool consumes and hashes actual street/rate bytes; it invents no emission rate. Malformed input produces a coded diagnostic under normal and optimized Python.

GR results from actual native fields

StudyRelative superposition defectRelative rate errorHeld-out relative errorTraining rankGR
Uniform laminar source-response, winds 270/2503.153e-163.629e-162.212e-163/3Pass
WH1 canyon, winds 270/2253.230e-82.859e-94.363e-73/3Pass

The canyon uses the opt-in implicit flow recipe, fixed linear scalar transport and coarse existing geometry. Its residual-level superposition error is consistent with independently terminated scalar solves; it is below the frozen gate. Whole held-out rides are excluded from fitting, weighting and selection. The reference station is excluded from the fit. Appending a deliberately collocated identical street-b response gives rank 3 of 4, nullity 1, with the street-b/alias ambiguity named rather than individually interpreted.

The virtual sensor travels at 1.5 m/s, records every 0.25 s and has a 1 s response time, starting at zero. Declared sensor sigma is 2e-10 kg/m3 and coherent between-pass sigma 1e-9 kg/m3. Neither is sampled or estimated from data.

StudySelected route/wind opportunitiesRiding + setup secondsBudget secondsWorst-direction informationMaster solves
Source-responseNear at 270 and 25026.666736236.18704
CanyonCanyon path at 270 and 225323679160.16334

LP-IP-craft 0.29.0’s native mixed integer solves and eigenvector cuts converge within the 1e-7 normalized floating-point gap. All 16 candidate subsets are independently enumerated for each four-candidate campaign; normalized objective defects are below 2e-16. The selected matrices have rank 3. A separate five-route fixture checks 32 patterns and a nontrivial optimum. Cut/time/native-solver limits preserve the incumbent and actual failure/bounds without claiming a certificate. No exact rational optimality proof is claimed.

Conditional pass planning and station ratios

With a 10% relative mean half-width, Gaussian z=1.96, five effective independent samples/pass and zero systematic floor, the assumed pass counts are:

Study / windFirst training pathSecond training path
Source-response 2703169
Source-response 25045102
Canyon 270132
Canyon 225115108

The high downwind count at 225° follows its tiny modeled increment and the assumed pass scatter; it is retained. Counts are planning calculations, not measured precision. A systematic uncertainty floor can make the target unachievable; correlated drift and CFD error are not removed by repetition.

The canyon’s modeled adjacent steady-path/station ratio is 1.0 at both winds on this coarse field. The lagged, zero-initial sensor-mean/station ratios are 0.2693913 and 0.2499111. Short-ride warm-up is part of this observation operator. These numbers neither validate sensors nor compare total ambient PM.

Independent review and limits

Separate reviewers tested R1, R2 and R3. Fixed issues included exact endpoint handling, bounded-memory tall-matrix SVD/whitening, complete named nullspace coefficients for disparate source scales, malformed street input diagnostics, frozen-flow adoption eligibility, timeout-row retention, original bent-route geometry and exact consumed-byte fit provenance. Resealed changes to each flow array, declared fingerprint or flow-update count are rejected by the independent checker in both normal Python and python -O.

No measured concentrations, traffic counts or calibrated sensor response were provided. V2 remains unopened under the mobile protocol. The existing OpenFOAM backend still does not translate an urban dispersion case. All previous urban failures and open gates remain part of the evidence; synthetic GR is not a substitute for those qualifications.

Changes of the code review

The code review of this release (14 November 2026) changed three things that this record touches. A route selection is now certified against the solver’s proven bound, not against the objective value of its incumbent. The study driver now recomputes the frozen-flow hash of every archive of a wind and requires them to be equal, and records a malformed archive as a failed audit. After these changes the source-response preset was run again and passed all its checks; the tables above are the recorded runs, unchanged.

Working on CFD-craft

This section is for contributors, human or agent, who change the solver, the adapters, the checks or the documentation. To run cases, start with the guide. The rules for every change are in AGENTS.md.

Pages in this section

The measurements behind these pages are listed in the evidence index; the plans as they were written are in the history.

Checks before a change

cargo fmt --all -- --check
cargo clippy --workspace --all-targets --locked -- -D warnings
cargo test --release --workspace --locked
ruff format --check . && ruff check .
python validation/test_cli.py -v
python -O validation/test_cli.py -v
python validation/test_manual_examples.py -v
python scripts/generate_reference.py --check
python validation/test_check_docs.py -v
python scripts/check_docs.py --smoke > runs/docs-check.json
python validation/run_suite.py --preset smoke --output runs/verification
python validation/flow_accuracy.py --output runs/flow-accuracy
python validation/cavity.py --output runs/cavity
python validation/scipy_reference.py --output runs/scipy-reference

Every validation/test_*.py runs normally and under python -O; the jobs rust, python-lint, numerical and external-contracts of .github/workflows/ci.yml list them all. The OpenFOAM tests without a runtime check contracts, not physical accuracy. A failed row stays in its report; a failed refinement run never becomes an accepted grid-convergence result.

Opt-in CI work

A manual dispatch of ci.yml installs the pinned OpenFOAM runtime. Its input external selects backend, resolution, mapping, refinement, comparison or all, and, not part of all, accuracy (the cavity grid sweep, with the inputs native_pressure, native_numerics and native_span), momentum (adds momentum_scheme), pressure and anisotropy. A recorded backstep failure keeps a job green; a workflow error fails it; comparison fails on any failed run. Chapters 16 and 19 of the guide show what these jobs run.

Accuracy and steady-solver work

The defaults are donor-cell momentum advection, explicit pseudo-time and the IC(0) pressure preconditioner. Opt-in selections are second-order momentum advection, the implicit_projection steady algorithm and multigrid (chapter 9). Start from the accuracy and steady-solver plan, the donor-cell baseline and the matched-accuracy record. validation/compare_backends.py --grid-sweep --grids 16 24 32 48 runs both backends on the same grids; --native-numerics JSON selects opt-in native numerics. Keep the default path, the acceptance thresholds and failed rows.

Performance work

Compare two builds at fixed work with the performance_probe example, validation/benchmark_native.py and the cases in cases/performance/: inputs, producers, work counts and fields are compared, and timing is a separate observation from acceptance. Record slower controls and memory costs. For phase attribution use profile; add exclusive times only. A same-grid ratio is not cost at matched accuracy, and an unreached target has no finite ratio. For pressure work, IC(0) stays the default and multigrid is rejected on masked grids, without fallback; validation/benchmark_pressure.py, benchmark_anisotropy.py and benchmark_anisotropic_flow.py keep cold setup, reused solves and accepted coupled cost apart (pressure multigrid). The current state is in the performance gap status.

Architecture

This page shows how the parts of CFD-craft fit together, where each part lives in the repository and what a native run does from the case file to the archive. It is for contributors; users start with the guide.

Components

flowchart TD
  A["Case JSON and budgets"] --> B["Native CLI"]
  A --> C["Rust library caller"]
  A --> Y["Python binding cfd_craft"]
  B --> D["Native solver"]
  C --> D
  Y --> D
  M["Map and street converters"] --> A
  P["Python workflows"] --> B
  P --> E["OpenFOAM adapter"]
  E --> F["Foundation 13 processes"]
  D --> G["Native run archive"]
  G --> R["Field checker, virtual rides, inference"]
  F --> H["External run archive"]
  J["Job and campaign runners"] --> P

The CLI, the library and the Python binding share one strict parser and one preflight (input.rs) and one solver. The binding runs the solver in process and returns a summary; only the CLI writes fields, archives, checkpoints and profiles. The paths share experiment concepts, not interchangeable result directories. Use cfd-craft report for native archives and the adapter’s report command for its archives. complete.json marks an integrity boundary; it does not claim numerical convergence or experimental validity.

Repository map

PathPurpose
crates/cfd-craft/src/case.rsTyped case contract, semantic checks and physics hash
input.rsStrict JSON parsing and the complete case preflight shared by every interface
grid.rs, geometry.rsUniform cells, staggered faces, box and polygon-prism masks by cell centers, per-shape volume and passage evidence, connected components
pressure.rs, multigrid.rs, multigrid/line.rsMatrix-free pressure operator, gauges, default IC(0)/PCG, opt-in symmetric point and line multigrid for grids without solids, projection
multigrid/masked.rsOpt-in multigrid for grids with solids: aggregates of face-connected fluid cells, one gauge per sealed fluid region, point smoothing
flow.rsLaminar and RANS momentum, turbulence, wall treatment, optional building-wall roughness
vegetation.rsPorous canopy volumes: drag, canopy terms of k and epsilon, leaf deposition coefficients, drag evidence
momentum_solve.rsImplicit momentum corrections of the steady algorithms, BiCGStab, CFL ramp
turbulence_solve.rsImplicit k and epsilon corrections of implicit_projection with RANS
transport.rsSource and receptor weights (point, volume, path), conservative scalar transport, particle settling and deposition
mobile_response.rsFrozen-flow source responses: adopt an accepted steady flow, then transport-only runs that never update it (PreparedFlow)
solver.rsState, control, time step, transactional step and assessment
profiling.rs, verification.rsPhase profile; the pressure fixture of verify
output.rsCheckpoint compatibility, archive publication and integrity reader
crates/cfd-craft/examples/Manual examples, performance_probe, pressure_probe, kernel_timing, mobile_response (the driver of the mobile study)
crates/cfd-craft-cliParsing, process, thread and signal policy, build provenance
bindings/python, python/cfd_craftThe PyO3 binding (its own workspace) and the Python package with its console script
cases/Committed cases: verification, canyon, performance (byte-identical; their hashes are provenance)
integrations/OpenFOAM backend, restart and mapping, the optional optimization-job worker
integrations/urban_map.py, traffic_sources.pyConverters that write a case: buildings from GeoJSON or CityJSON, line sources from street rates, each with a provenance file
integrations/virtual_ride.py, mobile_inference.pySensor ride along a path of an accepted run; rank, fit, pass planning and route selection
integrations/urban_job.py, launch_urban_command.pyWind-direction campaign as optimization-run command jobs
tutorials/Studies, source inference, the mobile-measurement study (mobile_measurements.py), the backstep tutorials and the optimization lessons
validation/Independent checks, references, contract tests, benchmarks, the wind-direction campaign (urban_campaign.py) and the data inventory
scripts/Documentation check, reference generator, release checks, case generator
docs/Guide, reference, model cards, developer pages, evidence records and history

The Rust file names from input.rs to output.rs are relative to crates/cfd-craft/src/. The converters, the ride tool and the inference module are Python and optional: the solver has no dependency on them or on their packages (Shapely, NumPy, SciPy, LP-IP-craft). The public low-level modules are inspectable research interfaces. For ordinary applications prefer Case, Control, solver::run and the CLI and archive API; using grid, face or state vectors directly requires respecting their invariants. Chapter 20 of the guide shows the library API.

Native execution lifecycle

  1. Deserialize strict typed JSON and reject unknown fields and variants.
  2. Check dimensions, units, budgets, geometry and physical combinations.
  3. Build the grid and the solid mask; normalize sources and receptor weights (path samples included); reject solid support.
  4. Initialize or import a compatible state, including cumulative mass budgets.
  5. Advance bounded steps while polling cancellation and the deadline and assessing fields.
  6. Retain the last accepted state and the actual stopping reason.
  7. Publish the case, summary, requested fields and checkpoint, and the manifest and marker.
  8. Verify integrity and separately audit archived physical quantities.

A frozen-flow response (mobile_response.rs) enters at step 4 with the state of an accepted flow run and advances only the constituents in step 5; its summary records the hash of the flow fields it kept.

The CLI adds a host-memory preflight, a Rayon pool, signal handlers and executable and build identity. The library is meant for callers that own those policies themselves, such as optimization workers. The Python binding adds a cancel file and releases the GIL while the solver runs (chapter 11).

Where the contracts are written down

  • Result contract: status words, archive files, check scope.
  • Diagnostics: every code with the field it names.
  • Model cards: what each model assumes and what evidence it has.
  • Reference: case and result schemas, command line, Python API.

Native phase profiling and cavity accuracy sweeps

Profiling measures the existing algorithm to establish a baseline for pressure multigrid and better momentum discretization. Read the iteration plan and the baseline results for scope and recorded results.

Profile a real run

cargo build --release --locked
mkdir -p runs
target/release/cfd-craft profile cases/verification/lid-cavity.json --output runs/profile-cavity
target/release/cfd-craft report runs/profile-cavity/run
python validation/check_profile.py runs/profile-cavity

The canonical cavity case runs a transient interval. For a steady measurement, make a case copy with run.mode set to steady and run.threads to 1. Case checks and resource limits apply to both commands. --restart CHECKPOINT uses the same verified native restart contract as run.

The output path must be new and its parent must exist. An envelope contains:

  • run/: an ordinary cfd-craft.manifest/0.1 archive, readable by the existing native reporter and independent field checker.
  • profile.json: cfd-craft.native-profile/0.1, containing the summary, consumed input/source/state/manifest identities, initial counters and a cfd-craft.phase-profile/0.1 timing record.

The command exits 0 for accepted numerical evidence with all requested artifacts, 2 for incomplete/failed numerical evidence or output omissions, and 1 for an invalid request or execution/I/O failure. A numerical failure retains its profile and ordinary archive. A process killed without a chance to write its results cannot guarantee a final profile.

check_profile.py checks the envelope’s link to the returned archive, work and nested time accounting. It runs the independent archived-field audit when fields are available. Its integrity verdict, native numerical assessment and independent audit remain distinct. These checks establish consistency; they do not authenticate a maliciously resealed archive or supply physical validation.

Interpret time and work

Each phase reports calls, inclusive seconds and exclusive seconds. For example, pressure_projection includes pressure_solve, which includes factor/operator setup. Add exclusive time only. The sum is compared with the enclosing solver and archive-write spans; the request remainder is unattributed_s.

solver_run includes grid/state setup, timesteps, monitoring and assessment. step includes momentum, pressure, turbulence and scalar subphases. Short operations such as intermediate allocations remain in their enclosing phase’s exclusive time. The control timer starts after preflight and checkpoint import, includes thread-pool setup, solver and archive writing, and ends before profile JSON serialization. The outer workflow measures independent checking and startup.

For pressure_solve, work_units counts attempted PCG iterations whose operator work started. operator_applications includes those compact products plus independent face-by-face true-residual checks; those checks have their own count. preconditioner_applications counts applications of the selected preconditioner. For opt-in multigrid, pressure_multigrid_setup and the optional pressure_solve.multigrid work object distinguish hierarchy construction and multilevel work; see the multigrid guide. A factor-setup span occurs only when construction runs, including a zero-RHS first projection. Timers and locks occur at phase boundaries; inner iterations update local integer counters.

With an implicit numerics.steady_algorithm, momentum_solve records the inexact momentum-correction solves: work_units counts inner iterations, and operator_applications is one per iteration for implicit_viscous (CG) and two for implicit_projection (BiCGStab). The envelope then carries initial_momentum_solver_iterations, and the checker requires the retained summary.momentum_solver_iterations to equal the attempted work for a run that ended without an error, and at most 50 iterations per solve.

With implicit_projection and neutral_rans, turbulence_solve (inside turbulence) records the implicit k and ε correction solves of each outer iteration: one call per outer iteration, work_units the inner BiCGStab iterations of both solves, operator_applications two per iteration. The checker requires that relation, at most 2 × 50 iterations per call, and no turbulence_solve calls for other algorithms or laminar flow.

Anisotropic levels add block updates, solves and level visits. The checker requires two block updates per block-level visit and total smoothing updates 4 * residual_cell_updates - 2 * block_level_cell_visits. Point-only records keep the previous fields and four-update relation. These counts measure cell visits, not the different arithmetic cost of a scalar and a block solve.

The ordinary summary’s steps/pressure iterations describe retained state. Profile work includes an unsuccessful step. Subtract initial_steps and initial_pressure_iterations for a restarted invocation. A failed projection can have positive attempted work and zero new retained iterations. Do not divide failed work by retained steps to estimate step cost.

Profiling consumes wall time. Cases close to a deadline can stop at different steps. Compare exact fields on fixed work or comfortably accepted runs, and measure on/off overhead with paired runs before making timing claims.

Rust API

Given a validated Case named case in a function returning cfd_craft::Result, use the same solver entry point:

#![allow(unused)]
fn main() {
use cfd_craft::solver::{self, Control};

let control = Control::new(case.run.wall_time_limit_s).with_profiling();
let result = solver::run(&case, &control, None)?;
let timing = control.profile()?.expect("profiling enabled");
println!("{} retained steps", result.state.steps);
println!("{} seconds accounted", timing.accounted_exclusive_s);
}

The caller owns its Rayon pool, producer identity and publication policy. Control::profile without with_profiling returns None. Custom Control::span(Phase) scopes must finish in nested order; snapshots with active or incorrectly nested spans return CFD-B003 profile.active or .nesting. Stacks are per thread. Concurrent callers can have aggregate exclusive time exceeding elapsed wall time; the CLI uses serial orchestration.

Measure cost at a declared accuracy

python validation/compare_backends.py --grid-sweep \
  --binary target/release/cfd-craft --foam-root runs/openfoam13/runtime/opt/openfoam13 \
  --levels 1 2 --sweep-rounds 3 --accuracy-target 0.01 \
  --native-wall-s 180 --timeout-s 180 --native-max-steps 20000 \
  --foam-iterations 3000 --output runs/accuracy-sweep

Install the pinned runtime through the backend guide. The sweep keeps one warmup and the requested timed rows for each configuration, alternating native/OpenFOAM order within each grid block. It adds a native 12² diagnostic. Supported paired levels 1,2,3 mean 24²,48²,72² in the flow plane. Native uses two periodic span cells by default (--native-span 1 for a two-dimensional native run); OpenFOAM keeps one empty span cell.

Every row retains numerical acceptance, independent evidence, the frozen 0.06 Ghia screen and measured maximum centerline-u error separately. A timeout, iteration limit or accuracy miss remains in report.json. The 0.01 target is a development objective; existing numerical checks still apply.

Best cost at the target uses configurations whose timed repetitions are all accepted and repeat their work, producer and sampled profile. Warmups do not enter medians. The native 12² diagnostic counts like any other configuration. If a backend misses the target on every tested grid/budget, its best cost and the cross-backend ratio are null, with an explicit target-not-reached status. No crossing is extrapolated.

The sweep exits 0 if all rows pass existing numerical/audit/reference checks, 2 when a valid workflow includes unaccepted evidence, and 1 for an invalid workflow, changed input or inconsistent repeated result. Missing the development target alone is a recorded outcome and does not invalidate a sweep.

Workflow time includes preparation, a bounded child, archive checks and the centerline sampling. Processes left in the child’s process group are stopped when it returns, and the row records stray_processes_stopped. Enumeration uses namespace-local PID/group IDs and excludes unrelated PID namespaces, including when procfs was mounted in an ancestor namespace. A row whose measurement fails validation keeps it as rejected_measurement beside the error. Native solver time is elapsed_s; OpenFOAM solver time is its foamRun child time. Separate process time and GNU-time RSS observations are retained. RSS means maximum individual process RSS, including waited descendants, rather than simultaneous aggregate memory; it is explicitly unavailable without GNU time. Inspect timer scopes before comparing the earlier comparison.

The old comparator without --grid-sweep retains its three-method, balanced permutation experiment and fail-on-unaccepted behavior.

For a hosted run, dispatch CFD checks with external=accuracy. It builds the release, installs the pinned runtime, runs the 24²/48² sweep with a 600 s native budget (the recorded baseline used 180 s, which a GitHub runner did not finish at 48²) and uploads the complete evidence. Notices show accepted-row counts, medians and unreached targets. This explicit opt-in is separate from the existing all budget.

Transfer evidence with its directory entries. An OpenFOAM archive’s progress record lists its numbered time directories, and one can hold no files (see the archive investigation); a file-only copy then fails openfoam_backend.py report although the original verifies. python validation/archive_evidence.py TREE NEW.zip writes a zip with every directory entry and checks that each archive in the extracted copy verifies exactly as the original does. It also lists archives whose progress records a time directory without files, which a verified archive does not rule out. The CI job uploads that zip and prints that list.

Momentum-verification grid list

--grid-sweep --grids 16 24 32 48 replaces the level-derived grid list with the same explicit list for native and OpenFOAM, omitting the native-only 12² diagnostic. The bounded cavity recipe also accepts --cavity-grid N; existing --level 1..3 recipes retain their generated numerical inputs. The list and all configurations are frozen in the sweep report before execution.

Dispatch external=momentum for the full Stage V protocol: the shifted operator fixture, translating vortex and time refinement, 1000-step stability baseline, shared-grid paired sweep, separately budgeted native 96² self-reference and default byte-identity controls. The 96² reference is not a timed cost-at-target configuration. Read the results for actual completion, retained failures and hosted status; an unreached target remains a null ratio.

Symmetric pressure multigrid

numerics.pressure_preconditioner selects ic0 (default) or multigrid. Multigrid accepts Cartesian cases without solids and cases with a geometry mask, also when the mask separates the fluid into several regions. Masked cases use the connected-aggregate path, which has point smoothing only. Laminar and neutral-RANS pressure use the same constant-density operator; no flow, scalar or turbulence model is changed. Prescribed-flow runs bypass pressure and gain no acceleration from this selection. Strong anisotropy now selects exact principal-line/small-plane relaxation and semicoarsening. check warns (CFD-W004) about its extra setup and memory cost; compare total time with IC(0). This extends the original point smoother, whose historical shape sweep showed poor convergence. Read the anisotropy results for measured coverage and limitations; extreme aspect ratios are not guaranteed.

Use it

Create an explicit case copy and retain it with the result:

mkdir -p runs
python - <<'PY'
import json
from pathlib import Path
c = json.loads(Path('cases/verification/lid-cavity.json').read_text())
c['run']['mode'] = 'steady'
c['run']['threads'] = 1
c['run']['wall_time_limit_s'] = 600
c['numerics']['pressure_preconditioner'] = 'multigrid'
Path('runs/cavity-multigrid.json').write_text(json.dumps(c, indent=2))
PY
target/release/cfd-craft check runs/cavity-multigrid.json
target/release/cfd-craft profile runs/cavity-multigrid.json --output runs/cavity-multigrid
target/release/cfd-craft report runs/cavity-multigrid/run
python validation/check_profile.py runs/cavity-multigrid

The preconditioner is part of the normalized numerics and checkpoint compatibility hash. Changing it starts a new run. An omitted selection and an explicit ic0 normalize identically to the old schema: old case/checkpoint hashes remain valid. The result/archive schemas and ordinary output layout are unchanged.

In Rust, set the case before building its grid or calling solver::run:

#![allow(unused)]
fn main() {
use cfd_craft::case::PressurePreconditioner;
case.numerics.pressure_preconditioner = PressurePreconditioner::Multigrid;
let grid = cfd_craft::grid::Grid::build(&case)?;
// pressure::solve/project on this grid use the selected preconditioner.
// After its first pressure solve:
let stats = cfd_craft::pressure::multigrid_stats(&grid);
}

describe exposes the case enum, supported preconditioners and explicit default. Its legacy pressure string continues to name the default IC(0)/PCG path.

Equation and hierarchy

The fine equation remains A p = b, with A = -D G, the original shared face weights and outlet correction equal to zero. Each closed component has a compatibility check and a mean-zero gauge. The compact fine PCG product and the independent final face-by-face residual use current grid coefficients, including duplicate two-cell periodic faces. The final tolerance remains 10 * pressure_relative_tolerance + 1e-12, relative to the compatible RHS.

The point hierarchy groups consecutive cells in pairs along each axis; an odd last group has one cell. Directions with at most two cells are retained, so the two span layers of the cavity keep separate coarse degrees of freedom. Coarse centers are the pair’s mean location. Transfers are tensor products of linear interpolation between centers, periodic across a wrapped boundary and clamped at a nonperiodic edge. Each row sums to one. Interpolation of an anchored case need not itself satisfy a boundary derivative: the unchanged fine operator supplies the boundary equation through Galerkin projection.

Restriction is exactly the transpose of prolongation, R = P^T, and A_c = P^T A P. The pressure inner product on the uniform fine grid differs from Euclidean only by a common cell-volume scalar. Coarse equations use sums, not volume averages; they are not rediscretized Laplacians on wider cells.

Construction transfers symmetric edge energies and outlet contributions. It stores symmetric off-diagonals and transfers row sums separately to preserve closed constants; rounding is at floating-point assembly precision. Coarse couplings can have either sign: treating every coarse edge as a positive physical face would be incorrect. Coarse diagonal positivity follows from Galerkin, not from an assumption that every coarse off-diagonal is negative.

Every application starts from zero. Point levels use exactly:

  1. Two forward Gauss–Seidel sweeps.
  2. A residual, transpose restriction and one recursive coarse correction.
  3. Linear prolongation and two backward Gauss–Seidel sweeps.

Anisotropic levels

At setup, calculate fine weights w[a] = 1/dx[a]^2. Compare their largest value (including two-cell axes) with the smallest value among axes having more than two cells. If the ratio exceeds 25, select stiff axes within a factor four of the largest weight. A weak two-cell span alone therefore does not trigger blocks; a stiff two-cell span does. This policy uses declared uniform spacings, not an adaptive residual estimate, and selects at most two stiff axes.

Coarsen the stiff axes first, retaining every weak-axis sample. When those axes reach two cells, coarsen the remaining weak axes. Transfers still interpolate linearly, restrict by their exact transpose and form the Galerkin operator. The policy and hierarchy remain fixed during PCG. It is a conservative first policy, not an automatically tuned optimal hierarchy.

On each nonterminal anisotropic level, one forward block sweep and one backward block sweep surround the coarse correction. Normally a block is a full line in the strongest direction. When two stiff axes together have at most 16 unknowns, use their joint small plane instead, so both retained stiff directions can be solved together. Each block solves the actual principal matrix, including Galerkin fill and duplicate periodic contributions, against the latest outside values. The fine equation is never replaced by a line approximation.

Factor each band block once by Cholesky; retain outside-block CSR rows and reuse scratch. Fold periodic ordering 0, n-1, 1, n-2, ... to avoid a dense cyclic band. Determine the bandwidth from actual entries. Both adjoint triangular solves use the same stored diagonal reciprocals. A nonpositive/nonfinite pivot is CFD-E036, with no shift or fallback. Dense pivoted Gaussian references test forward and reverse sweeps on odd, periodic, outlet and small-plane fixtures.

At at most 32 cells, dense Cholesky solves the anchored system directly. For a closed system, one pressure value is removed before factoring; compatible RHSs are solved and the mean-zero gauge restored. A single closed coarse cell has no remaining unknown. A nonpositive pivot produces CFD-E035, without modifying the equation or silently switching methods. There is no inner Krylov solve, inner stopping tolerance, residual-dependent cycle count or correction scaling.

Why ordinary PCG is appropriate

PCG requires a fixed symmetric positive preconditioner on the solved subspace (PETSc’s requirement). Here:

  • Tensor interpolation has full column rank: each one-dimensional interpolation has a strictly dominant submatrix formed from a distinct nearest fine sample for each coarse center. Tensor products preserve that rank. It preserves constants, so Galerkin retains precisely the closed constant nullspace; an outlet makes the coarse system anchored.
  • The direct coarse inverse is positive and symmetric, restricted to the compatible closed subspace when necessary.
  • Backward sweeps are the adjoints of the forward sweeps. A paired forward/back Gauss–Seidel correction has positive symmetrization F^T D F, with positive diagonal D; inserting a positive coarse correction and repeating paired smoothing preserves positivity and symmetry. Mean-zero projections are orthogonal and only remove the known constant mode.
  • All work and coefficients are fixed within each outer solve.

Block levels replace positive scalar diagonals by SPD principal blocks. Exact block factor solves and reverse block order give the same symmetric positive composition. The fixed one-pair block cycle and two-pair point cycle are both tested as complete matrices on the compatible subspace, including periodic and outlet anisotropic cases. Independent dense Galerkin tests also verify that semicoarsening preserves the retained weak-axis modes.

These are the mathematical conditions. Tests also assemble the entire small preconditioner and Cholesky-factor its compatible-subspace matrix; such finite checks supplement the argument. This cycle differs from the standalone, potentially nonsymmetric/scaled GAMG settings in the OpenFOAM recipe. No OpenFOAM or other separately licensed solver code is copied into the core. The line/semicoarsening approach is consistent with the numerical motivation in hypre’s structured multigrid documentation; this implementation has its own transfers, blocks and PCG contract.

Reuse, memory and profiling

One grid cache owns the hierarchy and reusable RHS, residual and correction vectors. A mutex holds it for a pressure solve, so concurrent callers sharing a grid serialize these solves. Cloned grids safely share the cache. The cache keeps the grid size, gauge and every interior or outlet face’s cells and pressure weight from its build (32 bytes per such face, not counted in allocated_bytes) and compares them exactly before each solve; any changed public face coefficient rebuilds the hierarchy. The exact cache signature now also compares spacing bits, which determine block selection; it does not hash the full grid per solve. Changing topology should rebuild the grid. No cycle allocates inside PCG; setup allocations are separate.

pressure::multigrid_stats reads a separate copy of the statistics and never waits for a running solve, so a Control::with_poll callback may call it. A poll callback must not itself run a pressure solve on the same grid or a clone of it: that solve would wait for the running one.

Case preflight adds 1024 bytes per cell for the point hierarchy, and a further 512 bytes per cell when the block policy is active, before the existing 25% safety margin. These cover retained storage and construction peak conservatively. This allowance differs from allocated_bytes, which counts retained numeric/index vector capacities and level records, excludes reporting/cache handles and allocator overhead and excludes the grid/outer PCG vectors. The stats list per-level cells and nonzeros (including diagonals and stored duplicate fine entries). Sum them relative to the fine level to inspect grid and operator complexity. level_dimensions makes semicoarsening visible. block_smoothers records each level’s axes, block size/count, half-bandwidth and retained bytes. Process peak RSS includes the complete child and is reported separately when GNU time is available.

Profiling records pressure_multigrid_setup only when construction is attempted. The pressure_solve.multigrid object counts hierarchy builds, maximum hierarchy dimensions/storage, cycles, coarse solves and cell updates for smoothing, residuals, restriction and prolongation. Each coarse solve belongs to one cycle. Point-only profiles retain their old shape and smoothing = 4 × residual. Block profiles add block_smoothing_cell_updates, block_solves and block_level_cell_visits. They satisfy block_smoothing = 2 × block_visits and smoothing = 4 × residual - 2 × block_visits; restriction = prolongation = residual still holds. These are cell visits, not floating-point operation or transfer-nonzero counts. The existing fine operator and PCG work counters keep their meanings. The profile checker validates both sets, including failure paths. IC(0) profiles retain their previous serialized shape.

Reproduce comparisons

cargo build --release --locked --examples
python validation/run_suite.py --pressure-preconditioner multigrid --output runs/verify-multigrid
python validation/benchmark_pressure.py --mode kernel --output runs/pressure-kernels
python validation/benchmark_pressure.py --mode cavity --grids 24 48 --output runs/pressure-cavity

Each campaign uses one thread, one warmup and three alternating timed pairs. Kernels repeat one cold setup/solve plus three reused solves in each child. Nominal pressure tolerance is 1e-11; the independent manufactured RMS gate is 1e-8 and the true residual gate is 1.01e-10. Cold/reused timers exclude JSON and hashing. Coupled runs use the existing cavity numerics, 600 s/20000-step bounds, independent archived-field audit and frozen Ghia screen. Returned velocity and pressure equivalence bounds are 1e-8 and 1e-7 respectively, with the same gauge. The opt-in verification suite also runs the unchanged Poiseuille and empty-ABL gates (and scalar Gaussian refinement) with the selected preconditioner. Rows, failures, input/producer identities, work, fields and RSS are retained; nonrepeating or unaccepted groups have no speedup ratio. Setup and solver/workflow times have distinct scopes. The baseline IC(0) probe runner is unchanged.

The opt-in CFD checks selector external=pressure runs this original campaign and packages evidence with directory entries and archive round-trip checks. See recorded results and the plan. No timing threshold is imposed in ordinary CI. Multigrid for masked grids and measurements of its setup cost were added later; its coupled runs show no consistent gain in run time. Anisotropic line blocks, second-order momentum and the implicit steady algorithms were also added later. This change alone does not qualify a canyon model or establish OpenFOAM parity.

The new selector external=anisotropy runs the three-method rough-pressure suite and the coupled 64x2x12 steady/transient checks. It builds the merged point core at 2ddf17d with only the shared probe and an unused empty source marker as measurement overlays. Locally, pass that probe to python validation/benchmark_anisotropy.py --baseline-probe PATH --output NEW_DIR; run python validation/benchmark_anisotropic_flow.py --output NEW_DIR separately. The frozen rough suite uses tolerance 1e-14, RMS recovery <=1e-8, true residual <=1.1e-12 and at most 1200 PCG iterations. It retains every failed row and gives no ratio to an unqualified method. Cold setup and reused solves are distinct. The coupled test retains the existing flow gates and distinguishes steady convergence from transient interval completion.

compare_backends.py --grid-sweep --native-pressure-preconditioner multigrid records this selection in its immutable accuracy plan. Its default remains ic0; the legacy comparison rejects this option outside grid-sweep mode. Hosted runs can select external=accuracy, native_pressure=multigrid. See the iteration plan and remaining gap and work.

Masked connected aggregates

The masked path compacts fluid unknowns and leaves solid entries exactly zero. Each coarsening step forms geometric 2x2x2 bins, then splits every bin by connectivity in the actual fine/coarse face graph. Sharing a bin is not enough to aggregate: there must be a fluid path wholly inside it. Coarse coordinates retain their geometric bins; thin passages, sealed pockets and outlets remain in the graph. This includes periodic wrap faces and single-cell periodic axes.

Prolongation P is piecewise-constant injection, with one unit coefficient per fine fluid row. Distinct aggregate columns have disjoint, nonempty support, so P has full column rank. Restriction is P transpose. Summing original edge energies between distinct aggregates and summing outlet anchors gives exactly A_c = P transpose A P. Internal aggregate edges vanish. No rediscretized wider face, diagonal shift or solid-cell pressure equation is introduced. This coarsening is intentionally different from the existing unmasked linear interpolation path; that path and its anisotropic line smoothers remain intact.

Every closed component is centered separately at every cycle stage. Smoothing is two forward Gauss–Seidel sweeps before the coarse correction and two backward sweeps after it. A zero-diagonal sealed singleton is an entirely null space and gets zero correction. Once each component has at most32 unknowns, remove one gauge per sealed component and apply a direct Cholesky solve component by component. Anchored components keep all their unknowns. The terminal direct lookup scales with the component size; many isolated pockets do not cause a quadratic all-grid initialization.

The fixed aggregate hierarchy, transpose transfers, positive principal Gauss–Seidel factors, orthogonal component gauges and positive coarse inverse produce a fixed symmetric positive preconditioner on the compatible pressure space. Independent full-cycle matrices, dense Galerkin products and a separate pivoted dense reference supplement this argument. Fixtures include mixed anchored/sealed components, incompatible tiny singleton flux, barriers, narrow passages, projection, changed coefficients and transactional cancellation. The fine PCG operator and final face residual use the existing pressure code.

The exact cache signature includes all fluid flags, anchor flags, dimensions, spacing bits and pressure face coefficients. Masked aggregate levels are irregular, so level_dimensions is omitted; actual level_cells, nonzeros, retained storage and work are reported. The existing conservative per-cell memory allowance covers this path. Construction polls cancellation between levels and during connectivity and aggregation scans. The first setup is measured separately from reused cycles.

A successful preconditioner verification does not close the coupled performance gate. The urban evidence reports both setup and whole-run costs and preserves the failed block and district rows. On isotropic canyon grids the masked path needs 3 to 6 times fewer pressure iterations than IC(0) at about the same run time. With strong anisotropy it is slower, because it has no line blocks: on an 18x16x96 canyon with a weight ratio of 256 it needed 2236 iterations and 4.48 s of pressure solve in 10 steps, IC(0) 1695 and 1.15 s. CFD-W004 says so for a case with geometry. Practical million-cell throughput remains unqualified.

Numerical decisions for 0.1

  1. Use face-flux projection on a uniform masked grid. Build and test one operator definition before adding geometry formats or refinement blocks.
  2. Use matrix-free PCG with cached IC(0). This improves the small reference cases but does not solve the fine-grid throughput problem. IC(0) stays the default; opt-in symmetric multigrid for grids without solids (with anisotropic line blocks) was added later after its own gates, and a multigrid path for grids with buildings after that. With buildings it cut pressure iterations but gave no consistent gain in run time (urban record), which is one reason the default did not change.
  3. Use explicit diffusion and bounded timestep selection. This is simple to verify and increasingly expensive on fine RANS grids. It remains the default and the transient method; steady runs can opt into implicit viscosity and implicit k–ε steps (decisions 9 and 10).
  4. Retain linear transport alongside MUSCL. It provides exact response matrices, reference comparisons and a simpler failure diagnosis.
  5. Keep one neutral inlet/wall/turbulence combination. Its coefficient and upper-boundary choices are recorded; a change needs the empty-ABL test.
  6. Keep execution artifacts separate from optimization claims. A completed command is not an inferred optimization optimum or a validated CFD result.
  7. Keep generated performance failures. A change in hardware or work budget needs a new run identity and evidence.
  8. Offer conservative second-order momentum advection as an opt-in selection beside the donor-cell default. Allow the unbounded second_order_upwind scheme, which matches the external cavity reference’s scheme class, and keep limited schemes for cases that need boundedness. A default change waits for a matched-accuracy measurement and is a separate, announced change of results and hashes.
  9. Offer implicit steady pseudo-time in delta form beside the explicit default: implicit viscosity in the SSPRK2 stages, and a SIMPLEC-type implicit correction with a projection per outer iteration. Inner tolerances, the CFL ramp and the inner solver are predeclared algorithm constants; acceptance is unchanged, because the delta form keeps the fixed point. A default change waits for the matched-accuracy measurement.
  10. Extend implicit_projection to RANS with segregated implicit k and ε steps in delta form (lagged wall functions and production, the explicit step’s implicit destruction terms) and to constituents with explicit sub-steps of the unchanged transport step inside each outer iteration (cap 16), rather than an implicit scalar solve, so the mass budget, positivity and receptors stay exactly those of the explicit step. Cap the CFL ramp at 5, and recommend inexact inner projections (relative tolerance 0.1) and a non-binding pseudo-time cap for implicit runs; both change the path, not the fixed point. A periodic axis may have one cell.

Roadmap

This page maps the development plan (version 2, which replaces the initial plan) to what 0.2.0 contains, and lists the next steps. The plan’s proposed case file is a draft; the schemas from cfd-craft describe are authoritative. RESULTS holds the numbers.

An external-backend workstream runs OpenFOAM Foundation 13 next to the native solver: a same-Re cavity cross-check and a preliminary comparison against public backstep measurements. EXTERNAL_RESULTS records the runs and the remaining gates. This gives the optimization ecosystem a path to an established solver while native numerical development continues. It does not close M3b: an external backstep is not a measured native street-canyon comparison. The native wall and throughput tasks below remain.

City blocks and mobile measurements

A second plan added city-block geometry, particles, vegetation and mobile measurements as opt-in features. Its stages are named U0 to U8 (urban) and R1 to R3 (rides), its gates G0 to G7 and GR, and its validation tracks V1 and V2. Numbers and failed rows are in the urban record and the mobile record; the user pages are guide chapters 22, 23 and 24.

StageContentState
U0 Throughput targetA declared target: an accepted one-million-cell steady district run within two hours on one thread (gate G0: target and baseline recorded)Declared and measured as a baseline; the target is not reached
U1 Multigrid with buildings (P2b, P2c)Masked pressure multigrid, its setup costImplemented and verified. Gate G1 (a measured end-to-end gain on the 27k and 93k canyons) is open: 3 to 6 times fewer pressure iterations, run-time ratios 1.05, 0.94 and 0.91; slower under strong anisotropy
U2 DefaultsDecision on default numericsDecided: the defaults stay (donor-cell, explicit, IC(0))
U3 Polygon prisms and wall roughnessfootprint_m, building_roughness_m, per-shape evidenceImplemented and verified. Gate G3 (a canyon rotated by 45 degrees reproduces the aligned receptor values at two resolutions) is not passed: one case rejected, two timed out
U4 Map converterintegrations/urban_map.pyImplemented with tests; flat ground only
U5 Particle size classes (M5a)Settling, deposition, PM sums, mass budget (gate G5)Implemented; fixtures and budget pass. Not validated
U6 Vegetation (M5b)Drag, canopy turbulence terms, leaf deposition (gate G6)Implemented; fixtures pass and zero leaf area leaves the state bytes unchanged. Not validated
U7 District campaignTwelve cold wind directions with retained rows (gate G7)The campaign keeps every row, as G7 asks. The steady study is open: no direction of the Delft demonstration converged within 45 s
U8 GPU experimentConditional on a measured pressure bottleneck at a million cellsNot triggered: pressure was 11 % of the profiled fine run
R1 Path receptors and virtual ridespath receptors, integrations/virtual_ride.pyImplemented and verified against analytic cases
R2 Street sourcesintegrations/traffic_sources.pyImplemented with tests; rates are supplied, never derived
R3 Inference and routesFrozen-flow responses, fit, pass planning, route selectionImplemented. Gate GR (recovery on held-out synthetic rides, ambiguity reported) passes on two synthetic studies of the same model; nothing beyond that
V1 OpenFOAM canyonThe same canyon in OpenFOAM with a body-fitted meshOpen; the backend still runs its two generated cases
V2 Measured dataRides or wind-tunnel data under a frozen protocolOpen; no data (protocol)

Milestones

MilestoneExit gate in the planState in 0.2.0
M0 Contracts and evidence skeletonCase/result schemas, diagnostics, resource estimator, data inventory, proposed protocolsDone. Diagnostics carry codes and field paths (catalog). The memory and output estimates bound the measured peak and the written artifacts. validation/data-inventory.json lists each dataset’s access status. The CODASC protocol is blocked_data
M1a Grid and elliptic operatorsUniform staggered grid, mask topology, pressure reference, projection identities, manufactured PoissonDone. The matrix-free operator matches an independently assembled reference on a masked grid with an outlet, a sealed pocket and a periodic axis (products to 1e-12, solutions to 1e-10). One gauge per closed component; projection and adjoint identities; second-order Poisson convergence
M1b Verified laminar flowDocumented time scheme, channel/cavity/manufactured flow, bounded execution, CPU profileMostly. Periodic shear has spatial and temporal order 2.00 and 2.01, with Poiseuille, Couette and the Re=100 cavity (decisions). Diffusion is explicit by default and in transient runs, where it limits the time step; the opt-in implicit steady algorithms treat viscosity implicitly. Measured CPU time and memory are in RESULTS
M2 Passive transport and response matricesSources/receptors, analytic transport, superposition, synthetic inverse tutorial, small command jobDone, without area sources. Point, line and volume sources; the Gaussian order is 2.32; superposition holds to 2.2e-16; there is a SciPy reference, the source-inference tutorial and the command launcher. The discrete adjoint is a later extension
M3a Neutral ABL packagek-ε with consistent wall, inlet and top; empty-domain profiles passPartly. The empty ABL drifts 0.23 % (U), 0.94 % (k) and 2.68 % (ε) in H..5H, under gates of 2 % and 5 %. Below H, ε drifts up to 16 %. There is one top configuration, the open atmosphere. By default the building-wall roughness is tied to the cell width, which the plan rules out (§5.3); the optional building_roughness_m sets it independently
M3b Finite canyon evaluationGrid and domain studies, development and held-out cases, external comparison, experimental verdictNot passed. The development case (W/H = 1, 270°) and the held-out analogs (W/H = 2; 225°) are steady on 18x16x12. The resolution series does not finish, there is no external comparison, and the experimental verdict is blocked_data
M4 Application integrationScalar adapter, budgets and cancellation, campaign reporting, replayPartly, ahead of order. An fcmaes worker runs evaluate, BiteOpt retry and the GP surrogate, within the evaluation’s thread allowance and with cancellation. There is also the command launcher. There is no experiment-craft campaign or fine-grid replay yet
M5a Particle settlingBin schema, settling and capture tests, mass budgetsImplemented as opt-in particle size classes with settling, ground, roof and leaf deposition and PM2.5 and PM10 sums; the settling fixtures and the mass budget pass (urban record). Not validated
M5b Vegetation and depositionDrag and deposition checks, factorial scenariosPartly, ahead of M3b: opt-in porous vegetation with drag, canopy turbulence terms and leaf deposition; the drag and deposition checks pass. No factorial scenarios, and M3b is still not passed
M6 Mitigation optimizationBudget-matched baseline, held-out scenarios, fine-grid replayNot started; needs M4 and validated physics
M7 Neighborhood and climatologyCity geometry, conditional scenario maps, separate annual gatePartly: polygon prisms, a map converter and a twelve-direction campaign exist. No direction of the district demonstration converged in its budget; there are no scenario maps and no climatology
M8 Time-resolved turbulenceLES with spin-up and averaging studiesNot started
M9 AccelerationOne targeted experiment on a measured bottleneckFirst native CPU experiment done: the performance results measure faster pressure solves and stencils at fixed work, with unchanged fields and gates and a higher memory estimate. Opt-in symmetric multigrid, also for grids with buildings, and opt-in implicit steady pseudo-time (P4/P5) are implemented; multigrid with buildings shows no consistent end-to-end gain, and semi-implicit transient diffusion remains open

The performance results give paired CPU and memory measurements of the current implementation against the previous one. Their hardware differs from that of the resource measurements in RESULTS. The backend comparison times the cavity with both backends on one machine: OpenFOAM is 4.7–5.5 times faster than native steady mode, mostly because the native method needs about three times as many explicit pseudo-time steps, each with a PCG pressure solve. The opt-in implicit steady algorithms (results) have since reversed that on the cavity at matched accuracy. The masked extension of the optional multigrid preconditioner (P2b) and the measurement of its setup cost (P2c) are done; they cut pressure iterations without a consistent gain in run time. The anisotropic line/semicoarsening substep is implemented; its results and a fresh gap status and iteration list separate throughput from accuracy. Accepted fine-grid and experimental-validation gates remain open.

First-release definition

RequirementState
One documented neutral RANS, wall and inflow combinationYes (flow card), with the below-H drift and the wall-roughness caveat
Conservative passive transport with explicit source unitsYes, for point, line and volume sources
A finite 3D canyon with end effectsYes: 10 m buildings in a 16 m wide domain
A development case and held-out geometry and wind casesYes, on a coarse grid
Grid, domain and parameter sensitivityDomain (extended outlet) and parameter (Sc_t 0.5 and 0.9) yes; grid no
Measured-data comparison with a frozen protocolBlocked: no data
Prompt-driven tutorial with smoke and study presetsYes (guide)
Runner integration that keeps CFD evidenceYes (integrations/)
Measured CPU time, peak memory and output size on named hardwareYes (RESULTS)

0.2.0 is therefore a research prototype with the verification evidence recorded above. The experimental package release is independent of physical qualification; a physically qualified canyon release still requires the grid study and measured data. See Releasing.

Numeric targets of the plan

TargetPlan0.2.0
Assembled versus matrix-free pressure≤ 1e-10Products ≤ 1e-12 relative, solutions ≤ 1e-10
Spatial order of the second-order modes≥ 1.82.00 (flow), 2.32 (MUSCL transport, gated at 1.8)
Temporal order≥ 1.82.01
Closed periodic scalar budget≤ 1e-10Below 1e-12 on the periodic fixture; the acceptance bound of a run is 1e-9
PositivityNo negative mass beyond round-off; report the minimum and the negative massCFD-E053 stops the run; each constituent reports its minimum and negative mass
RANS continuity1e-5 net, 1e-4 localThe same gates
RANS equation residuals1e-5, recomputedThe same gate, recomputed from the fields
Steady scalar balance1e-6The same gate
Receptor stability0.1 % over three successive 100-iteration windows0.1 % over three 100-step windows in every committed steady case, relative to each monitor’s window mean
Empty ABL2 % for U, 5 % for k and εMet in H..5H; below H reported, not gated
Superposition / transpose reciprocity1e-82.2e-16 / no adjoint yet
Study resolution< 5 % change between the two finest gridsNot reached; the study does not finish

Tutorials of the plan

TutorialState
1. Wind direction and a canyon sensorPartly: canyon_study.py with smoke, sensitivity and study presets and a prompt. Wind-convention regressions cover the cardinal and oblique directions and the inlet/outlet classification. There are no measured data, and the grid series does not finish
2. What sensors tell about emissionsDone on prescribed flow: superposition, held-out receptors, an unidentifiable pair (rank 2), bounded noise, and model mismatch from changed inflow and grid. The LP, SQP and adjoint extensions are not started
3. Trees, ventilation and particle removalPartly: chapter 22 runs particles and a hedge on the coarse canyon. There is no study with scenarios and no validation
4. Improving a design without exploiting the simulatorPartly: integrations/run_jobs.py compares evaluate, BiteOpt retry and the GP surrogate at 24 evaluations each, with no failed evaluations. Held-out and fine-grid replay are not started
5. A neighborhood map and the limits of annual claimsPartly: map import and a twelve-direction campaign (chapter 22); the district demonstration did not converge, and there is no annual statistic

Remaining differences from the plan

  • Building-wall roughness (§5.3): by default it is the smaller of the ground roughness and 0.001 cell widths. building_roughness_m specifies it independently of the ground and the grid, as the plan asks; it is optional, and the default did not change.
  • Top boundary (§5.3): only the open-atmosphere configuration exists; a wind-tunnel reproduction needs its own.
  • Diffusion (§5.2): explicit by default and in transient runs; implicit only in the opt-in steady algorithms.
  • Sources (§5.4): there are no area sources. A source that intersects a solid is rejected outright, so no redistribution policy is needed yet.
  • Preview (§6.2): it publishes the derived case and its geometry, and it rejects vanished boxes, topology changes and solid-volume changes above 20 %. It does not list per-box changes against the original.
  • Geometry evidence (§5.1): it records, per shape, the exact and represented volume and the narrowest street in cells. It has no facade/ground classification.
  • verify (§6.2): it runs the pressure fixture of one case. The suites run through the validation scripts.
  • Flow cache (§4.4): the library reuses one accepted flow for several releases (mobile_response::PreparedFlow, used by the mobile study). The command line has no such option.
  • Guideline document: the COST 732 numbers behind W002 and W003 come from secondary summaries. The primary document was not retrieved.

The gate that decides what comes next

Throughput is the limit; memory is not. One million cells peak at 851 MiB, against an estimate of 1064 MiB, which meets the plan’s M1/M2 memory gate. A three-step run at that size, including the grid construction, takes two minutes.

With the explicit default the steady canyon cost grows roughly with the sixth power of the refinement ratio: explicit diffusion and advection bound the pseudo-time step, and every step solves the pressure equation twice with about 50 CG iterations each, so the 36x32x24 and 54x48x36 canyon grids do not converge within 300 seconds. The opt-in implicit recipe accepts them with the tracer in 57.6 s and 615 s on one thread (P5c/P5d results), but the tutorial’s study preset still runs the explicit algorithm and the canyon is not grid-converged at 93k cells, so the resolution study, and with it any physical canyon claim, is still open.

Next steps, in order

The native accuracy track now starts with the Stage V verification protocol and its donor-cell baseline. Stages P3a (conservative second-order momentum), P4 (implicit viscous correction), P5a (implicit steady projection), P3b/P5c (open boundaries/RANS), P5d (scalar transport) and the matched-accuracy measurement M are implemented as opt-in choices with unchanged defaults; the conditional P5b was not needed (matched accuracy, performance iterations). The decision on defaults is made: they stay. Masked multigrid (P2b) and its setup-cost measurement (P2c) are done, without a consistent end-to-end gain.

The mesh-initialization plan provides an explicit accepted-coarse-to-new-fine start, verified against a cold fine cavity (results). A bounded refinement campaign maps once and chains eligible fine stages, with complete retained parents and work and archive checks; its results record the declared level-2 backstep campaign: three 4000-iteration stages, each passing the audit. It ended at the stage limit with the Uy and k residuals still above the gate. An accepted fine backstep is still missing; another declared trial would need more fine work. Mesh independence, inlet and model uncertainty and physical qualification remain separate open gates.

The external-backend track has a separate wall-resolution plan. Its wall-resolved SST reference converges and passes the independent audit at level 1; a mesh pair needs a larger per-case budget or a coarse-to-fine start, and inlet and model sensitivity remain open (results). This does not advance the native canyon’s physical-validation gate.

The continuation plan provides verified same-mesh field continuation in bounded stages, which lets a solve exceed one run’s 3600 s limit; staged, the coarse reference reaches the same converged solution as one run. A level-2 mesh still needs several stages of roughly an hour each, whose sources must pass the source flux gate as preregistered; whether that gate suits continuation is an open decision in the continuation results. Nearest-cell coarse-to-fine initialization exists for accepted cold sources; conservative interpolation, chained sources and an accepted fine/coarse turbulent pair remain work.

  1. Throughput (M1b, M3b): the measured profile of the district runs puts scalar sub-steps, canopy coefficients, the momentum residual and turbulence ahead of pressure, so these come first; line smoothing for multigrid with buildings; semi-implicit diffusion for transient runs; and solving the passive scalar after the flow has converged in the command line too. Each change is accepted only if the verification suite and the empty-ABL check pass with unchanged tolerances.
  2. Near-wall consistency (M3a): a log-consistent velocity gradient in wall-adjacent cells, so the empty ABL also stays homogeneous below H, and a building-wall roughness specified independently of the ground and the grid.
  3. Resolution study (M3b): the canyon at 10 or more cells per building height, a domain that meets the COST 732 clearances, and a GCI where the sequence supports one.
  4. Measured data (M3b):
    • CODASC or the Hamburg datasets; access requests are prepared for the owner to send.
    • A protocol frozen before evaluation.
    • A pinned OpenFOAM run of the same case.
  5. Replay and the open city-block gates, in parallel:
    • Fine-grid, held-out replay of the optimizer tutorial (M4).
    • The rotated-canyon study (G3) with wider streets and a full refinement series.
    • A district run that converges, before any district optimization.

Domain questions that would sharpen M3 onward:

  • Which practical question matters most: mean sensor interpretation, source attribution, mitigation comparison or short-term peaks?
  • Which instruments and measured quantities are available?
  • Which existing geometry, inflow or reference cases may be used?

The documentation check

scripts/check_docs.py runs the code blocks of the documentation and compares their outputs. Without arguments it checks the default set: the root README, the package READMEs, examples/manual/README.md and every page under docs/ except stubs, SUMMARY.md, the generated reference pages and the records in docs/history/. Each page is one session in a new temporary directory, never inside the checkout.

Run the documentation check

From the root of a checkout, with the Python binding of the checkout installed (maturin build --release --locked --out dist, then pip install dist/*.whl):

cargo build --release --workspace --locked
cargo build --release --workspace --examples --locked
python -m pip install -r requirements-validation.txt
python -m pip install fcmaes-rust==0.5.0 lp-ip-craft==0.33.0
python -m pip install -r integrations/requirements-mobile.txt
python scripts/check_docs.py --smoke > runs/docs-check.json
python scripts/check_docs.py docs/guide/03-cli-and-archive.md

--smoke does not execute pages and sections marked long; their blocks are still parsed, their script paths must exist and their JSON cases still pass cfd-craft check. Without --smoke (full mode) everything runs except the OpenFOAM and jobs sections. The last install line (Shapely) is needed in full mode only, for the map section of chapter 22. On a 2-core host the default set takes about 2.5 minutes in smoke mode and 3.5 minutes in full mode. The report on standard output lists, per page, the blocks run, the text blocks compared, the json blocks validated, the blocks not run and every unchecked block with its reason. A failure is printed as CFD-R003 docs.<field>: PAGE:LINE: message (diagnostics), and the exit code is 1.

Fences

FenceWhat the check does
pythonRuns it; the blocks of one level-2 section share one interpreter.
bashRuns it with bash -euo pipefail; each block is its own shell.
textThe exact output of the runnable block directly before it.
jsonStrict JSON; a case (cfd-craft.case/…) must pass cfd-craft check.
shbash -n only; a python PATH.py it names must exist. For installs, builds, placeholders and long or external commands.
tomlParsed.
rustEvery non-comment line must occur, in order, in the file named by fragment of PATH.
mermaidNot run.

A block without an info string fails. Both backtick and tilde fences work, also indented inside a list item.

Markers

Markers are one-line HTML comments check: … or file: …: under the title for the page, under a level-2 heading for the section, directly before a fence for the block. rel=1e-4 (page) declares the tolerance of floats; the setup section must then state it in the fixed sentence that the check compares with the marker (see the end of the setup of chapter 1). A tolerance looser than 1e-4 is refused. long, openfoam and jobs (page or section) select when blocks run. timeout=SECONDS (page or section) replaces the default limit of 180 s per block; the OpenFOAM chapters use the recorded run times. fragment, fragment of PATH, file: NAME and file: NAME = REPO_PATH belong to one block. none: REASON leaves a block or a page unchecked; the reason is listed in the report. A marker given twice or a comment that looks like a marker and does not parse fails.

Sessions and outputs

A first section ## Setup runs once; every other section starts from its own copy of what the setup made, so a link can land in the middle of a chapter. Python variables and shell state do not carry between sections. An expected non-zero exit is written in the block, COMMAND || echo "exit $?", and shown in the text block. Floats agree when |actual - shown| <= rel * max(|actual|, |shown|) + abs; integers, words, version strings and schema names must be identical, and so must the number of lines.

The ledger

docs/check-counts.json holds, per page, the minimum number of runnable blocks, compared text blocks and json blocks, separately for blocks that always run and for each of long, openfoam and jobs. Every run compares the pages with it in every mode: fewer blocks of a class, a page without an entry, or an entry whose page left the default set fails with docs.counts. After adding blocks, run python scripts/check_docs.py --write-counts and commit the file; it is written only when every page passes. Lower counts are a change that a reviewer sees in the diff.

Add a chapter

  1. Start with ## Setup: how the reader gets the command and the case.
  2. Show selected fields with a short python block and its text output, made by running it; add the tolerance marker and sentence if a float is shown.
  3. Mark sections over about a minute long, OpenFOAM sections openfoam, sections that need optimization-run jobs. A section that needs a package the job docs does not install is also marked long (the map section of chapter 22 needs Shapely).
  4. Run the check on the page, then --write-counts, and add the page to docs/SUMMARY.md.

What CI runs

The job docs of .github/workflows/ci.yml runs the default set in smoke mode on every push, normally and under python -O with identical reports, with scripts/generate_reference.py --check and the tests of both scripts. Two more jobs run what needs a runtime. runner-integration runs chapter 14 with --runner on every push. external-backend, a manual dispatch, runs chapters 15 to 19 with --smoke --foam-root; this path has not been exercised yet, because the OpenFOAM runtime does not exist on the host where the documentation was written. The F1 section of chapter 13 (jobs) is executed by no job: runner-integration does not install the two optimization packages, so its blocks are checked for syntax and script paths only. The same holds for the map section of chapter 22 (long, needs Shapely) and the wind-direction command of chapter 14 (an sh block); the job urban-mobile runs the tests of the converters, the ride tool, the inference and the campaign instead. Chapter 24 runs in the job docs: it needs the example mobile_response, NumPy, SciPy and LP-IP-craft, which the job has. Full mode for chapters 18 and 19 takes hours and is not part of any job. validation/manual_examples.py still runs its fixed suite of 11 native steps in the job numerical and its 8 OpenFOAM steps in external-backend; validation/test_manual_examples.py requires those steps to equal the blocks of chapters 15 and 17.

Releasing

One tag publishes every registry artifact with the workspace version:

RegistryPackageWorkflow
PyPIcfd-craft (abi3 wheels for Linux x86_64, Windows x64, macOS x86_64 and arm64, plus the source distribution)python-release.yml
crates.io / docs.rscfd-craft, cfd-craft-cli (binary cfd-craft)publish-crates.yml

The Python binding (bindings/python, Rust 1.88) and the optional fcmaes-cfd-worker are separate workspaces with publish = false. The version is set in [workspace.package] of Cargo.toml, in [package] of bindings/python/Cargo.toml and in pyproject.toml; scripts/package_version.py fails when they disagree (Cargo’s 0.2.0-dev.1 equals Python’s 0.2.0.dev1). scripts/check_release.py adds the crate checks: publishable members inheriting the version, a description, a README and a LICENSE identical to the root one, versioned path dependencies, and the version recorded in every lockfile that contains a CFD-craft crate. Both report failures as CFD-R001 release.<field>. Publication is irreversible: never reuse a version. MIT project licensing does not relicense dependencies or reference data.

A package release is not physical qualification. 0.2.0 is a research prototype: experimental canyon validation (blocked by access to raw benchmark data) and a successful fine-grid resolution study remain open.

One-time setup

  1. Create a GitHub environment named release. Restrict its deployment branches and tags to v* tags and, if releases should need approval, add a required reviewer: the environment holds the crates.io token.
  2. PyPI: create a pending Trusted Publisher for project cfd-craft: owner dietmarwo, repository CFD-craft, workflow python-release.yml, environment release. The first tag then creates the project.
  3. crates.io: the first version must be published with an API token, because crates.io accepts a Trusted Publisher only for an existing crate. On crates.io, Account Settings → API Tokens, create a token with the scopes publish-new and publish-update, restricted to cfd-craft*, with a short expiry, and add it as the secret CARGO_REGISTRY_TOKEN of the release environment. The tag then publishes cfd-craft and cfd-craft-cli in that order, skipping versions already on crates.io, so rerunning the job completes a partial upload. A tag run without a token and without Trusted Publishing fails instead of skipping. After the first upload, delete the secret, revoke the token, configure a Trusted Publisher for each crate (owner dietmarwo, repository CFD-craft, workflow publish-crates.yml, environment release) and set the repository variable CRATES_IO_TRUSTED_PUBLISHING to true.

Qualification before a release

From a clean checkout with committed lockfiles:

  1. Run fmt, clippy, the Rust tests and the Python CLI tests in normal and optimized mode; python3 scripts/check_release.py.
  2. Reproduce the analytic flow/transport, cavity, independent sparse-reference and empty-ABL results.
  3. Reproduce the canonical canyon smoke and sensitivity cases. Keep every failed refinement case.
  4. Record the actual executable and source fingerprints, compiler, initial-state identity and dependency versions.
  5. Check the input/output schemas and all documented examples.
  6. Build and test the optional worker independently and check actual runner result states.
  7. Package the crates and the Python distribution:
cargo publish -p cfd-craft -p cfd-craft-cli --dry-run --locked
python -m pip install maturin==1.9.6
maturin build --release --locked --out dist
python -m venv /tmp/cfd-check && /tmp/cfd-check/bin/python -m pip install dist/*.whl
cd /tmp && /tmp/cfd-check/bin/python -I /path/to/CFD-craft/validation/check_installed.py --output installed.json

The dry run packages both crates and builds each from its own archive (current stable Cargo stages the unpublished dependency); CI runs cargo package --workspace --locked on every push. A packaged crate carries its own normalized Cargo.lock, so its source fingerprint differs from a checkout build’s. Builds from crates.io use Cargo’s default release profile instead of the workspace’s thin-LTO profile: numerical results are the same, timings can differ from the native verification record.

publish-crates.yml runs the Rust checks and the dry run on pull requests that touch the crates and on every tag. python-release.yml builds the four wheels and the source distribution and runs validation/check_installed.py outside the checkout on CPython 3.10 and 3.14, normally and under -O, on pull requests that touch the packaging, manually and on tags; only a tag publishes.

Before a physically validated canyon release, additionally acquire authorized measured data, reconstruct the exact setup, freeze the sample/threshold protocol before held-out evaluation, and obtain successful grid/domain studies with uncertainty appropriate to the claimed effect.

The installed-package check

validation/check_installed.py exercises strict parsing, diagnostics, concurrent call identity, incomplete work, cancellation by file and by Ctrl-C during a long run (each must stop it within seconds), and the installed console script. --binary PATH also compares numerical summaries with the Rust CLI. Run the checker with python -I from outside the checkout, normally and under -O. The release workflow runs it for every wheel on CPython 3.10 and 3.14 and for the source distribution. Guide chapter 11 says what the build identity of an installed package is.

Tag and publish

Merge the release pull request, then GitHub → Releases → Draft a new release → new tag vX.Y.Z on main → publish. The tag push starts python-release.yml and publish-crates.yml; both refuse a tag that does not equal v plus the version. From a computer:

version="$(python3 scripts/package_version.py)"
git tag -a "v$version" -m "Release CFD-craft $version"
git push origin "v$version"

Hosted macOS arm64 runners are sometimes unavailable: a job then waits, is cancelled after about 15 minutes without running a step, and the publish job that depends on it is skipped. retry-runner-shortage.yml notices such a run and reruns its failed jobs, up to three attempts in total. It leaves real failures and runs cancelled by a person alone. If the last attempt still finds no runner, rerun the failed jobs by hand (Actions → the run → Re-run failed jobs); never re-tag.

Publication is not atomic across registries. If one workflow fails, inspect the registry versions and rerun only that workflow; never bump or republish a version blindly.

Post-release verification

python -m venv /tmp/cfd-craft-check
/tmp/cfd-craft-check/bin/python -m pip install cfd-craft
cd /tmp && /tmp/cfd-craft-check/bin/python -I /path/to/CFD-craft/validation/check_installed.py --output installed.json
cargo install cfd-craft-cli --version "$version" --locked && cfd-craft describe

Check the PyPI page (its description is python/README.md), the crate pages and docs.rs.

About these pages

These are the development plans of CFD-craft as they were written, kept unchanged apart from link and fence-label updates. Each plan states its scope and its gates before the work; the results are in the evidence records, and the current state of the code is in the guide and the developer pages. A plan is not a description of what the code does now.

The dates are the ones each plan states. Plans without a date name the code revision they started from.

Iteration numbers are those of the plans; numbers without a page here had no separate plan.

CFD-craft: native accuracy and steady-solver plan (P3–P5)

Date: 1 November 2026. Base: main at f358be6 (merged PR #14, anisotropic pressure multigrid).

Implementation status

Stage V is implemented. Read the frozen verification protocol and measured baseline for its actual evidence, retained failures and hosted-reproduction status.

Status on 1 November 2026, after PR #16: stages P3a, P3b, P4, P5a, P5c, P5d and M are implemented and recorded (second-order momentum, implicit steady, RANS and constituents, matched accuracy); ten performance iterations followed (results). P5b was not built, because P5a passed its cost gate. The P4 and P5c fixed-point shrink statistics each failed on one decade; both failures are recorded. All new numerics are opt-in; the defaults remain donor-cell advection, the explicit steady algorithm and IC(0). Open: masked multigrid (P2b), setup cost (P2c) and a decision on defaults. The rest of this document is the plan as written.

Goal

Close the native/OpenFOAM gap where it actually lies: accuracy per cell and the number of iterations to a steady state. Pressure is no longer the main cost.

The plan does this by implementing published finite-volume methods in Rust from the literature: second-order momentum advection, implicit treatment in pseudo-time and an implicit steady iteration. It does not port or translate OpenFOAM code (see Ground rules). OpenFOAM stays what it is today: an external reference run through the adapter.

Where the gap is now

Hosted accuracy sweep on the solver code merged as f358be6 (run 41267955525; GitHub runner, AMD EPYC 9V74, 4 CPUs, one solver thread), steady Re=100 lid-driven cavity, native with opt-in multigrid:

GridNative Ghia errorNative stepsNative solver sOpenFOAM Ghia errorOpenFOAM iterationsOpenFOAM solver s
12²0.05976300.31———
24²0.02762,0104.420.00906960.64
48²0.01706,39059.60.00712,1325.42
  • Accuracy per cell.
    • Native momentum advection is first-order donor-cell in advective form (flow.rs, momentum_rhs). Its numerical viscosity, about U·h/2, is twice the physical viscosity at 24².
    • Native does not reach the 0.01 target through 48², so equal-accuracy cost is undefined today.
  • What the OpenFOAM reference actually runs (integrations/openfoam_cases.py):
    • Advection: bounded Gauss linearUpwind grad(U) with an unlimited Gauss linear gradient. That is unlimited second-order upwind. “Bounded” there is OpenFOAM’s correction for steady-state continuity errors, not a limiter.
    • Coupling: SIMPLE with consistent yes, which is SIMPLEC. Under-relaxation is 0.5 for U and 0.2 for p; GAMG pressure solves use relTol 0.01.
    • Stopping rule: residualControl 1e-7, which differs from native acceptance through assess. Iteration counts are therefore not directly comparable; cost at equal accuracy is.
    • Ghia metric: OpenFOAM improves only from 0.0090 to 0.0071 between 24² and 48², an observed order of about 0.3. The metric is near a floor, so the Ghia error alone cannot measure a scheme’s order.
  • Steps to a steady state. Steady mode marches SSPRK2 pseudo-time with a projection per stage. The step is limited by advection and diffusion together (solver.rs, timestep). Diffusion is about 40% of the limit at 24² and 57% at 48², and steps grow about 3.2× per refinement.
  • Span cells. Native computes two span cells for a 2D case, OpenFOAM one. That doubles native cavity work but does not matter for the 3D canyon.

Stages

StageChangeDefault output changes?Exit gate (summary)Expected effect (estimate, not measured)
VVerification fixtures and baseline; same grid list for both backendsNoFixtures in CI; donor-cell baseline recorded; fixtures distinguish first from second orderNone by itself
P3aSecond-order momentum advection, laminar, walls and periodic boundaries, opt-inNoOrder, conservation, stability, insulation tests; accepted cavity sweepGhia error near OpenFOAM’s at equal grid; a first finite equal-accuracy ratio
P4Implicit viscous term in steady pseudo-time, delta form, opt-inNoSame fixed point as explicit steady mode; unchanged gates1.7× (24²) to 2.3× (48²) fewer steps, minus solve cost
P5aImplicit steady iteration with a uniform pseudo-time step and projection, delta form, opt-inNoSame fixed point; unchanged gates; restart identity; cost gateA large reduction in iterations (amount unknown)
P5bLocal pseudo-time steps with a consistent face-weighted projection; only if P5a fails its cost gateNoPressure-operator rules in AGENTS.md; same fixed pointFaster convergence in slow-flow regions
P3b, P5cOpen boundaries and RANS for P3a and P5aNoOutlet closure tests, empty-ABL check, canyon, model cardSame levers on the canyon
P5dScalar transport with the implicit flow algorithmsNoAGENTS.md transport checksNeeded for the dust study
MMatched-accuracy measurement against OpenFOAM, hosted reproductionNoPredeclared protocol; failures keptThe first honest cost-at-accuracy ratio

Recommended order: V → P3a → P4 → P5a → (decision) P5b → P3b, P5c, P5d, with M after each stage. P2b (masked multigrid) can run in parallel. Nothing here depends on it, because the implicit stages work with IC(0) on masked grids.

Ground rules

Clean-room implementation

  • AGENTS.md already says: “Do not copy separately licensed CFD implementations into the MIT core.” OpenFOAM is GPL v3; CFD-craft is MIT. A translation of OpenFOAM code would generally be a derivative work.
  • Implement from the papers and textbooks listed under Sources. Implementers do not consult OpenFOAM source code, its listings on cpp.openfoam.org, its code listings in books, or other GPL CFD code while working on these stages.
  • The flow model card currently links an OpenFOAM source listing (atmBoundaryLayer_8H_source.html) as a method reference. Replace that link with a non-source reference before P3b and P5c, which touch that area (see Decisions).
  • Each PR lists the sources it implements, in its plan and in the model card.
  • OpenFOAM is used only as a black-box reference through the adapter: run it, compare its fields and costs. Reading our own OpenFOAM case files (the recipe) is fine.
  • Names are generic (second_order_upwind, limited_upwind, implicit_projection), not OpenFOAM dictionary keywords.

Opt-in, with unchanged defaults

  • Every new behavior sits behind a new numerics field whose default reproduces the current behavior. Defaults are not serialized (skip_serializing_if, as for pressure_preconditioner), so existing case and checkpoint hashes are unchanged.
  • Default runs stay byte-identical to main in fields.json, checkpoint.json, probes.csv, geometry.json and case.json, with identical steps and work. Each stage adds this control for the steady cavity, a transient case and a masked canyon.
  • Changing a default is a separate later decision (see Decisions).

Acceptance never moves

  • assess stays the single acceptance path. It recomputes the steady momentum residual from momentum_rhs and the pressure gradient, plus continuity, the volume balance and the monitor stability check. Their thresholds (steady_residual_tolerance, steady_monitor_tolerance, 1e-4 local continuity, 1e-5 volume balance) are unchanged.

  • momentum_rhs dispatches on the selected advection scheme, so the steady residual is always the residual of the equations actually solved.

  • Implicit stages are written in delta form: they solve for a correction driven by the full steady residual. Inexact inner solves, approximate Jacobians, under-relaxation and pseudo-time steps then change only the path.

    • At a fixed point, δ = 0, so the residual R = 0.
    • The pressure update α_p·φ is constant at a fixed point, so Gφ = 0.
    • Together these are exactly what assess checks.

    Inner solves start from a zero initial guess for δ, which keeps them deterministic.

  • No limiter freezing, residual smoothing of the acceptance check, or other device that changes the discrete equations at the end of a run.

  • max_time_step_s keeps its meaning, an upper bound on the (pseudo-)time step, in every mode. The measurement protocol predeclares its value for each configuration.

Evidence and repository rules

  • Predeclare each measurement protocol in the stage plan before measuring. Keep failed and slower rows in the reports.
  • A fix comes with a test that fails without it. Each new diagnostic gets a code in docs/diagnostics.md with the offending field path.
  • Each numerical change updates docs/model-cards/flow.md. RANS changes add the empty-ABL check and a published model-card change. Transport changes need the mass, positivity, unit-normalization and refinement checks.
  • Required checks for every PR:
    • Rust: cargo fmt, clippy with -D warnings on all targets, cargo test --release --workspace --locked;
    • Python: ruff format --check . and ruff check ., with the Python suites passing in normal and python -O mode;
    • evidence code: explicit exceptions, and zip(..., strict=True) for records that must correspond.
  • Each stage gets an opt-in CI selector or input that reproduces its campaign on a GitHub runner, and a results document with a hosted-reproduction section.

Stage V: verification fixtures and baseline

The existing periodic-shear fixture (validation/flow_accuracy.py) has zero advection (u depends on z only), so it cannot see the momentum scheme’s order. Add fixtures that can, and record donor-cell results first.

  1. Operator truncation test (Rust, new tests/momentum.rs).
    • Evaluate the advective part of momentum_rhs on an analytic, divergence-free, periodic field (a 2D Taylor–Green velocity in x–z) at 8 predeclared random phase offsets, on grids N = 32, 64, 128, 256. Compare with the analytic ∂(u_d u_a)/∂x_d at the face centers.
    • The phase offsets prevent a false pass: with an unshifted field and N divisible by 4, the extrema sit exactly on nodes or zero-flux faces.
    • Report L1, L2 and max-norm errors. The gate statistic is the least-squares slope of log L1 against log h over the four grids, per phase.
    • For donor-cell, assert a mean slope below 1.2. This proves the test can tell first from second order; a NumPy model of the operator gives 0.97.
    • Add a test-only entry point for the advective part. The donor-cell production path keeps its floating-point operation order; today advection and viscosity accumulate per direction in one loop. The byte-identity controls check that.
  2. Translating Taylor–Green vortex (Python, validation/momentum_accuracy.py).
    • Periodic x and z, two periodic span cells, plus a uniform offset velocity U₀. Without the offset, a second-order scheme’s advective error is mostly a pressure gradient that the projection removes, so the fixture would test mainly the viscous terms. With U₀, it tests advection.
    • Choose the viscosity so that cell Peclet numbers span about 1–10 over the grids.
    • Supply the initial field through a generated, checksummed checkpoint, as flow_accuracy.py does. The exact solution decays as exp(−2νk²t) while translating with U₀.
    • Run grids 16, 32, 64 with a fixed small time step, and a separate time-step refinement showing that the time error is negligible. Record the observed L1, L2 and max-norm orders.
  3. Momentum conservation. In the fully periodic box with the offset U₀, track the total momentum of each component. Normalize its change by Σ|u_a|·V. Donor-cell in advective form is the recorded baseline.
  4. Boundedness and stability. A transverse velocity step v(x) carried by a uniform periodic flow U in x is divergence-free and advected passively. Record new extrema and any growth after 1,000 steps at the case’s advective_cfl_max.
  5. Insulation across solids. Perturb face velocities on the far side of a blocked face. The momentum right-hand side on the near side must stay bit-identical. This guards the wider stencils of P3a.
  6. Same grid list for both backends.
    • The OpenFOAM recipe currently accepts only n = 24·{1, 2, 3} (integrations/openfoam_cases.py, validation/accuracy_sweep.py). Extend the recipe, the sweep and compare_backends.py to a predeclared list, for example 16, 24, 32, 48, run for both backends. Comparing native at 16 or 32 with OpenFOAM at 24 only would bias “coarsest grid reaching 0.01” toward native.
    • Keep “no extrapolated crossing”.
  7. Native self-convergence. Add a native reference run at 96² (or finer if the budget allows) with the same scheme. Report the observed order of the centerline velocity against it, because the Ghia metric is near its floor and cannot show scheme order by itself.

Exit: all fixtures in CI. The donor-cell baseline (operator slopes, Taylor–Green orders, conservation, extrema, the two-backend sweep on the new grid list, self-convergence) is recorded in a results document. No numerical change.

Stage P3a: second-order momentum advection (laminar)

Method

  • New field: numerics.momentum_advection, with values:

    • "donor_cell": default, unchanged;
    • "second_order_upwind": unlimited (s = a below; ψ(r) = r in Sweby’s notation). This is the scheme class the OpenFOAM recipe uses;
    • "limited_upwind": requires numerics.momentum_limiter, one of "van_albada", "van_leer" or "monotonized_central".

    The limiter field is rejected otherwise, with coded diagnostics.

  • Flux form on the staggered grid (Harlow and Welch; Ferziger, Perić and Street, ch. 7):

    • for the velocity component on an a-face, the momentum control volume is centered on that face;
    • the advecting volume fluxes through its faces are second-order interpolations of the face velocities (the classic MAC averages);
    • the transported component is reconstructed on each momentum-cell face.

    Each momentum-cell face carries one single-valued flux shared by its two momentum cells. The fluxes telescope, so the scheme conserves momentum in a periodic box. The interpolated fluxes of a momentum cell also sum to the mean of the discrete divergences of its two pressure cells. That sum is zero after projection, which makes the flux form consistent with the advective form.

  • Reconstruction: an upwind-biased MUSCL-type face value (van Leer), written with Sweby’s limiter function. With U, UU and D the upwind, far-upwind and downwind samples, a = φ_U − φ_UU and b = φ_D − φ_U, the face value is φ_f = φ_U + ½·s(a, b). Use division-free forms, because b = 0 occurs in uniform regions, in Poiseuille and Couette flow, and at a start from rest:

    • unlimited second-order upwind: s = a;
    • van Albada: s = ab(a + b)/(a² + b²) if ab > 0, else 0;
    • van Leer: s = 2ab/(a + b) if ab > 0, else 0;
    • monotonized central: s = sign(b)·min(2|a|, |a + b|/2, 2|b|) if ab > 0, else 0, as in transport.rs;
    • test-only control s = 0, which is flux-form first-order upwind. It is not the production donor-cell scheme (advective form, advecting velocity averaged from cell centers); the two differ at O(h). It is checked against an independent NumPy flux-form reference instead.
  • Boundary closure in this stage:

    • Supported: walls, moving walls, blocked faces and periodic axes. The U and D samples use the existing sample and wall_ghost logic.
    • No reach through solids: where UU is not a real interior face (a ghost, a blocked face or a domain edge), use s = 0 on that momentum face, which is a local first-order closure.
    • Open boundaries: the momentum cell of an outlet face lies half outside the domain, so its outer flux is undefined. Reject open boundaries with a coded diagnostic until P3b defines and tests an outlet and inflow closure.
  • Time integration is unchanged: SSPRK2 with a projection per stage.

    • Bounded schemes: in the semi-discrete form above, the forward-Euler TVD bound is CFL ≤ 0.5, and SSPRK2 keeps it (Gottlieb and Shu). The existing advective_cfl_max cap of 0.45 lies inside the bound.
    • Unlimited scheme: second-order upwind is unstable with forward Euler at any CFL. With two-stage RK2 it is stable up to CFL 0.5 in 1D. The stability fixture checks the multidimensional case at the cap.
  • RANS: the new schemes with flow.kind = neutral_rans are rejected with a coded diagnostic until P3b.

  • Cost: the wider stencil roughly doubles the advective part of the momentum right-hand side. Measure it and record it in the profile.

Gates (predeclared)

  1. Operator order (8 phases, N = 32–256, least-squares L1 slope):

    • each limited scheme: mean slope ≥ 1.8 and every phase ≥ 1.6. A NumPy model of the operator gives minimum 1.87 and mean 1.93 for van Albada, 1.78 and 1.96 for van Leer, 1.77 and 2.13 for MC. TVD limiters fall back to first order in strips around smooth extrema, so L2 and max-norm slopes are reported, not gated;
    • second_order_upwind: every phase ≥ 1.9 in L1, L2 and max norm (model: 2.05).
  2. Translating Taylor–Green: L1 velocity order ≥ 1.7 for every scheme; L2 and max-norm orders reported.

  3. Conservation: total momentum change, normalized by Σ|u_a|·V, at most 1e-13 per 100 steps.

  4. Boundedness and stability:

    • limited schemes: no new extrema beyond 1e-12 of the initial range after 1,000 steps at advective_cfl_max;
    • second_order_upwind: overshoot reported, and no growth of the maximum over the run (stability).

    A scheme that needs a smaller advective_cfl_max is rejected; the cap is not raised.

  5. Insulation: bit-identical near-side right-hand side.

  6. Controls:

    • default byte-identity (see Ground rules);
    • Poiseuille and Couette: the advective contribution is zero to round-off, and the fields match donor-cell’s to round-off;
    • the s = 0 control matches the NumPy flux-form reference;
    • restart bit-identity for a cavity with each new scheme (resume after 3 steps, compare with the uninterrupted run).
  7. Cavity sweep on the shared grid list plus the native self-convergence reference:

    • every run reaches the unchanged steady gates within 20,000 steps and 600 s;
    • report the Ghia error, the self-convergence order, steps and solver time.
    • A scheme that stalls above the steady residual tolerance fails, and its rows are kept. The stall described by Venkatakrishnan is a known risk for limiters. Do not rescue it by freezing the limiter or changing the tolerance.

Selection rule (predeclared)

  • Among the schemes that pass all gates, recommend the one with the lowest native solver time on the coarsest grid that reaches Ghia error ≤ 0.01. If none reaches it, recommend the one with the lowest error at 48², and report that the target was missed.
  • If an unlimited and a limited scheme tie within timing noise, prefer the limited one, because the canyon needs boundedness.
  • Keep only passing schemes selectable. Donor-cell stays the default.

Stage P3b: open boundaries and RANS for second-order advection

  • Outlet and inflow closures:

    • outlet: the outer momentum-cell flux uses the outlet face velocity as the advecting flux and a zero-gradient upwind value with s = 0;
    • inflow: the prescribed inflow value.

    Test with an open-channel case (Poiseuille with an outlet) and with the insulation and conservation fixtures adapted to open boundaries.

  • RANS: allow the new schemes with neutral_rans only after:

    • the empty-ABL check passes with unchanged gates (2% U, 5% k and ε in H..5H);
    • the development canyon case (W/H = 1, 270°, 18×16×12) reaches the steady gates with zero floor events;
    • the flow model card is updated, with the OpenFOAM source-listing link replaced.
  • Unchanged: the k and ε equations keep their current advection, Advection::LinearUpwind in transport.rs, which is first-order upwind despite its name. Changing that is a separate transport change with its own AGENTS.md checks.

  • If the empty-ABL check fails, keep the rejection diagnostic and record the failure.

Stage P4: implicit viscous term in steady pseudo-time

Method

  • New field: numerics.steady_algorithm, with "explicit" (default: today’s SSPRK2 pseudo-time) and "implicit_viscous". Rejected in transient mode, with constituents (until P5d) and with RANS (until P5c), each with a coded diagnostic.

  • Delta form inside the SSPRK2 stage structure. Forward Euler is unstable for unlimited second-order upwind, so keep both stages. In each stage:

    1. R(u, p) = momentum_rhs(u) − G p, the same residual that assess checks.
    2. Solve (I − Δτ·L_ν) δ = Δτ·R, where L_ν is the existing viscous stencil. The wall ghosts are affine (2·target − value), so δ satisfies the homogeneous ghost condition.
    3. Add δ, enforce boundary velocities, project with the existing operator and preconditioner, and update the pressure incrementally.

    The step average is unchanged. At a fixed point both stages give δ = 0.

  • Time step: Δτ follows the advective limit only, advective_cfl_max / Σ_a (max|u_a|/h_a), capped by max_time_step_s.

  • Linear solver: each face-component system is symmetric positive definite. Use matrix-free PCG with a Jacobi or symmetric Gauss–Seidel preconditioner, separate from the pressure operator (so the pressure-operator rules do not apply).

    • Inner relative tolerance and iteration cap are predeclared algorithm parameters, for example 1e-3 and 50, not changed after seeing results.
    • The inner loops check cancellation and the wall-time limit.
  • Profiling and results:

    • new phase MomentumSolve, counters for inner iterations and solves, and check_profile.py rules for them (for example inner iterations ≤ cap × solves);
    • the summary gains an optional momentum_solver_iterations, omitted when zero so existing results are unchanged; update the result contract.

Gates (predeclared)

  1. Same fixed point. Cavity 24² with donor-cell and with the P3a scheme.
    • Run the explicit and implicit modes at the case tolerance and at tolerances tightened 10× and 100×. These are stricter test settings, not looser gates.
    • The maximum field difference between the modes must shrink by at least 5× for each 10× tightening.
    • Also compare one pair converged as far as round-off allows.
  2. Unchanged acceptance: all steady cavity, Poiseuille and Couette cases accepted with unchanged gates.
  3. Restart identity: checkpoint after 3 steps, resume, and compare bit-for-bit. Δτ depends only on the state, so no new checkpoint fields are needed.
  4. Cost: steps and solver time on the cavity sweep. A slower result is recorded and closes the stage as “not useful”.

Stage P5a: implicit steady iteration with a uniform pseudo-time step

Method

  • New value: numerics.steady_algorithm = "implicit_projection", with the same rejections as P4.
  • Outer iteration n:
    1. Compute R(uⁿ, pⁿ).

    2. Assemble A ≈ I/Δτ − ∂R/∂u from two parts:

      • the advective part is the first-order upwind operator with advecting fluxes frozen at uⁿ (Picard linearization);
      • the viscous part is −L_ν, as in P4.

      A is a diagonally dominant M-matrix, and I/Δτ > 0 keeps it nonsingular, including on fully periodic grids.

    3. Solve A δ = R approximately, starting from zero.

    4. Set u* = uⁿ + δ and enforce boundary velocities.

    5. Project with the existing operator at scale Δτ; set pⁿ⁺¹ = pⁿ + α_p·φ.

  • Relation to SIMPLEC. With a uniform Δτ and divergence-free fluxes, the momentum-matrix coefficient a_P − Σ a_nb equals 1/Δτ away from walls. That is the consistent SIMPLEC coefficient. So projecting at scale Δτ is a SIMPLEC-type correction except next to walls, where the viscous ghost terms add to it. The OpenFOAM recipe uses SIMPLEC as well. A uniform Δτ is therefore the consistent starting point; local steps come only in P5b.
  • Deferred correction: the second-order part of the advective term enters only through R, explicitly (Khosla and Rubin; Hayase, Humphrey and Greif). In delta form the converged solution is the solution of the full P3a equations.
  • Pseudo-time schedule: a deterministic CFL ramp from the outer-iteration count, CFL_n = min(CFL_max, CFL_0·gⁿ). Δτ = CFL_n / Σ_a (max|u_a|/h_a), capped by max_time_step_s, so a fluid at rest gets a finite step.
    • For reference, the cavity file’s max_time_step_s of 0.1 caps the CFL at about 3.5 at 24² and 7 at 48². The protocol predeclares the cap per configuration and runs a larger value as a separate predeclared variant.
    • Because Δτ depends only on steps and the state, restarts need no new state. Residual-based switched evolution relaxation (Mulder and van Leer) is a later option; it would need a checkpoint field with a migration test.
  • Linear solver for A (nonsymmetric). Two candidates, chosen by a predeclared pilot on cavity 24 and 48 by solver time to acceptance:
    • k symmetric Gauss–Seidel sweeps (k ∈ {2, 4});
    • BiCGStab (van der Vorst) with a Jacobi preconditioner, to a relative tolerance of 0.1.
  • Masks: blocked faces are fixed at zero and excluded from A. The pressure projection uses IC(0) on masked grids, so P5a does not wait for P2b.
  • Accounting:
    • steps counts outer iterations;
    • physical_time_s reports accumulated pseudo-time, as the explicit steady mode does;
    • the monitor window, max_steps and all acceptance checks are unchanged in meaning.

Gates (predeclared)

  1. Fixed point, acceptance, restart: same fixed point (with the P4 tightening test), unchanged acceptance and restart identity, as in P4.
  2. Cost gate: solver time to acceptance on cavity 24² and 48² at least 2× below the better of explicit mode and P4, with the selected P3a scheme.
    • OpenFOAM’s iteration counts are reported for context only, because its stopping rule differs.
    • If P5a fails the gate, or converges only with a CFL cap that leaves slow regions (the cavity core, canyon recirculation) lagging, P5b starts.
  3. Diagnostics recorded: outer iterations, inner work, pressure work and the CFL schedule actually used, so that failure modes can be distinguished.

Stage P5b (conditional): local pseudo-time steps with a consistent projection

  • Only if P5a fails its cost gate.

  • Method (Patankar; Van Doormaal and Raithby):

    • local Δτ_f per face, from the local advective rate and capped;
    • the projection uses the matching face coefficients, the SIMPLEC coefficients of A including the wall terms. The pressure operator becomes face-weighted, −div(d_f G).

    A local Δτ with a global projection scale is inconsistent, and that is where over-correction comes from; this stage removes it. The staggered grid needs no Rhie–Chow interpolation.

  • Pressure-operator rules apply (AGENTS.md): topology and nullspace tests, projection tests, and an independently assembled reference.

  • Preconditioner: for the weighted operator, use the cached plain-Laplacian hierarchy (multigrid or IC(0)). It is still symmetric positive definite and needs no rebuild per outer iteration. Measure whether rebuilding pays off.

  • Gates: as P5a, plus the pressure-operator tests.

Stage P5c: implicit steady iteration with RANS

  • Method:
    • segregated implicit k and ε steps after each momentum–pressure update, in delta form;
    • keep the current positive implicit destruction terms;
    • lag the wall functions (explicit, from uⁿ), because they are nonlinear.
  • Gates:
    • same fixed point as the explicit steady mode on the development canyon, with the tightening test;
    • empty-ABL check with unchanged gates;
    • zero floor events;
    • canyon 27k and 93k accepted;
    • model card updated.
  • This is the stage that matters for the dust study, and where the steady canyon cost can be compared with OpenFOAM’s (P6 in the gap status).

Stage P5d: scalar transport with the implicit flow algorithms

  • step advances constituents explicitly with the flow step. With P4 or P5, that step exceeds the scalar diffusion and advection limits, and positivity would fail (CFD-E053). P4 and P5 therefore reject constituents until this stage.
  • Options, decided in this stage’s plan:
    1. Sub-step the existing explicit transport within each outer iteration, at its own stable step.
    2. Implicit steady transport in delta form on the converged flow.
    3. A frozen-flow transport run that restarts from a converged flow checkpoint. This needs a restart-contract change, because prescribed flow is uniform-only today.
  • Gates: the AGENTS.md transport checks (mass, positivity, unit normalization, refinement), the steady mass balance and the existing receptor and superposition tests.

Stage M: matched-accuracy measurement

  • Protocol (predeclared):
    • same host, one solver thread, Rust stable and locked dependencies;
    • one warmup plus three alternating timed native/OpenFOAM pairs;
    • steady cavity on the shared grid list, native budgets 600 s and 20,000 steps, the OpenFOAM recipe unchanged apart from the grid list;
    • the existing archive and field audits and the 0.06 Ghia screen.
  • Report:
    • solver and workflow time;
    • Ghia error, the native self-convergence order;
    • steps or outer iterations, PCG and inner-solver work;
    • both backends’ cost on the coarsest grid that reaches 0.01;
    • native_over_openfoam_at_target once native reaches the target;
    • the two stopping rules side by side;
    • no extrapolated crossing.
  • Configurations:
    • donor-cell explicit (baseline);
    • the passing P3a schemes, explicit;
    • the selected P3a scheme with P4;
    • the selected P3a scheme with P5a, and with P5b if built.
  • Hosted reproduction: extend external=accuracy with inputs native_momentum and native_steady next to native_pressure.
  • Afterwards: update validation/PERFORMANCE_GAP_STATUS.md and the roadmap.

Schema, diagnostics and code summary

ItemValuesDefaultRejections (coded diagnostics)
numerics.momentum_advectiondonor_cell, second_order_upwind, limited_upwind (only passing schemes stay)donor_cell, not serializednew schemes with open boundaries until P3b; with RANS until P3b
numerics.momentum_limitervan_albada, van_leer, monotonized_central (only passing ones stay)nonerequired with limited_upwind; rejected otherwise
numerics.steady_algorithmexplicit, implicit_viscous, implicit_projection (implicit_local if P5b is built)explicit, not serializednon-explicit in transient mode; with constituents until P5d; with RANS until P5c
Implicit parameters (CFL ramp, inner tolerance and cap, α_p)predeclared constants in the first version—values outside the declared ranges, if exposed later

Code areas:

  • flow.rs: a test entry point for the advective part; the flux-form second-order advection; the upwind Jacobian assembly for P5a.
  • New momentum_solve.rs: face-component matrix-free operators; PCG for P4; symmetric Gauss–Seidel and BiCGStab for P5a.
  • solver.rs: dispatch on steady_algorithm; delta-form stages and outer iterations; Δτ policy.
  • case.rs: fields, defaults, validation, memory preflight for the inner-solver storage.
  • profiling.rs, validation/check_profile.py: new phases and counters.
  • integrations/openfoam_cases.py, validation/: the shared grid list; momentum_accuracy.py; accuracy_sweep and compare_backends options; CI inputs.
  • Docs:
    • docs/model-cards/flow.md, docs/decisions/numerics.md, docs/diagnostics.md, docs/result-contract.md (optional summary field), docs/ai-context.md;
    • the user manual’s numerics section;
    • one plan and one results document per stage.

Risks

RiskEffectMitigation
Limiter chatter stalls steady convergence above the residual toleranceSteady runs never acceptSeveral limiters plus the unlimited scheme in the sweep; failures kept; no limiter freezing
TVD limiters drop to first order at smooth extrema, and the Ghia metric samples extremaLimited schemes less accurate than the unlimited oneUnlimited second-order upwind is a candidate; selection by cost at target
Unlimited scheme oscillates at high cell Peclet numbersOvershoot; unsuitable for RANS or transport-coupled casesOvershoot reported; limited schemes kept for the canyon
First-order closure at walls and solidsGlobal order below 2Measured by self-convergence; a second-order one-sided closure only with its own test
Inconsistent projection scale (local steps)Oscillating outer iterationsUniform Δτ in P5a; consistent face weights in P5b
Inner solves dominate costNo net gainPredeclared pilot; stop at “not useful” and record it
Nonlinear wall functions in implicit RANSSlow or unstable convergenceLagged wall terms; RANS only after the laminar stages
Scalar transport with large pseudo-time stepsPositivity failureRejected until P5d
Default driftExisting results changeByte-identity controls at every stage

Decisions needed

  1. Clean-room rule. Confirm that implementers work only from the cited literature and do not consult OpenFOAM source code. This plan assumes yes. Related: replace the model card’s link to the OpenFOAM atmBoundaryLayer_8H_source.html listing with a non-source reference. The card already states that no OpenFOAM code is included, but the link points implementers at source code.
  2. Inner tolerances. P4 and P5 need loose inner tolerances and caps as algorithm parameters. Final acceptance is unchanged, and the delta form keeps the fixed point exact. The project rules treat tolerance policy as an owner decision, so this needs approval in principle; the values are predeclared in each stage plan.
  3. Unbounded scheme. The OpenFOAM cavity reference uses unlimited second-order upwind. Allowing second_order_upwind as a selectable, unbounded option (with overshoot reported) makes the comparison fair and is probably the most accurate choice on the cavity. Limited schemes remain for the canyon.
  4. Defaults. Keep donor-cell and the explicit steady mode as defaults until stage M shows the new options are better at equal accuracy. Changing a default changes the results and hashes of existing cases, so it should be a separate, announced change.
  5. Order. Accuracy first (P3a), then steps (P4, P5a), is recommended: accuracy is the larger lever, and P5a’s deferred correction is built around the final scheme. The alternative, P4 first, is easier to verify because it does not change the discrete equations, but it improves cost at a grid where native still misses the target.

Expected outcome

All figures in this section are estimates, not measurements.

  • After P3a: Ghia error close to OpenFOAM’s at the same grid. Native would probably reach 0.01 at 24–32², giving the first finite equal-accuracy ratio. With today’s native cost at 24² (4.4 s against OpenFOAM’s 0.64 s, hosted), that ratio would be roughly 5–20×.
  • After P4: 1.7–2.3× fewer pseudo-time steps on the cavity, minus the cost of the viscous solves.
  • After P5a or P5b: outer iterations of the same order as OpenFOAM’s SIMPLEC. The goal is native within about 2× of OpenFOAM’s solver time at equal accuracy on the cavity. The real test is the RANS canyon after P5c and P5d.
  • Optional later:
    • a native 2D mode with one span cell, which halves cavity cost and makes the comparison like-for-like;
    • P2c hierarchy setup cost;
    • kernel fusion and SIMD;
    • parallel momentum and smoother kernels.

Sources

Implement from these. None of them is OpenFOAM source code.

  • Textbooks:
    • S. V. Patankar, Numerical Heat Transfer and Fluid Flow, Hemisphere, 1980. SIMPLE, under-relaxation, staggered grids.
    • J. H. Ferziger, M. Perić and R. L. Street, Computational Methods for Fluid Dynamics, 4th ed., Springer, 2020. Finite volumes, deferred correction, SIMPLE/SIMPLEC, steady solvers.
    • H. K. Versteeg and W. Malalasekera, An Introduction to Computational Fluid Dynamics: The Finite Volume Method, 2nd ed., Pearson, 2007. TVD schemes, SIMPLEC.
    • H. Jasak, Error Analysis and Estimation for the Finite Volume Method with Applications to Fluid Flows, PhD thesis, Imperial College London, 1996. Background on second-order finite-volume schemes. Use the text, not code.
  • Staggered grid and flux form:
    • F. H. Harlow and J. E. Welch, Phys. Fluids 8 (1965) 2182–2189.
    • Y. Morinishi, T. S. Lund, O. V. Vasilyev and P. Moin, J. Comput. Phys. 143 (1998) 90–124.
  • Reconstruction, limiters and TVD time integration:
    • B. van Leer, J. Comput. Phys. 14 (1974) 361–370.
    • B. van Leer, J. Comput. Phys. 23 (1977) 276–299 (monotonized central).
    • P. K. Sweby, SIAM J. Numer. Anal. 21 (1984) 995–1011.
    • G. D. van Albada, B. van Leer and W. W. Roberts, Astron. Astrophys. 108 (1982) 76–84.
    • S. Gottlieb and C.-W. Shu, Math. Comp. 67 (1998) 73–85.
  • Steady convergence with limiters: V. Venkatakrishnan, J. Comput. Phys. 118 (1995) 120–130.
  • Deferred correction:
    • P. K. Khosla and S. G. Rubin, Comput. Fluids 2 (1974) 207–209.
    • T. Hayase, J. A. C. Humphrey and R. Greif, J. Comput. Phys. 98 (1992) 108–118.
  • Delta form and pseudo-time continuation:
    • R. M. Beam and R. F. Warming, AIAA J. 16 (1978) 393–402.
    • W. A. Mulder and B. van Leer, J. Comput. Phys. 59 (1985) 232–246.
    • C. T. Kelley and D. E. Keyes, SIAM J. Numer. Anal. 35 (1998) 508–523.
  • Pressure–velocity coupling: J. P. Van Doormaal and G. D. Raithby, Numer. Heat Transfer 7 (1984) 147–163 (SIMPLEC).
  • Linear solvers: H. A. van der Vorst, SIAM J. Sci. Stat. Comput. 13 (1992) 631–644 (BiCGStab).
  • Verification:
    • G. I. Taylor and A. E. Green, Proc. R. Soc. A 158 (1937) 499–521.
    • P. J. Roache, J. Fluids Eng. 124 (2002) 4–10.
    • U. Ghia, K. N. Ghia and C. T. Shin, J. Comput. Phys. 48 (1982) 387–411.

Iteration 02: established-solver execution and experimental evidence

Date: 29 October 2026. Baseline: 0bcbc8c9bae55923513c953aac7c8b7183e31605 (merged first-release and plan-v2-alignment PRs).

Decision

Develop CFD-craft as an optimization and validation workbench with a native research solver and an established external backend. Experimental credibility is specific to a configuration and observable. Code agreement, numerical convergence and agreement with measurements remain separate assessments.

The merged code already strengthens memory/output preflight, structured diagnostics, returned-field audits, source identity, pressure references and three 100-step steady monitor windows. Preserve those changes.

Work and acceptance gates

  1. Add a bounded, shell-free adapter for OpenFOAM Foundation 13, tested with package 20260407. Generate original input dictionaries for two canonical cases; do not copy solver implementations or silently accept another fork. Preserve fresh-directory behavior, input and runtime hashes, logs, actual iterations, timeouts and failures. A zero process exit alone is insufficient.
  2. Run a laminar Re=100 cavity in both backends. Compare corresponding centerline velocities and the existing Ghia numerical reference. Use the existing maximum-error target of 0.06 lid-speed units for each solver. This is numerical cross-checking, not experimental validation.
  3. Fetch the Driver–Seegmiller backward-facing-step raw measurements from TMR with frozen SHA-256 identities and explicit provenance. Do not make CI depend on restricted data or bundle another project’s licensed code. Use the upstream x/H=-4 mean-velocity profile as an inlet condition; downstream x/H=1,4,6,10 profiles remain evaluation data.
  4. Freeze a development comparison protocol before running the case: downstream mean-U profile RMSE <=0.10 Uref at each station, lower-wall Cf RMSE <=0.001, and reattachment error <=0.75 H against 6.26 H. These are project screening targets, not published certification criteria. Retain failed metrics. Experimental uncertainty of reattachment is +/-0.10 H; profile uncertainty and unmeasured inlet turbulence components must remain explicit. A single coarse comparison cannot qualify the native canyon model.
  5. Execute a small mesh series within a declared per-case budget. Report convergence, input assumptions and mesh sensitivity separately from measurement error. Do not tune constants or relax thresholds after observing predictions.
  6. Add negative tests for corrupted input/data/sample identity, malformed or nonfinite results, incomplete execution, timeout, version mismatch and optimized-Python behavior. Run repository-required Rust and Python checks.
  7. Provide an agent prompt, a reproduction guide and recorded results. Keep generated large fields outside the source tree.

Deliberate limits

No new native physics or claimed Rust speed advantage. The native wall roughness and pressure throughput still need their own numerical iteration. The external backstep uses its own documented RANS/inlet package; it does not inherit the native canyon’s assumptions. No scalar-dispersion validation is implied by a velocity-only experiment. No purchases, owner contact, publication or deployment is needed.

Primary references

Iteration 03: resolve the backstep convergence gate

Date: 29 October 2026. Base: merged PR #3, 4ea88a3.

Evidence and decision

The merged external backend has copied-input checks, environment isolation, archive verification, first-solve residual parsing, diagnostic codes, residual trends and comparison baselines. A nonconverged iterate does not pass the measurement screen. These properties are retained.

The backstep stalls with the first cell in the wall-function buffer layer. The present SIMPLEC recipe also under-relaxes pressure by 0.2. These are two different hypotheses, which require controlled comparisons. More iterations alone are not the proposed fix.

Implementation

  1. Preserve the legacy mesh and numerical settings as named defaults. Add explicit wall-resolved and simplec options for the backstep only.
  2. Generate a conforming graded mesh with first-cell heights derived from geometric series. Refine all four solid walls, including the vertical step. Use k=0, zero wall eddy viscosity and the low-Re omega treatment of the existing SST model. Retain the same geometry, Reynolds number, measured inlet and unmeasured-inlet assumptions. Do not fit downstream measurements.
  3. Add a SIMPLEC profile with pressure relaxation 1 and transport relaxation 0.7. Keep the nonlinear residual, continuity and experimental thresholds unchanged. Compare pressure-coupling and mesh/wall-package effects separately, in a 2x2 design at level 1.
  4. Independently read the actual Cartesian OpenFOAM mesh. Recompute cell volumes, local finite-volume divergence from stored phi and first-cell distances/y+ from stored wall traction. Check generated geometry against represented geometry, not just metadata. This auditor supports the bounded generated hexahedral cases; it is not a general unstructured-mesh reader.
  5. Supply a bounded comparison/refinement tutorial with numerical, mesh, near-wall and measurement verdicts separate. Require local normalized divergence <=1e-4 for the new independent audit, and first-cell y+ <=1 for the wall-resolved candidate. These are development gates frozen before runs.
  6. Run small controlled cases and a refinement series within cloud resources. Preserve all failed runs. Numerical acceptance is required before a measurement screen; a mesh pair requires the same wall/numerical package.
  7. Test geometry/flux corruption, metadata mismatch, options, legacy behavior and optimized Python. Run required Rust/Ruff checks, the existing external suite and the native analytic/empty-ABL suite.

Acceptance and limits

The software gate is complete, reproducible generation/execution/audit with passing regression tests. The scientific target is at least one numerically accepted, independently audited wall-resolved backstep. A converged mesh pair is a further target, not permission to conceal a budget or convergence failure. Do not claim GCI outside an appropriate refinement regime. The original screening protocol remains unchanged and its broad-target limitations remain.

There are no native RANS/kernel changes, new scalar physics, GPU or MPI requirements. Velocity evidence still does not qualify the native canyon or concentrations. Physical uncertainty and inlet/model sensitivity remain separate gates even if numerical convergence is achieved.

Primary references

Outcome

The software gate is met. The scientific target is met at level 1: the wall-resolved/simplec recipe converges to the unchanged nonlinear gate, passes the independent local-flux and all-wall y+ audit, and its measurement screen is assessed. A converged mesh pair is not reached: a level-2 case has four times the cells of a level-1 solve that took about 50 minutes, so it is not expected to finish within the 3600 s per-case limit. The first streamwise spacing had a 140:1 cell-width jump at the step plane and diverged under every profile tried; with only the spacing changed, the same simple recipe became stable. The legacy-mesh stall is unchanged by the pressure-coupling control. See the resolution results.

Iteration 04: verified bounded steady continuation

Date: 30 October 2026. Base: merged PR #4, dee9c5afb9ef5ab8455f3d2b5da4651e2cb39035.

Evidence and decision

The merged wall-resolved/simplec level-1 backstep converges after 18412 iterations in one run of about 3000 s and passes the independent audit and the measurement screen. A passing coarse screen is not physical qualification. A level-2 case has four times the cells, so a single 3600-second run cannot converge it. The first prerequisite is verified same-mesh field continuation in bounded stages. The mesh, SST package, inlet, pressure scheme and acceptance thresholds stay unchanged.

Implementation and invariants

  1. prepare-restart --source RUN --iterations N --output NEW_INPUT accepts a sealed, completed archive from the current generator with finite final fields. Timeout, cancellation and failure snapshots are ineligible. An unconverged completed stage is eligible if its stored face flux is a solver state (see below).
  2. Keep the exact consumed physics/mesh dictionaries and boundary definitions. Copy final U/p/phi and, for SST, k/omega/nut into a new local iteration-0 directory, and change only endTime/writeInterval. This is a steady field restart: local pseudo-iteration numbering and solver history reset. Cumulative iteration counts report work, not physical time or bitwise equivalence.
  3. Record the source manifest/case hashes, metadata, controls, acceptance and work, the copied field identities, the fixed-input and actual mesh identities and the runtime identity. Check the copied bytes, the field snapshot times, the rebuilt mesh and the exact runtime before solving, and again when reading an archive. Unkeyed hashes are consistency, not authenticity.
  4. Add --max-stages (default 1, at most 8) to the resolution tutorial. Continue only a completed, unconverged stage; stop at numerical acceptance, a converged but unaccepted stage, failure, timeout, cancellation, an ineligible source or the stage limit, and record which. Keep every stage and distinguish final-stage convergence from cumulative work. Finer meshes still require accepted coarser levels.
  5. A run that stops at its iteration limit writes a final field only if the limit is a multiple of the write cadence; endTime 400 with cadence 250 leaves none. Use the largest divisor of the limit up to 250, and reject limits without a divisor between 50 and 250, which would force nearly per-iteration writes of 8 MB snapshots.
  6. Test source eligibility, corruption and races, receipt and archive consistency, mesh/runtime/input mismatches, cumulative counts, occupied paths, the stage loop and optimized Python. Provide tools that repeat the field comparisons from the repository.

Source eligibility

A completed source is eligible only if its stored face flux passes the auditor’s independent local gate, max abs(div(phi))*H/U <=1e-4. This gate was preregistered and stays in force. Two properties limit it: it follows the last pressure solve’s relative tolerance rather than the state (a PCG profile with relative tolerance 0 passes by orders of magnitude, a GAMG SIMPLEC iterate at iteration 500 fails), and it tightens like H/dx with refinement, the use case of continuation. Whether a scale-free integrity check should replace it is an open decision, recorded with its evidence in the results; it is not changed after the gate rejected a source.

Acceptance and experiments

The software target is an auditable field restart with all relevant tests passing. Fixed-work comparisons continue FIRST iterations for SECOND and compare the final fields with an uninterrupted FIRST + SECOND run of the same recipe: maximum component-wise U and p differences of 1e-6 for the cavity (400 + 200) and 1e-5 for the wall-resolved backstep; for k/omega/nut, the maximum difference over the control’s largest magnitude is at most 1e-5. The planned simplec 500 + 500 backstep comparison cannot start, because its source fails the flux gate; the simple profile (250 + 250) supplies the backstep comparison. The final local-flux audits must pass. These equivalence checks do not require nonlinear convergence and imply no measurement screen.

The reference-recipe check runs the wall-resolved/simplec level-1 case in stages of 6000 iterations (up to four) and in one 20000-iteration run on the same runner. Preregistered before the result: both are numerically accepted and pass the audit and screen; the chain’s cumulative work is within 5% of the single run’s; reattachment agrees within 0.01 H, Cf RMSE within 1e-5, each profile RMSE within 1e-4 and each wall’s maximum y+ within 0.01; the final U and p differ by at most 1e-3 (U_ref, U_ref^2, without removing an offset) and k/omega/nut by at most 1e-3 of the control’s largest magnitude.

The scientific mesh-pair, inlet-sensitivity and model-form gates remain open. Cross-mesh mapping, changes to the turbulence treatment, native-kernel changes, GPU and MPI are outside this plan.

Outcome

The results record the checks on GitHub runners. The staged reference solve meets every preregistered bound: four stages converge after 18412 cumulative iterations, as the single run does, with identical metrics to all digits reported and final fields within 2e-12. The cavity and simple-profile fixed-work comparisons meet their equivalence bounds and their final local-flux audits pass. The simplec 500-iteration source fails the flux gate, as before. Whether that gate, which follows the pressure solver’s tolerance, should decide eligibility is open; a development continuation of that source under a scale-free check exceeded the fixed-work bounds (U 7.25e-5). Level-2 stage lengths, the SST state a restart does not carry and an unexplained extra time directory in an earlier staged archive are also open.

Primary reference

Foundation 13 time/I-O controls describe startTime, endTime, writeInterval and ASCII precision. This work uses a fresh local pseudo-time zero for steady field initialization, with explicit source and work provenance, rather than a transient-history restart.

Iteration 05: explicit coarse-to-fine field initialization

Date: 30 October 2026. Base: PR #5, e6134cd2e74d675819b8acd696af7d813c06809b.

Evidence and decision

Same-mesh continuation reaches the single-run solution of the wall-resolved level-1 backstep in stages (continuation results). Its source-flux gate stays as preregistered. A fine-grid campaign needs a different operation first: initialize a newly generated finer case from accepted coarse volume fields. The new mesh has no transferable face flux; the solver initializes phi from its new U and corrects it. Preparation makes no claim of initial conservation or of an accepted fine solution.

Implementation

  1. prepare-mapped accepts a cold-generated, numerically accepted source with a passing independent audit, built by the current generator, and maps it to exactly one finer level of the same case, mesh family and solver profile. Restarted or mapped sources are not accepted.
  2. Foundation 13’s separately licensed mapFields runs with -consistent -mapMethod mapNearest on checked copies. This is nearest-cell initialization, not conservative interpolation or an accuracy method. No OpenFOAM code is copied into the repository.
  3. Only the mapped internal U and p and, for SST, k, omega and nut are imported. The target’s generated boundary definitions, dimensions, geometry, inlet and controls stay byte-identical; phi and wall stress are not mapped. Field counts, finite values and turbulence signs are checked. The raw mapper output, templates and logs are kept as inputs.
  4. A distinct receipt binds the source case, manifest, summary, audit, fields and work, the target metadata and templates, the mapper output and mesh, and the runtime and mapper identities. Validation before solving and during archive verification rechecks this chain and replays the nearest-cell mapping independently from the stored source copy. A solved case requires the recorded runtime and a passed, identical rebuilt mesh. A failed preparation stays non-runnable and keeps its diagnostic and logs.
  5. Same-mesh restart is unchanged. A completed mapped run can be continued on its mesh; the new stage’s receipt names the mapped parent, and the mapping receipt is removed from the stage. Coarse work is not counted as fine-grid iterations.
  6. Tests cover boundary preservation, exact nearest mapping on known fields, source eligibility, source-copy races, provenance, missing or altered evidence, runtime and mesh mismatch, limits, occupied outputs and optimized Python. Real Foundation-13 tests cover cavity 1->2 and nonuniform SST fields on the real backstep meshes, distinguished from an accepted turbulent flow.

Acceptance and experiments

Declared before the runs: a mapped and a cold level-2 cavity, with identical final settings, both pass the nonlinear and local-continuity gates; their final U and p differ by at most 1e-4 (U_ref, U_ref^2, no pressure offset removed); both Ghia centerline errors are at most 0.06. All work, including the source and the mapping, is reported; one run supports no speed claim.

A mapped and a cold start of the wall-resolved level-2 backstep, from the accepted single level-1 run, run with equal iteration limits and budgets. This is a report, with no gate: it shows whether the path works on the backstep and what each start reaches, not an accepted fine solution.

No source-flux, final residual, wall-y+ or measurement threshold changes. A GCI, mesh independence and physical validation remain open, as do native physics, GPU and MPI.

Outcome

The results record the GitHub runs. The mapped and cold level-2 cavities meet every declared bound (U 5.1e-9). On the real backstep meshes, Foundation 13’s mapNearest takes a nearby source cell other than the nearest for 4.9% of the level-2 cells, so the replay accepts any of the 27 nearest cells, the same one in every field, and records how many and how far. From the accepted level-1 backstep, a mapped level-2 start reaches a pressure residual of 1.1e-6 after 3000 iterations, a cold start 6.4e-5; neither reaches the nonlinear gate. An accepted level-2 backstep, its stage lengths and the source-gate decision remain open.

Primary source

Foundation 13 mapFields supports mapNearest, interpolate and cellPointInterpolate. Only mapNearest is used, with the generated target boundary dictionaries.

Iteration 06: archive anomaly investigation

On a cloud machine, a sealed archive twice acquired an old time directory after it was sealed, and the verifier rejected it (CFD-X006 archive.progress). It has not happened in any GitHub run. This record states what was observed, what the tests show and what remains unknown; the cause is not established.

Observations

  • Staged study (continuation results). After the workflow sealed a stage, its archive contained an additional case/250 directory.
  • Cavity source. A level-1 cavity run (2.25 s, converged at 696, saved times 0 and 696) was reused later from the same working directory. The check then found saved times 0, 500 and 696, with an empty case/500/uniform. Every file still had its sealed size and hash: the change was an empty directory, which the file inventory does not list and the progress check does.
  • Timing. The empty directory’s modification time lies within the 2.25 s solve, its status-change time about 3.7 s later, after the run had returned. This fits something recreating the directory after the solver purged it, with its original time (a copy or synchronization step, for example), but it is not proof. A long campaign run was executing on the same machine at the time.
  • Repetition. The same cavity source and campaign, regenerated under a fresh private path, verified at every checkpoint.
  • Cavity accuracy sweep (31 October 2026). In three of four 48² cavity runs on a cloud machine (2132 iterations, snapshots every 250 with purgeWrite 1), the summary written at sealing already listed an old time directory, 250 or 500, without files. The adapter records progress after foamRun and foamPostProcess return, so the directory existed then. The 24² runs and the 48² warmup did not show it. A file-only evidence copy dropped the directories, and the copies then failed the progress check. A directory recorded at sealing passes the verifier on the original disk, so a verified archive does not show that this did not happen; validation/archive_evidence.py lists such directories, and the hosted accuracy job prints them.

The rejected archives were kept unchanged, including the empty directory; a file-only copy would lose this evidence.

Process lifecycle

The backend starts each child in its own process session and always stops the process group before execute returns, including when the leader has exited (TERM, then KILL, then a wait). The real-process tests cover a timed-out group, cancellation and an exited leader with a TERM-ignoring descendant, in normal and optimized Python. Snapshot purging belongs to the solver while it runs; the disk-budget scan tolerates files disappearing during purgeWrite, and the numerical assessment and the final inventory happen after the child returns. No defect was found that would explain the anomaly, and no process cleanup was changed.

Containment

The refinement campaign copies its source with checked bytes, verifies both inventories, and reverifies every archive after each stage and at final collection, requiring each archive to keep its first checkpoint’s manifest. The real-runtime tests add a late file (case/123/U) or an empty purged directory (case/200/uniform) to a sealed cavity stage: the campaign stops at the next checkpoint with CFD-X015 refinement.archives.* and the underlying CFD-X006, starts no further stage, and leaves the archive, its manifest and the added entry unchanged. These checks find when evidence stops matching its seal; they do not prove exclusive ownership of a path.

Next steps if it recurs

The Stage V campaign (1 November 2026) reproduced the anomaly, including full old snapshot files as well as empty directories. Records that passed at child return later failed progress/file checks, including in a sequential campaign. The accuracy sweep now rechecks all archives at final collection, retains measurement-time acceptance and invalidates late changes before pricing them; regression tests cover that transition and changed manifests. No archive verifier was relaxed and no old output was repaired.

A separately declared campaign with identical numerical and timing settings, run in a fresh temporary directory, passed all 32 paired records at collection. Its evidence archive was packed, extracted and rechecked there and again after copying: 51/51 sealed archives verified, including intentional work-limit controls. Filesystem-event logs, process snapshots, the reproduction driver and the rejected attempts were retained. This contains the observation for that campaign; it does not establish the cause. The hosted reproduction of the same protocol on a GitHub runner rejected no row at collection and verified 51/51 archives. See the Stage V report.

Keep the changed archive and its first failed checkpoint. Record file-system events and processes for the run directory in a separately instrumented reproduction. Do not delete the directory, reseal the run or infer a cause from a clean repetition.

Iteration 06: bounded mapped refinement campaign

Date: 30 October 2026. Base: merged PR #6, 06bf8b5d894e5252a5b04d14ff04cda06e010bb8.

Evidence and decision

The mapping results record mapped and cold level-2 backstep starts after 3000 iterations; neither converged, and neither is a source for anything else. The next step connects mapping, same-mesh continuation and final acceptance in one bounded campaign that keeps every archive it uses. The numerical, local-flux, wall-y+ and measurement gates, the native equations, the solver recipes, the experimental protocols and the mapping and restart schemas stay unchanged.

Implementation

  1. Snapshot a verified, accepted, cold coarse archive into a fresh campaign directory: check the copied bytes and both inventories, and keep the complete parent rather than a summary or an external path. The source must pass its numerical gate, the independent audit and its measurement screen.
  2. Freeze a plan with the source identity, the producer identities, the next level, the work, the stage count and the per-stage preparation and solve limits before anything is executed.
  3. Map once, then continue completed eligible fine stages with the existing restart API. Verify every stage and bind its parent, runtime, mesh and cumulative fine work to the previous stage. Keep coarse work separate.
  4. Keep the numerical, independent-audit and measurement verdicts of every stage. Stop at accepted convergence, converged-but-rejected evidence, an execution stop, an ineligible source or the declared stage limit. Never restart a timeout or cancellation or promote an earlier snapshot.
  5. Reverify every complete archive after each stage and at final collection, and require each archive to keep its first checkpoint’s manifest. An archive or progress mismatch stops the workflow; nothing is repaired or resealed.
  6. Compare coarse and fine observables only when both numerical assessments and independent audits pass. Pair velocity samples by exact identity and compare Cf at common measured positions without extrapolation. Two grids are not a GCI or a mesh-independence certificate.
  7. Test the rules in normal and optimized Python, including real mapped cavity stages, rejected sources and archives, parent and work mismatches, stopping and gate semantics; run the campaign in the optional CI workflow and keep its complete archives.

Declared campaign

Source: the accepted cold wall-resolved simplec level-1 backstep (48896 cells, 18412 iterations), verified and checked against its measurement screen. Target: level 2 (195584 cells). At most three stages of 4000 iterations, at most 3500 s per solve, 1024 MiB output and 4096 MiB child address space per stage, 900 s for the preparation. The source’s coarse iterations are provenance, not fine work. No cold level-2 control and no speed claim.

A successful outcome requires final numerical acceptance, the independent local gate (<=1e-4), maximum y+ <=1 on each wall and the original backstep measurement screen. Otherwise the actual stop reason and the unaccepted evidence are the result. No threshold is adjusted after results are read. Inlet and model sensitivity, another refinement and native canyon qualification remain later work.

Executions before the declared run

The campaign was first exercised on a cloud machine (eight-core quota). A prototype was cancelled at started iteration 238 to correct the cancellation rule; two runs of the declared campaign then ended without a returned solver record or seal, at started iterations 1457 and 1193, for reasons that are unknown. None of these fields was used as a source. A reduced campaign (two 400-iteration stages, 450 s per solve, 180 s preparation) then ran to the end; its limits were frozen in its report before it started, but an earlier version of this document was changed to declare it only afterwards. It is a workflow check, not the declared campaign, and is recorded as such in the results. The declared campaign above then ran on a GitHub runner through the manual external=refinement selection.

Outcome

The declared campaign ran on a GitHub runner (workflow run 41151497327) with the limits above. All three stages completed; none was numerically accepted, and the stop reason is stage_limit after 12000 fine iterations. Every stage passed the independent audit. At the end the Ux, p and omega residuals met the 1e-7 gate, while Uy (1.8e-7) and k (1.05e-7) did not; the residuals fell in every stage. The two-grid comparison was not assessed, and there is no accepted fine backstep. The thresholds were not changed. See the results.

Iterations 07–14: native CPU throughput

Declared before implementation on merged PR #7, 402a15036636d8f48591a2d9b5f4ed203cb5ab91. Date: 30 October 2026.

Baseline review

Keep PR #7’s frozen-source, first-manifest, returned-summary and producer checks, source measurement screening, observation failures as evidence, error precedence, started-work accounting and split notices. Its actual 12000-iteration fine backstep is still numerically unaccepted; declining residuals do not imply a stall or an accepted mesh pair. The source-flux decision and physical-validation gates remain open and unchanged.

The native roadmap identifies repeated IC(0)-PCG projection and explicit stepping as the throughput limit. The increments below reduce implementation cost without a new pressure equation, turbulence closure, advection scheme or convergence policy. They need serial CPU validation only, not GPU or MPI.

Eight increments

IterationTargetProposed implementationDecisive validation
07Allocation in every PCG preconditioner applicationReuse the preconditioned residual vector; add a bounded, deterministic kernel/fixed-step benchmarkSame pressure solve, independent true residual and allocation-free repeated application
08Pointer chasing in IC(0) triangular sweepsStore lower factors in contiguous row offsets, columns and valuesPeriodic duplicate faces, masked components, outlets, independent assembled reference
09Per-row heap allocation and searches during cold factor setupAssemble sorted/coalesced lower edges directly into contiguous storage, preserving accumulation orderCold versus warmed timings; equivalence to the prior factor on odd/even periodic and masked cases
10Large face objects, branches and divisions in every PCG multiplyBuild compact active pressure-face entries once per solve, retain face accumulation order and the public operator’s semanticsTopology/nullspace/projection suite; independent matrix products and true solve residuals
11Temporary full-grid/face arrays in projectionForm projection RHS/scales directly and apply pressure gradients without a temporary face vectorOpen/closed/masked projection, gauge and compatibility checks, final-field comparison
12Repeated neighbor lookups in RANS gradientsReuse local cell-neighbor indices in production and variable-viscosity termsExisting wall/ABL tests, unchanged arithmetic and independent empty-ABL gate
13Duplicate staggered-face lookup in momentum sampling and viscosityShare each face-neighbor lookup between advective sampling and viscous coefficientsLaminar/channel/cavity and oblique/canyon RANS fixtures
14State copies immediately discarded by SSPRK stagesBuild a candidate state only for needed fields, move monitor history only after all fallible checksTransactional failure/cancellation, scalar mass/positivity/superposition and identical accepted results

Each increment is a separate commit with its own measurements. If a proposed change does not help its measured target, retain that negative finding and revise or replace the implementation before calling it a gain. Do not reduce accuracy, use fewer required solver iterations, or remove checks.

Frozen measurement protocol

Use the same compiler, Cargo.lock, release profile, cases, thread allowances, work counts and output settings for all versions. Build the baseline before optimizing. Preserve binaries privately with hashes and source identities.

Measure grid setup, cold/warm pressure solves, momentum, production, scalar RHS and a fixed number of coupled steps through a deterministic Rust probe. Use moderate masked canyon grids and a periodic transport case; keep each child below 180 seconds, preserve failures and actual iterations. Warm up once, then use at least five alternating baseline/candidate measurements for final speed claims. Record medians and ranges, CPU time and peak RSS where available. Kernel results are not end-to-end speedups. Include one/four-thread comparisons where relevant; do not treat this host as a ranking of machines.

Run numerical tests after each affected change. Pressure changes require the independent assembled operator/reference, disconnected/nullspace and projection checks. RANS changes require the unchanged empty-ABL check and a model-card update. Transport/state changes require mass, positivity, unit normalization, refinement and failed-step atomicity. Final verification also includes the existing native analytic/order/cavity/SciPy suites and an accepted coarse canyon.

For baseline/final fixed-work comparisons require the same case/physics, completed work and stopping state, no new floor events, valid finite fields and independent mass/continuity checks. Compare all retained fields and budgets with a preregistered relative scale of 1e-11 plus 1e-13 absolute (report exact agreement too); pressure nullspaces use the same gauges. Tolerances in the solver and scientific verification suites are unchanged. A speedup that fails these requirements is rejected.

Update the memory estimate if caches/workspaces raise the bound. Report measured RSS alongside it; do not trade an unreported memory regression for speed.

Record

Record the source and binary identities, the frozen cases, every paired measurement and the test results. Keep the native canyon’s physical and model limits and the external fine backstep gate explicit. Report actual results, including slower cases, the memory cost and any remaining throughput limits.

Detailed user manual and project banner

Base: merged PR #9 (4f156e5).

Scope

Provide one human entry point that explains the architecture, numerical and evidence concepts, and the actual supported APIs. Cover the merged native solver, OpenFOAM adapter and existing optimization-jobs/fcmaes integration; describe only implemented features (particles, for example, are not part of the native model). Preserve the reviewed backend timing definitions, shared cavity helpers and numerical/physical acceptance distinctions.

Deliverables

  1. docs/USER_MANUAL.md: navigation, quickstart, architecture diagrams and a complete case walkthrough; CLI, Rust and Python examples; outputs, budgets, cancellation, restart, external workflows, optimizer jobs, troubleshooting, validation and performance interpretation. Link to detailed model cards.
  2. Small runnable examples under examples/manual/ and the Rust crate’s examples directory. Test real API calls with a fast source-response case, receptor lookup by ID, checkpoint continuation, archive verification, cancellation and coded invalid input. Include an optional actual OpenFOAM cavity example and the existing runner integration without inventing APIs.
  3. A generated engineering banner under docs/images/, displayed at the top of README with meaningful alternative text and a prominent manual link. Treat the artwork as illustration, not a CFD result or validation badge.
  4. Documentation-example checks in CI: the small native examples on every push, and the manual’s OpenFOAM recipes in the manual external backend job.

Implementation and acceptance

  • Read CLI describe, public Rust definitions and existing Python workflow entry points before documenting them. Case/result schemas remain 0.1.
  • Explain the two independent backends and the outer job/campaign layers; Rust is the native library API, Python orchestrates the CLI and adapters.
  • Use small bounded, serial examples and fresh output roots that run on a modest CPU host without remote commissioning.
  • Keep required fields, units, coordinate conventions, source normalization, receptor ordering and unknown-field rejection explicit.
  • Demonstrate that Result::Ok, exit 0, numerical assessment, archive integrity and experimental validation answer different questions. Preserve failures.
  • Explain native transient restart separately from steady OpenFOAM continuation and cross-mesh field initialization. Neither replaces final acceptance.
  • Compile and execute every new Rust example; run Python examples normally and under -O; verify source budgets, mass/receptor checks and real returned fields. Run the optional OpenFOAM example against the pinned runtime.
  • Run locked workspace release tests, fmt/clippy, Python Ruff and the relevant CLI/backend/benchmark/integration contracts. Do not rerun expensive unrelated campaigns for a documentation change or weaken scientific thresholds.
  • Check Markdown links/anchors and example-to-manual references. Inspect the banner’s text and appearance and the README reference.

Boundaries

No solver method, physical model, numerical tolerance, package pin or job protocol change is needed. Documentation examples are executable API usage, not additions to numerical scope. The manual must preserve the measured OpenFOAM advantage on the cavity and avoid extrapolating it to canyon or particle workloads. Source-gate decisions and experimental qualification remain separate work.

Iteration 17: measure the native/OpenFOAM performance gap (P0)

Baseline: merged PR #10, 67599967afde765ba10d947cef5e5a0211549768. This is the first implementation stage of the reviewed gap-closing plan.

Scope and decisions

  1. Add opt-in, aggregated native phase profiling. A new profile command owns a fresh envelope containing run/ (an ordinary native archive) and a separately versioned profile.json. The existing case, result and archive formats remain readable. Record input/build/archive identities, attempted pressure work, committed steps, inclusive/exclusive timings and unattributed request time. No per-cell or per-iteration locks/timers.
  2. Extend the existing backend comparator with an explicit accuracy-sweep mode. Use supported OpenFOAM levels 1..3 (24/48/72), matching native flow-plane grids and the existing span treatments. Retain every warmup and timed row, including failure/time/iteration limits. Keep workflow success, numerical acceptance, the frozen 0.06 screen and a new 0.01 development target distinct. Calculate cost at the target only from repeated accepted qualifying runs; report an unreached target without an invented ratio.
  3. Profile actual evolving native runs and compare profiling on/off and the merged baseline in alternating one-thread rounds. Check exact state/archive fields and counters, independently audit fields, and report overhead without interpreting instrumentation as a solver speedup.

Validation and declared compute limits

  • Core release tests, formatting, all-target Clippy with warnings denied; normal and optimized Python contracts and Ruff.
  • Profiling: laminar cavity, prescribed scalar transport and a bounded RANS canyon; restart, cancellation, failed projection, output preflight and archive readers. Preserve partial-work accounting when a step does not commit.
  • Reproduce the accepted 24² native/OpenFOAM pair with the old comparator; execute a two-grid 24/48 accuracy sweep on the same host. Use one warmup and three alternating timed pairs per grid; per-run 180 s native wall budget and 180 s OpenFOAM allowance, 3000 OpenFOAM outer iterations. Native 12² is an additional diagnostic. One profiled 48² run uses the same 180 s budget; a separate short-budget run demonstrates censored rows.
  • Profile overhead: one warmup and five alternating pairs at 24², plus fixed-work scalar and canyon controls. Do not time independent CPU-heavy campaigns at the same time. Compiler, CPU, binaries, runtime and consumed cases are retained.
  • The 72² campaign is not run; its plan and budget handling are tested. Record a 48² timeout rather than increasing its frozen budget.

Completion and next stage

The profiler must account for nested time without adding it twice, retain failed attempted work, and leave the solver’s numerical results unchanged. The sweep must retain unsuccessful rows and explicitly show whether each backend reaches the target on the tested grids. New diagnostics include field paths. The next numerical stage is P1, a symmetric PCG-compatible multigrid preconditioner; it is not part of the measurement stage. (P1 is done since; see the gap status.)

Symmetric pressure multigrid plan

Baseline and objective

Start from main bbd191b (PRs #11 and #12). Preserve the stricter profile and measurement contracts, process-group cleanup, 600 s hosted native accuracy budget and evidence ZIP round-trip checks including empty directories. Pressure occupied 78–88% of the recorded native solver time. This change targets that equation before changing momentum, pseudo-time stepping or scientific gates.

Implementation boundary

Add numerics.pressure_preconditioner: "multigrid" as an explicit opt-in; "ic0" remains the default. Omitted/default selections retain the previous normalized case and checkpoint hash. Refuse masks with a coded field diagnostic, without an implicit fallback. Support closed, periodic and outlet unmasked grids, odd dimensions, two-cell periodic directions and unequal spacings. Robust anisotropy and masked coarsening are later work.

Build a geometric hierarchy with tensor linear interpolation, its Euclidean transpose as restriction, and exact Galerkin coarse operators. Uniform fine cell volume is a common scalar in the pressure inner product; coarse equations use aggregate sums, without an inconsistent volume average. Preserve directions with at most two cells on every level. Use two forward Gauss–Seidel pre-sweeps and their two backward adjoint post-sweeps, one recursive V-cycle and a dense Cholesky solve at at most 32 coarse cells. For closed systems solve a gauge-reduced coarse matrix and restore mean zero; a single collapsed closed cell has no remaining unknown. No inner tolerance, residual-dependent work or correction scaling is allowed inside ordinary PCG.

Cache the hierarchy and scratch storage for a valid operator, identify current face coefficients at every solve, and rebuild after coefficient changes. Reuse all cycle buffers without allocation in PCG iterations. Keep the fine PCG operator, compatibility check, independent face-by-face residual, correction, nullspace gauge and numerical acceptance unchanged. Record setup, hierarchy size and actual multilevel work in opt-in profiling. Account for setup memory in case preflight; distinguish allocated hierarchy storage from process peak RSS.

Validation before measurement

  • Assemble independent -D G matrices, prolongation matrices and P^T A P; check hierarchy entries, nullspace/anchor preservation and pressure solutions.
  • Check preconditioner linearity, adjoint symmetry and positive eigenvalues on anchored systems and the compatible closed subspace. Explain the SPD argument; finite tests supplement it.
  • Exercise analytical/manufactured pressure, projection, incompatible RHS, cancellation, pressure iteration limits and changed public face coefficients.
  • Retain IC(0) exact-output controls and restart/hash behavior; test schema and mask rejection, profile counters and independent archived-field checks.
  • Run fmt, clippy with warnings denied, release workspace tests, Python lint and relevant Python checks in normal and optimized modes.

Predeclared measurements

One thread, same host/compiler, one warmup and three alternating timed pairs. Pressure kernels use the existing manufactured RHS, nominal tolerance 1e-11 and 10000 iteration bound on cavity 24/48/96 and unmasked 24^3/48^3 grids; the first solve includes hierarchy construction and subsequent solves reuse it. Compare solutions to the manufactured field, not iteration-count equality between algorithms. Require RMS pressure error <=1e-8 and true relative residual <=1.01e-10; repeated work/results for each configuration must agree.

Accepted coupled measurements use steady Re=100 cavity 24 and 48, max_steps 20000, wall budget 600 s per run, otherwise the unchanged canonical numerics. Keep both returned fields, all failed rows, solver/workflow times, source/case identities and peak RSS when available. Independently audit each archive and apply the existing Ghia screen. Compare velocity with absolute max <=1e-8 and pressure <=1e-7 (same gauge); report actual stopping steps and sampled reference error. These are preconditioner-equivalence bounds, not weaker scientific gates. Do not claim target accuracy, masked-grid improvement or OpenFOAM parity from this experiment. Repeating the external CFD campaign is a separate cost/error measurement after native pressure evidence is sound.

Prototype decision

The first piecewise-constant prototype passed the small-matrix and projection checks but reduced cavity-48 PCG iterations only from 102 to 50 and made reused pressure solves slower. Linear interpolation with immediate span collapse also left weakly coupled span modes unresolved. Tensor linear transfers with short axes retained reduced this manufactured case to 6 iterations in a preliminary run. The final paired campaign measures this design, including its more costly setup and retained storage. The initial observations are retained separately.

Anisotropic pressure acceleration plan

Baseline and scope

Start from merged main 2ddf17d (PR #13). Preserve its independent pressure residual, default IC(0), exact coefficient reuse checks, nonblocking statistics, anisotropy warning and hosted notices. This is the anisotropy substep of P2; masked/component-preserving coarsening remains P2b, so this does not complete P2.

The reviewed point smoother can exceed 1200 PCG iterations on 64x8x64 in a 1x1x0.02 m domain while IC(0) converges. Add exact line-block relaxation for strongly unequal pressure weights, retaining the point path on the isotropic cavity. Retain tensor interpolation and the Galerkin equation; choose coarsening axes at setup as described below. Do not introduce residual-dependent cycles, inner tolerances or relaxed gates.

Mathematical design

Choose stiff axes from the declared uniform cell spacings at setup. Ignore a weak two-cell invariant span when deciding whether the coarsened axes are anisotropic, but include a stiff two-cell axis. Above weight ratio 25, use one or two stiff axes (within a factor four of the largest). A forward block sweep solves each principal line matrix exactly against the latest outside-line values. The backward sweep is its adjoint. Use one forward/backward adjoint block pair on anisotropic levels, with the dominant stiff direction (or the small joint plane). Isotropic levels retain the original two-forward/two-back point sweeps. Block diagonals are SPD principal submatrices; their symmetric Gauss-Seidel composition and positive coarse inverse give a fixed SPD preconditioner on the compatible subspace.

Preserve weak-axis modes by coarsening stiff axes first. When two stiff axes have at most 16 cells together, solve their small plane blocks exactly; this permits remaining weak directions to coarsen after stiff axes reach two cells. This setup policy is fixed throughout a solve.

Use stored band Cholesky factors and scratch. Fold periodic line ordering to keep cyclic couplings in a narrow band; derive the actual bandwidth from stored matrix entries, including duplicate short periodic edges and Galerkin fill. Retain current gauges, compatibility check, fine PCG product, face correction and independent true residual. A nonpositive block pivot must fail with a coded field diagnostic, without a diagonal repair or hidden fallback. Cache identity must include spacing-dependent selection, and memory estimates must include line factors/maps. Statistics and profiling must identify line work.

Tests and predeclared evidence

  • Independent dense line-block solves, including odd/periodic/outlet lines and two-cell duplicates; full small preconditioner symmetry/positive-energy and Galerkin checks; manufactured/continuous pressure and projection tests.
  • Preserve cancellation, iteration-limit state retention, compatibility, coefficient rebuild, nonblocking statistics and checkpoint contracts.
  • Minimum Rust 1.88 and actual stable: fmt, all-target clippy -D warnings and locked release workspace tests. Python suites in normal and optimized modes, lint/format, independent archived-field audits and unchanged scientific gates.
  • Before timings, freeze one warmup plus three balanced timed triplets per shape. Compare merged point MG, candidate line MG and IC(0), including failed rows, cold/reused time, PCG work, true residual, independent recovery and RSS. Include the review’s failing 64x8x64, one-stiff-axis wall/open/periodic cases, plate anisotropy, odd shapes, stiff two-cell span and isotropic controls. Use nominal pressure tol 1e-14 for the ill-conditioned rough kernels, at most 1200 iterations; independent RMS error <=1e-8 and true residual <=1.1e-12. No threshold is loosened after failure.
  • Coupled anisotropic square cavity: 64x2x12, Re=100, canonical physics and numerics. Measure steady convergence and a transient interval to 1 s with one warmup and three alternating IC(0)/MG timed pairs, 600 s/20000-step bounds, independent archives/fields and velocity/pressure differences <=1e-8/1e-7. The transient assessment is interval completion, not steady convergence. Stop a configuration after an unaccepted warmup and retain it without a timing ratio. Its coarse vertical grid is a throughput fixture; steady measurements retain the 0.06 Ghia screen; the standard 24/48 sweep separately reports cost at the 0.01 accuracy objective.
  • Fresh native/OpenFOAM cavity sweep: multigrid explicitly recorded in the native plan, levels 24/48, one warmup and three timed rows, native 600 s, 20000 steps, OpenFOAM 3000 iterations/180 s, error objective 0.01 and existing 0.06 screen. Distinguish same-grid configured solver/workflow ratios from cost at matched accuracy. An unreached target has no finite accuracy ratio.

Remaining roadmap

P0 profiling and P1 isotropic pressure MG are merged. P2a is this anisotropy substep. P2b needs component-preserving masked coarsening, narrow-passage tests, 27k/93k canyon controls and accepted coupled benefit. P2c targets hierarchy construction/coarse complexity if still material. P3 adds independently verified higher-order momentum. P4 is a bounded implicit-diffusion go/no-go; P5 is a dedicated implicit steady method. P6 measures canyon and optimization-campaign payoff, with the physical model and experimental-data gates kept explicit. (Status 1 November 2026: P2a, P3, P4 and P5 are done; P2b, P2c and P6 remain; see the gap status.)

Pilot correction before the formal campaign

The initial rough-RHS pilot at 1e-12 met the solver residual gate but missed the independent 1e-8 pressure-recovery bound on the most stretched grid, for IC(0) as well as the candidate. Keep those records. The formal ill-conditioned kernel campaign tightens the common tolerance to 1e-14; the recovery bound stays 1e-8. This adds algebraic accuracy, rather than relaxing a test.

The pilot also showed divisions while classifying block couplings dominating the fine sweeps. Precompute outside-block row entries during setup and retain them in the memory/accounting estimate. Coefficients stay fixed per solve.

The formal candidate caches outside rows and diagonal reciprocals. One exact block pair replaces two point pairs on anisotropic levels; complete matrix symmetry/positivity tests cover this fixed SPD composition. Profiling counts block-level cell visits independently from smoothing updates.

Each rough-kernel child makes one cold and one cached solve; three balanced timed children provide the reused median, preceded by one warmup per method.

Stage V: momentum verification and donor-cell baseline

Protocol declared 1 November 2026, before the campaign. Base: f358be6 (PR #14); this is the first stage of the accuracy/steady-solver plan. No production Rust stencil, case schema, default, tolerance or acceptance rule changes in this stage. Implement from analytic equations and the project plan; do not consult OpenFOAM implementation source.

Frozen protocol

  1. tests/momentum.rs evaluates the production momentum RHS with viscosity and acceleration set to zero in a test-only helper after building the valid grid. No production floating-point operations are rearranged. Use periodic Taylor–Green velocities u=sin(X)cos(Z), w=-cos(X)sin(Z), X=2πx+φx, Z=2πz+φz. The exact negative advection is (-π sin(2X), 0, -π sin(2Z)) at component face centers. Grids are 32, 64, 128, 256 with two periodic span cells. Eight fixed phase pairs in radians: (0.137,0.271), (0.419,1.103), (1.337,0.593), (2.017,1.771), (2.693,2.291), (3.349,0.887), (4.123,3.517), (5.071,4.237). Report L1/L2/L∞ errors and least-squares log(h) slopes for the two nonzero components together. The donor-cell mean L1 slope must be between 0.8 and 1.2; all errors must be finite and positive. A solid-barrier test requires bit-identical near-side RHS after changing far-side velocities, plus a near-side sensitivity control.
  2. validation/momentum_accuracy.py runs translating Taylor–Green vortices in a unit periodic box, two span cells, ν=0.005, amplitude 0.2, uniform offset (0.7,0.2,0.3), phase (0.137,0.271), final time 0.05. The exact perturbation decays as exp(-8π²νt) and translates with the offset. Grids 16,32,64 use fixed maximum dt=0.0005. Repeat grid 64 at dt/2 and dt/4; the last time-refinement difference must be below 1% of the grid-64 spatial L1 error. Record L1/L2/L∞ orders, actual steps, momentum change normalized by initial sum(abs(u))*V, and initial cell Peclet numbers. Donor-cell’s spatial baseline is expected to be first order. Supply a generated checksummed checkpoint through the public restart contract and record its identity. Normal numerical/archive audits apply.
  3. A periodic transverse velocity step v(x) in uniform u=1, w=0, grid 64x2x2, ν=1e-8, advective_cfl_max=0.45, runs exactly 1000 steps. Its intentional iteration-limit termination is recorded, not called transient acceptance. Report extrema, growth and actual timestep/CFL.
  4. Extend the external cavity recipe with an explicit bounded grid selector, retaining the existing level interface. --grids 16 24 32 48 means the same list for both backends, without the native-only 12 diagnostic. One warmup and three alternating timed pairs per grid, one solver thread, native multigrid, 600 s/20000 steps; reference 180 s/3000 iterations. Keep the 0.06 screen and the separate 0.01 objective. Keep every failed row; no extrapolated crossing. All recipe files other than mesh size and matching sample stations retain the current method and controls.
  5. Separately attempt native 96² at 1800 s/80000 steps, same steady equations and acceptance tolerances. This extra budget is for self-convergence, never a timed cost-at-target sample. Compare accepted centerline profiles on fixed 257 physical stations; report errors relative to the 96² profile and descriptive slopes. A finite reference is not an exact solution/GCI. If this run is incomplete, retain it and mark self-convergence unavailable.
  6. Compare default runs with an unmodified-main binary: steady cavity24, transient Poiseuille and a masked canyon limited to three steps. Require identical fields.json, checkpoint.json, probes.csv, geometry.json, case.json, steps and pressure work. Timers/build identities are not fields.

Checks and hosted reproduction

Rust fmt, all-target clippy with warnings denied, release locked workspace tests; all Python suites in normal and optimized modes; repository-wide Ruff. Fixtures run in ordinary numerical CI; external=momentum runs the full paired grid sweep and self-convergence campaign on a hosted runner. New evidence errors use CFD-B007 momentum.<field>; invalid sweep selectors keep CFD-B004 and external recipe selectors keep CFD-X001.

Campaign addendum, before the repeat: one full 32-row local sweep had accepted timed rows on every grid, but its OpenFOAM-48 warmup failed the existing archive.progress check (a 1250 snapshot was in the sealed file inventory but absent from the recorded directory list). Retain that entire campaign and its failure. Repeat the complete identical protocol once, using the fixed binary and frozen producer files, after builds finish. Do not repair the old archive, relax its verifier, substitute a timed row for the warmup, or select the faster campaign. Report the full repeat as the final baseline if its audits pass.

Reference addendum, before continuation: the cold 96² solver returned converged fields at 21390 steps, but failed while writing executable identity after the running executable had been replaced during a build. Retain the unsealed run and its exit-1 failure. Initialize a new run from its unchanged checksummed native checkpoint through the public restart contract, using the fixed binary. Require fresh numerical acceptance and independent archive/field checks, and compare its fields/checkpoint bytes with the predecessor. Record the exact initial-state provenance and both runs’ work/timers; the continuation’s timer is not the cold solve’s timer or a cost-at-target sample. Do not repair or manually seal the original output directory.

Stage V changes measurement capability, not solver performance. (P3a and the later stages are done since; see the plan status.) P3a is next: opt-in conservative second-order advection; then P4 implicit diffusion, P5a implicit steady coupling, conditional P5b local steps, P3b/P5c open/RANS, P5d scalar transport, with matched-accuracy measurements after each stage.

Final collection addendum: the complete repeat’s initial passes did not survive later re-auditing; three OpenFOAM records subsequently failed. A new collection check and regression tests now invalidate rows after a late manifest/archive change. A sequential reproduction also encountered the already documented cloud anomaly (see 06-archive-investigation.md), so it remains failed. Before the final attempt, declare the identical numerical/timing protocol under a fresh temporary directory; pack and round-trip-check the evidence archive there before copying only the archive. Record filesystem events and scoped processes. This containment is not a diagnosis or a repair of any old archive.