Skip to main content

cfd_craft/
solver.rs

1//! The native solve: bounded execution of a [`Case`], its state, and the
2//! result contract `cfd-craft.result/0.1`.
3//!
4//! [`run`] is the entry point. It validates the case, builds the grid and the
5//! source and receptor weights, starts from the initial state or a restart
6//! [`State`], and advances transactional steps until the steady checks pass,
7//! the transient interval is complete, or a budget, cancellation or failed
8//! step stops it. A [`Control`] supplies the wall-time allowance,
9//! cancellation, an optional external poll and optional profiling. The
10//! returned [`RunResult`] holds the [`Summary`] (the JSON result), the final
11//! state and the geometry evidence.
12//!
13//! Keep the questions of the result separate:
14//!
15//! - [`Summary::termination`] says why execution stopped: `completed`,
16//!   `iteration_limit`, `wall_time_limit`, `cancelled` or `diverged`.
17//! - [`Summary::assessment`] says what the recomputed [`Check`]s support:
18//!   `steady_discrete_solution`, `transient_interval_completed`,
19//!   `failed_checks` or `incomplete`.
20//! - [`Summary::experimental_validation`] is always `not_validated`: a
21//!   numerically accepted run is not a validated urban flow.
22//!
23//! A failed step never commits its candidate: the returned state is the last
24//! accepted one, and [`Summary::error`] records the failure. The result types
25//! derive `JsonSchema`; their doc comments are the `description` entries of
26//! the `result_schema` that `cfd-craft describe` prints. See the
27//! [result contract](https://github.com/dietmarwo/CFD-craft/blob/main/docs/result-contract.md).
28//!
29//! The lower-level functions ([`step`], [`assess`], [`timestep`],
30//! [`monitor`]) are research interfaces; they expect a grid built from the
31//! same case and state vectors of its dimensions.
32use crate::{
33    Result,
34    case::*,
35    flow,
36    grid::{GeometryEvidence, Grid},
37    pressure,
38    profiling::{Collector, Phase, Profile, Span},
39    transport,
40};
41use schemars::JsonSchema;
42use serde::{Deserialize, Serialize};
43use std::{
44    collections::BTreeMap,
45    sync::{
46        Arc,
47        atomic::{AtomicBool, Ordering},
48    },
49    time::{Duration, Instant},
50};
51
52/// Cooperative execution control of one solve: a wall-time allowance, a
53/// cancellation flag, an optional external poll and optional phase
54/// profiling.
55///
56/// The solver calls [`check`](Self::check) before every step and every eight
57/// iterations of the pressure and implicit inner solves, so cancellation is
58/// prompt but not instantaneous. The clock starts when the control is
59/// created. A stop between steps ends the run as `cancelled` or
60/// `wall_time_limit` with the last accepted state.
61///
62/// ```
63/// use cfd_craft::solver::Control;
64/// use std::sync::atomic::Ordering;
65///
66/// let control = Control::new(60.0);
67/// assert!(control.check().is_ok());
68/// control.cancelled.store(true, Ordering::Relaxed);
69/// assert_eq!(control.check().unwrap_err(), "cancelled");
70///
71/// // An external poll: any error stops the run as `cancelled`.
72/// let polled = Control::with_poll(60.0, || Err("job deadline".to_string()));
73/// assert_eq!(polled.check().unwrap_err(), "cancelled");
74/// ```
75pub struct Control {
76    /// Set to `true`, from any thread, to request cancellation. Clone the
77    /// `Arc` before starting the solve; the CLI sets it from its SIGINT and
78    /// SIGTERM handlers.
79    pub cancelled: Arc<AtomicBool>,
80    start: Instant,
81    limit: Duration,
82    external: Option<Box<dyn Fn() -> Result<()> + Send + Sync>>,
83    profiling: Option<Collector>,
84}
85impl Control {
86    /// A control with a wall-time allowance of `seconds`, counted from now,
87    /// and no poll or profiling. Pass the case's `run.wall_time_limit_s` to
88    /// reproduce the CLI's limit.
89    ///
90    /// # Panics
91    ///
92    /// If `seconds` is negative, not finite or too large for a
93    /// [`Duration`]; validate user input first ([`Case::check`] requires a
94    /// finite positive `run.wall_time_limit_s` of at most seven days).
95    pub fn new(seconds: f64) -> Self {
96        Self {
97            cancelled: Arc::new(AtomicBool::new(false)),
98            start: Instant::now(),
99            limit: Duration::from_secs_f64(seconds),
100            external: None,
101            profiling: None,
102        }
103    }
104    /// A wall-time allowance plus an external cancellation or deadline poll.
105    ///
106    /// A poll error stops the run as `cancelled`, or as `wall_time_limit` when the
107    /// poll returns exactly that text. Its own message is not kept, so a run is
108    /// never reported as diverged because an external caller stopped it.
109    ///
110    /// # Panics
111    ///
112    /// As [`new`](Self::new), for an invalid `seconds`.
113    pub fn with_poll(seconds: f64, poll: impl Fn() -> Result<()> + Send + Sync + 'static) -> Self {
114        let mut c = Self::new(seconds);
115        c.external = Some(Box::new(poll));
116        c
117    }
118    /// `Ok` while the solve may continue. Otherwise the error is exactly
119    /// `"cancelled"` (a poll error other than `"wall_time_limit"`, or the
120    /// [`cancelled`](Self::cancelled) flag) or `"wall_time_limit"` (the poll
121    /// returned that text, or the allowance is used up). The poll runs first.
122    pub fn check(&self) -> Result<()> {
123        if let Some(poll) = &self.external {
124            poll().map_err(|e| {
125                if e == "wall_time_limit" {
126                    e
127                } else {
128                    "cancelled".to_string()
129                }
130            })?;
131        }
132        if self.cancelled.load(Ordering::Relaxed) {
133            Err("cancelled".into())
134        } else if self.start.elapsed() >= self.limit {
135            Err("wall_time_limit".into())
136        } else {
137            Ok(())
138        }
139    }
140    /// Wall seconds since the control was created; reported as the summary's
141    /// `elapsed_s`.
142    pub fn elapsed(&self) -> f64 {
143        self.start.elapsed().as_secs_f64()
144    }
145    /// Enable phase measurements without changing case or result schemas.
146    /// Read them with [`profile`](Self::profile) after the solve; see the
147    /// [`profiling`](crate::profiling) module.
148    pub fn with_profiling(mut self) -> Self {
149        self.profiling = Some(Collector::default());
150        self
151    }
152    /// Start timing `phase` until the returned [`Span`] is dropped. Spans
153    /// must finish in nested order on the thread that started them. Without
154    /// [`with_profiling`](Self::with_profiling) the span is disabled and
155    /// costs neither a clock read nor a lock.
156    pub fn span(&self, phase: Phase) -> Span {
157        self.profiling
158            .as_ref()
159            .map_or_else(Span::disabled, |p| p.span(phase))
160    }
161    /// Snapshot after every span has finished; work includes failed attempts.
162    ///
163    /// `Ok(None)` without [`with_profiling`](Self::with_profiling). An
164    /// active or out-of-order span is an error, `CFD-B003 profile.active` or
165    /// `CFD-B003 profile.nesting`.
166    ///
167    /// ```
168    /// use cfd_craft::{profiling::Phase, solver::Control};
169    ///
170    /// assert!(Control::new(10.0).profile().unwrap().is_none());
171    /// let control = Control::new(10.0).with_profiling();
172    /// drop(control.span(Phase::Monitor));
173    /// let profile = control.profile().unwrap().expect("profiling enabled");
174    /// assert_eq!(profile.schema_version, "cfd-craft.phase-profile/0.1");
175    /// assert_eq!(profile.phases["monitor"].calls, 1);
176    /// ```
177    pub fn profile(&self) -> Result<Option<Profile>> {
178        self.profiling
179            .as_ref()
180            .map(|p| p.snapshot(self.elapsed()))
181            .transpose()
182    }
183}
184/// Cumulative mass budget of one constituent, in kg. At any accepted state
185/// the mass in the domain should equal `initial_kg + emitted_kg + inflow_kg -
186/// outflow_kg`; the `mass_budget` check bounds the relative defect. Every
187/// entry is finite and nonnegative.
188#[derive(Clone, Debug, Serialize, Deserialize)]
189#[serde(deny_unknown_fields)]
190pub struct Budget {
191    /// Mass at the cold start of the calculation; restarts keep it.
192    pub initial_kg: f64,
193    /// Mass emitted by the sources so far.
194    pub emitted_kg: f64,
195    /// Mass that entered through boundary faces so far.
196    pub inflow_kg: f64,
197    /// Mass that left through boundary faces so far.
198    pub outflow_kg: f64,
199    /// Cumulative removed particle mass by surface class, including restarts.
200    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
201    pub deposited_kg: BTreeMap<String, f64>,
202}
203/// The complete solver state: what fields.json archives and a checkpoint
204/// restores. Vectors follow the grid layout of [`Grid`]: one value per face
205/// (in `Grid::faces` order) or per cell (x fastest), with solid cells
206/// included. Counters are cumulative from the cold start, across restarts.
207///
208/// [`validate_state`] checks a state against a case before it is used.
209#[derive(Clone, Debug, Serialize, Deserialize)]
210#[serde(deny_unknown_fields)]
211pub struct State {
212    /// Accepted steps, or outer iterations with an implicit steady algorithm.
213    pub steps: usize,
214    /// Time covered in seconds: physical time in transient mode, pseudo-time
215    /// in steady mode.
216    pub time_s: f64,
217    /// Face-normal velocity of every face in m/s, the native staggered field.
218    pub velocity: Vec<f64>,
219    /// Kinematic pressure of every cell in m2/s2, with a mean-zero gauge in
220    /// each fluid component without an outlet.
221    pub pressure: Vec<f64>,
222    /// Turbulent kinetic energy of every cell in m2/s2; zero without
223    /// `neutral_rans` and in solid cells.
224    pub k: Vec<f64>,
225    /// Dissipation rate of every cell in m2/s3; zero without `neutral_rans`
226    /// and in solid cells.
227    pub epsilon: Vec<f64>,
228    /// Concentration fields in kg/m3, one per constituent in case order, one
229    /// value per cell (always zero in solid cells).
230    pub concentrations: Vec<Vec<f64>>,
231    /// Mass budget of each constituent, in case order.
232    pub budgets: Vec<Budget>,
233    /// Turbulence updates that hit the 1e-14 floor of k or epsilon; any
234    /// event fails the `turbulence_floor_events` check.
235    pub floor_events: usize,
236    /// Pressure PCG iterations of the retained steps, including the initial
237    /// projection.
238    pub pressure_iterations: usize,
239    /// Inner iterations of implicit momentum-correction solves; omitted when
240    /// zero, so explicit checkpoints keep their bytes.
241    #[serde(default, skip_serializing_if = "is_zero")]
242    pub momentum_solver_iterations: usize,
243    /// Pseudo-time the constituents have covered, when it differs from
244    /// `time_s`: an implicit steady algorithm advances them in at most
245    /// `SCALAR_SUBSTEPS_MAX` explicit stable sub-steps per outer iteration.
246    /// Emitted mass is the source rate times this time. Omitted (and equal to
247    /// `time_s`) for explicit runs, so their checkpoints keep their bytes.
248    #[serde(default, skip_serializing_if = "Option::is_none")]
249    pub scalar_time_s: Option<f64>,
250    /// The last monitor rows, at most three monitor windows, one per step:
251    /// see [`monitor`] for the columns. They feed the `monitor_stability`
252    /// check of steady runs.
253    pub monitor_history: Vec<Vec<f64>>,
254}
255fn is_zero(v: &usize) -> bool {
256    *v == 0
257}
258/// One numerical check, recomputed by the solver from the current fields. A
259/// check passes when its value is finite and at most its threshold.
260/// Continuity and residual values are normalized with the case's velocity and
261/// length scales (`neutral_rans`: `speed_m_s` and `reference_height_m`;
262/// otherwise the reference speed, at least 1 m/s, and the shortest domain
263/// side).
264#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
265#[serde(deny_unknown_fields)]
266pub struct Check {
267    /// What is checked: `local_continuity`, `boundary_volume_balance`,
268    /// `steady_momentum_equations`, `steady_turbulence_equations`,
269    /// `turbulence_floor_events`, `monitor_stability`, or per constituent
270    /// `<id>.mass_budget`, `<id>.negative_mass`, `<id>.steady_equation` and
271    /// `<id>.steady_mass_balance`. The steady checks appear in steady mode
272    /// only, the turbulence checks with `neutral_rans` only.
273    pub name: String,
274    /// The measured value, or null when it is not finite or not available,
275    /// such as `monitor_stability` before three full monitor windows. A null
276    /// value fails.
277    pub value: Option<f64>,
278    /// Largest accepted value, a fixed gate or the tolerance from the case.
279    pub threshold: f64,
280    /// Whether the value is finite and at most the threshold.
281    pub passed: bool,
282    /// How the value was obtained, for example `application recomputation
283    /// from current fields`.
284    pub method: String,
285}
286/// Evidence for one constituent at the returned state: mass budget,
287/// extrema, the steady residual, instantaneous rates and receptor values.
288/// Cumulative quantities are in kg, rates in kg/s, concentrations in kg/m3.
289#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
290#[serde(deny_unknown_fields)]
291pub struct ScalarEvidence {
292    /// The constituent ID.
293    pub id: String,
294    /// Mass in the domain, the sum of concentration times cell volume.
295    pub mass_kg: f64,
296    /// Cumulative mass emitted by the sources.
297    pub emitted_kg: f64,
298    /// Cumulative mass that entered through boundary faces.
299    pub inflow_kg: f64,
300    /// Cumulative mass that left through boundary faces.
301    pub outflow_kg: f64,
302    /// Cumulative particle deposition by surface class, in kg.
303    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
304    pub deposited_kg: BTreeMap<String, f64>,
305    /// Current deposition rate by surface class, in kg/s.
306    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
307    pub deposition_rate_kg_s: BTreeMap<String, f64>,
308    /// Resolved particle settling speed; omitted for gases.
309    #[serde(default, skip_serializing_if = "Option::is_none")]
310    pub settling_velocity_m_s: Option<f64>,
311    /// Unit-density equivalent aerodynamic diameter used for PM sums.
312    #[serde(default, skip_serializing_if = "Option::is_none")]
313    pub aerodynamic_diameter_m: Option<f64>,
314    /// `mass_kg` minus initial, emitted and inflow mass plus outflow mass.
315    pub budget_defect_kg: f64,
316    /// Absolute budget defect over the sum of initial, emitted, inflow and
317    /// outflow mass; the `mass_budget` check requires at most 1e-9.
318    pub relative_budget_defect: f64,
319    /// Smallest concentration over the fluid cells.
320    pub minimum_kg_m3: f64,
321    /// Largest concentration over all cells, at least 0.
322    pub maximum_kg_m3: f64,
323    /// Mass of the negative concentrations, as a positive number; never
324    /// clipped.
325    pub negative_mass_kg: f64,
326    /// Largest steady-equation residual |dc/dt| over the cells, normalized by
327    /// the velocity scale, the length scale and `maximum_kg_m3`.
328    pub steady_residual: f64,
329    /// Emission rate of the represented sources.
330    pub source_rate_kg_s: f64,
331    /// Current rate of mass entering through boundary faces.
332    pub boundary_inflow_rate_kg_s: f64,
333    /// Current rate of mass leaving through boundary faces.
334    pub boundary_outflow_rate_kg_s: f64,
335    /// Concentration at each receptor, keyed by receptor ID. JSON maps are
336    /// sorted lexically (`R10` before `R2`), so look values up by ID.
337    pub receptors_kg_m3: BTreeMap<String, f64>,
338    /// Ordered path samples and their arc-length means, keyed by path ID.
339    /// Omitted when no path receptor is declared, preserving legacy output bytes.
340    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
341    pub paths: BTreeMap<String, PathEvidence>,
342}
343/// A path receptor sampled from one constituent's returned concentration field.
344#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
345#[serde(deny_unknown_fields)]
346pub struct PathEvidence {
347    /// Local east/north/up positions in meters, in route order.
348    pub points_m: Vec<[f64; 3]>,
349    /// Arc length from the first route vertex, in meters.
350    pub distance_m: Vec<f64>,
351    /// Linear-interpolated concentration increments, in kg/m3.
352    pub concentrations_kg_m3: Vec<f64>,
353    /// Arc-length trapezoidal mean, also in receptors_kg_m3 for this ID.
354    pub mean_kg_m3: f64,
355}
356/// Sum over particle bins passing an aerodynamic-size cutoff.
357#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
358#[serde(deny_unknown_fields)]
359pub struct ParticulateEvidence {
360    /// Integrated airborne mass, in kg.
361    pub mass_kg: f64,
362    /// Local-source concentration increments at receptors, in kg/m3.
363    pub receptors_kg_m3: BTreeMap<String, f64>,
364}
365/// The result of one native run (schema `cfd-craft.result/0.1`), written as
366/// summary.json: identities, the stopping reason and numerical verdict, work
367/// counters, geometry, the recomputed checks and per-constituent evidence.
368/// `termination` says why execution stopped; `assessment` says what the
369/// checks support; experimental validation is a separate question. Null
370/// means unavailable in the stated context, not zero.
371#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
372#[serde(deny_unknown_fields)]
373pub struct Summary {
374    /// Always `cfd-craft.result/0.1`.
375    pub schema_version: String,
376    /// The case name.
377    pub name: String,
378    /// SHA-256 of the consumed, normalized case as compact JSON.
379    pub case_sha256: String,
380    /// Physics hash of the case: the case without `name`, `run` and
381    /// `output`. Checkpoints are compatible across cases with the same value.
382    pub physics_sha256: String,
383    /// SHA-256 of the starting state (cold or restored), so restarts from
384    /// different states stay distinguishable.
385    pub initial_state_sha256: String,
386    /// Why execution stopped: `completed`, `iteration_limit` (step budget),
387    /// `wall_time_limit`, `cancelled` or `diverged` (a failed step, recorded
388    /// in `error`).
389    pub termination: String,
390    /// Numerical verdict: `steady_discrete_solution` or
391    /// `transient_interval_completed` (completed with every check passed),
392    /// `failed_checks` (completed, some check failed) or `incomplete` (any
393    /// other termination). Never upgraded because the last state looks
394    /// reasonable.
395    pub assessment: String,
396    /// The failure that stopped the run, usually with its code (for example
397    /// `CFD-E033: pressure iteration limit 100`), or `cancelled` /
398    /// `wall_time_limit` when the stop came inside a step; null otherwise.
399    pub error: Option<String>,
400    /// Model label: `incompressible_laminar`,
401    /// `prescribed_flow_passive_transport` or `neutral_k_epsilon_rough_wall`;
402    /// the CLI prefixes `preview: ` for a coarsened preview.
403    pub model_scope: String,
404    /// Always `not_validated; see validation/data-inventory.json`: numerical
405    /// acceptance is not experimental validation.
406    pub experimental_validation: String,
407    /// Retained steps (outer iterations with an implicit steady algorithm),
408    /// cumulative across restarts.
409    pub steps: usize,
410    /// Time covered in seconds; pseudo-time in steady mode.
411    pub physical_time_s: f64,
412    /// Wall seconds of this invocation, from the creation of its control.
413    pub elapsed_s: f64,
414    /// Cumulative pressure PCG iterations of the retained steps.
415    pub pressure_iterations: usize,
416    /// Inner iterations of implicit momentum-correction solves, when selected.
417    #[serde(default, skip_serializing_if = "Option::is_none")]
418    pub momentum_solver_iterations: Option<usize>,
419    /// Turbulence updates that hit the k or epsilon floor; any event fails
420    /// the turbulence checks.
421    pub turbulent_floor_events: usize,
422    /// Number of fluid cells.
423    pub fluid_cells: usize,
424    /// Number of solid cells.
425    pub solid_cells: usize,
426    /// Number of face-connected fluid regions, each with its own pressure
427    /// gauge unless it touches an outlet.
428    pub fluid_components: usize,
429    /// SHA-256 of the cell mask, one byte per cell (1 fluid, 0 solid) in
430    /// cell order; also in geometry.json.
431    pub mask_sha256: String,
432    /// The preflight memory estimate of the case check, in MiB.
433    pub estimated_peak_mib: f64,
434    /// Every recomputed check of the returned state.
435    pub checks: Vec<Check>,
436    /// Evidence for each constituent, in case order.
437    pub constituents: Vec<ScalarEvidence>,
438    /// PM2.5/PM10 airborne mass and receptor sums for spherical particle bins.
439    /// No interpolation within a bin: its representative aerodynamic diameter
440    /// is either below the cutoff or excluded. Omitted without particles.
441    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
442    pub particulate_matter: BTreeMap<String, ParticulateEvidence>,
443    /// Recomputed porous canopy drag/coverage, absent without nonzero LAD.
444    #[serde(default, skip_serializing_if = "Option::is_none")]
445    pub vegetation: Option<crate::vegetation::Evidence>,
446    /// Largest absolute face velocity in m/s.
447    pub velocity_max_m_s: f64,
448    /// Largest normalized momentum residual, null for prescribed flow.
449    pub momentum_residual: Option<f64>,
450    /// Largest normalized k or epsilon residual, `neutral_rans` only.
451    pub turbulence_residual: Option<f64>,
452    /// Largest relative change between the means of three successive monitor
453    /// windows over all monitor columns (flow norm, constituent masses,
454    /// receptor values and, with `neutral_rans`, mean k and epsilon); null
455    /// before three full windows. The `monitor_stability` value of steady
456    /// runs.
457    pub receptor_relative_change: Option<f64>,
458    /// Source fingerprint of the producing build. A library run reports the
459    /// core crate's; the CLI and the Python binding combine it with their own.
460    pub source_sha256: String,
461    /// Package version and compiler of the producing build, as
462    /// `<version>; <rustc version>`.
463    pub build_version: String,
464    /// The case's declared `run.threads`, not a measurement of the pool.
465    pub threads: usize,
466    /// Optional verified fixed-flow initialization and zero-flow-update evidence.
467    /// Ordinary coupled runs omit this field.
468    #[serde(default, skip_serializing_if = "Option::is_none")]
469    pub frozen_flow: Option<crate::mobile_response::FrozenFlowEvidence>,
470}
471/// The cold-start state of a case: face velocities from
472/// [`Flow::vector`], zero pressure, the `neutral_rans` equilibrium k and
473/// epsilon in fluid cells, the initial concentrations and their initial
474/// masses, and zero counters.
475pub fn initial_state(c: &Case, g: &Grid) -> State {
476    let concentrations = transport::initial_fields(c, g);
477    let budgets = concentrations
478        .iter()
479        .map(|v| Budget {
480            initial_kg: v.iter().sum::<f64>() * g.volume,
481            emitted_kg: 0.0,
482            inflow_kg: 0.0,
483            outflow_kg: 0.0,
484            deposited_kg: BTreeMap::new(),
485        })
486        .collect();
487    let k = (0..g.count())
488        .map(|i| {
489            if g.fluid[i] {
490                c.flow.turbulence(g.center(i)[2]).0
491            } else {
492                0.0
493            }
494        })
495        .collect();
496    let epsilon = (0..g.count())
497        .map(|i| {
498            if g.fluid[i] {
499                c.flow.turbulence(g.center(i)[2]).1
500            } else {
501                0.0
502            }
503        })
504        .collect();
505    State {
506        steps: 0,
507        time_s: 0.0,
508        velocity: g.initial_velocity(c),
509        pressure: vec![0.0; g.count()],
510        k,
511        epsilon,
512        concentrations,
513        budgets,
514        floor_events: 0,
515        pressure_iterations: 0,
516        momentum_solver_iterations: 0,
517        scalar_time_s: None,
518        monitor_history: vec![],
519    }
520}
521/// Checks that a state fits the case and grid before it is used, for example
522/// a restart: vector dimensions (`CFD-E050`), finite values, nonnegative k,
523/// epsilon and budgets, a `scalar_time_s` within `time_s`, a finite monitor
524/// history, and zero concentration in solid cells (all `CFD-E051`). It does
525/// not check the physics identity; [`output::read_checkpoint`](crate::output::read_checkpoint)
526/// does that.
527pub fn validate_state(c: &Case, g: &Grid, s: &State) -> Result<()> {
528    validate_with_history(c, g, s, &s.monitor_history)
529}
530fn validate_with_history(c: &Case, g: &Grid, s: &State, history: &[Vec<f64>]) -> Result<()> {
531    if s.velocity.len() != g.faces.len()
532        || s.pressure.len() != g.count()
533        || s.k.len() != g.count()
534        || s.epsilon.len() != g.count()
535        || s.concentrations.len() != c.constituents.len()
536        || s.budgets.len() != c.constituents.len()
537        || s.concentrations.iter().any(|v| v.len() != g.count())
538    {
539        return Err("CFD-E050: checkpoint dimensions do not match case".into());
540    }
541    if !s.time_s.is_finite()
542        || s.time_s < 0.0
543        || s.scalar_time_s
544            .is_some_and(|t| !t.is_finite() || t < 0.0 || t > s.time_s * (1.0 + 1e-12) + 1e-300)
545        || s.velocity
546            .iter()
547            .chain(&s.pressure)
548            .chain(&s.k)
549            .chain(&s.epsilon)
550            .chain(s.concentrations.iter().flatten())
551            .any(|v| !v.is_finite())
552        || s.k.iter().chain(&s.epsilon).any(|v| *v < 0.0)
553        || s.budgets.iter().any(|b| {
554            [b.initial_kg, b.emitted_kg, b.inflow_kg, b.outflow_kg]
555                .iter()
556                .any(|v| !v.is_finite() || *v < 0.0)
557                || b.deposited_kg.iter().any(|(surface, v)| {
558                    !matches!(surface.as_str(), "ground" | "roof" | "vegetation")
559                        || !v.is_finite()
560                        || *v < 0.0
561                })
562        })
563        || history.iter().flatten().any(|v| !v.is_finite())
564    {
565        return Err("CFD-E051: nonfinite or invalid state".into());
566    }
567    if c.constituents
568        .iter()
569        .zip(&s.budgets)
570        .any(|(sp, b)| sp.particle.is_none() && !b.deposited_kg.is_empty())
571    {
572        return Err(
573            "CFD-E051: budgets.deposited_kg: passive gas cannot have particle deposition".into(),
574        );
575    }
576    // Transport never changes a solid cell, so a state with mass there is not one it produced.
577    if s.concentrations
578        .iter()
579        .any(|v| v.iter().zip(&g.fluid).any(|(x, fluid)| !fluid && *x != 0.0))
580    {
581        return Err("CFD-E051: nonzero concentration in a solid cell".into());
582    }
583    Ok(())
584}
585pub(crate) fn diffusivity(c: &Case, nut: &[f64], s: usize) -> Vec<f64> {
586    let sc = if let Flow::NeutralRans {
587        turbulent_schmidt, ..
588    } = &c.flow
589    {
590        *turbulent_schmidt
591    } else {
592        1.0
593    };
594    nut.iter()
595        .map(|n| c.constituents[s].diffusivity_m2_s + n / sc)
596        .collect()
597}
598/// The next stable time step in seconds for the case's steady algorithm,
599/// capped by `numerics.max_time_step_s`. `explicit` limits advection and
600/// diffusion together with `numerics.advective_cfl_max` (at most 0.45),
601/// `implicit_viscous` limits advection only, and `implicit_projection`
602/// follows the CFL ramp of
603/// [`momentum_solve::ramp_cfl`](crate::momentum_solve::ramp_cfl). `nut` is
604/// the eddy viscosity per cell ([`flow::eddy_viscosity`]). [`run`] clips the
605/// step to the end time of a transient run.
606pub fn timestep(c: &Case, g: &Grid, s: &State, nut: &[f64]) -> f64 {
607    timestep_for(c.numerics.steady_algorithm, c, g, s, nut)
608}
609pub(crate) fn timestep_for(
610    algorithm: SteadyAlgorithm,
611    c: &Case,
612    g: &Grid,
613    s: &State,
614    nut: &[f64],
615) -> f64 {
616    let mut umax = [0.0f64; 3];
617    for (f, u) in g.faces.iter().zip(&s.velocity) {
618        umax[f.axis] = umax[f.axis].max(u.abs());
619    }
620    let adv = (0..3).map(|a| umax[a] / g.dx[a]).sum::<f64>();
621    let maxnut = nut.iter().copied().fold(0.0, f64::max);
622    let sc = if let Flow::NeutralRans {
623        turbulent_schmidt, ..
624    } = &c.flow
625    {
626        *turbulent_schmidt
627    } else {
628        1.0
629    };
630    let dmax = c
631        .constituents
632        .iter()
633        .map(|x| x.diffusivity_m2_s + maxnut / sc)
634        .fold(c.flow.viscosity() + maxnut, f64::max);
635    let diffusion = 2.0 * dmax * g.dx.iter().map(|h| 1.0 / (h * h)).sum::<f64>();
636    // Settling and surface deposition share the forward-Euler positivity
637    // allowance with advection/diffusion; SSPRK2 retains that same bound.
638    let particle_loss = c
639        .constituents
640        .iter()
641        .filter_map(|sp| sp.particle.as_ref())
642        .map(|p| {
643            (p.settling_speed()
644                + p.ground_deposition_velocity_m_s
645                    .max(p.roof_deposition_velocity_m_s))
646                / g.dx[2]
647        })
648        .fold(0.0, f64::max);
649    let leaf_loss = if c.constituents.iter().any(|sp| sp.particle.is_some()) {
650        crate::vegetation::maximum_leaf_loss(c, g)
651    } else {
652        0.0
653    };
654    match algorithm {
655        SteadyAlgorithm::Explicit => c.numerics.max_time_step_s.min(
656            c.numerics.advective_cfl_max.min(0.45)
657                / (adv + diffusion + particle_loss + leaf_loss).max(1e-30),
658        ),
659        // Implicit viscosity removes the diffusive limit; advection stays explicit.
660        SteadyAlgorithm::ImplicitViscous => c
661            .numerics
662            .max_time_step_s
663            .min(c.numerics.advective_cfl_max.min(0.45) / adv.max(1e-30)),
664        // A deterministic CFL ramp from the outer-iteration count; restarts need no state.
665        SteadyAlgorithm::ImplicitProjection => c
666            .numerics
667            .max_time_step_s
668            .min(crate::momentum_solve::ramp_cfl(s.steps) / adv.max(1e-30)),
669    }
670}
671fn flow_euler(
672    c: &Case,
673    g: &Grid,
674    u: &[f64],
675    p: &[f64],
676    nut: &[f64],
677    dt: f64,
678    control: &Control,
679) -> Result<(Vec<f64>, Vec<f64>, usize, usize)> {
680    let rhs = {
681        let _phase = control.span(Phase::MomentumRhs);
682        flow::momentum_rhs(c, g, u, nut)
683    };
684    let velocity_update = control.span(Phase::VelocityUpdate);
685    let grad = g.gradient(p);
686    let drag = crate::vegetation::face_drag(c, g, u);
687    let mut inner = 0;
688    let mut v: Vec<_> = if c.numerics.steady_algorithm == SteadyAlgorithm::ImplicitViscous {
689        // Delta form: (I - dt L_nu) delta = dt R with the full steady residual R.
690        let b: Vec<_> = rhs.iter().zip(&grad).map(|(r, p)| dt * (r - p)).collect();
691        let stencil = g
692            .momentum_stencil
693            .get_or_init(|| crate::momentum_solve::Stencil::build(c, g));
694        let (delta, info) = crate::momentum_solve::solve_viscous_with_drag(
695            stencil,
696            c.flow.viscosity(),
697            dt,
698            &b,
699            &drag,
700            control,
701        )?;
702        inner = info.iterations;
703        u.iter().zip(delta).map(|(u, d)| u + d).collect()
704    } else {
705        u.iter()
706            .zip(rhs)
707            .zip(grad)
708            .enumerate()
709            .map(|(i, ((u, r), p))| {
710                if drag.is_empty() {
711                    u + dt * (r - p)
712                } else {
713                    u + dt * (r - p) / (1.0 + dt * drag[i])
714                }
715            })
716            .collect()
717    };
718    g.enforce_velocity(c, &mut v);
719    let mut pp = p.to_vec();
720    drop(velocity_update);
721    let info = pressure::project(
722        g,
723        &mut v,
724        &mut pp,
725        dt,
726        c.numerics.pressure_relative_tolerance,
727        c.numerics.pressure_max_iterations,
728        control,
729    )?;
730    g.enforce_velocity(c, &mut v);
731    Ok((v, pp, info.iterations, inner))
732}
733/// One outer iteration of the implicit steady algorithm (P5a), in delta form:
734/// A δ = R(u, p), u* = u + δ, then a projection at the pseudo-time step. At a
735/// fixed point δ = 0 and the projection's correction is zero, so R = 0 and the
736/// velocity is solenoidal, which is what `assess` checks.
737fn implicit_iteration(
738    c: &Case,
739    g: &Grid,
740    u: &[f64],
741    p: &[f64],
742    nut: &[f64],
743    dt: f64,
744    control: &Control,
745) -> Result<(Vec<f64>, Vec<f64>, usize, usize)> {
746    let rhs = {
747        let _phase = control.span(Phase::MomentumRhs);
748        flow::momentum_rhs(c, g, u, nut)
749    };
750    let velocity_update = control.span(Phase::VelocityUpdate);
751    let residual: Vec<_> = rhs.iter().zip(g.gradient(p)).map(|(r, p)| r - p).collect();
752    let stencil = g
753        .momentum_stencil
754        .get_or_init(|| crate::momentum_solve::Stencil::build(c, g));
755    let mut matrix = if c.flow.rans() {
756        stencil.implicit_matrix_rans(c, g, u, nut, dt)
757    } else {
758        stencil.implicit_matrix(u, c.flow.viscosity(), dt)
759    };
760    matrix.add_drag(&crate::vegetation::face_drag(c, g, u));
761    drop(velocity_update);
762    let (delta, info) =
763        crate::momentum_solve::solve_implicit(stencil, &matrix, &residual, control)?;
764    let mut v: Vec<_> = u.iter().zip(delta).map(|(u, d)| u + d).collect();
765    g.enforce_velocity(c, &mut v);
766    let mut pp = p.to_vec();
767    let projection = pressure::project(
768        g,
769        &mut v,
770        &mut pp,
771        dt,
772        c.numerics.pressure_relative_tolerance,
773        c.numerics.pressure_max_iterations,
774        control,
775    )?;
776    g.enforce_velocity(c, &mut v);
777    Ok((v, pp, projection.iterations, info.iterations))
778}
779/// Cap on explicit scalar sub-steps per implicit outer iteration (P5d). The
780/// constituents then advance by at most this many explicit stable steps per
781/// outer iteration; their steady state does not depend on the step sizes.
782pub const SCALAR_SUBSTEPS_MAX: usize = 16;
783
784/// Sub-step count and size for a pseudo-time step `dt` with explicit stable
785/// step `stable`: the fewest equal sub-steps of at most `stable`, capped at
786/// `SCALAR_SUBSTEPS_MAX` steps of size `stable`.
787pub fn scalar_substeps(dt: f64, stable: f64) -> (usize, f64) {
788    let needed = (dt / stable).ceil();
789    if needed <= SCALAR_SUBSTEPS_MAX as f64 {
790        let n = (needed as usize).max(1);
791        (n, dt / n as f64)
792    } else {
793        (SCALAR_SUBSTEPS_MAX, stable)
794    }
795}
796
797/// Reused buffers of the SSPRK2 scalar step.
798#[derive(Default)]
799pub(crate) struct ScalarBuffers {
800    r1: Vec<f64>,
801    stage: Vec<f64>,
802    r2: Vec<f64>,
803}
804
805/// One SSPRK2 step of scalar transport, with its budget increments, written
806/// into `concentration` in place.
807#[allow(clippy::too_many_arguments)]
808pub(crate) fn advance_scalar(
809    c: &Case,
810    g: &Grid,
811    species: usize,
812    concentration: &mut [f64],
813    velocity: &[f64],
814    d: &[f64],
815    source: &[f64],
816    dt: f64,
817    budget: &mut Budget,
818    buffers: &mut ScalarBuffers,
819    fixed: Option<&transport::FixedRhs>,
820) {
821    let ScalarBuffers { r1, stage, r2 } = buffers;
822    // Linear upwind with a fixed flow: evaluate from the gathered faces.
823    let fixed = fixed.filter(|_| c.numerics.transport == crate::case::Advection::LinearUpwind);
824    let rhs = |x: &[f64], out: &mut Vec<f64>| {
825        let (emitted, inflow, mut outflow) = match fixed {
826            Some(op) => op.eval(x, source, out),
827            None => transport::rhs_into(
828                g,
829                x,
830                velocity,
831                d,
832                source,
833                c.numerics.transport,
834                |_| 0.0,
835                out,
836            ),
837        };
838        let mut deposited = BTreeMap::new();
839        if let Some(particle) = &c.constituents[species].particle {
840            let (leaving, surfaces) = transport::particle_terms(c, g, particle, x, out);
841            outflow += leaving;
842            deposited = surfaces;
843            let leaves = crate::vegetation::leaf_terms(c, g, x, out);
844            if leaves != 0.0 {
845                deposited.insert("vegetation".into(), leaves);
846            }
847        }
848        (emitted, inflow, outflow, deposited)
849    };
850    let (source1, inflow1, outflow1, deposition1) = rhs(concentration, r1);
851    stage.clear();
852    stage.extend(concentration.iter().zip(r1.iter()).map(|(a, b)| a + dt * b));
853    let (source2, inflow2, outflow2, deposition2) = rhs(stage, r2);
854    for ((a, b), r) in concentration.iter_mut().zip(stage.iter()).zip(r2.iter()) {
855        *a = 0.5 * (*a + b + dt * r);
856    }
857    budget.emitted_kg += 0.5 * dt * (source1 + source2);
858    budget.inflow_kg += 0.5 * dt * (inflow1 + inflow2);
859    budget.outflow_kg += 0.5 * dt * (outflow1 + outflow2);
860    for (surface, rate) in deposition1.into_iter().chain(deposition2) {
861        *budget.deposited_kg.entry(surface).or_insert(0.0) += 0.5 * dt * rate;
862    }
863}
864
865/// Advances `s` by one step (one outer iteration with an implicit steady
866/// algorithm) of size `dt`, transactionally.
867///
868/// The candidate state is built beside `s`: flow (SSPRK2 with a projection
869/// per stage, or one implicit correction and projection), turbulence and the
870/// constituents with their budgets. It replaces `s` only when every gate
871/// passes, so on `Err` the state is unchanged. `sources` are the source
872/// densities of [`transport::source_fields`], one per constituent; a shorter
873/// slice leaves the remaining constituents unchanged. Errors are the
874/// control's `"cancelled"` / `"wall_time_limit"`, or a coded failure such as
875/// `CFD-E033` (pressure limit), `CFD-E051` (nonfinite state), `CFD-E052`
876/// (velocity divergence) or `CFD-E053` (negative concentration).
877///
878/// The monitor history is not updated; [`run`] appends [`monitor`] rows.
879pub fn step(
880    c: &Case,
881    g: &Grid,
882    s: &mut State,
883    sources: &[Vec<f64>],
884    dt: f64,
885    control: &Control,
886) -> Result<()> {
887    let _step = control.span(Phase::Step);
888    control.check()?;
889    let nut = flow::eddy_viscosity(g, &s.k, &s.epsilon);
890    // Build the next state off to the side: pressure/cancellation failure cannot publish half a step.
891    let mut next = State {
892        steps: s.steps,
893        time_s: s.time_s,
894        velocity: if c.flow.prescribed() {
895            s.velocity.clone()
896        } else {
897            Vec::new()
898        },
899        pressure: if c.flow.prescribed() {
900            s.pressure.clone()
901        } else {
902            Vec::new()
903        },
904        k: s.k.clone(),
905        epsilon: s.epsilon.clone(),
906        concentrations: Vec::with_capacity(s.concentrations.len()),
907        budgets: s.budgets.clone(),
908        floor_events: s.floor_events,
909        pressure_iterations: s.pressure_iterations,
910        momentum_solver_iterations: s.momentum_solver_iterations,
911        scalar_time_s: s.scalar_time_s,
912        monitor_history: Vec::new(),
913    };
914    if c.numerics.steady_algorithm == SteadyAlgorithm::ImplicitProjection {
915        let (v, p, n, m) = implicit_iteration(c, g, &s.velocity, &s.pressure, &nut, dt, control)?;
916        next.velocity = v;
917        next.pressure = p;
918        next.pressure_iterations += n;
919        next.momentum_solver_iterations += m;
920        if c.flow.rans() {
921            let _phase = control.span(Phase::Turbulence);
922            let info = crate::turbulence_solve::implicit_step(
923                c,
924                g,
925                &next.velocity,
926                &mut next.k,
927                &mut next.epsilon,
928                dt,
929                control,
930            )?;
931            next.floor_events += info.floor_events;
932        }
933    } else if !c.flow.prescribed() {
934        let (v, p, n1, m1) = flow_euler(c, g, &s.velocity, &s.pressure, &nut, dt, control)?;
935        let (v2, p2, n2, m2) = flow_euler(c, g, &v, &p, &nut, dt, control)?;
936        next.momentum_solver_iterations += m1 + m2;
937        next.velocity = s
938            .velocity
939            .iter()
940            .zip(v2)
941            .map(|(a, b)| 0.5 * (a + b))
942            .collect();
943        next.pressure = p2;
944        g.enforce_velocity(c, &mut next.velocity);
945        next.pressure_iterations += n1 + n2;
946        if c.flow.rans() {
947            let _phase = control.span(Phase::Turbulence);
948            next.floor_events +=
949                flow::turbulence_step(c, g, &next.velocity, &mut next.k, &mut next.epsilon, dt);
950        }
951    }
952    if !sources.is_empty() {
953        // The implicit steady algorithm's pseudo-time step exceeds the explicit
954        // transport limits, so constituents advance in explicit sub-steps (P5d).
955        let (substeps, sub_dt) = if c.numerics.steady_algorithm == SteadyAlgorithm::Explicit {
956            (1, dt)
957        } else {
958            scalar_substeps(
959                dt,
960                timestep_for(SteadyAlgorithm::Explicit, c, g, &next, &nut),
961            )
962        };
963        for (j, source) in sources.iter().enumerate() {
964            let _phase = control.span(Phase::ScalarTransport);
965            let d = diffusivity(c, &nut, j);
966            let mut concentration = s.concentrations[j].clone();
967            let mut buffers = ScalarBuffers::default();
968            // Several sub-steps share one flow: gather its faces once.
969            let fixed = (substeps > 1
970                && c.numerics.transport == crate::case::Advection::LinearUpwind)
971                .then(|| transport::FixedRhs::new(g, &next.velocity, &d));
972            for _ in 0..substeps {
973                advance_scalar(
974                    c,
975                    g,
976                    j,
977                    &mut concentration,
978                    &next.velocity,
979                    &d,
980                    source,
981                    sub_dt,
982                    &mut next.budgets[j],
983                    &mut buffers,
984                    fixed.as_ref(),
985                );
986            }
987            next.concentrations.push(concentration);
988        }
989        // The constituents' own pseudo-time, kept once it can differ from time_s.
990        if c.numerics.steady_algorithm != SteadyAlgorithm::Explicit || s.scalar_time_s.is_some() {
991            let covered =
992                (0..substeps).fold(s.scalar_time_s.unwrap_or(s.time_s), |t, _| t + sub_dt);
993            next.scalar_time_s = Some(covered);
994        }
995    }
996    // Preserve the public step function's unchanged trailing constituents when
997    // a caller supplies only a prefix of source arrays.
998    next.concentrations
999        .extend(s.concentrations.iter().skip(sources.len()).cloned());
1000    next.time_s += dt;
1001    next.steps += 1;
1002    // History is borrowed until every fallible gate below has passed.
1003    {
1004        let _phase = control.span(Phase::StateValidation);
1005        validate_with_history(c, g, &next, &s.monitor_history)?;
1006    }
1007    if next
1008        .velocity
1009        .iter()
1010        .any(|v| v.abs() > 1e6 * c.flow.reference_speed())
1011    {
1012        return Err("CFD-E052: velocity divergence".into());
1013    }
1014    for vals in &next.concentrations {
1015        let scale = vals.iter().copied().fold(0.0, f64::max).max(1e-30);
1016        if vals.iter().any(|v| *v < -1e-10 * scale) {
1017            return Err("CFD-E053: transport positivity failure; no clipping applied".into());
1018        }
1019    }
1020    next.monitor_history = std::mem::take(&mut s.monitor_history);
1021    *s = next;
1022    Ok(())
1023}
1024/// One monitor row of the state: the RMS face velocity, then for each
1025/// constituent its mass (kg) followed by its receptor values (kg/m3, in
1026/// receptor order), then with `neutral_rans` the mean k and the mean
1027/// epsilon over all cells. `weights` are the receptor weights of
1028/// [`transport::receptor_weights`], in receptor order.
1029pub fn monitor(c: &Case, g: &Grid, s: &State, weights: &[transport::Weights]) -> Vec<f64> {
1030    let mut v =
1031        vec![s.velocity.iter().map(|v| v * v).sum::<f64>().sqrt() / (g.faces.len() as f64).sqrt()];
1032    for values in &s.concentrations {
1033        v.push(values.iter().sum::<f64>() * g.volume);
1034        for w in weights {
1035            v.push(w.iter().map(|(i, w)| values[*i] * w).sum());
1036        }
1037    }
1038    if c.flow.rans() {
1039        v.push(s.k.iter().sum::<f64>() / g.count() as f64);
1040        v.push(s.epsilon.iter().sum::<f64>() / g.count() as f64);
1041    }
1042    v
1043}
1044/// Largest relative change between the column means of three successive
1045/// windows of `numerics.monitor_window` rows, each change relative to the
1046/// largest absolute mean of its column (at least 1e-30). The windows are the
1047/// first three of the monitor history, which [`run`] keeps at the last three
1048/// windows. `None` until the history holds three full windows.
1049pub fn monitor_change(c: &Case, s: &State) -> Option<f64> {
1050    let w = c.numerics.monitor_window;
1051    if s.monitor_history.len() < 3 * w {
1052        return None;
1053    }
1054    let mut delta = 0.0f64;
1055    for col in 0..s.monitor_history[0].len() {
1056        let mean = |a: usize| {
1057            s.monitor_history[a * w..(a + 1) * w]
1058                .iter()
1059                .map(|v| v[col])
1060                .sum::<f64>()
1061                / w as f64
1062        };
1063        let means = [mean(0), mean(1), mean(2)];
1064        let scale = means.iter().map(|x| x.abs()).fold(1e-30, f64::max);
1065        delta = delta
1066            .max((means[1] - means[0]).abs() / scale)
1067            .max((means[2] - means[1]).abs() / scale);
1068    }
1069    Some(delta)
1070}
1071/// Recomputes the numerical checks of a state from its fields.
1072///
1073/// Returns the [`Check`]s, the [`ScalarEvidence`] of each constituent, the
1074/// normalized momentum residual (`None` for prescribed flow) and the
1075/// normalized turbulence residual (`None` without `neutral_rans`). Steady
1076/// checks are included in steady mode only. `sources` and `weights` are the
1077/// source densities and receptor weights of the case on grid `g`.
1078pub fn assess(
1079    c: &Case,
1080    g: &Grid,
1081    s: &State,
1082    sources: &[Vec<f64>],
1083    weights: &[transport::Weights],
1084) -> (Vec<Check>, Vec<ScalarEvidence>, Option<f64>, Option<f64>) {
1085    let mut checks = vec![];
1086    let mut add = |name: &str, value: f64, threshold: f64| {
1087        checks.push(Check {
1088            name: name.into(),
1089            value: if value.is_finite() { Some(value) } else { None },
1090            threshold,
1091            passed: value.is_finite() && value <= threshold,
1092            method: "application recomputation from current fields".into(),
1093        })
1094    };
1095    let div = g.divergence(&s.velocity);
1096    let length = if let Flow::NeutralRans {
1097        reference_height_m, ..
1098    } = c.flow
1099    {
1100        reference_height_m
1101    } else {
1102        c.domain
1103            .size_m
1104            .iter()
1105            .copied()
1106            .fold(f64::INFINITY, f64::min)
1107    };
1108    let speed = c.flow.reference_speed();
1109    let maxdiv = div.iter().map(|v| v.abs()).fold(0.0, f64::max) * length / speed;
1110    let mut net = 0.0;
1111    let mut absolute = 0.0;
1112    for (f, u) in g.faces.iter().zip(&s.velocity) {
1113        if f.lo.is_some() && f.hi.is_none() {
1114            net += u * f.area;
1115            absolute += u.abs() * f.area;
1116        }
1117        if f.lo.is_none() && f.hi.is_some() {
1118            net -= u * f.area;
1119            absolute += u.abs() * f.area;
1120        }
1121    }
1122    add("local_continuity", maxdiv, 1e-4);
1123    add(
1124        "boundary_volume_balance",
1125        net.abs() / absolute.max(speed * c.domain.size_m[1] * c.domain.size_m[2]),
1126        1e-5,
1127    );
1128    let nut = flow::eddy_viscosity(g, &s.k, &s.epsilon);
1129    let momentum = if c.flow.prescribed() {
1130        None
1131    } else {
1132        let rhs = flow::momentum_rhs(c, g, &s.velocity, &nut);
1133        let grad = g.gradient(&s.pressure);
1134        let residual = rhs
1135            .iter()
1136            .zip(grad)
1137            .map(|(a, b)| (a - b).abs())
1138            .fold(0.0, f64::max)
1139            * length
1140            / (speed * speed);
1141        if c.run.mode == Mode::Steady {
1142            add(
1143                "steady_momentum_equations",
1144                residual,
1145                c.numerics.steady_residual_tolerance,
1146            );
1147        }
1148        Some(residual)
1149    };
1150    let turbulence = if c.flow.rans() {
1151        // The residual probe uses the explicit step size for every algorithm,
1152        // so the reported residual does not depend on the pseudo-time step.
1153        let dt = 1e-6 * timestep_for(SteadyAlgorithm::Explicit, c, g, s, &nut);
1154        let mut k = s.k.clone();
1155        let mut e = s.epsilon.clone();
1156        flow::turbulence_step(c, g, &s.velocity, &mut k, &mut e, dt);
1157        let rk = (0..g.count())
1158            .filter(|i| g.fluid[*i])
1159            .map(|i| (k[i] - s.k[i]).abs() / dt * length / (speed.powi(3)))
1160            .fold(0.0, f64::max);
1161        let re = (0..g.count())
1162            .filter(|i| g.fluid[*i])
1163            .map(|i| (e[i] - s.epsilon[i]).abs() / dt * length * length / speed.powi(4))
1164            .fold(0.0, f64::max);
1165        let r = rk.max(re);
1166        if c.run.mode == Mode::Steady {
1167            add(
1168                "steady_turbulence_equations",
1169                r,
1170                c.numerics.steady_residual_tolerance,
1171            );
1172        }
1173        add("turbulence_floor_events", s.floor_events as f64, 0.0);
1174        Some(r)
1175    } else {
1176        None
1177    };
1178    let mut scalars = vec![];
1179    for (j, sp) in c.constituents.iter().enumerate() {
1180        let values = &s.concentrations[j];
1181        let mass = values.iter().sum::<f64>() * g.volume;
1182        let b = &s.budgets[j];
1183        let deposited_mass = b.deposited_kg.values().sum::<f64>();
1184        let defect =
1185            mass - b.initial_kg - b.emitted_kg - b.inflow_kg + b.outflow_kg + deposited_mass;
1186        let scale =
1187            (b.initial_kg + b.emitted_kg + b.inflow_kg + b.outflow_kg + deposited_mass).max(1e-30);
1188        let minimum = values
1189            .iter()
1190            .enumerate()
1191            .filter(|(i, _)| g.fluid[*i])
1192            .map(|(_, v)| *v)
1193            .fold(f64::INFINITY, f64::min);
1194        let maximum = values.iter().copied().fold(0.0, f64::max);
1195        let negative = -values.iter().filter(|v| **v < 0.0).sum::<f64>() * g.volume;
1196        let mut rhs = transport::rhs(
1197            g,
1198            values,
1199            &s.velocity,
1200            &diffusivity(c, &nut, j),
1201            &sources[j],
1202            c.numerics.transport,
1203            |_| 0.0,
1204        );
1205        let mut deposition_rate_kg_s = BTreeMap::new();
1206        if let Some(particle) = &sp.particle {
1207            let (leaving, surfaces) =
1208                transport::particle_terms(c, g, particle, values, &mut rhs.values);
1209            rhs.outflow += leaving;
1210            deposition_rate_kg_s = surfaces;
1211            let leaves = crate::vegetation::leaf_terms(c, g, values, &mut rhs.values);
1212            if leaves != 0.0 {
1213                deposition_rate_kg_s.insert("vegetation".into(), leaves);
1214            }
1215        }
1216        let deposited_rate = deposition_rate_kg_s.values().sum::<f64>();
1217        let residual = rhs.values.iter().map(|v| v.abs()).fold(0.0, f64::max) * length
1218            / (speed * maximum.max(1e-30));
1219        add(
1220            &format!("{}.mass_budget", sp.id),
1221            defect.abs() / scale,
1222            1e-9,
1223        );
1224        add(&format!("{}.negative_mass", sp.id), negative / scale, 1e-12);
1225        if c.run.mode == Mode::Steady {
1226            add(
1227                &format!("{}.steady_equation", sp.id),
1228                residual,
1229                c.numerics.steady_residual_tolerance,
1230            );
1231            let flux_scale = if rhs.source + rhs.inflow > 0.0 {
1232                rhs.source + rhs.inflow + rhs.outflow + deposited_rate
1233            } else {
1234                (rhs.outflow + deposited_rate).max(b.initial_kg * speed / length)
1235            }
1236            .max(1e-30);
1237            add(
1238                &format!("{}.steady_mass_balance", sp.id),
1239                (rhs.source + rhs.inflow - rhs.outflow - deposited_rate).abs() / flux_scale,
1240                1e-6,
1241            );
1242        }
1243        let receptors: BTreeMap<String, f64> = c
1244            .receptors
1245            .iter()
1246            .zip(weights)
1247            .map(|(r, w)| {
1248                (
1249                    r.id().to_string(),
1250                    w.iter().map(|(i, w)| values[*i] * w).sum(),
1251                )
1252            })
1253            .collect();
1254        let paths = c
1255            .receptors
1256            .iter()
1257            .filter(|r| matches!(r, Receptor::Path { .. }))
1258            .map(|r| {
1259                let path =
1260                    transport::receptor_path_weights(g, r).expect("path receptor passed preflight");
1261                let concentrations = path
1262                    .weights
1263                    .iter()
1264                    .map(|weights| weights.iter().map(|(cell, w)| values[*cell] * w).sum())
1265                    .collect();
1266                (
1267                    r.id().to_string(),
1268                    PathEvidence {
1269                        points_m: path.samples.points_m,
1270                        distance_m: path.samples.distance_m,
1271                        concentrations_kg_m3: concentrations,
1272                        mean_kg_m3: receptors[r.id()],
1273                    },
1274                )
1275            })
1276            .collect();
1277        scalars.push(ScalarEvidence {
1278            id: sp.id.clone(),
1279            mass_kg: mass,
1280            emitted_kg: b.emitted_kg,
1281            inflow_kg: b.inflow_kg,
1282            outflow_kg: b.outflow_kg,
1283            deposited_kg: b.deposited_kg.clone(),
1284            deposition_rate_kg_s,
1285            settling_velocity_m_s: sp.particle.as_ref().map(ParticleBin::settling_speed),
1286            aerodynamic_diameter_m: sp
1287                .particle
1288                .as_ref()
1289                .map(ParticleBin::aerodynamic_diameter_m),
1290            budget_defect_kg: defect,
1291            relative_budget_defect: defect.abs() / scale,
1292            minimum_kg_m3: minimum,
1293            maximum_kg_m3: maximum,
1294            negative_mass_kg: negative,
1295            steady_residual: residual,
1296            source_rate_kg_s: rhs.source,
1297            boundary_inflow_rate_kg_s: rhs.inflow,
1298            boundary_outflow_rate_kg_s: rhs.outflow,
1299            receptors_kg_m3: receptors,
1300            paths,
1301        });
1302    }
1303    if c.run.mode == Mode::Steady {
1304        add(
1305            "monitor_stability",
1306            monitor_change(c, s).unwrap_or(f64::INFINITY),
1307            c.numerics.steady_monitor_tolerance,
1308        );
1309    }
1310    (checks, scalars, momentum, turbulence)
1311}
1312/// Everything a solve returns: the JSON summary, the final accepted state
1313/// and the geometry evidence. [`output::write_run`](crate::output::write_run)
1314/// publishes it as a run archive.
1315pub struct RunResult {
1316    /// The result record (summary.json).
1317    pub summary: Summary,
1318    /// The last accepted state (fields.json, or a checkpoint for a restart).
1319    pub state: State,
1320    /// Cell counts, fluid components and mask hash (geometry.json).
1321    pub geometry: GeometryEvidence,
1322}
1323
1324fn particulate_sums(c: &Case, scalars: &[ScalarEvidence]) -> BTreeMap<String, ParticulateEvidence> {
1325    let mut sums = BTreeMap::new();
1326    if !c.constituents.iter().any(|sp| sp.particle.is_some()) {
1327        return sums;
1328    }
1329    for (name, cutoff) in [("PM2.5", 2.5e-6), ("PM10", 10e-6)] {
1330        let mut evidence = ParticulateEvidence {
1331            mass_kg: 0.0,
1332            receptors_kg_m3: c
1333                .receptors
1334                .iter()
1335                .map(|r| (r.id().to_string(), 0.0))
1336                .collect(),
1337        };
1338        for (sp, scalar) in c.constituents.iter().zip(scalars) {
1339            if sp
1340                .particle
1341                .as_ref()
1342                .is_some_and(|p| p.aerodynamic_diameter_m() <= cutoff)
1343            {
1344                evidence.mass_kg += scalar.mass_kg;
1345                for (rid, value) in &scalar.receptors_kg_m3 {
1346                    *evidence
1347                        .receptors_kg_m3
1348                        .get_mut(rid)
1349                        .expect("declared receptor") += value;
1350                }
1351            }
1352        }
1353        sums.insert(name.to_string(), evidence);
1354    }
1355    sums
1356}
1357
1358/// Solves a case within the limits of `control`, from the cold-start state or
1359/// from a `restart` state, and returns the inspectable outcome.
1360///
1361/// `Err` means the solve could not start: an invalid case (the error is the
1362/// serialized [`CheckReport`], as from [`Case::validate`]) or a grid, source,
1363/// receptor or restart-state failure with its code (`CFD-E028` to
1364/// `CFD-E044`, `CFD-E050`, `CFD-E051`). Once stepping has begun the result is
1365/// `Ok`, also when the run was cancelled, ran out of budget or diverged:
1366/// always read [`Summary::termination`] and [`Summary::assessment`].
1367///
1368/// A restart state should come from
1369/// [`output::read_checkpoint`](crate::output::read_checkpoint), which also
1370/// checks its physics identity; `run` checks only its dimensions and values.
1371/// The library does not create a Rayon pool from `run.threads`; run inside
1372/// `pool.install` when thread accounting matters. Steady runs assess their
1373/// checks every `numerics.monitor_window` steps and stop when all pass.
1374///
1375/// ```
1376/// use cfd_craft::{case::Case, solver::{self, Control}};
1377///
1378/// let case: Case = serde_json::from_str(r#"{
1379///   "schema_version": "cfd-craft.case/0.1", "name": "tiny",
1380///   "domain": {"size_m": [4.0, 1.0, 1.0]}, "grid": {"cells": [8, 2, 2]},
1381///   "boundaries": {"x": "open", "y": "periodic", "z": "periodic"},
1382///   "flow": {"kind": "prescribed_uniform", "velocity_m_s": [1.0, 0.0, 0.0]},
1383///   "constituents": [{"id": "tracer", "diffusivity_m2_s": 0.01}],
1384///   "sources": [{"kind": "point", "id": "S0", "constituent": "tracer",
1385///                "point_m": [0.5, 0.5, 0.5], "rate_kg_s": 1e-6}],
1386///   "numerics": {"transport": "linear_upwind", "max_time_step_s": 1.0,
1387///     "advective_cfl_max": 0.4, "pressure_relative_tolerance": 1e-10,
1388///     "pressure_max_iterations": 100, "steady_residual_tolerance": 1e-5,
1389///     "steady_monitor_tolerance": 1e-3, "monitor_window": 10},
1390///   "run": {"mode": "steady", "end_time_s": 1.0, "max_steps": 5,
1391///     "wall_time_limit_s": 30.0, "threads": 1, "memory_limit_mib": 64},
1392///   "output": {"fields": false, "checkpoint": false, "max_total_mib": 4}
1393/// }"#).unwrap();
1394///
1395/// // Five steps cannot reach a steady state: the result is still `Ok`.
1396/// let result = solver::run(&case, &Control::new(case.run.wall_time_limit_s), None)?;
1397/// assert_eq!(result.summary.termination, "iteration_limit");
1398/// assert_eq!(result.summary.assessment, "incomplete");
1399/// assert_eq!(result.state.steps, 5);
1400///
1401/// // Continue from the returned state with a larger step budget.
1402/// let mut more = case.clone();
1403/// more.run.max_steps = 2000;
1404/// let control = Control::new(more.run.wall_time_limit_s);
1405/// let resumed = solver::run(&more, &control, Some(result.state))?;
1406/// assert_eq!(resumed.summary.termination, "completed");
1407/// assert_eq!(resumed.summary.assessment, "steady_discrete_solution");
1408/// assert!(resumed.summary.checks.iter().all(|c| c.passed));
1409/// # Ok::<(), String>(())
1410/// ```
1411pub fn run(c: &Case, control: &Control, restart: Option<State>) -> Result<RunResult> {
1412    let _run = control.span(Phase::SolverRun);
1413    {
1414        let _phase = control.span(Phase::CaseValidation);
1415        c.validate()?;
1416    }
1417    let g = {
1418        let _phase = control.span(Phase::GridSetup);
1419        Grid::build(c)?
1420    };
1421    let input_setup = control.span(Phase::InputSetup);
1422    let sources = transport::source_fields(c, &g)?;
1423    let weights = c
1424        .receptors
1425        .iter()
1426        .map(|r| transport::receptor_weights(&g, r))
1427        .collect::<Result<Vec<_>>>()?;
1428    drop(input_setup);
1429    let state_setup = control.span(Phase::StateSetup);
1430    let mut state = restart.unwrap_or_else(|| initial_state(c, &g));
1431    validate_state(c, &g, &state)?;
1432    let initial_state_sha256 = hash_bytes(&serde_json::to_vec(&state).map_err(|e| e.to_string())?);
1433    drop(state_setup);
1434    let mut termination = "iteration_limit".to_string();
1435    let mut error = None;
1436    if state.steps == 0 && !c.flow.prescribed() {
1437        match pressure::project(
1438            &g,
1439            &mut state.velocity,
1440            &mut state.pressure,
1441            1.0,
1442            c.numerics.pressure_relative_tolerance,
1443            c.numerics.pressure_max_iterations,
1444            control,
1445        ) {
1446            Ok(initial) => {
1447                state.pressure_iterations += initial.iterations;
1448                state.pressure.fill(0.0);
1449                if c.flow.rans() {
1450                    let _phase = control.span(Phase::Turbulence);
1451                    state.floor_events += flow::turbulence_step(
1452                        c,
1453                        &g,
1454                        &state.velocity,
1455                        &mut state.k,
1456                        &mut state.epsilon,
1457                        0.0,
1458                    );
1459                }
1460            }
1461            Err(e) => {
1462                termination = if e == "cancelled" || e == "wall_time_limit" {
1463                    e.clone()
1464                } else {
1465                    "diverged".into()
1466                };
1467                error = Some(e);
1468            }
1469        }
1470    }
1471    while error.is_none() && state.steps < c.run.max_steps {
1472        if c.run.mode == Mode::Transient && state.time_s >= c.run.end_time_s * (1.0 - 1e-13) {
1473            termination = "completed".into();
1474            break;
1475        }
1476        if let Err(e) = control.check() {
1477            termination = e;
1478            break;
1479        }
1480        let timestep_phase = control.span(Phase::Timestep);
1481        let nut = flow::eddy_viscosity(&g, &state.k, &state.epsilon);
1482        if nut
1483            .iter()
1484            .any(|v| !v.is_finite() || *v > 100.0 * c.flow.reference_speed() * c.domain.size_m[2])
1485        {
1486            termination = "diverged".into();
1487            error =
1488                Some("CFD-E054: turbulent viscosity outside the declared numerical regime".into());
1489            break;
1490        }
1491        let mut dt = timestep(c, &g, &state, &nut);
1492        if c.run.mode == Mode::Transient {
1493            dt = dt.min(c.run.end_time_s - state.time_s);
1494        }
1495        if dt <= 0.0 || !dt.is_finite() {
1496            termination = "diverged".into();
1497            error = Some("CFD-E055: the time step is not finite and positive".into());
1498            break;
1499        }
1500        drop(timestep_phase);
1501        if let Err(e) = step(c, &g, &mut state, &sources, dt, control) {
1502            termination = if e == "cancelled" || e == "wall_time_limit" {
1503                e.clone()
1504            } else {
1505                "diverged".into()
1506            };
1507            error = Some(e);
1508            break;
1509        }
1510        let monitor_phase = control.span(Phase::Monitor);
1511        state.monitor_history.push(monitor(c, &g, &state, &weights));
1512        let keep = 3 * c.numerics.monitor_window;
1513        if state.monitor_history.len() > keep {
1514            state.monitor_history.remove(0);
1515        }
1516        drop(monitor_phase);
1517        if c.run.mode == Mode::Steady && state.steps.is_multiple_of(c.numerics.monitor_window) {
1518            let _phase = control.span(Phase::Assessment);
1519            let (checks, _, _, _) = assess(c, &g, &state, &sources, &weights);
1520            if checks.iter().all(|x| x.passed) {
1521                termination = "completed".into();
1522                break;
1523            }
1524        }
1525    }
1526    if c.run.mode == Mode::Transient && state.time_s >= c.run.end_time_s * (1.0 - 1e-13) {
1527        termination = "completed".into();
1528    }
1529    Ok(finish_run(
1530        c,
1531        &g,
1532        state,
1533        &sources,
1534        &weights,
1535        termination,
1536        error,
1537        initial_state_sha256,
1538        control,
1539    ))
1540}
1541
1542/// Shared unchanged numerical assessment and archive result construction.
1543#[allow(clippy::too_many_arguments)]
1544pub(crate) fn finish_run(
1545    c: &Case,
1546    g: &Grid,
1547    state: State,
1548    sources: &[Vec<f64>],
1549    weights: &[transport::Weights],
1550    termination: String,
1551    error: Option<String>,
1552    initial_state_sha256: String,
1553    control: &Control,
1554) -> RunResult {
1555    let (checks, constituents, momentum_residual, turbulence_residual) = {
1556        let _phase = control.span(Phase::Assessment);
1557        assess(c, g, &state, sources, weights)
1558    };
1559    let passed = checks.iter().all(|x| x.passed);
1560    let assessment = if termination == "completed" && passed {
1561        if c.run.mode == Mode::Steady {
1562            "steady_discrete_solution"
1563        } else {
1564            "transient_interval_completed"
1565        }
1566    } else if termination == "completed" {
1567        "failed_checks"
1568    } else {
1569        "incomplete"
1570    };
1571    let geo = g.evidence();
1572    let summary = Summary {
1573        schema_version: "cfd-craft.result/0.1".into(),
1574        name: c.name.clone(),
1575        case_sha256: hash_bytes(&serde_json::to_vec(c).unwrap()),
1576        physics_sha256: c.physics_hash(),
1577        initial_state_sha256,
1578        termination,
1579        assessment: assessment.into(),
1580        error,
1581        model_scope: if c.constituents.iter().any(|sp| sp.particle.is_some()) {
1582            if c.flow.rans() {
1583                "neutral_k_epsilon_particle_transport"
1584            } else if c.flow.prescribed() {
1585                "prescribed_flow_particle_transport"
1586            } else {
1587                "incompressible_laminar_particle_transport"
1588            }
1589        } else if c.flow.rans() {
1590            "neutral_k_epsilon_rough_wall"
1591        } else if c.flow.prescribed() {
1592            "prescribed_flow_passive_transport"
1593        } else {
1594            "incompressible_laminar"
1595        }
1596        .into(),
1597        experimental_validation: "not_validated; see validation/data-inventory.json".into(),
1598        steps: state.steps,
1599        physical_time_s: state.time_s,
1600        elapsed_s: control.elapsed(),
1601        pressure_iterations: state.pressure_iterations,
1602        momentum_solver_iterations: (c.numerics.steady_algorithm != SteadyAlgorithm::Explicit)
1603            .then_some(state.momentum_solver_iterations),
1604        turbulent_floor_events: state.floor_events,
1605        fluid_cells: geo.fluid_cells,
1606        solid_cells: geo.solid_cells,
1607        fluid_components: geo.fluid_components,
1608        mask_sha256: geo.mask_sha256.clone(),
1609        estimated_peak_mib: c.check().estimated_peak_mib,
1610        checks,
1611        vegetation: crate::vegetation::evidence(c, g, &state.velocity),
1612        particulate_matter: particulate_sums(c, &constituents),
1613        constituents,
1614        velocity_max_m_s: state.velocity.iter().map(|v| v.abs()).fold(0.0, f64::max),
1615        momentum_residual,
1616        turbulence_residual,
1617        receptor_relative_change: monitor_change(c, &state),
1618        source_sha256: crate::SOURCE_SHA256.into(),
1619        build_version: format!("{}; {}", env!("CARGO_PKG_VERSION"), crate::RUSTC_VERSION),
1620        threads: c.run.threads,
1621        frozen_flow: None,
1622    };
1623    RunResult {
1624        summary,
1625        state,
1626        geometry: geo,
1627    }
1628}