1use 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
52pub struct Control {
76 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 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 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 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 pub fn elapsed(&self) -> f64 {
143 self.start.elapsed().as_secs_f64()
144 }
145 pub fn with_profiling(mut self) -> Self {
149 self.profiling = Some(Collector::default());
150 self
151 }
152 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 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#[derive(Clone, Debug, Serialize, Deserialize)]
189#[serde(deny_unknown_fields)]
190pub struct Budget {
191 pub initial_kg: f64,
193 pub emitted_kg: f64,
195 pub inflow_kg: f64,
197 pub outflow_kg: f64,
199 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
201 pub deposited_kg: BTreeMap<String, f64>,
202}
203#[derive(Clone, Debug, Serialize, Deserialize)]
210#[serde(deny_unknown_fields)]
211pub struct State {
212 pub steps: usize,
214 pub time_s: f64,
217 pub velocity: Vec<f64>,
219 pub pressure: Vec<f64>,
222 pub k: Vec<f64>,
225 pub epsilon: Vec<f64>,
228 pub concentrations: Vec<Vec<f64>>,
231 pub budgets: Vec<Budget>,
233 pub floor_events: usize,
236 pub pressure_iterations: usize,
239 #[serde(default, skip_serializing_if = "is_zero")]
242 pub momentum_solver_iterations: usize,
243 #[serde(default, skip_serializing_if = "Option::is_none")]
249 pub scalar_time_s: Option<f64>,
250 pub monitor_history: Vec<Vec<f64>>,
254}
255fn is_zero(v: &usize) -> bool {
256 *v == 0
257}
258#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
265#[serde(deny_unknown_fields)]
266pub struct Check {
267 pub name: String,
274 pub value: Option<f64>,
278 pub threshold: f64,
280 pub passed: bool,
282 pub method: String,
285}
286#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
290#[serde(deny_unknown_fields)]
291pub struct ScalarEvidence {
292 pub id: String,
294 pub mass_kg: f64,
296 pub emitted_kg: f64,
298 pub inflow_kg: f64,
300 pub outflow_kg: f64,
302 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
304 pub deposited_kg: BTreeMap<String, f64>,
305 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
307 pub deposition_rate_kg_s: BTreeMap<String, f64>,
308 #[serde(default, skip_serializing_if = "Option::is_none")]
310 pub settling_velocity_m_s: Option<f64>,
311 #[serde(default, skip_serializing_if = "Option::is_none")]
313 pub aerodynamic_diameter_m: Option<f64>,
314 pub budget_defect_kg: f64,
316 pub relative_budget_defect: f64,
319 pub minimum_kg_m3: f64,
321 pub maximum_kg_m3: f64,
323 pub negative_mass_kg: f64,
326 pub steady_residual: f64,
329 pub source_rate_kg_s: f64,
331 pub boundary_inflow_rate_kg_s: f64,
333 pub boundary_outflow_rate_kg_s: f64,
335 pub receptors_kg_m3: BTreeMap<String, f64>,
338 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
341 pub paths: BTreeMap<String, PathEvidence>,
342}
343#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
345#[serde(deny_unknown_fields)]
346pub struct PathEvidence {
347 pub points_m: Vec<[f64; 3]>,
349 pub distance_m: Vec<f64>,
351 pub concentrations_kg_m3: Vec<f64>,
353 pub mean_kg_m3: f64,
355}
356#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
358#[serde(deny_unknown_fields)]
359pub struct ParticulateEvidence {
360 pub mass_kg: f64,
362 pub receptors_kg_m3: BTreeMap<String, f64>,
364}
365#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
372#[serde(deny_unknown_fields)]
373pub struct Summary {
374 pub schema_version: String,
376 pub name: String,
378 pub case_sha256: String,
380 pub physics_sha256: String,
383 pub initial_state_sha256: String,
386 pub termination: String,
390 pub assessment: String,
396 pub error: Option<String>,
400 pub model_scope: String,
404 pub experimental_validation: String,
407 pub steps: usize,
410 pub physical_time_s: f64,
412 pub elapsed_s: f64,
414 pub pressure_iterations: usize,
416 #[serde(default, skip_serializing_if = "Option::is_none")]
418 pub momentum_solver_iterations: Option<usize>,
419 pub turbulent_floor_events: usize,
422 pub fluid_cells: usize,
424 pub solid_cells: usize,
426 pub fluid_components: usize,
429 pub mask_sha256: String,
432 pub estimated_peak_mib: f64,
434 pub checks: Vec<Check>,
436 pub constituents: Vec<ScalarEvidence>,
438 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
442 pub particulate_matter: BTreeMap<String, ParticulateEvidence>,
443 #[serde(default, skip_serializing_if = "Option::is_none")]
445 pub vegetation: Option<crate::vegetation::Evidence>,
446 pub velocity_max_m_s: f64,
448 pub momentum_residual: Option<f64>,
450 pub turbulence_residual: Option<f64>,
452 pub receptor_relative_change: Option<f64>,
458 pub source_sha256: String,
461 pub build_version: String,
464 pub threads: usize,
466 #[serde(default, skip_serializing_if = "Option::is_none")]
469 pub frozen_flow: Option<crate::mobile_response::FrozenFlowEvidence>,
470}
471pub 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}
521pub 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 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}
598pub 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 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 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 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 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}
733fn 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}
779pub const SCALAR_SUBSTEPS_MAX: usize = 16;
783
784pub 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#[derive(Default)]
799pub(crate) struct ScalarBuffers {
800 r1: Vec<f64>,
801 stage: Vec<f64>,
802 r2: Vec<f64>,
803}
804
805#[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 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
865pub 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 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 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 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 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 next.concentrations
999 .extend(s.concentrations.iter().skip(sources.len()).cloned());
1000 next.time_s += dt;
1001 next.steps += 1;
1002 {
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}
1024pub 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}
1044pub 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}
1071pub 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 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}
1312pub struct RunResult {
1316 pub summary: Summary,
1318 pub state: State,
1320 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
1358pub 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#[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}