Skip to main content

cfd_craft/
vegetation.rs

1//! Porous canopy sources on the unchanged uniform-grid pressure operator.
2//! Green1992 and Sanz2003 select source coefficients only; see the flow model card.
3use crate::{case::Case, grid::Grid};
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6use std::collections::BTreeMap;
7
8/// Whether any nonzero leaf area is declared. This early return preserves all
9/// arithmetic and state bytes of cases with only zero-LAD volumes.
10pub fn active(c: &Case) -> bool {
11    c.vegetation.iter().any(|v| v.leaf_area_density_m2_m3 > 0.0)
12}
13#[derive(Clone, Copy, Default)]
14struct Coefficients {
15    drag: f64,
16    k_source: f64,
17    k_sink: f64,
18    e_source: f64,
19    e_sink: f64,
20    leaf: f64,
21}
22fn coefficients(c: &Case, g: &Grid) -> Vec<Coefficients> {
23    (0..g.count())
24        .map(|i| {
25            let mut r = Coefficients::default();
26            if !g.fluid[i] {
27                return r;
28            }
29            let p = g.center(i);
30            for v in &c.vegetation {
31                if v.leaf_area_density_m2_m3 == 0.0
32                    || !(0..3).all(|a| v.min_m[a] <= p[a] && p[a] < v.max_m[a])
33                {
34                    continue;
35                }
36                let d = v.drag_coefficient * v.leaf_area_density_m2_m3;
37                let [bp, bd, c4, c5] = v.turbulence_closure.coefficients();
38                r.drag += d;
39                r.k_source += bp * d;
40                r.k_sink += bd * d;
41                r.e_source += c4 * bp * d;
42                r.e_sink += c5 * bd * d;
43                r.leaf += v.leaf_area_density_m2_m3 * v.leaf_deposition_velocity_m_s;
44            }
45            r
46        })
47        .collect()
48}
49fn speed(u: [f64; 3]) -> f64 {
50    u.iter().map(|v| v * v).sum::<f64>().sqrt()
51}
52/// Frozen nonnegative drag coefficient at each staggered face (1/s), obtained
53/// by averaging the represented cell coefficients Cd*LAD*|U|. Empty if inactive.
54pub fn face_drag(c: &Case, g: &Grid, u: &[f64]) -> Vec<f64> {
55    if !active(c) {
56        return Vec::new();
57    }
58    let cells = g.cell_velocity(u);
59    let d: Vec<_> = coefficients(c, g)
60        .iter()
61        .zip(cells)
62        .map(|(v, u)| v.drag * speed(u))
63        .collect();
64    g.faces
65        .iter()
66        .map(|f| match (f.lo, f.hi) {
67            (Some(i), Some(j)) => 0.5 * (d[i] + d[j]),
68            (Some(i), None) | (None, Some(i)) => d[i],
69            _ => 0.0,
70        })
71        .collect()
72}
73/// Canopy production and implicit loss rates for the k and epsilon equations.
74pub(crate) struct TurbulenceSources {
75    pub k_source: Vec<f64>,
76    pub k_sink: Vec<f64>,
77    pub e_source: Vec<f64>,
78    pub e_sink: Vec<f64>,
79}
80pub(crate) fn turbulence(
81    c: &Case,
82    g: &Grid,
83    u: &[f64],
84    k: &[f64],
85    eps: &[f64],
86) -> Option<TurbulenceSources> {
87    if !active(c) {
88        return None;
89    }
90    let cells = g.cell_velocity(u);
91    let mut r = TurbulenceSources {
92        k_source: vec![0.0; g.count()],
93        k_sink: vec![0.0; g.count()],
94        e_source: vec![0.0; g.count()],
95        e_sink: vec![0.0; g.count()],
96    };
97    for (i, (v, u)) in coefficients(c, g).iter().zip(cells).enumerate() {
98        let q = speed(u);
99        r.k_source[i] = v.k_source * q.powi(3);
100        r.k_sink[i] = v.k_sink * q;
101        r.e_source[i] = v.e_source * q.powi(3) * eps[i].max(1e-14) / k[i].max(1e-14);
102        r.e_sink[i] = v.e_sink * q;
103    }
104    Some(r)
105}
106/// Additional explicit particle sink rate max(LAD*v_leaf), in 1/s.
107pub fn maximum_leaf_loss(c: &Case, g: &Grid) -> f64 {
108    if !active(c) {
109        return 0.0;
110    }
111    coefficients(c, g)
112        .iter()
113        .map(|v| v.leaf)
114        .fold(0.0, f64::max)
115}
116/// Add a leaf-collection sink to an existing particle RHS and return its
117/// integrated mass removal rate (kg/s). Overlapping boxes add leaf area.
118pub fn leaf_terms(c: &Case, g: &Grid, concentrations: &[f64], rhs: &mut [f64]) -> f64 {
119    if !active(c) {
120        return 0.0;
121    }
122    let mut removal = 0.0;
123    for (i, v) in coefficients(c, g).iter().enumerate() {
124        let sink = v.leaf * concentrations[i];
125        rhs[i] -= sink;
126        removal += sink * g.volume;
127    }
128    removal
129}
130/// Instantaneous canopy evidence; integrated drag is per unit air density.
131#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
132#[serde(deny_unknown_fields)]
133pub struct Evidence {
134    /// Positive rate of work against canopy drag, divided by density (m5/s3).
135    pub drag_power_per_density_m5_s3: f64,
136    /// Integral of drag acceleration over fluid volume (m4/s2), with its sign.
137    pub integrated_drag_acceleration_m4_s2: [f64; 3],
138    /// Number of represented fluid cells per vegetation ID; overlaps count twice.
139    pub volume_fluid_cells: BTreeMap<String, usize>,
140    /// Quadrature of the actual staggered momentum sink over active face
141    /// dual volumes (area times face gradient distance).
142    pub drag_quadrature: String,
143    /// The model remains numerically verified and physically unvalidated.
144    pub validation: String,
145}
146/// Recompute current canopy drag and coverage from the returned flow field.
147pub fn evidence(c: &Case, g: &Grid, u: &[f64]) -> Option<Evidence> {
148    if !active(c) {
149        return None;
150    }
151    let drag = face_drag(c, g, u);
152    let mut r = Evidence {
153        drag_power_per_density_m5_s3: 0.0,
154        integrated_drag_acceleration_m4_s2: [0.0; 3],
155        volume_fluid_cells: BTreeMap::new(),
156        drag_quadrature: "staggered_active_faces_dual_volumes".into(),
157        validation: "verified_numerics_unvalidated_physics".into(),
158    };
159    for (fi, face) in g.faces.iter().enumerate() {
160        if matches!(
161            face.kind,
162            crate::grid::FaceKind::Interior | crate::grid::FaceKind::Outlet
163        ) {
164            let dual_volume = face.area * face.distance;
165            r.drag_power_per_density_m5_s3 += drag[fi] * u[fi] * u[fi] * dual_volume;
166            r.integrated_drag_acceleration_m4_s2[face.axis] -= drag[fi] * u[fi] * dual_volume;
167        }
168    }
169    for v in &c.vegetation {
170        let count = (0..g.count())
171            .filter(|i| {
172                g.fluid[*i]
173                    && (0..3).all(|a| {
174                        let x = g.center(*i)[a];
175                        v.min_m[a] <= x && x < v.max_m[a]
176                    })
177            })
178            .count();
179        r.volume_fluid_cells.insert(v.id.clone(), count);
180    }
181    Some(r)
182}