Skip to main content

cfd_craft/
lib.rs

1#![forbid(unsafe_code)]
2#![warn(missing_docs)]
3//! The core library of [CFD-craft](https://github.com/dietmarwo/CFD-craft): a
4//! bounded, inspectable CPU research solver for incompressible flow on
5//! uniform Cartesian grids and conservative dispersion of passive gases and
6//! particle size classes, built to be driven and checked by programs and
7//! agents.
8//!
9//! A case is data: one strict JSON document ([`case::Case`]) declares the
10//! domain, grid, boundaries, flow model, solid boxes and polygon prisms,
11//! vegetation, constituents, sources, receptors, numerics and every budget. A run reports why it stopped, what
12//! its recomputed numerical checks support, the model scope, and the identity
13//! of its input, initial state and build.
14//!
15//! # Status
16//!
17//! Version 0.2.0 is a **research prototype**. The coarse finite-canyon
18//! examples converge under independent continuity and mass checks.
19//! Experimental canyon validation (blocked by access to raw benchmark data)
20//! and a successful fine-grid resolution study remain open; the first
21//! finer-grid study exceeded its compute budgets. These are
22//! physical-qualification gates: a numerically accepted run is not
23//! experimentally validated urban CFD, and every result says so in
24//! [`Summary::experimental_validation`](solver::Summary::experimental_validation).
25//!
26//! The 0.2.0 scope is uniform grids, buildings as boxes and polygon prisms,
27//! passive gases, particle size classes with settling and deposition, porous
28//! vegetation, and CPU execution. These features are numerically verified and
29//! not experimentally validated. LES, chemistry, annual statistics, stretched
30//! grids and GPU execution are not implemented.
31//! See the [roadmap](https://github.com/dietmarwo/CFD-craft/blob/main/docs/developer/roadmap.md),
32//! the [recorded results](https://github.com/dietmarwo/CFD-craft/blob/main/docs/evidence/native-verification.md)
33//! and the [model cards](https://github.com/dietmarwo/CFD-craft/blob/main/docs/model-cards/README.md).
34//!
35//! # What is implemented
36//!
37//! - Staggered finite volumes with face velocities, masks of boxes and
38//!   polygon prisms rasterized by cell centers, and fluid-component discovery
39//!   ([`grid`], [`geometry`]).
40//! - Matrix-free pressure projection with one gauge per closed fluid
41//!   component, IC(0)-preconditioned PCG by default and opt-in symmetric
42//!   multigrid, also on grids with buildings ([`pressure`], [`multigrid`]).
43//! - Laminar flow, moving walls and one neutral k-epsilon package with
44//!   rough-wall functions ([`flow`]); donor-cell or opt-in conservative
45//!   second-order momentum advection; SSPRK2 pseudo-time or opt-in implicit
46//!   steady algorithms ([`momentum_solve`], [`turbulence_solve`]).
47//! - Passive gases and particle size classes (Stokes settling with Cunningham
48//!   correction, ground, roof and leaf deposition) with point, line and volume
49//!   sources and point, volume-average or path receptors, by first-order
50//!   upwind or bounded MUSCL transport ([`transport`]).
51//! - Porous vegetation with leaf drag and canopy turbulence terms
52//!   ([`vegetation`]).
53//! - Source responses on one accepted, frozen flow: one transport run per
54//!   source group without a flow update ([`mobile_response`]).
55//! - Explicit step, time, memory and output budgets, cooperative
56//!   cancellation, transactional steps, checksummed restarts and run archives
57//!   ([`solver`], [`output`]), and opt-in phase profiling ([`profiling`]).
58//!
59//! # Entry points
60//!
61//! | Task | API |
62//! |---|---|
63//! | Parse a case strictly, with JSON paths in errors | [`input::parse_case`] |
64//! | Check a case (coded diagnostics, estimates) | [`Case::check`](case::Case::check), [`Case::validate`](case::Case::validate), [`input::full_check`] |
65//! | Run a case within limits | [`solver::run`] with a [`Control`](solver::Control) |
66//! | Read the outcome | [`RunResult`](solver::RunResult): [`Summary`](solver::Summary), [`State`](solver::State) |
67//! | Save and resume | [`output::checkpoint_bytes`], [`output::read_checkpoint`] |
68//! | Publish or verify a run archive | [`output::create_run_dir`], [`output::write_run`], [`output::read_verified`] |
69//! | Measure solver phases | [`Control::with_profiling`](solver::Control::with_profiling), [`profiling::Profile`] |
70//!
71//! For ordinary applications prefer these to the low-level modules. Grid,
72//! face and state vectors can be used directly, but they carry invariants
73//! (layout, gauges, fixed boundary faces) that the module docs state.
74//!
75//! # Quickstart
76//!
77//! A point source in a uniform 1 m/s flow, solved to a steady state on a
78//! 32-cell grid:
79//!
80//! ```
81//! use cfd_craft::{input, solver::{self, Control}};
82//!
83//! let json = r#"{
84//!   "schema_version": "cfd-craft.case/0.1", "name": "quickstart",
85//!   "domain": {"size_m": [4.0, 1.0, 1.0]}, "grid": {"cells": [8, 2, 2]},
86//!   "boundaries": {"x": "open", "y": "periodic", "z": "periodic"},
87//!   "flow": {"kind": "prescribed_uniform", "velocity_m_s": [1.0, 0.0, 0.0]},
88//!   "constituents": [{"id": "tracer", "diffusivity_m2_s": 0.01}],
89//!   "sources": [{"kind": "point", "id": "S0", "constituent": "tracer",
90//!                "point_m": [0.5, 0.5, 0.5], "rate_kg_s": 1e-6}],
91//!   "receptors": [{"kind": "point", "id": "R1", "point_m": [3.0, 0.5, 0.5]}],
92//!   "numerics": {"transport": "linear_upwind", "max_time_step_s": 1.0,
93//!     "advective_cfl_max": 0.4, "pressure_relative_tolerance": 1e-10,
94//!     "pressure_max_iterations": 100, "steady_residual_tolerance": 1e-5,
95//!     "steady_monitor_tolerance": 1e-3, "monitor_window": 10},
96//!   "run": {"mode": "steady", "end_time_s": 1.0, "max_steps": 2000,
97//!     "wall_time_limit_s": 30.0, "threads": 1, "memory_limit_mib": 64},
98//!   "output": {"fields": false, "checkpoint": false, "max_total_mib": 4}
99//! }"#;
100//!
101//! // Strict parsing: an unknown field fails as CFD-E000 with its JSON path.
102//! let case = input::parse_case(json.as_bytes())
103//!     .map_err(|report| serde_json::to_string(&report).unwrap())?;
104//! // Semantic checks: ranges, units, budgets and geometry.
105//! case.validate()?;
106//!
107//! let control = Control::new(case.run.wall_time_limit_s);
108//! let result = solver::run(&case, &control, None)?;
109//! let summary = &result.summary;
110//! // Ok(..) can still be cancelled or incomplete: read both verdicts.
111//! assert_eq!(summary.termination, "completed");
112//! assert_eq!(summary.assessment, "steady_discrete_solution");
113//! assert!(summary.checks.iter().all(|check| check.passed));
114//!
115//! // Look receptors up by ID. Downstream, the plume has mixed over the
116//! // 1 m2 cross-section, so the concentration approaches rate / (U A).
117//! let tracer = summary.constituents.iter().find(|c| c.id == "tracer").unwrap();
118//! let r1 = tracer.receptors_kg_m3["R1"];
119//! assert!((r1 - 1e-6).abs() < 1e-8);
120//! println!("R1 = {:.3} micrograms/m3 after {} steps", r1 * 1e9, summary.steps);
121//! # Ok::<(), String>(())
122//! ```
123//!
124//! The library does not create a Rayon thread pool from `run.threads`; run
125//! [`solver::run`] inside `pool.install` when thread accounting matters. The
126//! CLI and the Python binding do this, and also own signal handling, host
127//! memory preflight and archive provenance.
128//!
129//! # Conventions
130//!
131//! - SI units, named in the field suffixes (`_m`, `_m_s`, `_kg_s`, `_kg_m3`).
132//!   Concentrations are kg/m3; multiply by 1e9 for micrograms/m3. Pressure is
133//!   kinematic, m2/s2.
134//! - Coordinates are local east (x), north (y) and up (z). Wind directions
135//!   are meteorological: where the wind blows from, clockwise from north.
136//! - Cells are ordered x fastest, index `(k * ny + j) * nx + i`; face arrays
137//!   are concatenated by axis (see [`grid::Grid`]).
138//! - Errors are [`Result`] with a `String` message that starts with a stable
139//!   code such as `CFD-E033`, listed in the
140//!   [diagnostics catalog](https://github.com/dietmarwo/CFD-craft/blob/main/docs/diagnostics.md).
141//!   Match the code, not the English text.
142//!
143//! # Related crates and documents
144//!
145//! - [`cfd-craft-cli`](https://crates.io/crates/cfd-craft-cli): the
146//!   `cfd-craft` command (`describe`, `check`, `run`, `profile`, `preview`,
147//!   `report`, `verify`) with checksummed archives, restarts and signals.
148//! - [`cfd-craft` on PyPI](https://pypi.org/project/cfd-craft/): the Python
149//!   binding (`check`, `simulate`, `describe`), see the
150//!   [Python chapter](https://dietmarwo.github.io/CFD-craft/guide/11-python.html).
151//! - The [guide](https://dietmarwo.github.io/CFD-craft/guide/) explains the
152//!   numerical and evidence concepts in worked chapters, ordered by
153//!   difficulty; its [Rust library chapter](https://dietmarwo.github.io/CFD-craft/guide/20-rust-library.html)
154//!   covers this crate.
155//! - The [result contract](https://github.com/dietmarwo/CFD-craft/blob/main/docs/result-contract.md)
156//!   defines termination, assessment, archives and identities; the
157//!   [flow](https://github.com/dietmarwo/CFD-craft/blob/main/docs/model-cards/flow.md)
158//!   and [transport](https://github.com/dietmarwo/CFD-craft/blob/main/docs/model-cards/transport.md)
159//!   model cards state the numerical methods and their limits.
160//! - [Runnable library examples](https://github.com/dietmarwo/CFD-craft/tree/main/crates/cfd-craft/examples)
161//!   and the [repository](https://github.com/dietmarwo/CFD-craft) with its
162//!   verification cases, independent checkers and recorded evidence.
163pub mod case;
164pub mod flow;
165/// Polygon-prism geometry and grid-resolution evidence.
166pub mod geometry;
167pub mod grid;
168/// Fixed-flow scalar responses for mobile-receptor inference studies.
169pub mod mobile_response;
170pub mod momentum_solve;
171pub mod multigrid;
172pub mod output;
173pub mod pressure;
174pub mod profiling;
175pub mod solver;
176pub mod transport;
177pub mod turbulence_solve;
178/// Opt-in porous vegetation drag, canopy turbulence and leaf deposition.
179pub mod vegetation;
180pub mod verification;
181
182/// Result of the fallible library functions. The error is a message that
183/// normally starts with a stable code (`CFD-E…: …`). For an invalid case,
184/// [`case::Case::validate`] and the functions that call it, such as
185/// [`grid::Grid::build`] and [`solver::run`], return the serialized
186/// [`case::CheckReport`] instead.
187pub type Result<T> = std::result::Result<T, String>;
188
189pub mod input;
190/// Fingerprint of the core package sources and its build lockfile.
191///
192/// Lowercase hex SHA-256 over this crate's `src` Rust files, build script
193/// and manifest, plus the root workspace manifest and lockfile in a checkout,
194/// or the packaged lockfile in a crates.io build, so the two differ. A bare
195/// library run reports it as `source_sha256`; the CLI and the Python binding
196/// combine it with their own fingerprints.
197pub const SOURCE_SHA256: &str = env!("CFD_SOURCE_SHA");
198/// Compiler used to build the core: the `rustc --version` line, part of the
199/// summary's `build_version`.
200pub const RUSTC_VERSION: &str = env!("CFD_RUSTC");