cfd_craft/case.rs
1//! The case contract `cfd-craft.case/0.1`: the typed JSON input of a native
2//! run, its semantic checks and its identities.
3//!
4//! A [`Case`] describes one calculation completely: domain and grid, boundary
5//! conditions, the flow model, solid boxes, passive constituents with their
6//! sources, initial conditions and receptors, numerics, run budgets and the
7//! output policy. Nothing outside the case configures the solver.
8//!
9//! Checking happens in three layers:
10//!
11//! 1. Deserialization is strict: unknown fields and variants are rejected.
12//! [`input::parse_case`](crate::input::parse_case) reports a failure as
13//! `CFD-E000` with the JSON path of the offending element.
14//! 2. [`Case::check`] applies the semantic checks (units, ranges, budgets,
15//! geometry, physical combinations) and returns a [`CheckReport`] of coded
16//! [`Diagnostic`]s; [`Case::validate`] turns an invalid report into an
17//! error.
18//! 3. Checks that need the built grid (box representation, source and
19//! receptor support) run in [`Grid::build`](crate::grid::Grid::build),
20//! [`transport::source_fields`](crate::transport::source_fields) and
21//! [`input::full_check`](crate::input::full_check).
22//!
23//! Every code is listed in the
24//! [diagnostics catalog](https://github.com/dietmarwo/CFD-craft/blob/main/docs/diagnostics.md).
25//!
26//! Units follow the field names: `_m` meters, `_m_s` m/s, `_m2_s` m2/s,
27//! `_kg_s` kg/s, `_kg_m3` kg/m3, `_s` seconds, `_mib` MiB. Coordinates are
28//! local east (x), north (y) and up (z) from the lower domain corner.
29//!
30//! These types derive `JsonSchema`, and `cfd-craft describe` prints the
31//! generated `case_schema`; the schemas there are authoritative for JSON
32//! clients. [`Case::physics_hash`] identifies the physical and numerical
33//! problem for restarts, and [`hash_bytes`] is the digest used for every
34//! identity.
35//!
36//! # Example
37//!
38//! ```
39//! use cfd_craft::case::Case;
40//!
41//! let json = r#"{
42//! "schema_version": "cfd-craft.case/0.1", "name": "tiny",
43//! "domain": {"size_m": [4.0, 1.0, 1.0]}, "grid": {"cells": [8, 2, 2]},
44//! "boundaries": {"x": "open", "y": "periodic", "z": "periodic"},
45//! "flow": {"kind": "prescribed_uniform", "velocity_m_s": [1.0, 0.0, 0.0]},
46//! "constituents": [{"id": "tracer", "diffusivity_m2_s": 0.01}],
47//! "sources": [{"kind": "point", "id": "S0", "constituent": "tracer",
48//! "point_m": [0.5, 0.5, 0.5], "rate_kg_s": 1e-6}],
49//! "receptors": [{"kind": "point", "id": "R1", "point_m": [3.0, 0.5, 0.5]}],
50//! "numerics": {"transport": "linear_upwind", "max_time_step_s": 1.0,
51//! "advective_cfl_max": 0.4, "pressure_relative_tolerance": 1e-10,
52//! "pressure_max_iterations": 100, "steady_residual_tolerance": 1e-5,
53//! "steady_monitor_tolerance": 1e-3, "monitor_window": 10},
54//! "run": {"mode": "steady", "end_time_s": 1.0, "max_steps": 1000,
55//! "wall_time_limit_s": 30.0, "threads": 1, "memory_limit_mib": 64},
56//! "output": {"fields": false, "checkpoint": false, "max_total_mib": 4}
57//! }"#;
58//! let case: Case = serde_json::from_str(json).unwrap();
59//! let report = case.validate().unwrap();
60//! assert!(report.valid);
61//! assert_eq!(report.cells, 32);
62//!
63//! // Unknown fields are a deserialization error, not a semantic warning.
64//! let typo = json.replace("\"point_m\": [0.5", "\"position_m\": [0.5");
65//! assert!(serde_json::from_str::<Case>(&typo).is_err());
66//! ```
67
68// Doc comments on these types become `description` entries of the generated
69// case schema. Two kinds of item carry rustdoc-only docs
70// (`#[cfg_attr(doc, doc = ...)]`) instead: unit variants of string enums, where
71// a `///` comment would turn the schema's `enum` into a `oneOf`, and fields
72// whose type is another schema type, where it would wrap the field's `$ref` in
73// an `allOf`. Both would change the schema's shape. The meaning of those items
74// is also stated in the documented container, which the schema keeps.
75use crate::Result;
76use schemars::JsonSchema;
77use serde::{Deserialize, Serialize};
78use sha2::{Digest, Sha256};
79use std::collections::BTreeSet;
80
81/// A complete native case, schema version `cfd-craft.case/0.1`. Nothing
82/// outside the case configures the solver. Unknown fields are rejected; the
83/// lists default to empty when omitted. Deserialization checks only the
84/// types: the semantic checks (ranges, units, budgets, geometry) are those of
85/// `cfd-craft check`, which reports coded diagnostics with field paths.
86#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
87#[serde(deny_unknown_fields)]
88pub struct Case {
89 /// Contract version; must be `cfd-craft.case/0.1` (CFD-E001).
90 pub schema_version: String,
91 /// Nonempty experiment label (CFD-E002), copied into the result. It is
92 /// excluded from the physics hash, so renaming keeps checkpoints
93 /// compatible.
94 pub name: String,
95 #[cfg_attr(doc, doc = "Physical extent of the domain; see [`Domain`].")]
96 #[allow(missing_docs)]
97 pub domain: Domain,
98 #[cfg_attr(doc, doc = "Uniform cell counts per axis; see [`GridSpec`].")]
99 #[allow(missing_docs)]
100 pub grid: GridSpec,
101 #[cfg_attr(doc, doc = "Boundary condition per axis; see [`Boundaries`].")]
102 #[allow(missing_docs)]
103 pub boundaries: Boundaries,
104 #[cfg_attr(doc, doc = "Flow model; see [`Flow`].")]
105 #[allow(missing_docs)]
106 pub flow: Flow,
107 /// Axis-aligned solid boxes (buildings, obstacles). A cell is solid when
108 /// its center lies inside a box. Not allowed with `prescribed_uniform`
109 /// flow (CFD-E013). Optional footprint_m selects polygon prisms.
110 /// Masked multigrid is supported. Default: empty.
111 #[serde(default)]
112 pub geometry: Vec<Block>,
113 /// Optional aerodynamic roughness of building walls in meters, independent
114 /// of cell width. Omission reproduces the legacy wall recipe (CFD-E085).
115 #[serde(default, skip_serializing_if = "Option::is_none")]
116 pub building_roughness_m: Option<f64>,
117 /// Warn if a represented street between solids is narrower than this
118 /// number of horizontal cells. Omitted for legacy cases (CFD-W011).
119 #[serde(default, skip_serializing_if = "Option::is_none")]
120 pub geometry_min_passage_cells: Option<usize>,
121 /// Tangentially moving `wall` faces of the domain, such as a cavity lid;
122 /// laminar flow only (CFD-E021). Default: empty.
123 #[serde(default)]
124 pub moving_walls: Vec<MovingWall>,
125 /// Passive gases transported by the flow. Default: empty, which solves
126 /// the flow only.
127 #[serde(default)]
128 pub constituents: Vec<Constituent>,
129 /// Opt-in porous canopy boxes; zero leaf density has no numerical effect.
130 #[serde(default, skip_serializing_if = "Vec::is_empty")]
131 pub vegetation: Vec<Vegetation>,
132 /// Continuous emissions into the constituents. Default: empty.
133 #[serde(default)]
134 pub sources: Vec<Source>,
135 /// Initial concentration fields, at most one per constituent (CFD-E018);
136 /// a constituent without one starts at zero. Default: empty.
137 #[serde(default)]
138 pub initial_conditions: Vec<Initial>,
139 /// Named concentration samples, reported for every constituent in the
140 /// result's `receptors_kg_m3` and in probes.csv. Default: empty.
141 #[serde(default)]
142 pub receptors: Vec<Receptor>,
143 #[cfg_attr(
144 doc,
145 doc = "Discretization choices, tolerances and the steady monitor window; see [`Numerics`]."
146 )]
147 #[allow(missing_docs)]
148 pub numerics: Numerics,
149 #[cfg_attr(doc, doc = "Mode, endpoint and execution budgets; see [`Run`].")]
150 #[allow(missing_docs)]
151 pub run: Run,
152 #[cfg_attr(doc, doc = "Artifact retention and output budget; see [`Output`].")]
153 #[allow(missing_docs)]
154 pub output: Output,
155}
156/// Physical extent of the domain: a box from the origin to `size_m`.
157#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
158#[serde(deny_unknown_fields)]
159pub struct Domain {
160 /// Lengths along x (east), y (north) and z (up) in meters, each finite
161 /// and within 1e-6..1e9 (CFD-E003).
162 pub size_m: [f64; 3],
163}
164/// Uniform Cartesian grid: the cell size along an axis is the domain length
165/// divided by the cell count.
166#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
167#[serde(deny_unknown_fields)]
168pub struct GridSpec {
169 /// Cell counts along x, y and z: 2..4096 per axis, or 1..4096 on a
170 /// periodic axis, which makes a two-dimensional run (CFD-E004). The total
171 /// enters the memory estimate and may not exceed 1e8 cells (CFD-E006).
172 pub cells: [usize; 3],
173}
174/// Boundary condition of the pair of domain faces normal to one axis.
175/// `periodic` identifies the two faces. `open` lets flow in or out: each face
176/// is an inlet or an outlet by the sign of the case flow's normal velocity
177/// there; inlets prescribe that velocity and a zero concentration increment,
178/// outlets fix the pressure level, and faces without normal flow are slip
179/// faces. `wall` is impermeable and no-slip (a rough wall with
180/// `neutral_rans`). `slip` is impermeable and stress-free. `ground_open_top`
181/// (z only, CFD-E005) is a rough ground with a top that applies the
182/// boundary-layer shear stress; `neutral_rans` requires it (CFD-E011) and
183/// laminar flow may not use it (CFD-E023).
184#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
185#[serde(rename_all = "snake_case")]
186pub enum Boundary {
187 #[cfg_attr(
188 doc,
189 doc = "The two faces are identified, so flow and constituents leaving one enter the other. A periodic axis may have one cell."
190 )]
191 #[allow(missing_docs)]
192 Periodic,
193 #[cfg_attr(
194 doc,
195 doc = "Inflow or outflow, decided per face by the normal component of [`Flow::vector`] at the face center: inlets prescribe that velocity and a zero concentration increment, outlets fix the pressure level and anchor their fluid component, and faces without normal flow act as slip faces."
196 )]
197 #[allow(missing_docs)]
198 Open,
199 #[cfg_attr(
200 doc,
201 doc = "Impermeable no-slip wall, optionally moving tangentially ([`MovingWall`]); with `neutral_rans` a rough wall with the wall functions of the flow model card."
202 )]
203 #[allow(missing_docs)]
204 Wall,
205 #[cfg_attr(
206 doc,
207 doc = "Impermeable and stress-free: zero normal velocity and zero tangential gradient."
208 )]
209 #[allow(missing_docs)]
210 Slip,
211 #[cfg_attr(
212 doc,
213 doc = "z only: a rough ground at z = 0 with roughness `roughness_m`, and an impermeable top that applies the equilibrium shear stress of the `neutral_rans` inflow. Required by `neutral_rans`, rejected for laminar flow, where the top would act as a no-slip lid."
214 )]
215 #[allow(missing_docs)]
216 GroundOpenTop,
217}
218/// Boundary conditions of the domain: `x`, `y` and `z` each set the condition
219/// of the two domain faces normal to that axis (west and east, south and
220/// north, ground and top).
221#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
222#[serde(deny_unknown_fields)]
223pub struct Boundaries {
224 #[cfg_attr(doc, doc = "Condition at x = 0 and x = Lx (west and east).")]
225 #[allow(missing_docs)]
226 pub x: Boundary,
227 #[cfg_attr(doc, doc = "Condition at y = 0 and y = Ly (south and north).")]
228 #[allow(missing_docs)]
229 pub y: Boundary,
230 #[cfg_attr(doc, doc = "Condition at z = 0 and z = Lz (ground and top).")]
231 #[allow(missing_docs)]
232 pub z: Boundary,
233}
234impl Boundaries {
235 /// The condition of axis `a` (0 = x, 1 = y, 2 = z).
236 ///
237 /// # Panics
238 ///
239 /// If `a > 2`.
240 pub fn at(&self, a: usize) -> Boundary {
241 [self.x, self.y, self.z][a]
242 }
243}
244/// Flow model, selected by `kind`: `prescribed_uniform` (a fixed uniform
245/// velocity; only the constituents are solved), `laminar` (incompressible
246/// flow with constant viscosity) or `neutral_rans` (a neutral atmospheric
247/// boundary layer with the k-epsilon model). The numeric fields are checked
248/// as CFD-E012.
249#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
250#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
251pub enum Flow {
252 /// A fixed uniform velocity with no flow solve. Its normal component must
253 /// be zero at impermeable boundaries (CFD-E024), and solid boxes are not
254 /// allowed (CFD-E013).
255 PrescribedUniform {
256 /// Velocity [u, v, w] in m/s, finite.
257 velocity_m_s: [f64; 3],
258 },
259 /// Incompressible laminar flow with constant kinematic viscosity, started
260 /// from a uniform velocity.
261 Laminar {
262 /// Uniform initial velocity [u, v, w] in m/s, finite. It also sets
263 /// the velocity of `open` inlet faces and decides which open faces are
264 /// inlets or outlets.
265 initial_velocity_m_s: [f64; 3],
266 /// Kinematic viscosity in m2/s, finite and positive.
267 viscosity_m2_s: f64,
268 /// Uniform body acceleration [x, y, z] in m/s2, for example the
269 /// pressure-gradient drive of a periodic channel. Default: zero.
270 #[serde(default)]
271 acceleration_m_s2: [f64; 3],
272 },
273 /// Neutral atmospheric boundary layer with the k-epsilon model (C_mu 0.09,
274 /// C_epsilon1 1.44, C_epsilon2 1.92, kappa 0.4). Inflow and initial fields
275 /// are the logarithmic equilibrium profiles U = u*/kappa ln((z + z0)/z0),
276 /// k = u*^2/sqrt(C_mu) and epsilon = u*^3/(kappa (z + z0)), with u* set by
277 /// `speed_m_s` at `reference_height_m`. Requires `boundaries.z =
278 /// ground_open_top` (CFD-E011).
279 NeutralRans {
280 /// Mean wind speed at `reference_height_m` in m/s, finite and
281 /// positive. It is also the velocity scale of the normalized checks.
282 speed_m_s: f64,
283 /// Height of `speed_m_s` above the ground in meters, positive and not
284 /// above the domain top. It is also the length scale of the
285 /// normalized checks.
286 reference_height_m: f64,
287 /// Aerodynamic roughness length z0 of the ground in meters, positive.
288 /// Building and other wall faces use min(z0, 0.001 cell width), which
289 /// ties that wall roughness to the grid (see the flow model card).
290 roughness_m: f64,
291 /// Meteorological wind direction in degrees: where the wind blows
292 /// from, clockwise from north. 270 blows toward +x (east), 180 toward
293 /// +y (north). Finite; any value is accepted.
294 direction_deg_from: f64,
295 /// Molecular kinematic viscosity in m2/s, positive; the eddy viscosity
296 /// C_mu k^2/epsilon is added to it.
297 viscosity_m2_s: f64,
298 /// Turbulent Schmidt number Sc_t, positive: constituents diffuse with
299 /// their molecular diffusivity plus nu_t / Sc_t.
300 turbulent_schmidt: f64,
301 },
302}
303impl Flow {
304 /// True for `prescribed_uniform`, whose velocity stays fixed: no
305 /// momentum or pressure equations are solved.
306 pub fn prescribed(&self) -> bool {
307 matches!(self, Self::PrescribedUniform { .. })
308 }
309 /// True for `neutral_rans`, which adds the k and epsilon fields.
310 pub fn rans(&self) -> bool {
311 matches!(self, Self::NeutralRans { .. })
312 }
313 /// Molecular kinematic viscosity in m2/s; zero for prescribed flow.
314 pub fn viscosity(&self) -> f64 {
315 match self {
316 Self::PrescribedUniform { .. } => 0.0,
317 Self::Laminar { viscosity_m2_s, .. } | Self::NeutralRans { viscosity_m2_s, .. } => {
318 *viscosity_m2_s
319 }
320 }
321 }
322 /// The case's reference velocity at height `z` (meters), in m/s: the
323 /// prescribed velocity, the laminar initial velocity, or the logarithmic
324 /// `neutral_rans` profile in the wind direction (negative heights are
325 /// evaluated at the ground).
326 ///
327 /// It initializes the face velocities, sets the velocity of `open` inlet
328 /// faces and decides whether an open face is an inlet, an outlet or a
329 /// slip face.
330 ///
331 /// ```
332 /// use cfd_craft::case::Flow;
333 ///
334 /// let flow: Flow = serde_json::from_str(
335 /// r#"{"kind": "neutral_rans", "speed_m_s": 3.0, "reference_height_m": 10.0,
336 /// "roughness_m": 0.1, "direction_deg_from": 270.0,
337 /// "viscosity_m2_s": 1.5e-5, "turbulent_schmidt": 0.7}"#,
338 /// )
339 /// .unwrap();
340 /// let [u, v, w] = flow.vector(10.0);
341 /// // A wind from the west blows toward +x, at the declared reference speed.
342 /// assert!((u - 3.0).abs() < 1e-12 && v.abs() < 1e-12 && w == 0.0);
343 /// assert!(flow.vector(1.0)[0] < u);
344 /// ```
345 pub fn vector(&self, z: f64) -> [f64; 3] {
346 match self {
347 Self::PrescribedUniform { velocity_m_s } => *velocity_m_s,
348 Self::Laminar {
349 initial_velocity_m_s,
350 ..
351 } => *initial_velocity_m_s,
352 Self::NeutralRans {
353 speed_m_s,
354 reference_height_m,
355 roughness_m,
356 direction_deg_from,
357 ..
358 } => {
359 let u = speed_m_s * ((z.max(0.0) + roughness_m) / roughness_m).ln()
360 / ((reference_height_m + roughness_m) / roughness_m).ln();
361 let t = direction_deg_from.to_radians();
362 [-u * t.sin(), -u * t.cos(), 0.0]
363 }
364 }
365 }
366 /// Velocity scale of the normalized checks and divergence limits, in m/s:
367 /// `speed_m_s` for `neutral_rans`, otherwise the magnitude of
368 /// [`vector`](Self::vector) at z = 1 m, but at least 1 m/s.
369 pub fn reference_speed(&self) -> f64 {
370 match self {
371 Self::NeutralRans { speed_m_s, .. } => *speed_m_s,
372 _ => self
373 .vector(1.0)
374 .iter()
375 .map(|v| v * v)
376 .sum::<f64>()
377 .sqrt()
378 .max(1.0),
379 }
380 }
381 /// Friction velocity of the `neutral_rans` inflow profile in m/s,
382 /// u* = kappa speed / ln((z_ref + z0)/z0) with kappa = 0.4; zero for the
383 /// other flow models.
384 pub fn ustar(&self) -> f64 {
385 match self {
386 Self::NeutralRans {
387 speed_m_s,
388 reference_height_m,
389 roughness_m,
390 ..
391 } => 0.4 * speed_m_s / ((reference_height_m + roughness_m) / roughness_m).ln(),
392 _ => 0.0,
393 }
394 }
395 /// Equilibrium `(k, epsilon)` of the `neutral_rans` inflow at height `z`
396 /// (meters): k = u*^2/sqrt(C_mu) in m2/s2 and epsilon = u*^3/(kappa (z +
397 /// z0)) in m2/s3. `(0, 0)` for the other flow models. These values
398 /// initialize the fields and set the inlet and top values.
399 pub fn turbulence(&self, z: f64) -> (f64, f64) {
400 if let Self::NeutralRans { roughness_m, .. } = self {
401 let u = self.ustar();
402 (u * u / 0.3, u.powi(3) / (0.4 * (z + roughness_m)))
403 } else {
404 (0.0, 0.0)
405 }
406 }
407}
408/// An axis-aligned solid box. Cells whose centers lie inside it (lower bound
409/// inclusive, upper bound exclusive) are solid; boxes may overlap. The bounds
410/// must increase on every axis and lie inside the domain (CFD-E014), and the
411/// box must contain at least one cell center (CFD-E028). Fewer than ten cells
412/// across its height draws warning CFD-W001.
413#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
414#[serde(deny_unknown_fields)]
415pub struct Block {
416 /// Unique nonempty ID (CFD-E014); the key of the box's cell count in
417 /// geometry.json.
418 pub id: String,
419 /// Lower corner [x, y, z] in meters.
420 pub min_m: [f64; 3],
421 /// Upper corner [x, y, z] in meters.
422 pub max_m: [f64; 3],
423 /// Optional simple footprint polygon in local x/y meters. With this field
424 /// the shape is a prism between `min_m[2]` and `max_m[2]`; the other bounds
425 /// must equal the footprint bounds. Holes and self-intersections are
426 /// rejected (CFD-E084). Omission selects the original box.
427 #[serde(default, skip_serializing_if = "Option::is_none")]
428 pub footprint_m: Option<Vec<[f64; 2]>>,
429}
430#[cfg(test)]
431thread_local! {
432 /// Calls of [`Block::contains`] on this thread, for tests that bound the
433 /// work of building masks.
434 pub(crate) static CONTAINS_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
435}
436impl Block {
437 /// Cell-center containment, with lower bounds inclusive and upper exclusive.
438 pub fn contains(&self, p: [f64; 3]) -> bool {
439 #[cfg(test)]
440 CONTAINS_CALLS.with(|c| c.set(c.get() + 1));
441 (0..3).all(|a| p[a] >= self.min_m[a] && p[a] < self.max_m[a])
442 && self
443 .footprint_m
444 .as_ref()
445 .is_none_or(|v| crate::geometry::contains(v, [p[0], p[1]]))
446 }
447 /// Exact geometric volume of this box or polygon prism in m3.
448 pub fn volume(&self) -> f64 {
449 let area = self.footprint_m.as_ref().map_or(
450 (self.max_m[0] - self.min_m[0]) * (self.max_m[1] - self.min_m[1]),
451 |p| crate::geometry::area(p),
452 );
453 area * (self.max_m[2] - self.min_m[2])
454 }
455}
456/// A tangential velocity of one `wall` face of the domain, such as a cavity
457/// lid. Laminar flow only, at most one per face, and the velocity component
458/// normal to the wall must be zero (CFD-E021).
459#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
460#[serde(deny_unknown_fields)]
461pub struct MovingWall {
462 /// Axis normal to the wall: 0 (x), 1 (y) or 2 (z). That axis must have
463 /// `wall` boundaries.
464 pub axis: usize,
465 /// True for the face at the upper end of the axis (for example z = Lz),
466 /// false for the face at 0.
467 pub upper: bool,
468 /// Wall velocity [u, v, w] in m/s, finite; the component along `axis`
469 /// must be zero.
470 pub velocity_m_s: [f64; 3],
471}
472/// A passive gas: transported and diffused by the flow without affecting it.
473/// Concentrations are in kg/m3.
474#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
475#[serde(deny_unknown_fields)]
476pub struct Constituent {
477 /// Unique nonempty ID (CFD-E015), referenced by sources and initial
478 /// conditions and used in the result.
479 pub id: String,
480 /// Molecular diffusivity in m2/s, finite and nonnegative (CFD-E015).
481 /// With `neutral_rans` the turbulent diffusivity nu_t/Sc_t is added.
482 pub diffusivity_m2_s: f64,
483 /// Optional spherical aerosol bin. Omitted for gases, preserving old hashes.
484 #[serde(default, skip_serializing_if = "Option::is_none")]
485 pub particle: Option<ParticleBin>,
486}
487/// Dilute spherical particle bin, with no feedback, chemistry or resuspension.
488/// The declared deposition velocities exclude gravitational settling, which is
489/// added separately on upward-facing ground and roofs.
490#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
491#[serde(deny_unknown_fields)]
492pub struct ParticleBin {
493 /// Geometric diameter in meters (1e-8..1e-4).
494 pub diameter_m: f64,
495 /// Particle material density in kg/m3, above the reference air density.
496 pub density_kg_m3: f64,
497 /// Direct nonnegative settling speed, bypassing the Stokes validity gate.
498 #[serde(default, skip_serializing_if = "Option::is_none")]
499 pub settling_velocity_m_s: Option<f64>,
500 /// Additional ground deposition speed, in m/s, excluding settling.
501 #[serde(default)]
502 pub ground_deposition_velocity_m_s: f64,
503 /// Additional roof deposition speed, in m/s, excluding settling.
504 #[serde(default)]
505 pub roof_deposition_velocity_m_s: f64,
506}
507impl ParticleBin {
508 /// Cunningham-corrected spherical terminal speed at the declared reference
509 /// atmosphere (293.15 K, 101325 Pa): rho_air=1.204 kg/m3,
510 /// mu=1.81e-5 Pa s, lambda=6.6e-8 m, g=9.80665 m/s2.
511 pub fn settling_speed(&self) -> f64 {
512 self.settling_velocity_m_s.unwrap_or_else(|| {
513 (self.density_kg_m3 - 1.204)
514 * 9.80665
515 * self.diameter_m.powi(2)
516 * Self::slip(self.diameter_m)
517 / (18.0 * 1.81e-5)
518 })
519 }
520 /// Particle Reynolds number under the reference atmosphere.
521 pub fn reynolds_number(&self) -> f64 {
522 1.204 * self.settling_speed() * self.diameter_m / 1.81e-5
523 }
524 /// Equivalent unit-density spherical aerodynamic diameter, including slip.
525 /// PM sums use this diameter, not the geometric diameter.
526 pub fn aerodynamic_diameter_m(&self) -> f64 {
527 if self.density_kg_m3 == 1000.0 {
528 return self.diameter_m;
529 }
530 let target = (self.density_kg_m3 - 1.204) / (1000.0 - 1.204)
531 * self.diameter_m.powi(2)
532 * Self::slip(self.diameter_m);
533 let (mut lo, mut hi) = (0.0, self.diameter_m * self.density_kg_m3.sqrt().max(1.0));
534 for _ in 0..80 {
535 let mid = 0.5 * (lo + hi);
536 if mid * mid * Self::slip(mid) < target {
537 lo = mid;
538 } else {
539 hi = mid;
540 }
541 }
542 0.5 * (lo + hi)
543 }
544 fn slip(d: f64) -> f64 {
545 let kn = 2.0 * 6.6e-8 / d;
546 1.0 + kn * (1.257 + 0.4 * (-1.1 / kn).exp())
547 }
548}
549/// Published canopy source-coefficient set; the ambient k-epsilon constants
550/// are unchanged. Both alternatives are unvalidated in this urban solver.
551#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, JsonSchema)]
552#[serde(rename_all = "snake_case")]
553pub enum CanopyClosure {
554 /// Green (1992): beta_p=1, beta_d=4, C_e4=C_e5=1.5.
555 #[default]
556 Green1992,
557 /// Sanz/Katul: beta_p=1, beta_d=5.1, C_e4=C_e5=0.9.
558 Sanz2003,
559}
560impl CanopyClosure {
561 /// (beta_p, beta_d, C_e4, C_e5), in the published source-term convention.
562 pub fn coefficients(self) -> [f64; 4] {
563 match self {
564 Self::Green1992 => [1.0, 4.0, 1.5, 1.5],
565 Self::Sanz2003 => [1.0, 5.1, 0.9, 0.9],
566 }
567 }
568}
569/// Flat-ground porous vegetation volume. Box membership uses cell centers,
570/// lower-inclusive and upper-exclusive, exactly as building masks.
571#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
572#[serde(deny_unknown_fields)]
573pub struct Vegetation {
574 /// Unique nonempty volume ID.
575 pub id: String,
576 /// Box lower corner in meters.
577 pub min_m: [f64; 3],
578 /// Box upper corner in meters.
579 pub max_m: [f64; 3],
580 /// Leaf area per air volume, in m2/m3 (inverse meters).
581 pub leaf_area_density_m2_m3: f64,
582 /// Dimensionless form-drag coefficient.
583 pub drag_coefficient: f64,
584 /// Particle collection velocity per leaf area, m/s; excludes settling.
585 #[serde(default)]
586 pub leaf_deposition_velocity_m_s: f64,
587 /// Canopy k-epsilon source coefficient set.
588 #[serde(default)]
589 pub turbulence_closure: CanopyClosure,
590}
591/// A continuous emission into one constituent, selected by `kind`. Rates are
592/// finite and nonnegative (CFD-E016); the support is nondegenerate and inside
593/// the domain (CFD-E017). The integrated rate is distributed over the cells
594/// the support covers. Support touching a solid cell is rejected (CFD-E040),
595/// as is a steady source in a fluid region without an outlet (CFD-E043, and
596/// CFD-E020 when no boundary is open).
597#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
598#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
599pub enum Source {
600 /// A point emission, deposited in the cell that contains the point.
601 Point {
602 /// Unique nonempty source ID (CFD-E016).
603 id: String,
604 /// ID of the emitted constituent (CFD-E016).
605 constituent: String,
606 /// Position [x, y, z] in meters, inside the domain (each coordinate
607 /// at least 0 and below the domain length).
608 point_m: [f64; 3],
609 /// Emission rate in kg/s.
610 rate_kg_s: f64,
611 },
612 /// A straight line emission. The integrated rate is `rate_kg_s_m` times
613 /// the line length, distributed over the cells the segment crosses in
614 /// proportion to its length in each.
615 Line {
616 /// Unique nonempty source ID (CFD-E016).
617 id: String,
618 /// ID of the emitted constituent (CFD-E016).
619 constituent: String,
620 /// Start point [x, y, z] in meters, inside the domain.
621 from_m: [f64; 3],
622 /// End point [x, y, z] in meters, inside the domain and different
623 /// from `from_m`.
624 to_m: [f64; 3],
625 /// Emission rate per meter of line, kg/(s m).
626 rate_kg_s_m: f64,
627 },
628 /// A uniform emission over a box. The integrated rate is `rate_kg_s_m3`
629 /// times the box volume, distributed over the cells by their exact overlap
630 /// with the box.
631 Volume {
632 /// Unique nonempty source ID (CFD-E016).
633 id: String,
634 /// ID of the emitted constituent (CFD-E016).
635 constituent: String,
636 /// Lower corner [x, y, z] in meters.
637 min_m: [f64; 3],
638 /// Upper corner [x, y, z] in meters; every bound above `min_m` and
639 /// inside the domain.
640 max_m: [f64; 3],
641 /// Emission rate per cubic meter, kg/(s m3).
642 rate_kg_s_m3: f64,
643 },
644}
645impl Source {
646 /// The source ID.
647 pub fn id(&self) -> &str {
648 match self {
649 Self::Point { id, .. } | Self::Line { id, .. } | Self::Volume { id, .. } => id,
650 }
651 }
652 /// ID of the constituent the source emits.
653 pub fn constituent(&self) -> &str {
654 match self {
655 Self::Point { constituent, .. }
656 | Self::Line { constituent, .. }
657 | Self::Volume { constituent, .. } => constituent,
658 }
659 }
660 /// The rate field as declared, with its name (per second, per meter or per cubic meter).
661 pub fn declared_rate(&self) -> (&'static str, f64) {
662 match self {
663 Self::Point { rate_kg_s, .. } => ("rate_kg_s", *rate_kg_s),
664 Self::Line { rate_kg_s_m, .. } => ("rate_kg_s_m", *rate_kg_s_m),
665 Self::Volume { rate_kg_s_m3, .. } => ("rate_kg_s_m3", *rate_kg_s_m3),
666 }
667 }
668 /// Integrated emission rate in kg/s: `rate_kg_s`, `rate_kg_s_m` times the
669 /// line length, or `rate_kg_s_m3` times the box volume. The represented
670 /// source fields emit exactly this rate.
671 ///
672 /// ```
673 /// use cfd_craft::case::Source;
674 ///
675 /// let line: Source = serde_json::from_str(
676 /// r#"{"kind": "line", "id": "road", "constituent": "tracer",
677 /// "from_m": [1.0, 1.0, 2.0], "to_m": [1.0, 6.0, 2.0], "rate_kg_s_m": 2e-8}"#,
678 /// )
679 /// .unwrap();
680 /// // 2e-8 kg/s per meter over 5 m.
681 /// assert!((line.rate() - 1e-7).abs() < 1e-20);
682 /// assert_eq!(line.declared_rate(), ("rate_kg_s_m", 2e-8));
683 /// ```
684 pub fn rate(&self) -> f64 {
685 match self {
686 Self::Point { rate_kg_s, .. } => *rate_kg_s,
687 Self::Line {
688 rate_kg_s_m,
689 from_m,
690 to_m,
691 ..
692 } => {
693 rate_kg_s_m
694 * (0..3)
695 .map(|a| (to_m[a] - from_m[a]).powi(2))
696 .sum::<f64>()
697 .sqrt()
698 }
699 Self::Volume {
700 rate_kg_s_m3,
701 min_m,
702 max_m,
703 ..
704 } => rate_kg_s_m3 * (0..3).map(|a| max_m[a] - min_m[a]).product::<f64>(),
705 }
706 }
707}
708/// Initial concentration of one constituent, selected by `kind`. Each
709/// constituent has at most one (CFD-E018); without one it starts at zero.
710/// Solid cells always hold zero.
711#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
712#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
713pub enum Initial {
714 /// The same concentration in every fluid cell.
715 Uniform {
716 /// ID of the initialized constituent.
717 constituent: String,
718 /// Concentration in kg/m3, finite and nonnegative (CFD-E025).
719 concentration_kg_m3: f64,
720 },
721 /// A Gaussian puff, periodized over the domain, integrated per cell and
722 /// scaled to exactly `total_mass_kg` of fluid mass. Needs periodic
723 /// boundaries on all three axes (CFD-E026); used by the transport
724 /// verification fixtures.
725 PeriodicGaussian {
726 /// ID of the initialized constituent.
727 constituent: String,
728 /// Center [x, y, z] in meters, inside the domain.
729 center_m: [f64; 3],
730 /// Standard deviations along x, y and z in meters, each positive and
731 /// at most twice the domain length.
732 sigma_m: [f64; 3],
733 /// Mass of the puff in kg, positive.
734 total_mass_kg: f64,
735 },
736}
737impl Initial {
738 /// ID of the constituent this condition initializes.
739 pub fn constituent(&self) -> &str {
740 match self {
741 Self::Uniform { constituent, .. } | Self::PeriodicGaussian { constituent, .. } => {
742 constituent
743 }
744 }
745 }
746}
747/// A named concentration sample, selected by `kind` and reported in kg/m3 for
748/// every constituent (`receptors_kg_m3` of the result, probes.csv). IDs are
749/// unique and nonempty (CFD-E019); the support is nondegenerate and inside the
750/// domain (CFD-E027) and may not sample a solid cell (CFD-E042).
751#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
752#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
753pub enum Receptor {
754 /// Trilinear interpolation between the eight surrounding cell centers,
755 /// clamped at the domain boundary.
756 Point {
757 /// Unique nonempty receptor ID (CFD-E019).
758 id: String,
759 /// Position [x, y, z] in meters, inside the domain.
760 point_m: [f64; 3],
761 },
762 /// The average over a box, weighted by the exact overlap of each cell
763 /// with the box. Not a point sample or a peak bound.
764 VolumeAverage {
765 /// Unique nonempty receptor ID (CFD-E019).
766 id: String,
767 /// Lower corner [x, y, z] in meters.
768 min_m: [f64; 3],
769 /// Upper corner [x, y, z] in meters; every bound above `min_m` and
770 /// inside the domain.
771 max_m: [f64; 3],
772 },
773 /// Polyline sampling at a constant height. Samples are equally spaced
774 /// in arc length, including both endpoints, with spacing at most the
775 /// declared maximum. The receptor mean is normalized trapezoidal quadrature.
776 Path {
777 /// Unique nonempty receptor ID (CFD-E019).
778 id: String,
779 /// Local metric x/y vertices; 2..4097, without repeated neighbors.
780 polyline_m: Vec<[f64; 2]>,
781 /// Constant sample height above flat ground, in meters.
782 height_m: f64,
783 /// Positive finite maximum arc-length spacing, in meters.
784 sample_spacing_m: f64,
785 },
786}
787/// Maximum generated sample points in one path receptor.
788pub const PATH_SAMPLES_MAX: usize = 20001;
789/// Maximum generated sample points across all path receptors in one case.
790pub const PATH_SAMPLES_TOTAL_MAX: usize = 50000;
791impl Receptor {
792 /// Generated sample count for a path (None for other receptor kinds).
793 /// Invalid/nonfinite lengths or spacings return usize::MAX, so preflight
794 /// can reject them before allocation.
795 pub fn path_sample_count(&self) -> Option<usize> {
796 let Self::Path {
797 polyline_m,
798 sample_spacing_m,
799 ..
800 } = self
801 else {
802 return None;
803 };
804 let length = polyline_m
805 .windows(2)
806 .map(|p| (p[1][0] - p[0][0]).hypot(p[1][1] - p[0][1]))
807 .sum::<f64>();
808 if !length.is_finite()
809 || length <= 0.0
810 || !sample_spacing_m.is_finite()
811 || *sample_spacing_m <= 0.0
812 {
813 return Some(usize::MAX);
814 }
815 Some(
816 ((length / sample_spacing_m).ceil() as usize)
817 .max(1)
818 .saturating_add(1),
819 )
820 }
821 /// The receptor ID.
822 pub fn id(&self) -> &str {
823 match self {
824 Self::Point { id, .. } | Self::VolumeAverage { id, .. } | Self::Path { id, .. } => id,
825 }
826 }
827}
828/// Advection scheme of the constituents. `linear_upwind` is first-order
829/// upwind; it is linear in the concentrations, so responses to sources
830/// superpose exactly in a fixed flow. `muscl` adds a second-order slope with
831/// the bounded monotonized-central limiter; it is nonlinear, so superposition
832/// is not exact.
833#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
834#[serde(rename_all = "snake_case")]
835pub enum Advection {
836 #[cfg_attr(
837 doc,
838 doc = "First-order upwind, linear in the concentrations: exact source superposition in a fixed flow."
839 )]
840 #[allow(missing_docs)]
841 LinearUpwind,
842 #[cfg_attr(
843 doc,
844 doc = "MUSCL with the monotonized-central limiter: second order in smooth regions and bounded, but nonlinear."
845 )]
846 #[allow(missing_docs)]
847 Muscl,
848}
849/// Preconditioner of the pressure PCG solve. `ic0` (the default) is an
850/// incomplete Cholesky factor built once per grid and works on every grid.
851/// `multigrid` is a fixed symmetric multigrid cycle. On an unmasked grid it is
852/// geometric, and strongly anisotropic spacings select line or plane
853/// smoothing. With geometry it aggregates connected fluid cells and uses
854/// point smoothing only, so strong anisotropy can make it slower than `ic0`.
855/// Strong anisotropy draws warning CFD-W004 in both cases. Both
856/// preconditioners solve the same equation to the same tolerance and
857/// recomputed residual.
858#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
859#[serde(rename_all = "snake_case")]
860pub enum PressurePreconditioner {
861 #[cfg_attr(
862 doc,
863 doc = "Incomplete Cholesky IC(0) of a slightly shifted operator, built on the first pressure solve and cached in the grid (default)."
864 )]
865 #[allow(missing_docs)]
866 #[default]
867 Ic0,
868 #[cfg_attr(
869 doc,
870 doc = "Fixed symmetric multigrid cycle: geometric on unmasked grids, connected aggregates with geometry. See the [pressure multigrid guide](https://github.com/dietmarwo/CFD-craft/blob/main/docs/developer/pressure-multigrid.md)."
871 )]
872 #[allow(missing_docs)]
873 Multigrid,
874}
875impl PressurePreconditioner {
876 fn is_default(&self) -> bool {
877 *self == Self::Ic0
878 }
879}
880/// Momentum advection on the staggered grid. Donor-cell (advective form) is the
881/// default; the others are conservative flux forms with an upwind-biased
882/// reconstruction of the transported component (van Leer's MUSCL in Sweby's notation).
883#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
884#[serde(rename_all = "snake_case")]
885pub enum MomentumAdvection {
886 /// First-order donor-cell upwind in advective form (default).
887 #[default]
888 DonorCell,
889 /// Unlimited second-order upwind: face value 1.5 phi_U - 0.5 phi_UU. Not bounded.
890 SecondOrderUpwind,
891 /// Second-order upwind with the limiter in `numerics.momentum_limiter`.
892 LimitedUpwind,
893}
894impl MomentumAdvection {
895 fn is_default(&self) -> bool {
896 *self == Self::DonorCell
897 }
898}
899/// Steady pseudo-time algorithm. `explicit` is the SSPRK2 march of the earlier
900/// release. The implicit options solve for a correction driven by the full
901/// steady residual (delta form), so they share its fixed point.
902#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
903#[serde(rename_all = "snake_case")]
904pub enum SteadyAlgorithm {
905 /// SSPRK2 pseudo-time steps with a projection per stage, limited by
906 /// advection and diffusion together (default).
907 #[default]
908 Explicit,
909 /// SSPRK2 stages with an implicit viscous term: (I − Δτ L_ν) δ = Δτ R.
910 ImplicitViscous,
911 /// One implicit correction per outer iteration, A δ = R with a Picard
912 /// first-order upwind and viscous Jacobian and a CFL ramp, followed by a
913 /// projection at the pseudo-time step (a SIMPLEC-type coupling).
914 ImplicitProjection,
915}
916impl SteadyAlgorithm {
917 fn is_default(&self) -> bool {
918 *self == Self::Explicit
919 }
920}
921/// Limiter of `limited_upwind` momentum advection, in Sweby's notation
922/// s(a, b) with a and b the upwind and downwind differences: `van_albada`
923/// s = ab(a + b)/(a^2 + b^2), `van_leer` s = 2ab/(a + b), or
924/// `monotonized_central` s = sign(b) min(2|a|, |a + b|/2, 2|b|). Each is zero
925/// where a and b differ in sign.
926#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
927#[serde(rename_all = "snake_case")]
928pub enum MomentumLimiter {
929 #[cfg_attr(doc, doc = "van Albada: s = ab(a + b)/(a² + b²).")]
930 #[allow(missing_docs)]
931 VanAlbada,
932 #[cfg_attr(doc, doc = "van Leer: s = 2ab/(a + b).")]
933 #[allow(missing_docs)]
934 VanLeer,
935 #[cfg_attr(
936 doc,
937 doc = "Monotonized central: s = sign(b) min(2|a|, |a + b|/2, 2|b|)."
938 )]
939 #[allow(missing_docs)]
940 MonotonizedCentral,
941}
942/// Discretization choices, tolerances and the steady monitor window. The
943/// optional selections `pressure_preconditioner`, `momentum_advection`,
944/// `momentum_limiter` and `steady_algorithm` are left out of the normalized
945/// case when they have their default, so cases written before they existed
946/// keep their case and physics hashes.
947#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
948#[serde(deny_unknown_fields)]
949pub struct Numerics {
950 #[cfg_attr(doc, doc = "Advection scheme of the constituents; see [`Advection`].")]
951 #[allow(missing_docs)]
952 pub transport: Advection,
953 /// Upper bound of the time step in seconds, finite and positive
954 /// (CFD-E009). The step is the smaller of this and the stability limit;
955 /// in transient mode the last step is clipped to end at `run.end_time_s`.
956 pub max_time_step_s: f64,
957 /// Stability factor of explicit steps, 0 < CFL <= 0.45 (CFD-E010): with
958 /// the explicit algorithm and for constituent sub-steps, dt = CFL / (sum
959 /// of max|u|/dx + 2 D sum of 1/dx^2), D the largest viscosity or
960 /// diffusivity. `implicit_viscous` applies it to advection only;
961 /// `implicit_projection` uses its own CFL ramp for the flow.
962 pub advective_cfl_max: f64,
963 /// Relative residual target of each pressure solve, finite and positive
964 /// (CFD-E009). A solve is accepted when the recomputed residual is within
965 /// 10 times this plus 1e-12. A loose value changes the path to a steady
966 /// state, not the steady checks.
967 pub pressure_relative_tolerance: f64,
968 /// PCG iteration limit of each pressure solve, nonzero (CFD-E008).
969 /// Reaching it fails the step with CFD-E033.
970 pub pressure_max_iterations: usize,
971 /// Preconditioner of the pressure solve: `ic0` (default) or `multigrid`.
972 /// Omitted from the normalized case when `ic0`, which keeps existing case
973 /// and checkpoint hashes.
974 #[serde(default, skip_serializing_if = "PressurePreconditioner::is_default")]
975 pub pressure_preconditioner: PressurePreconditioner,
976 /// Momentum advection: `donor_cell` (default), `second_order_upwind` or
977 /// `limited_upwind`. Omitted from the normalized case when `donor_cell`,
978 /// which keeps existing case and checkpoint hashes.
979 #[serde(default, skip_serializing_if = "MomentumAdvection::is_default")]
980 pub momentum_advection: MomentumAdvection,
981 /// Limiter of `limited_upwind`: required with it and rejected otherwise
982 /// (CFD-E037). Omitted when absent.
983 #[serde(default, skip_serializing_if = "Option::is_none")]
984 pub momentum_limiter: Option<MomentumLimiter>,
985 /// Pseudo-time algorithm of steady runs: `explicit` (default),
986 /// `implicit_viscous` (laminar only) or `implicit_projection` (laminar or
987 /// `neutral_rans`). The implicit options need `run.mode = steady`
988 /// (CFD-E045) and a solved flow (CFD-E047). Omitted from the normalized
989 /// case when `explicit`, which keeps existing hashes.
990 #[serde(default, skip_serializing_if = "SteadyAlgorithm::is_default")]
991 pub steady_algorithm: SteadyAlgorithm,
992 /// Threshold of the normalized steady equation residuals (momentum,
993 /// turbulence and each constituent), finite and positive (CFD-E009).
994 /// Steady mode only.
995 pub steady_residual_tolerance: f64,
996 /// Threshold of `monitor_stability`, the largest relative change between
997 /// the means of three successive monitor windows; finite and positive
998 /// (CFD-E009). Steady mode only.
999 pub steady_monitor_tolerance: f64,
1000 /// Steps per monitor window, 2..100000 (CFD-E008). A steady run assesses
1001 /// its checks every `monitor_window` steps and needs three full windows
1002 /// before `monitor_stability` can pass.
1003 pub monitor_window: usize,
1004}
1005/// Run mode. `steady` iterates in pseudo-time until every steady check passes;
1006/// `run.end_time_s` does not bound it. `transient` integrates the physical
1007/// interval up to `run.end_time_s`.
1008#[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
1009#[serde(rename_all = "snake_case")]
1010pub enum Mode {
1011 #[cfg_attr(
1012 doc,
1013 doc = "Pseudo-time iteration until every steady check passes; success is `completed` / `steady_discrete_solution`."
1014 )]
1015 #[allow(missing_docs)]
1016 Steady,
1017 #[cfg_attr(
1018 doc,
1019 doc = "Time-accurate integration up to `run.end_time_s`; success is `completed` / `transient_interval_completed`."
1020 )]
1021 #[allow(missing_docs)]
1022 Transient,
1023}
1024/// Mode, endpoint and execution budgets. The whole group is excluded from the
1025/// physics hash, so budgets can change between a run and its restart.
1026#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
1027#[serde(deny_unknown_fields)]
1028pub struct Run {
1029 #[cfg_attr(doc, doc = "Steady or transient; see [`Mode`].")]
1030 #[allow(missing_docs)]
1031 pub mode: Mode,
1032 /// Physical end time of a transient run in seconds: finite, positive and
1033 /// at most 1e12 (CFD-E009, CFD-E022). It does not bound a steady run.
1034 pub end_time_s: f64,
1035 /// Maximum number of retained steps (outer iterations with an implicit
1036 /// steady algorithm), counted from the cold start including the steps of
1037 /// a restart checkpoint; nonzero (CFD-E008). Reaching it ends the run as
1038 /// `iteration_limit`.
1039 pub max_steps: usize,
1040 /// Wall-time allowance in seconds: finite, positive and at most seven
1041 /// days (CFD-E009, CFD-E022). The CLI and the Python binding enforce it;
1042 /// a Rust caller passes it, or its own limit, to `Control::new`.
1043 pub wall_time_limit_s: f64,
1044 /// Worker threads, 1..64 (CFD-E008). The CLI and the Python binding solve
1045 /// on a pool of this size; the Rust library does not create one.
1046 pub threads: usize,
1047 /// Memory budget in MiB for the preflight estimate (CFD-E006); a restart
1048 /// checkpoint may be at most half of it (CFD-E065). An estimate check, not
1049 /// an enforced process limit.
1050 pub memory_limit_mib: usize,
1051}
1052/// Which optional artifacts a run archive keeps, and its output budget.
1053#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
1054#[serde(deny_unknown_fields)]
1055pub struct Output {
1056 /// Write fields.json, the full final state including the native face
1057 /// velocities.
1058 pub fields: bool,
1059 /// Write checkpoint.json, a checksummed restart state.
1060 pub checkpoint: bool,
1061 /// Budget for all artifacts in MiB. The preflight estimate must fit
1062 /// (CFD-E007); at publication, fields and checkpoint are omitted and
1063 /// listed in the manifest when they would exceed it (CFD-E061).
1064 pub max_total_mib: usize,
1065}
1066/// One finding of a check: a stable code, its severity, the path of the
1067/// offending field and a message.
1068#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
1069#[serde(deny_unknown_fields)]
1070pub struct Diagnostic {
1071 /// Stable code such as `CFD-E010` (error) or `CFD-W001` (warning), listed
1072 /// in docs/diagnostics.md.
1073 pub code: String,
1074 /// `error`, which makes the case invalid, or `warning`.
1075 pub severity: String,
1076 /// Path of the offending field, for example `numerics.advective_cfl_max`
1077 /// or `sources[0].rate_kg_s`; empty for a document-level parse error.
1078 pub path: String,
1079 /// Explanation for people. Programs should match `code` and `path`, not
1080 /// this text.
1081 pub message: String,
1082}
1083/// Result of a case check (schema `cfd-craft.check/0.1`), as `cfd-craft
1084/// check` prints it: validity, the size and resource estimates, and every
1085/// diagnostic.
1086#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
1087pub struct CheckReport {
1088 /// Always `cfd-craft.check/0.1`.
1089 pub schema_version: String,
1090 /// True when no diagnostic has severity `error`.
1091 pub valid: bool,
1092 /// Total cell count (saturating at `usize::MAX`); 0 in the report of an
1093 /// unparsable case.
1094 pub cells: usize,
1095 /// Conservative estimate of the solver's peak memory in MiB, checked
1096 /// against `run.memory_limit_mib`; not measured process memory.
1097 pub estimated_peak_mib: f64,
1098 /// Estimated size of all archive artifacts in MiB, checked against
1099 /// `output.max_total_mib`.
1100 pub estimated_output_mib: f64,
1101 /// Every error and warning, in check order.
1102 pub diagnostics: Vec<Diagnostic>,
1103}
1104impl Case {
1105 /// SHA-256 (lowercase hex) of the case's compact JSON without `name`,
1106 /// `run` and `output`: the identity of the physical and numerical
1107 /// problem. A checkpoint restarts only a case with the same physics hash
1108 /// (CFD-E060), so budgets, the endpoint and the output policy may change
1109 /// between a run and its restart, while grid, physics, sources, receptors
1110 /// and numerics may not.
1111 ///
1112 /// ```
1113 /// # let json = r#"{"schema_version": "cfd-craft.case/0.1", "name": "tiny",
1114 /// # "domain": {"size_m": [4.0, 1.0, 1.0]}, "grid": {"cells": [8, 2, 2]},
1115 /// # "boundaries": {"x": "open", "y": "periodic", "z": "periodic"},
1116 /// # "flow": {"kind": "prescribed_uniform", "velocity_m_s": [1.0, 0.0, 0.0]},
1117 /// # "constituents": [{"id": "tracer", "diffusivity_m2_s": 0.01}],
1118 /// # "sources": [{"kind": "point", "id": "S0", "constituent": "tracer",
1119 /// # "point_m": [0.5, 0.5, 0.5], "rate_kg_s": 1e-6}],
1120 /// # "numerics": {"transport": "linear_upwind", "max_time_step_s": 1.0,
1121 /// # "advective_cfl_max": 0.4, "pressure_relative_tolerance": 1e-10,
1122 /// # "pressure_max_iterations": 100, "steady_residual_tolerance": 1e-5,
1123 /// # "steady_monitor_tolerance": 1e-3, "monitor_window": 10},
1124 /// # "run": {"mode": "steady", "end_time_s": 1.0, "max_steps": 1000,
1125 /// # "wall_time_limit_s": 30.0, "threads": 1, "memory_limit_mib": 64},
1126 /// # "output": {"fields": false, "checkpoint": false, "max_total_mib": 4}}"#;
1127 /// use cfd_craft::case::{Case, Source};
1128 ///
1129 /// let case: Case = serde_json::from_str(json).unwrap();
1130 /// let mut longer = case.clone();
1131 /// longer.name = "tiny, longer budget".into();
1132 /// longer.run.max_steps *= 10;
1133 /// assert_eq!(case.physics_hash(), longer.physics_hash());
1134 ///
1135 /// let mut weaker = case.clone();
1136 /// if let Source::Point { rate_kg_s, .. } = &mut weaker.sources[0] {
1137 /// *rate_kg_s *= 0.5;
1138 /// }
1139 /// assert_ne!(case.physics_hash(), weaker.physics_hash());
1140 /// ```
1141 pub fn physics_hash(&self) -> String {
1142 let mut v = serde_json::to_value(self).expect("serializable case");
1143 for k in ["run", "output", "name"] {
1144 v.as_object_mut().unwrap().remove(k);
1145 }
1146 hash_bytes(&serde_json::to_vec(&v).unwrap())
1147 }
1148 /// The semantic checks that need no grid: schema version, ranges and
1149 /// units, budgets, physical combinations, IDs, and that geometry, sources,
1150 /// receptors and initial conditions lie inside the domain. It also
1151 /// estimates peak memory and output size and checks them against
1152 /// `run.memory_limit_mib` (CFD-E006) and `output.max_total_mib`
1153 /// (CFD-E007).
1154 ///
1155 /// Every problem is reported at once; the report is invalid when any
1156 /// diagnostic is an error. It never fails or allocates the grid. The
1157 /// checks that need the built grid are in
1158 /// [`input::full_check`](crate::input::full_check), which the CLI and
1159 /// the Python binding run, and are repeated by
1160 /// [`solver::run`](crate::solver::run).
1161 ///
1162 /// ```
1163 /// # let json = r#"{"schema_version": "cfd-craft.case/0.1", "name": "tiny",
1164 /// # "domain": {"size_m": [4.0, 1.0, 1.0]}, "grid": {"cells": [8, 2, 2]},
1165 /// # "boundaries": {"x": "open", "y": "periodic", "z": "periodic"},
1166 /// # "flow": {"kind": "prescribed_uniform", "velocity_m_s": [1.0, 0.0, 0.0]},
1167 /// # "numerics": {"transport": "linear_upwind", "max_time_step_s": 1.0,
1168 /// # "advective_cfl_max": 0.4, "pressure_relative_tolerance": 1e-10,
1169 /// # "pressure_max_iterations": 100, "steady_residual_tolerance": 1e-5,
1170 /// # "steady_monitor_tolerance": 1e-3, "monitor_window": 10},
1171 /// # "run": {"mode": "steady", "end_time_s": 1.0, "max_steps": 1000,
1172 /// # "wall_time_limit_s": 30.0, "threads": 1, "memory_limit_mib": 64},
1173 /// # "output": {"fields": false, "checkpoint": false, "max_total_mib": 4}}"#;
1174 /// use cfd_craft::case::Case;
1175 ///
1176 /// let mut case: Case = serde_json::from_str(json).unwrap();
1177 /// case.numerics.advective_cfl_max = 0.9;
1178 /// case.run.threads = 0;
1179 /// let report = case.check();
1180 /// assert!(!report.valid);
1181 /// let found: Vec<_> = report
1182 /// .diagnostics
1183 /// .iter()
1184 /// .map(|d| (d.code.as_str(), d.path.as_str()))
1185 /// .collect();
1186 /// assert!(found.contains(&("CFD-E010", "numerics.advective_cfl_max")));
1187 /// assert!(found.contains(&("CFD-E008", "run.threads")));
1188 /// ```
1189 pub fn check(&self) -> CheckReport {
1190 let cells = self
1191 .grid
1192 .cells
1193 .iter()
1194 .try_fold(1usize, |x, n| x.checked_mul(*n))
1195 .unwrap_or(usize::MAX);
1196 let species = self.constituents.len() as f64;
1197 // Volume receptors keep sparse (cell, weight) pairs; Vec growth can double them.
1198 let receptor_bytes: f64 = self
1199 .receptors
1200 .iter()
1201 .map(|r| match r {
1202 Receptor::Point { .. } => 8.0 * 16.0,
1203 Receptor::VolumeAverage { min_m, max_m, .. } => {
1204 32.0 * self.covered_cells(min_m, max_m)
1205 }
1206 Receptor::Path { .. } => {
1207 512.0 * r.path_sample_count().unwrap_or(0).min(PATH_SAMPLES_MAX + 1) as f64
1208 }
1209 })
1210 .sum();
1211 // One dense weight vector exists while each source is represented.
1212 let source_bytes = if self.sources.is_empty() {
1213 0.0
1214 } else {
1215 8.0 * cells as f64
1216 };
1217 // The state keeps one monitor row per step for the last three windows: the flow
1218 // norm, each constituent's mass and receptor values, and mean k and epsilon.
1219 let monitor_rows = self
1220 .numerics
1221 .monitor_window
1222 .saturating_mul(3)
1223 .min(self.run.max_steps) as f64;
1224 let monitor_values = monitor_rows * (3.0 + species * (1.0 + self.receptors.len() as f64));
1225 let monitor_bytes = 8.0 * monitor_values + 32.0 * monitor_rows;
1226 // Include contiguous pressure factor construction and a compact per-solve
1227 // operator allowance (112 bytes/cell), before the existing 25% margin.
1228 // Extra hierarchy, reusable cycle vectors and construction peak allowance.
1229 // This is a conservative preflight allowance, not measured process RSS.
1230 let multigrid_bytes =
1231 if self.numerics.pressure_preconditioner == PressurePreconditioner::Multigrid {
1232 let dx = std::array::from_fn(|a| self.domain.size_m[a] / self.grid.cells[a] as f64);
1233 1024.0
1234 + if crate::multigrid::line_axes(self.grid.cells, dx).is_empty() {
1235 0.0
1236 } else {
1237 512.0
1238 }
1239 } else {
1240 0.0
1241 };
1242 // Canopy raster coefficients, cell speeds, staggered drag and four
1243 // turbulence source/sink arrays coexist with the ordinary workspaces.
1244 let canopy_bytes = if crate::vegetation::active(self) {
1245 256.0
1246 } else {
1247 0.0
1248 };
1249 let peak = ((cells as f64) * (880.0 + multigrid_bytes + canopy_bytes + 96.0 * species) * 1.25
1250 + receptor_bytes
1251 + source_bytes
1252 + monitor_bytes)
1253 / 1048576.0
1254 // Process baseline (measured near 19 MiB) and the worker threads' stacks.
1255 + 24.0
1256 + self.run.threads as f64;
1257 // JSON text of f64 values is at most about 24 bytes; fields hold six flow arrays
1258 // (three face-velocity sets, pressure, k, epsilon) plus one array per constituent,
1259 // and both fields and checkpoint carry the monitor history.
1260 let output_fields = (cells as f64) * (24.0 * (6.0 + species) + 4.0) + 26.0 * monitor_values;
1261 let output_checkpoint =
1262 (cells as f64) * (26.0 * (6.0 + species) + 4.0) + 27.0 * monitor_values;
1263 // case.json, summary.json, geometry.json and probes.csv list every receptor, box
1264 // and source as pretty-printed text, receptor values once per constituent in
1265 // summary.json and probes.csv; identifiers count twice for JSON escaping.
1266 let ids: f64 = self.constituents.iter().map(|x| x.id.len() as f64).sum();
1267 let element_text: f64 = self
1268 .receptors
1269 .iter()
1270 .map(|r| {
1271 let id = r.id().len() as f64;
1272 400.0 + 2.0 * id + species * (100.0 + 4.0 * id) + 2.0 * ids
1273 })
1274 .chain(
1275 self.geometry
1276 .iter()
1277 .map(|b| 500.0 + 4.0 * b.id.len() as f64),
1278 )
1279 .chain(
1280 self.sources
1281 .iter()
1282 .map(|x| 600.0 + 2.0 * x.id().len() as f64),
1283 )
1284 .chain(
1285 self.vegetation
1286 .iter()
1287 .map(|v| 900.0 + 4.0 * v.id.len() as f64),
1288 )
1289 .chain(
1290 self.constituents
1291 .iter()
1292 .filter(|sp| sp.particle.is_some())
1293 .map(|_| 700.0 + 200.0 * self.receptors.len() as f64),
1294 )
1295 .sum();
1296 let path_output_bytes = self
1297 .receptors
1298 .iter()
1299 .filter_map(Receptor::path_sample_count)
1300 .map(|n| n.min(PATH_SAMPLES_MAX + 1) as f64 * (160.0 + 64.0 * species))
1301 .sum::<f64>();
1302 let output = (element_text
1303 + path_output_bytes
1304 + if self.output.fields {
1305 output_fields
1306 } else {
1307 0.0
1308 }
1309 + if self.output.checkpoint {
1310 output_checkpoint
1311 } else {
1312 0.0
1313 })
1314 / 1048576.0
1315 + 2.0;
1316 let mut d = Vec::new();
1317 let mut add = |code: &str, severity: &str, path: &str, message: &str| {
1318 d.push(Diagnostic {
1319 code: code.into(),
1320 severity: severity.into(),
1321 path: path.into(),
1322 message: message.into(),
1323 })
1324 };
1325 if self.schema_version != "cfd-craft.case/0.1" {
1326 add(
1327 "CFD-E001",
1328 "error",
1329 "schema_version",
1330 "Use cfd-craft.case/0.1.",
1331 );
1332 }
1333 if self.name.is_empty() {
1334 add("CFD-E002", "error", "name", "Supply a nonempty case name.");
1335 }
1336 match (
1337 self.numerics.momentum_advection,
1338 self.numerics.momentum_limiter,
1339 ) {
1340 (MomentumAdvection::LimitedUpwind, None) => add(
1341 "CFD-E037",
1342 "error",
1343 "numerics.momentum_limiter",
1344 "limited_upwind needs a limiter: van_albada, van_leer or monotonized_central.",
1345 ),
1346 (MomentumAdvection::DonorCell | MomentumAdvection::SecondOrderUpwind, Some(_)) => add(
1347 "CFD-E037",
1348 "error",
1349 "numerics.momentum_limiter",
1350 "A momentum limiter is used only with momentum_advection = limited_upwind.",
1351 ),
1352 _ => {}
1353 }
1354 if self.numerics.steady_algorithm != SteadyAlgorithm::Explicit {
1355 let path = "numerics.steady_algorithm";
1356 if self.run.mode != Mode::Steady {
1357 add(
1358 "CFD-E045",
1359 "error",
1360 path,
1361 "Implicit pseudo-time changes the time accuracy; use it only with run.mode = steady.",
1362 );
1363 }
1364 if self.flow.prescribed()
1365 || (self.flow.rans()
1366 && self.numerics.steady_algorithm == SteadyAlgorithm::ImplicitViscous)
1367 {
1368 add(
1369 "CFD-E047",
1370 "error",
1371 path,
1372 "Prescribed flow needs no steady algorithm, and implicit_viscous supports laminar flow only; use explicit, or implicit_projection for neutral_rans.",
1373 );
1374 }
1375 }
1376 if self.numerics.pressure_preconditioner == PressurePreconditioner::Multigrid {
1377 let dx = std::array::from_fn(|a| self.domain.size_m[a] / self.grid.cells[a] as f64);
1378 let axes = crate::multigrid::line_axes(self.grid.cells, dx);
1379 if !axes.is_empty() {
1380 add(
1381 "CFD-W004",
1382 "warning",
1383 "numerics.pressure_preconditioner",
1384 if self.geometry.is_empty() {
1385 "Strong pressure anisotropy selects symmetric line-block smoothing with additional setup and memory; compare measured cost with ic0. Extreme anisotropy can still reach the pressure limit (CFD-E033)."
1386 } else {
1387 // Geometry always masks at least one cell (CFD-E028), which selects the aggregate path.
1388 "Strong pressure anisotropy with geometry: the masked multigrid path uses point smoothing and has no line-block smoothing, so it can need more iterations and time than ic0; compare measured cost with ic0. Extreme anisotropy can still reach the pressure limit (CFD-E033)."
1389 },
1390 );
1391 }
1392 }
1393
1394 for a in 0..3 {
1395 if !(self.domain.size_m[a].is_finite()
1396 && self.domain.size_m[a] >= 1e-6
1397 && self.domain.size_m[a] <= 1e9)
1398 {
1399 add(
1400 "CFD-E003",
1401 "error",
1402 &format!("domain.size_m[{a}]"),
1403 "Supported lengths are 1e-6..1e9 m.",
1404 );
1405 }
1406 let minimum = if self.boundaries.at(a) == Boundary::Periodic {
1407 1
1408 } else {
1409 2
1410 };
1411 if self.grid.cells[a] < minimum || self.grid.cells[a] > 4096 {
1412 add(
1413 "CFD-E004",
1414 "error",
1415 &format!("grid.cells[{a}]"),
1416 "Each axis needs 2..4096 cells; a periodic axis may have one (a two-dimensional run).",
1417 );
1418 }
1419 if a != 2 && self.boundaries.at(a) == Boundary::GroundOpenTop {
1420 add(
1421 "CFD-E005",
1422 "error",
1423 &format!("boundaries.{}", ["x", "y", "z"][a]),
1424 "ground_open_top is supported on z only.",
1425 );
1426 }
1427 }
1428 if cells > 100_000_000 || peak > self.run.memory_limit_mib as f64 {
1429 add(
1430 "CFD-E006",
1431 "error",
1432 "run.memory_limit_mib",
1433 "Estimated memory exceeds the budget; reduce grid/constituents or raise an available budget.",
1434 );
1435 }
1436 if output > self.output.max_total_mib as f64 {
1437 add(
1438 "CFD-E007",
1439 "error",
1440 "output.max_total_mib",
1441 "Estimated artifacts exceed the output budget.",
1442 );
1443 }
1444 for (path, ok, message) in [
1445 (
1446 "run.threads",
1447 (1..=64).contains(&self.run.threads),
1448 "Use 1..64 threads.",
1449 ),
1450 (
1451 "run.max_steps",
1452 self.run.max_steps > 0,
1453 "Use a nonzero step budget.",
1454 ),
1455 (
1456 "numerics.pressure_max_iterations",
1457 self.numerics.pressure_max_iterations > 0,
1458 "Use a nonzero pressure iteration budget.",
1459 ),
1460 (
1461 "numerics.monitor_window",
1462 (2..=100000).contains(&self.numerics.monitor_window),
1463 "Use a monitor window of 2..100000 steps.",
1464 ),
1465 ] {
1466 if !ok {
1467 add("CFD-E008", "error", path, message);
1468 }
1469 }
1470 if self.run.wall_time_limit_s > 604800.0 {
1471 add(
1472 "CFD-E022",
1473 "error",
1474 "run.wall_time_limit_s",
1475 "The wall-time limit may not exceed seven days.",
1476 );
1477 }
1478 if self.run.end_time_s > 1e12 {
1479 add(
1480 "CFD-E022",
1481 "error",
1482 "run.end_time_s",
1483 "The physical horizon may not exceed 1e12 seconds.",
1484 );
1485 }
1486 for (path, x) in [
1487 ("run.end_time_s", self.run.end_time_s),
1488 ("run.wall_time_limit_s", self.run.wall_time_limit_s),
1489 ("numerics.max_time_step_s", self.numerics.max_time_step_s),
1490 (
1491 "numerics.pressure_relative_tolerance",
1492 self.numerics.pressure_relative_tolerance,
1493 ),
1494 (
1495 "numerics.steady_residual_tolerance",
1496 self.numerics.steady_residual_tolerance,
1497 ),
1498 (
1499 "numerics.steady_monitor_tolerance",
1500 self.numerics.steady_monitor_tolerance,
1501 ),
1502 ] {
1503 if !x.is_finite() || x <= 0.0 {
1504 add("CFD-E009", "error", path, "Must be finite and positive.");
1505 }
1506 }
1507 if !(self.numerics.advective_cfl_max > 0.0 && self.numerics.advective_cfl_max <= 0.45) {
1508 add(
1509 "CFD-E010",
1510 "error",
1511 "numerics.advective_cfl_max",
1512 "Use 0 < CFL <= 0.45; the combined advective and diffusive step allowance is capped at 0.45 for positivity.",
1513 );
1514 }
1515 if self.flow.rans() && self.boundaries.z != Boundary::GroundOpenTop {
1516 add(
1517 "CFD-E011",
1518 "error",
1519 "boundaries.z",
1520 "Neutral RANS requires ground_open_top.",
1521 );
1522 }
1523 if matches!(self.flow, Flow::Laminar { .. }) && self.boundaries.z == Boundary::GroundOpenTop
1524 {
1525 add(
1526 "CFD-E023",
1527 "error",
1528 "boundaries.z",
1529 "ground_open_top has an open top only with the neutral RANS stress closure; for laminar flow use wall, slip or periodic.",
1530 );
1531 }
1532 match &self.flow {
1533 Flow::NeutralRans {
1534 speed_m_s,
1535 reference_height_m,
1536 roughness_m,
1537 direction_deg_from,
1538 viscosity_m2_s,
1539 turbulent_schmidt,
1540 } => {
1541 for (path, x) in [
1542 ("flow.speed_m_s", *speed_m_s),
1543 ("flow.reference_height_m", *reference_height_m),
1544 ("flow.roughness_m", *roughness_m),
1545 ("flow.viscosity_m2_s", *viscosity_m2_s),
1546 ("flow.turbulent_schmidt", *turbulent_schmidt),
1547 ] {
1548 if !x.is_finite() || x <= 0.0 {
1549 add("CFD-E012", "error", path, "Must be finite and positive.");
1550 }
1551 }
1552 if !direction_deg_from.is_finite() {
1553 add(
1554 "CFD-E012",
1555 "error",
1556 "flow.direction_deg_from",
1557 "Must be finite.",
1558 );
1559 }
1560 if *reference_height_m > self.domain.size_m[2] {
1561 add(
1562 "CFD-E012",
1563 "error",
1564 "flow.reference_height_m",
1565 "The reference height must lie inside the domain.",
1566 );
1567 }
1568 }
1569 Flow::Laminar {
1570 initial_velocity_m_s,
1571 viscosity_m2_s,
1572 acceleration_m_s2,
1573 } => {
1574 if !viscosity_m2_s.is_finite()
1575 || *viscosity_m2_s <= 0.0
1576 || initial_velocity_m_s
1577 .iter()
1578 .chain(acceleration_m_s2)
1579 .any(|x| !x.is_finite())
1580 {
1581 add(
1582 "CFD-E012",
1583 "error",
1584 "flow",
1585 "Laminar viscosity must be positive; initial_velocity_m_s and acceleration_m_s2 must be finite.",
1586 );
1587 }
1588 }
1589 Flow::PrescribedUniform { velocity_m_s } => {
1590 if velocity_m_s.iter().any(|x| !x.is_finite()) {
1591 add(
1592 "CFD-E012",
1593 "error",
1594 "flow.velocity_m_s",
1595 "Velocity must be finite.",
1596 );
1597 }
1598 if !self.geometry.is_empty() {
1599 add(
1600 "CFD-E013",
1601 "error",
1602 "geometry",
1603 "Uniform prescribed flow supports no obstacles; use laminar or neutral_rans flow.",
1604 );
1605 }
1606 for (a, &v) in velocity_m_s.iter().enumerate() {
1607 if v != 0.0
1608 && matches!(
1609 self.boundaries.at(a),
1610 Boundary::Wall | Boundary::Slip | Boundary::GroundOpenTop
1611 )
1612 {
1613 add(
1614 "CFD-E024",
1615 "error",
1616 &format!("flow.velocity_m_s[{a}]"),
1617 "Prescribed velocity must have zero normal component at impermeable boundaries.",
1618 );
1619 }
1620 }
1621 }
1622 }
1623 let inside = |p: &[f64; 3]| {
1624 (0..3).all(|a| p[a].is_finite() && p[a] >= 0.0 && p[a] < self.domain.size_m[a])
1625 };
1626 let box_ok = |lo: &[f64; 3], hi: &[f64; 3]| {
1627 (0..3).all(|a| {
1628 lo[a].is_finite()
1629 && hi[a].is_finite()
1630 && lo[a] >= 0.0
1631 && hi[a] <= self.domain.size_m[a]
1632 && hi[a] > lo[a]
1633 })
1634 };
1635 let mut ids = BTreeSet::new();
1636 let mut wall_ids = BTreeSet::new();
1637 for (i, wall) in self.moving_walls.iter().enumerate() {
1638 if wall.axis > 2
1639 || !wall_ids.insert((wall.axis, wall.upper))
1640 || wall.velocity_m_s.iter().any(|v| !v.is_finite())
1641 || (wall.axis < 3
1642 && (self.boundaries.at(wall.axis) != Boundary::Wall
1643 || wall.velocity_m_s[wall.axis] != 0.0))
1644 || !matches!(self.flow, Flow::Laminar { .. })
1645 {
1646 add(
1647 "CFD-E021",
1648 "error",
1649 &format!("moving_walls[{i}]"),
1650 "Use unique tangential moving domain walls in laminar flow only.",
1651 );
1652 }
1653 }
1654 for (i, b) in self.geometry.iter().enumerate() {
1655 if b.id.is_empty() || !ids.insert(b.id.clone()) {
1656 add(
1657 "CFD-E014",
1658 "error",
1659 &format!("geometry[{i}].id"),
1660 "Boxes need unique nonempty IDs.",
1661 );
1662 }
1663 if !box_ok(&b.min_m, &b.max_m) {
1664 add(
1665 "CFD-E014",
1666 "error",
1667 &format!("geometry[{i}]"),
1668 "Box bounds must increase on every axis and lie inside the domain.",
1669 );
1670 continue;
1671 }
1672 if let Some(polygon) = &b.footprint_m
1673 && !crate::geometry::valid_polygon(polygon, &b.min_m, &b.max_m)
1674 {
1675 add(
1676 "CFD-E084",
1677 "error",
1678 &format!("geometry[{i}].footprint_m"),
1679 "Use a finite, simple, nonzero-area polygon with 3..2048 vertices and matching bounding box; holes and repeated closing vertices are not supported.",
1680 );
1681 }
1682 let cells_high = (b.max_m[2] - b.min_m[2])
1683 / (self.domain.size_m[2] / self.grid.cells[2].max(1) as f64);
1684 if cells_high < 10.0 {
1685 add(
1686 "CFD-W001",
1687 "warning",
1688 &format!("geometry[{i}]"),
1689 &format!(
1690 "Box {} spans {cells_high:.1} vertical cells; fewer than 10 across a building height is too coarse for physical interpretation.",
1691 b.id
1692 ),
1693 );
1694 }
1695 }
1696 if let Some(z0) = self.building_roughness_m
1697 && (!z0.is_finite() || z0 <= 0.0 || !self.flow.rans())
1698 {
1699 add(
1700 "CFD-E085",
1701 "error",
1702 "building_roughness_m",
1703 "Building roughness must be finite and positive and requires neutral_rans.",
1704 );
1705 }
1706 if let Some(minimum) = self.geometry_min_passage_cells {
1707 if minimum == 0 {
1708 add(
1709 "CFD-E084",
1710 "error",
1711 "geometry_min_passage_cells",
1712 "Minimum passage resolution must be positive.",
1713 );
1714 } else if cells > 10_000_000 {
1715 // The scan is bounded; a skipped request must not read as satisfied.
1716 if !self.geometry.is_empty() {
1717 add(
1718 "CFD-W011",
1719 "warning",
1720 "geometry_min_passage_cells",
1721 "The passage resolution was not evaluated: this check scans at most 10000000 cells. Read narrowest_fluid_passage_cells of each shape in geometry.json.",
1722 );
1723 }
1724 } else if self.grid.cells.iter().all(|n| *n > 0)
1725 && let Some(width) = crate::geometry::minimum_passage(self)
1726 && width < minimum
1727 {
1728 add(
1729 "CFD-W011",
1730 "warning",
1731 "geometry_min_passage_cells",
1732 &format!(
1733 "Narrowest represented horizontal passage is {width} cells; requested at least {minimum}."
1734 ),
1735 );
1736 }
1737 }
1738 if self.flow.rans() {
1739 self.domain_warnings(&mut add);
1740 }
1741 let mut vegetation_ids = BTreeSet::new();
1742 for (i, v) in self.vegetation.iter().enumerate() {
1743 if v.id.is_empty() || !vegetation_ids.insert(v.id.clone()) {
1744 add(
1745 "CFD-E082",
1746 "error",
1747 &format!("vegetation[{i}].id"),
1748 "Use unique nonempty canopy IDs.",
1749 );
1750 }
1751 if !(0..3).all(|a| {
1752 v.min_m[a].is_finite()
1753 && v.max_m[a].is_finite()
1754 && v.min_m[a] >= 0.0
1755 && v.max_m[a] <= self.domain.size_m[a]
1756 && v.max_m[a] > v.min_m[a]
1757 }) {
1758 add(
1759 "CFD-E082",
1760 "error",
1761 &format!("vegetation[{i}].min_m"),
1762 "Canopy box must be finite, nondegenerate and inside the domain.",
1763 );
1764 }
1765 if self.flow.prescribed() && v.leaf_area_density_m2_m3 > 0.0 && v.drag_coefficient > 0.0
1766 {
1767 add(
1768 "CFD-E083",
1769 "error",
1770 &format!("vegetation[{i}].drag_coefficient"),
1771 "Prescribed flow cannot respond to canopy drag; set zero drag for a leaf-only study or solve laminar/RANS flow.",
1772 );
1773 }
1774 for (name, value, max) in [
1775 ("leaf_area_density_m2_m3", v.leaf_area_density_m2_m3, 100.0),
1776 ("drag_coefficient", v.drag_coefficient, 10.0),
1777 (
1778 "leaf_deposition_velocity_m_s",
1779 v.leaf_deposition_velocity_m_s,
1780 10.0,
1781 ),
1782 ] {
1783 if !value.is_finite() || !(0.0..=max).contains(&value) {
1784 add(
1785 "CFD-E082",
1786 "error",
1787 &format!("vegetation[{i}].{name}"),
1788 "Canopy parameters must be finite and within the documented nonnegative limits.",
1789 );
1790 }
1791 }
1792 }
1793 let mut species = BTreeSet::new();
1794 for (i, s) in self.constituents.iter().enumerate() {
1795 if s.id.is_empty() || !species.insert(s.id.clone()) {
1796 add(
1797 "CFD-E015",
1798 "error",
1799 &format!("constituents[{i}].id"),
1800 "Use unique nonempty constituent IDs.",
1801 );
1802 }
1803 if !s.diffusivity_m2_s.is_finite() || s.diffusivity_m2_s < 0.0 {
1804 add(
1805 "CFD-E015",
1806 "error",
1807 &format!("constituents[{i}].diffusivity_m2_s"),
1808 "Use a finite nonnegative diffusivity.",
1809 );
1810 }
1811 }
1812 for (i, species) in self.constituents.iter().enumerate() {
1813 if let Some(p) = &species.particle {
1814 let prefix = format!("constituents[{i}].particle");
1815 if !p.diameter_m.is_finite() || !(1e-8..=1e-4).contains(&p.diameter_m) {
1816 add(
1817 "CFD-E080",
1818 "error",
1819 &format!("{prefix}.diameter_m"),
1820 "Spherical bin diameter must be finite and in 1e-8..1e-4 m.",
1821 );
1822 }
1823 if !p.density_kg_m3.is_finite()
1824 || p.density_kg_m3 <= 1.204
1825 || p.density_kg_m3 > 30000.0
1826 {
1827 add(
1828 "CFD-E080",
1829 "error",
1830 &format!("{prefix}.density_kg_m3"),
1831 "Density must be finite, above reference air and at most 30000 kg/m3.",
1832 );
1833 }
1834 for (name, value) in [
1835 (
1836 "settling_velocity_m_s",
1837 p.settling_velocity_m_s.unwrap_or(0.0),
1838 ),
1839 (
1840 "ground_deposition_velocity_m_s",
1841 p.ground_deposition_velocity_m_s,
1842 ),
1843 (
1844 "roof_deposition_velocity_m_s",
1845 p.roof_deposition_velocity_m_s,
1846 ),
1847 ] {
1848 if !value.is_finite() || !(0.0..=10.0).contains(&value) {
1849 add(
1850 "CFD-E080",
1851 "error",
1852 &format!("{prefix}.{name}"),
1853 "Use a finite speed in 0..10 m/s.",
1854 );
1855 }
1856 }
1857 if p.settling_velocity_m_s.is_none()
1858 && (!p.reynolds_number().is_finite() || p.reynolds_number() > 0.1)
1859 {
1860 add(
1861 "CFD-E081",
1862 "error",
1863 &format!("{prefix}.settling_velocity_m_s"),
1864 "Stokes-Cunningham requires particle Reynolds number <= 0.1; supply a separately justified direct settling speed.",
1865 );
1866 }
1867 }
1868 }
1869 let mut source_ids = BTreeSet::new();
1870 for (i, s) in self.sources.iter().enumerate() {
1871 if s.id().is_empty() || !source_ids.insert(s.id().to_string()) {
1872 add(
1873 "CFD-E016",
1874 "error",
1875 &format!("sources[{i}].id"),
1876 "Use unique nonempty source IDs.",
1877 );
1878 }
1879 if !species.contains(s.constituent()) {
1880 add(
1881 "CFD-E016",
1882 "error",
1883 &format!("sources[{i}].constituent"),
1884 "The source must name a declared constituent.",
1885 );
1886 }
1887 let (rate_field, declared) = s.declared_rate();
1888 if !declared.is_finite() || declared < 0.0 {
1889 add(
1890 "CFD-E016",
1891 "error",
1892 &format!("sources[{i}].{rate_field}"),
1893 "Emission rates must be finite and nonnegative.",
1894 );
1895 }
1896 let ok = match s {
1897 Source::Point { point_m, .. } => inside(point_m),
1898 Source::Line { from_m, to_m, .. } => {
1899 inside(from_m) && inside(to_m) && from_m != to_m
1900 }
1901 Source::Volume { min_m, max_m, .. } => box_ok(min_m, max_m),
1902 };
1903 if !ok {
1904 add(
1905 "CFD-E017",
1906 "error",
1907 &format!("sources[{i}]"),
1908 "Source support must be nondegenerate and inside the domain.",
1909 );
1910 }
1911 }
1912 let mut initial_species = BTreeSet::new();
1913 for (i, s) in self.initial_conditions.iter().enumerate() {
1914 if !species.contains(s.constituent())
1915 || !initial_species.insert(s.constituent().to_string())
1916 {
1917 add(
1918 "CFD-E018",
1919 "error",
1920 &format!("initial_conditions[{i}].constituent"),
1921 "One initial condition per declared constituent is supported.",
1922 );
1923 }
1924 match s {
1925 Initial::Uniform {
1926 concentration_kg_m3,
1927 ..
1928 } => {
1929 if !concentration_kg_m3.is_finite() || *concentration_kg_m3 < 0.0 {
1930 add(
1931 "CFD-E025",
1932 "error",
1933 &format!("initial_conditions[{i}].concentration_kg_m3"),
1934 "Initial concentration must be nonnegative and finite.",
1935 );
1936 }
1937 }
1938 Initial::PeriodicGaussian {
1939 center_m,
1940 sigma_m,
1941 total_mass_kg,
1942 ..
1943 } => {
1944 if !inside(center_m)
1945 || (0..3).any(|a| {
1946 !sigma_m[a].is_finite()
1947 || sigma_m[a] <= 0.0
1948 || sigma_m[a] > 2.0 * self.domain.size_m[a]
1949 })
1950 || !total_mass_kg.is_finite()
1951 || *total_mass_kg <= 0.0
1952 || (0..3).any(|a| self.boundaries.at(a) != Boundary::Periodic)
1953 {
1954 add(
1955 "CFD-E026",
1956 "error",
1957 &format!("initial_conditions[{i}]"),
1958 "Periodic Gaussian needs three periodic axes, positive sigmas/mass and a center inside the domain.",
1959 );
1960 }
1961 }
1962 }
1963 }
1964 let mut receptor_ids = BTreeSet::new();
1965 let mut path_samples_total = 0usize;
1966 for (i, r) in self.receptors.iter().enumerate() {
1967 if r.id().is_empty() || !receptor_ids.insert(r.id().to_string()) {
1968 add(
1969 "CFD-E019",
1970 "error",
1971 &format!("receptors[{i}].id"),
1972 "Use unique, nonempty receptor IDs.",
1973 );
1974 }
1975 let ok = match r {
1976 Receptor::Point { point_m, .. } => inside(point_m),
1977 Receptor::VolumeAverage { min_m, max_m, .. } => box_ok(min_m, max_m),
1978 Receptor::Path {
1979 polyline_m,
1980 height_m,
1981 sample_spacing_m,
1982 ..
1983 } => {
1984 if !(2..=4097).contains(&polyline_m.len())
1985 || polyline_m.windows(2).any(|p| p[0] == p[1])
1986 || polyline_m.iter().any(|p| {
1987 !(0..2).all(|a| {
1988 p[a].is_finite() && p[a] >= 0.0 && p[a] < self.domain.size_m[a]
1989 })
1990 })
1991 {
1992 add(
1993 "CFD-E086",
1994 "error",
1995 &format!("receptors[{i}].polyline_m"),
1996 "Path needs 2..4097 finite in-domain vertices and positive-length segments.",
1997 );
1998 }
1999 if !height_m.is_finite()
2000 || *height_m < 0.0
2001 || *height_m >= self.domain.size_m[2]
2002 {
2003 add(
2004 "CFD-E086",
2005 "error",
2006 &format!("receptors[{i}].height_m"),
2007 "Path height must be finite and inside the vertical domain.",
2008 );
2009 }
2010 if !sample_spacing_m.is_finite() || *sample_spacing_m <= 0.0 {
2011 add(
2012 "CFD-E086",
2013 "error",
2014 &format!("receptors[{i}].sample_spacing_m"),
2015 "Use a finite positive maximum sample spacing.",
2016 );
2017 }
2018 let count = r.path_sample_count().unwrap_or(usize::MAX);
2019 path_samples_total = path_samples_total.saturating_add(count);
2020 if count > PATH_SAMPLES_MAX {
2021 add(
2022 "CFD-E088",
2023 "error",
2024 &format!("receptors[{i}].sample_spacing_m"),
2025 "A path may produce at most 20001 samples; increase spacing or split the study.",
2026 );
2027 }
2028 true
2029 }
2030 };
2031 if !ok {
2032 add(
2033 "CFD-E027",
2034 "error",
2035 &format!("receptors[{i}]"),
2036 "Receptor support must be nondegenerate and inside the domain.",
2037 );
2038 }
2039 }
2040 if path_samples_total > PATH_SAMPLES_TOTAL_MAX {
2041 add(
2042 "CFD-E088",
2043 "error",
2044 "receptors",
2045 "A case may produce at most 50000 total path samples.",
2046 );
2047 }
2048 if self.run.mode == Mode::Steady
2049 && !self.sources.is_empty()
2050 && !(0..3).any(|a| self.boundaries.at(a) == Boundary::Open)
2051 && !self.sources.iter().all(|source| {
2052 self.constituents
2053 .iter()
2054 .find(|sp| sp.id == source.constituent())
2055 .and_then(|sp| sp.particle.as_ref())
2056 .is_some_and(|particle| {
2057 // This is only a candidate screen. The source/grid
2058 // preflight requires a represented positive sink in
2059 // every source-bearing fluid component (CFD-E043).
2060 ((matches!(self.boundaries.z, Boundary::Wall | Boundary::GroundOpenTop)
2061 && particle.settling_speed() + particle.ground_deposition_velocity_m_s
2062 > 0.0)
2063 || (!self.geometry.is_empty()
2064 && particle.settling_speed()
2065 + particle.roof_deposition_velocity_m_s
2066 > 0.0))
2067 || self.vegetation.iter().any(|v| {
2068 v.leaf_area_density_m2_m3 > 0.0
2069 && v.leaf_deposition_velocity_m_s > 0.0
2070 })
2071 })
2072 })
2073 {
2074 add(
2075 "CFD-E020",
2076 "error",
2077 "run.mode",
2078 "Steady sources need an open removal boundary, or for particles a represented deposition sink in their fluid component.",
2079 );
2080 }
2081 CheckReport {
2082 schema_version: "cfd-craft.check/0.1".into(),
2083 valid: !d.iter().any(|d| d.severity == "error"),
2084 cells,
2085 estimated_peak_mib: peak,
2086 estimated_output_mib: output,
2087 diagnostics: d,
2088 }
2089 }
2090 /// Number of cells whose control volume intersects a box (for memory estimates).
2091 fn covered_cells(&self, lo: &[f64; 3], hi: &[f64; 3]) -> f64 {
2092 (0..3)
2093 .map(|a| {
2094 let n = self.grid.cells[a] as f64;
2095 let h = self.domain.size_m[a] / n.max(1.0);
2096 if !(h > 0.0 && lo[a].is_finite() && hi[a].is_finite()) {
2097 return 0.0;
2098 }
2099 let first = (lo[a] / h).floor().clamp(0.0, n);
2100 let last = (hi[a] / h).ceil().clamp(0.0, n);
2101 (last - first).max(0.0)
2102 })
2103 .product()
2104 }
2105 /// Best-practice domain warnings for RANS boundary-layer cases with buildings, following
2106 /// the COST 732 guideline: about 5 H_max of clearance at the inlet, sides and top, 15 H_max
2107 /// behind the buildings, and a blockage ratio below 3 %.
2108 fn domain_warnings(&self, add: &mut impl FnMut(&str, &str, &str, &str)) {
2109 let boxes: Vec<&Block> = self
2110 .geometry
2111 .iter()
2112 .filter(|b| (0..3).all(|a| b.max_m[a] > b.min_m[a]))
2113 .collect();
2114 if boxes.is_empty() {
2115 return;
2116 }
2117 let h = boxes.iter().map(|b| b.max_m[2]).fold(0.0, f64::max);
2118 let lo: [f64; 3] =
2119 std::array::from_fn(|a| boxes.iter().map(|b| b.min_m[a]).fold(f64::MAX, f64::min));
2120 let hi: [f64; 3] =
2121 std::array::from_fn(|a| boxes.iter().map(|b| b.max_m[a]).fold(0.0, f64::max));
2122 let wind = self.flow.vector(h.max(1e-9));
2123 let speed = wind[0].hypot(wind[1]).max(1e-300);
2124 // Periodic sides repeat the buildings, so clearance does not apply to them; open,
2125 // slip and wall sides all need it.
2126 for (a, name) in [(0, "x"), (1, "y")] {
2127 if self.boundaries.at(a) == Boundary::Periodic {
2128 continue;
2129 }
2130 let along = wind[a] / speed;
2131 let (low, high) = (lo[a], self.domain.size_m[a] - hi[a]);
2132 let message = if along.abs() > 0.1 {
2133 let (upstream, downstream) = if along > 0.0 {
2134 (low, high)
2135 } else {
2136 (high, low)
2137 };
2138 (upstream < 5.0 * h || downstream < 15.0 * h).then(|| format!(
2139 "Along {name} the buildings have {:.1} H_max of clearance upstream and {:.1} H_max downstream; the COST 732 guideline recommends about 5 H_max and 15 H_max.",
2140 upstream / h,
2141 downstream / h
2142 ))
2143 } else {
2144 (low.min(high) < 5.0 * h).then(|| format!(
2145 "Across the wind, along {name}, the buildings have {:.1} H_max and {:.1} H_max of lateral clearance; the COST 732 guideline recommends about 5 H_max on each side.",
2146 low / h,
2147 high / h
2148 ))
2149 };
2150 if let Some(message) = message {
2151 add(
2152 "CFD-W003",
2153 "warning",
2154 &format!("domain.size_m[{a}]"),
2155 &message,
2156 );
2157 }
2158 }
2159 if self.domain.size_m[2] - h < 5.0 * h {
2160 add(
2161 "CFD-W003",
2162 "warning",
2163 "domain.size_m[2]",
2164 &format!(
2165 "The domain top is {:.1} H_max above the tallest building; the COST 732 guideline recommends about 5 H_max.",
2166 (self.domain.size_m[2] - h) / h
2167 ),
2168 );
2169 }
2170 // Frontal area for wind along x (projection onto y-z) and along y (onto x-z),
2171 // as the union of box shadows, weighted by the wind components.
2172 let shadow = |u: usize| -> f64 {
2173 let mut edges: Vec<f64> = boxes
2174 .iter()
2175 .flat_map(|b| [b.min_m[u], b.max_m[u]])
2176 .collect();
2177 edges.sort_by(f64::total_cmp);
2178 edges.dedup();
2179 edges
2180 .windows(2)
2181 .map(|w| {
2182 let mid = 0.5 * (w[0] + w[1]);
2183 let top = boxes
2184 .iter()
2185 .filter(|b| b.min_m[u] <= mid && mid < b.max_m[u])
2186 .map(|b| b.max_m[2])
2187 .fold(0.0, f64::max);
2188 (w[1] - w[0]) * top
2189 })
2190 .sum()
2191 };
2192 let (wx, wy) = ((wind[0] / speed).abs(), (wind[1] / speed).abs());
2193 let frontal = wx * shadow(1) + wy * shadow(0);
2194 let section =
2195 (wx * self.domain.size_m[1] + wy * self.domain.size_m[0]) * self.domain.size_m[2];
2196 let blockage = frontal / section.max(1e-300);
2197 if blockage > 0.03 {
2198 add(
2199 "CFD-W002",
2200 "warning",
2201 "geometry",
2202 &format!(
2203 "The blockage ratio is about {:.1} %; the COST 732 guideline recommends below 3 %. Enlarge the domain cross-section.",
2204 100.0 * blockage
2205 ),
2206 );
2207 }
2208 }
2209 /// [`check`](Self::check) as a `Result`: the report when the case is
2210 /// valid (it may still carry warnings), otherwise an error whose text is
2211 /// the report serialized as JSON, so its codes and paths can be parsed
2212 /// back.
2213 ///
2214 /// ```
2215 /// # let json = r#"{"schema_version": "cfd-craft.case/0.1", "name": "tiny",
2216 /// # "domain": {"size_m": [4.0, 1.0, 1.0]}, "grid": {"cells": [8, 2, 2]},
2217 /// # "boundaries": {"x": "open", "y": "periodic", "z": "periodic"},
2218 /// # "flow": {"kind": "prescribed_uniform", "velocity_m_s": [1.0, 0.0, 0.0]},
2219 /// # "numerics": {"transport": "linear_upwind", "max_time_step_s": 1.0,
2220 /// # "advective_cfl_max": 0.4, "pressure_relative_tolerance": 1e-10,
2221 /// # "pressure_max_iterations": 100, "steady_residual_tolerance": 1e-5,
2222 /// # "steady_monitor_tolerance": 1e-3, "monitor_window": 10},
2223 /// # "run": {"mode": "steady", "end_time_s": 1.0, "max_steps": 1000,
2224 /// # "wall_time_limit_s": 30.0, "threads": 1, "memory_limit_mib": 64},
2225 /// # "output": {"fields": false, "checkpoint": false, "max_total_mib": 4}}"#;
2226 /// use cfd_craft::case::{Case, CheckReport};
2227 ///
2228 /// let mut case: Case = serde_json::from_str(json).unwrap();
2229 /// assert!(case.validate().is_ok());
2230 /// case.schema_version = "cfd-craft.case/9".into();
2231 /// let error = case.validate().unwrap_err();
2232 /// let report: CheckReport = serde_json::from_str(&error).unwrap();
2233 /// assert_eq!(report.diagnostics[0].code, "CFD-E001");
2234 /// assert_eq!(report.diagnostics[0].path, "schema_version");
2235 /// ```
2236 pub fn validate(&self) -> Result<CheckReport> {
2237 let r = self.check();
2238 if r.valid {
2239 Ok(r)
2240 } else {
2241 Err(serde_json::to_string(&r).unwrap())
2242 }
2243 }
2244}
2245/// Lowercase hex SHA-256 of `bytes`: the digest behind the case, physics,
2246/// state, mask, checkpoint and archive identities.
2247pub fn hash_bytes(bytes: &[u8]) -> String {
2248 format!("{:x}", Sha256::digest(bytes))
2249}