Skip to main content

cfd_craft/
transport.rs

1//! Conservative transport of passive gases and particle size classes: source
2//! densities, receptor weights, initial fields and the finite-volume
3//! right-hand side.
4//!
5//! Each face flux is advective (upwind or MUSCL) plus diffusive, applied with
6//! opposite signs to the two cells, so interior fluxes cancel and mass
7//! changes only through sources and boundary faces. Inlets bring zero
8//! concentration; outlets have no diffusive flux; walls, slip faces and
9//! solids have no flux at all. Concentrations are never clipped: a negative
10//! value beyond round-off fails the step (CFD-E053). See the
11//! [transport model card](https://github.com/dietmarwo/CFD-craft/blob/main/docs/model-cards/transport.md).
12use crate::{
13    Result,
14    case::*,
15    grid::{FaceKind, Grid},
16};
17
18/// Sparse receptor weights: `(cell index, weight)` pairs over fluid cells,
19/// summing to one. A receptor value is the weighted sum of the cell
20/// concentrations.
21pub type Weights = Vec<(usize, f64)>;
22/// Index of the cell that contains point `p` (meters). Coordinates beyond
23/// the domain are clamped to the boundary cells.
24pub fn cell_at(g: &Grid, p: [f64; 3]) -> usize {
25    Grid::index(
26        g.n,
27        std::array::from_fn(|a| ((p[a] / g.dx[a]).floor() as usize).min(g.n[a] - 1)),
28    )
29}
30/// Whether a particle has a represented positive removal mechanism in each
31/// fluid component. This is a connectivity/admissibility screen, not proof of
32/// scalar reachability or numerical convergence. Gases keep the outlet rule.
33fn particle_component_sinks(c: &Case, g: &Grid, particle: &ParticleBin) -> Vec<bool> {
34    let mut sinks = vec![false; g.components.len()];
35    let settling = particle.settling_speed();
36    for face in &g.faces {
37        if face.axis != 2 || face.lo.is_some() {
38            continue;
39        }
40        let Some(cell) = face.hi else {
41            continue;
42        };
43        let rate = match face.kind {
44            FaceKind::Wall => {
45                let ground = face.coord[2] == 0 && c.boundaries.z != Boundary::Periodic;
46                settling
47                    + if ground {
48                        particle.ground_deposition_velocity_m_s
49                    } else {
50                        particle.roof_deposition_velocity_m_s
51                    }
52            }
53            FaceKind::Inlet | FaceKind::Outlet | FaceKind::Slip
54                if c.boundaries.z == Boundary::Open && face.coord[2] == 0 =>
55            {
56                settling
57            }
58            _ => 0.0,
59        };
60        if rate > 0.0 {
61            sinks[g.component[cell]] = true;
62        }
63    }
64    for (cell, fluid) in g.fluid.iter().enumerate() {
65        if !fluid {
66            continue;
67        }
68        let point = g.center(cell);
69        if c.vegetation.iter().any(|v| {
70            v.leaf_area_density_m2_m3 > 0.0
71                && v.leaf_deposition_velocity_m_s > 0.0
72                && (0..3).all(|axis| v.min_m[axis] <= point[axis] && point[axis] < v.max_m[axis])
73        }) {
74            sinks[g.component[cell]] = true;
75        }
76    }
77    sinks
78}
79/// The represented source density of each constituent, in kg/(m3 s) per
80/// cell and in case order. Each source's integrated [`Source::rate`] is
81/// distributed over its support (the point's cell, the cells a line crosses,
82/// or the overlap of a volume), so the density integrates to that rate.
83///
84/// # Errors
85///
86/// `CFD-E040` when the support touches a solid cell (mass is never
87/// redistributed), `CFD-E041` without support, `CFD-E043` for a steady
88/// source in a fluid component without an outlet, `CFD-E044` for a nonfinite
89/// density.
90pub fn source_fields(c: &Case, g: &Grid) -> Result<Vec<Vec<f64>>> {
91    let mut fields = vec![vec![0.0; g.count()]; c.constituents.len()];
92    for s in &c.sources {
93        let si = c
94            .constituents
95            .iter()
96            .position(|x| x.id == s.constituent())
97            .ok_or("unknown source constituent")?;
98        let mut weights = vec![0.0; g.count()];
99        match s {
100            Source::Point { point_m, .. } => weights[cell_at(g, *point_m)] = 1.0,
101            Source::Line { from_m, to_m, .. } => {
102                let mut ts = vec![0.0, 1.0];
103                for a in 0..3 {
104                    let d = to_m[a] - from_m[a];
105                    if d.abs() > 1e-14 {
106                        for j in 1..g.n[a] {
107                            let t = (j as f64 * g.dx[a] - from_m[a]) / d;
108                            if t > 0.0 && t < 1.0 {
109                                ts.push(t);
110                            }
111                        }
112                    }
113                }
114                ts.sort_by(f64::total_cmp);
115                ts.dedup_by(|a, b| (*a - *b).abs() < 1e-14);
116                for p in ts.windows(2) {
117                    let t = 0.5 * (p[0] + p[1]);
118                    let center = std::array::from_fn(|a| from_m[a] + t * (to_m[a] - from_m[a]));
119                    weights[cell_at(g, center)] += p[1] - p[0];
120                }
121            }
122            Source::Volume { min_m, max_m, .. } => {
123                for (i, w) in weights.iter_mut().enumerate() {
124                    let p = g.center(i);
125                    *w = (0..3)
126                        .map(|a| {
127                            (max_m[a].min(p[a] + 0.5 * g.dx[a])
128                                - min_m[a].max(p[a] - 0.5 * g.dx[a]))
129                            .max(0.0)
130                        })
131                        .product();
132                }
133            }
134        }
135        if weights
136            .iter()
137            .zip(&g.fluid)
138            .any(|(w, fluid)| *w > 1e-14 && !*fluid)
139        {
140            return Err(format!(
141                "CFD-E040: source {} intersects masked solid; no implicit redistribution",
142                s.id()
143            ));
144        }
145        let particle_sinks = if c.run.mode == Mode::Steady && s.rate() > 0.0 {
146            c.constituents[si]
147                .particle
148                .as_ref()
149                .map(|particle| particle_component_sinks(c, g, particle))
150        } else {
151            None
152        };
153        if c.run.mode == Mode::Steady
154            && s.rate() > 0.0
155            && weights.iter().enumerate().any(|(i, w)| {
156                *w > 1e-14
157                    && !g.anchored[g.component[i]]
158                    && !particle_sinks
159                        .as_ref()
160                        .is_some_and(|sinks| sinks[g.component[i]])
161            })
162        {
163            return Err(format!(
164                "CFD-E043: steady source {} has no outlet or represented particle deposition sink in its fluid component",
165                s.id()
166            ));
167        }
168        let norm = weights.iter().sum::<f64>();
169        if norm <= 0.0 {
170            return Err(format!("CFD-E041: source {} has no support", s.id()));
171        }
172        for (dst, w) in fields[si].iter_mut().zip(weights) {
173            *dst += s.rate() * w / norm / g.volume;
174        }
175    }
176    if fields.iter().flatten().any(|v| !v.is_finite()) {
177        return Err("CFD-E044: represented source density is nonfinite".into());
178    }
179    Ok(fields)
180}
181/// Geometry and arc-length quadrature of a path receptor.
182#[derive(Clone, Debug)]
183pub struct PathSamples {
184    /// Ordered three-dimensional positions, in local meters.
185    pub points_m: Vec<[f64; 3]>,
186    /// Distance from the first vertex, in meters, including zero and full length.
187    pub distance_m: Vec<f64>,
188    /// Normalized trapezoidal coefficient of each sample in the path mean.
189    pub mean_weights: Vec<f64>,
190}
191/// A path's geometry and ordinary linear interpolation weights for every sample.
192#[derive(Clone, Debug)]
193pub struct PathWeights {
194    /// Generated sample geometry and path-mean quadrature.
195    pub samples: PathSamples,
196    /// Cell interpolation weights, one sparse vector per generated sample.
197    pub weights: Vec<Weights>,
198}
199/// Generate equally spaced arc-length samples with both endpoints included.
200/// The actual spacing is length/ceil(length/requested_spacing). No flow or
201/// transport equation is changed. Invalid paths/sample counts are CFD-E086/88.
202pub fn path_samples(receptor: &Receptor) -> Result<PathSamples> {
203    let Receptor::Path {
204        polyline_m,
205        height_m,
206        ..
207    } = receptor
208    else {
209        return Err("CFD-E086: receptors: path sampling requires a path receptor".into());
210    };
211    let count = receptor.path_sample_count().unwrap_or(usize::MAX);
212    if count > PATH_SAMPLES_MAX {
213        return Err(format!(
214            "CFD-E088: receptor {} exceeds 20001 path samples",
215            receptor.id()
216        ));
217    }
218    if !(2..=4097).contains(&polyline_m.len())
219        || !height_m.is_finite()
220        || polyline_m.iter().flatten().any(|v| !v.is_finite())
221    {
222        return Err(format!(
223            "CFD-E086: receptor {} has invalid path vertices/height",
224            receptor.id()
225        ));
226    }
227    let mut cumulative = vec![0.0];
228    for segment in polyline_m.windows(2) {
229        let length = (segment[1][0] - segment[0][0]).hypot(segment[1][1] - segment[0][1]);
230        if length <= 0.0 {
231            return Err(format!(
232                "CFD-E086: receptor {} has a zero-length segment",
233                receptor.id()
234            ));
235        }
236        cumulative.push(cumulative.last().unwrap() + length);
237    }
238    let length = *cumulative.last().unwrap();
239    let intervals = count - 1;
240    let mut result = PathSamples {
241        points_m: Vec::with_capacity(count),
242        distance_m: Vec::with_capacity(count),
243        mean_weights: Vec::with_capacity(count),
244    };
245    let mut segment = 0;
246    for sample in 0..count {
247        let distance = if sample == intervals {
248            length
249        } else {
250            length * sample as f64 / intervals as f64
251        };
252        while segment + 2 < cumulative.len() && cumulative[segment + 1] < distance {
253            segment += 1;
254        }
255        let t = ((distance - cumulative[segment])
256            / (cumulative[segment + 1] - cumulative[segment]))
257            .clamp(0.0, 1.0);
258        let point = if sample == intervals {
259            let p = polyline_m.last().unwrap();
260            [p[0], p[1], *height_m]
261        } else {
262            let from = polyline_m[segment];
263            let to = polyline_m[segment + 1];
264            [
265                from[0] + t * (to[0] - from[0]),
266                from[1] + t * (to[1] - from[1]),
267                *height_m,
268            ]
269        };
270        result.points_m.push(point);
271        result.distance_m.push(distance);
272        result
273            .mean_weights
274            .push(if sample == 0 || sample == intervals {
275                0.5 / intervals as f64
276            } else {
277                1.0 / intervals as f64
278            });
279    }
280    Ok(result)
281}
282fn check_path_segments(g: &Grid, receptor: &Receptor) -> Result<()> {
283    let Receptor::Path {
284        polyline_m,
285        height_m,
286        ..
287    } = receptor
288    else {
289        return Ok(());
290    };
291    if polyline_m.iter().any(|p| {
292        p[0] < 0.0
293            || p[1] < 0.0
294            || p[0] >= g.n[0] as f64 * g.dx[0]
295            || p[1] >= g.n[1] as f64 * g.dx[1]
296    }) || *height_m < 0.0
297        || *height_m >= g.n[2] as f64 * g.dx[2]
298    {
299        return Err(format!(
300            "CFD-E086: receptor {} path is outside the domain",
301            receptor.id()
302        ));
303    }
304    for (segment_index, segment) in polyline_m.windows(2).enumerate() {
305        let mut crossings = vec![0.0, 1.0];
306        for (axis, (&start, &end)) in segment[0].iter().zip(&segment[1]).enumerate() {
307            let delta = end - start;
308            if delta == 0.0 {
309                continue;
310            }
311            for k in 1..g.n[axis] {
312                let t = (k as f64 * g.dx[axis] - start) / delta;
313                if t > 0.0 && t < 1.0 {
314                    crossings.push(t);
315                }
316            }
317        }
318        crossings.sort_by(f64::total_cmp);
319        for pair in crossings.windows(2) {
320            if pair[1] <= pair[0] {
321                continue;
322            }
323            let t = 0.5 * (pair[0] + pair[1]);
324            let point = [
325                segment[0][0] + t * (segment[1][0] - segment[0][0]),
326                segment[0][1] + t * (segment[1][1] - segment[0][1]),
327                *height_m,
328            ];
329            if !g.fluid[cell_at(g, point)] {
330                return Err(format!(
331                    "CFD-E087: receptor {} path segment {segment_index} crosses a represented solid cell",
332                    receptor.id()
333                ));
334            }
335        }
336    }
337    Ok(())
338}
339/// Build the ordinary point interpolation weights of every generated path
340/// sample. Entire segments are checked for solid crossings, including between
341/// sample positions; each point also retains the strict through-wall stencil rule.
342pub fn receptor_path_weights(g: &Grid, receptor: &Receptor) -> Result<PathWeights> {
343    let samples = path_samples(receptor)?;
344    check_path_segments(g, receptor)?;
345    let weights = samples
346        .points_m
347        .iter()
348        .map(|point| {
349            receptor_weights(
350                g,
351                &Receptor::Point {
352                    id: receptor.id().to_string(),
353                    point_m: *point,
354                },
355            )
356            .map_err(|e| {
357                format!(
358                    "CFD-E087: receptor {} path sample has invalid interpolation support: {e}",
359                    receptor.id()
360                )
361            })
362        })
363        .collect::<Result<Vec<_>>>()?;
364    Ok(PathWeights { samples, weights })
365}
366/// The normalized sampling weights of a receptor: trilinear interpolation
367/// between cell centers (clamped at the domain boundary) for a point, exact
368/// cell overlap for a volume average.
369///
370/// # Errors
371///
372/// `CFD-E042` when the receptor has no weight or a positive weight on a
373/// solid cell.
374pub fn receptor_weights(g: &Grid, r: &Receptor) -> Result<Weights> {
375    let mut result = vec![];
376    match r {
377        Receptor::Point { point_m, .. } => {
378            let base: [isize; 3] =
379                std::array::from_fn(|a| (point_m[a] / g.dx[a] - 0.5).floor() as isize);
380            let frac: [f64; 3] =
381                std::array::from_fn(|a| point_m[a] / g.dx[a] - 0.5 - base[a] as f64);
382            for k in 0..2 {
383                for j in 0..2 {
384                    for i in 0..2 {
385                        let b = [i, j, k];
386                        let q = std::array::from_fn(|a| {
387                            (base[a] + b[a]).clamp(0, g.n[a] as isize - 1) as usize
388                        });
389                        let w = (0..3)
390                            .map(|a| if b[a] == 0 { 1.0 - frac[a] } else { frac[a] })
391                            .product::<f64>();
392                        if w > 1e-14 {
393                            result.push((Grid::index(g.n, q), w));
394                        }
395                    }
396                }
397            }
398        }
399        Receptor::VolumeAverage { min_m, max_m, .. } => {
400            for i in 0..g.count() {
401                let p = g.center(i);
402                let w = (0..3)
403                    .map(|a| {
404                        (max_m[a].min(p[a] + 0.5 * g.dx[a]) - min_m[a].max(p[a] - 0.5 * g.dx[a]))
405                            .max(0.0)
406                    })
407                    .product::<f64>();
408                if w > 1e-14 {
409                    result.push((i, w));
410                }
411            }
412        }
413        Receptor::Path { .. } => {
414            let path = receptor_path_weights(g, r)?;
415            let mut combined = std::collections::BTreeMap::<usize, f64>::new();
416            for (weights, coefficient) in path.weights.iter().zip(&path.samples.mean_weights) {
417                for (cell, value) in weights {
418                    *combined.entry(*cell).or_default() += coefficient * value;
419                }
420            }
421            result = combined.into_iter().collect();
422        }
423    }
424    if result.is_empty() || result.iter().any(|(i, _)| !g.fluid[*i]) {
425        return Err(format!(
426            "CFD-E042: receptor {} is empty or samples through a solid",
427            r.id()
428        ));
429    }
430    let norm = result.iter().map(|(_, w)| w).sum::<f64>();
431    for (_, w) in &mut result {
432        *w /= norm;
433    }
434    Ok(result)
435}
436/// Initial concentration of each constituent in kg/m3, per cell and in case
437/// order, from the case's initial conditions; zero without one and always
438/// zero in solid cells.
439pub fn initial_fields(c: &Case, g: &Grid) -> Vec<Vec<f64>> {
440    c.constituents
441        .iter()
442        .map(|sp| {
443            let mut v = vec![0.0; g.count()];
444            if let Some(init) = c
445                .initial_conditions
446                .iter()
447                .find(|x| x.constituent() == sp.id)
448            {
449                match init {
450                    Initial::Uniform {
451                        concentration_kg_m3,
452                        ..
453                    } => {
454                        for (i, x) in v.iter_mut().enumerate() {
455                            if g.fluid[i] {
456                                *x = *concentration_kg_m3;
457                            }
458                        }
459                    }
460                    Initial::PeriodicGaussian {
461                        center_m,
462                        sigma_m,
463                        total_mass_kg,
464                        ..
465                    } => {
466                        // Integrate a periodized Gaussian by 2-point Gauss quadrature in each cell.
467                        for (i, x) in v.iter_mut().enumerate() {
468                            if !g.fluid[i] {
469                                continue;
470                            }
471                            let p = g.center(i);
472                            let mut value = 1.0;
473                            for a in 0..3 {
474                                let mut part = 0.0;
475                                let images =
476                                    (8.0 * sigma_m[a] / c.domain.size_m[a]).ceil() as isize + 1;
477                                for sign in [-1.0, 1.0] {
478                                    let z = p[a] + sign * g.dx[a] / (2.0 * 3.0f64.sqrt());
479                                    for im in -images..=images {
480                                        let d = z - center_m[a] + im as f64 * c.domain.size_m[a];
481                                        part += 0.5 * (-0.5 * (d / sigma_m[a]).powi(2)).exp();
482                                    }
483                                }
484                                value *= part;
485                            }
486                            *x = value;
487                        }
488                        let sum = v.iter().sum::<f64>() * g.volume;
489                        for x in &mut v {
490                            *x *= total_mass_kg / sum;
491                        }
492                    }
493                }
494            }
495            v
496        })
497        .collect()
498}
499/// The fluid cell across the lower (`side = 0`) or upper (`side = 1`) face
500/// of cell `i` along axis `a`, or `None` when that face is not interior. On
501/// a one-cell periodic axis the neighbor is `i` itself.
502pub fn neighbor(g: &Grid, i: usize, a: usize, side: usize) -> Option<usize> {
503    let f = &g.faces[g.cell_faces[i][a][side]];
504    if f.kind == FaceKind::Interior {
505        if side == 0 { f.lo } else { f.hi }
506    } else {
507        None
508    }
509}
510fn minmod(a: f64, b: f64) -> f64 {
511    if a * b <= 0.0 {
512        0.0
513    } else {
514        a.signum() * a.abs().min(b.abs())
515    }
516}
517fn slope(g: &Grid, c: &[f64], i: usize, a: usize) -> f64 {
518    let lo = neighbor(g, i, a, 0).map(|j| c[j]).unwrap_or(c[i]);
519    let hi = neighbor(g, i, a, 1).map(|j| c[j]).unwrap_or(c[i]);
520    // Monotonized-central limiter: bounded reconstruction with a less diffusive
521    // smooth-region slope than the two-argument minmod reference.
522    minmod(
523        0.5 * (hi - lo),
524        minmod(2.0 * (c[i] - lo), 2.0 * (hi - c[i])),
525    )
526}
527/// One transporting face of `rhs` with the velocity and diffusivity fixed.
528struct FixedFace {
529    lo: Option<usize>,
530    hi: Option<usize>,
531    velocity: f64,
532    diffusivity: f64,
533    outlet: bool,
534    distance: f64,
535    area: f64,
536}
537
538/// `rhs` with `Advection::LinearUpwind`, zero inlet values and a fixed velocity
539/// and diffusivity, for repeated evaluation (the scalar sub-steps of the
540/// implicit steady algorithm). The faces are gathered once; `eval` repeats
541/// `rhs_into`'s arithmetic face by face in the same order, so it returns the
542/// same bits.
543pub(crate) struct FixedRhs<'a> {
544    g: &'a Grid,
545    faces: Vec<FixedFace>,
546}
547
548impl<'a> FixedRhs<'a> {
549    pub(crate) fn new(g: &'a Grid, u: &[f64], d: &[f64]) -> Self {
550        let faces = g
551            .faces
552            .iter()
553            .enumerate()
554            .filter(|(_, f)| {
555                matches!(
556                    f.kind,
557                    FaceKind::Interior | FaceKind::Inlet | FaceKind::Outlet
558                )
559            })
560            .map(|(fi, f)| FixedFace {
561                lo: f.lo,
562                hi: f.hi,
563                velocity: u[fi],
564                diffusivity: match (f.lo, f.hi) {
565                    (Some(i), Some(j)) => 0.5 * (d[i] + d[j]),
566                    (Some(i), None) | (None, Some(i)) => d[i],
567                    _ => 0.0,
568                },
569                outlet: f.kind == FaceKind::Outlet,
570                distance: f.distance,
571                area: f.area,
572            })
573            .collect();
574        Self { g, faces }
575    }
576
577    /// The rates and `v`, as `rhs_into(g, c, u, d, source, LinearUpwind, |_| 0.0, v)`.
578    pub(crate) fn eval(&self, c: &[f64], source: &[f64], v: &mut Vec<f64>) -> (f64, f64, f64) {
579        v.clear();
580        v.extend_from_slice(source);
581        let mut inflow = 0.0;
582        let mut outflow = 0.0;
583        let volume = self.g.volume;
584        for f in &self.faces {
585            let cl = f.lo.map(|i| c[i]).unwrap_or(0.0);
586            let cr = f.hi.map(|i| c[i]).unwrap_or(0.0);
587            // `+ 0.0` and `- 0.0` as in `rhs_into`, which adds the zero slope.
588            let donor = if f.velocity >= 0.0 {
589                f.lo.map(|_| cl + 0.0).unwrap_or(cl)
590            } else {
591                f.hi.map(|_| cr - 0.0).unwrap_or(cr)
592            };
593            let diff = if f.outlet {
594                0.0
595            } else {
596                f.diffusivity * (cl - cr) / f.distance
597            };
598            let flux = (f.velocity * donor + diff) * f.area;
599            let per_volume = flux / volume;
600            if let Some(i) = f.lo {
601                v[i] -= per_volume;
602            }
603            if let Some(i) = f.hi {
604                v[i] += per_volume;
605            }
606            if f.lo.is_none() || f.hi.is_none() {
607                let outward = if f.lo.is_some() { flux } else { -flux };
608                outflow += outward.max(0.0);
609                inflow += (-outward).max(0.0);
610            }
611        }
612        (source.iter().sum::<f64>() * volume, inflow, outflow)
613    }
614}
615
616/// The transport right-hand side of one constituent and its mass rates.
617pub struct Rhs {
618    /// Rate of change of the concentration per cell, in kg/(m3 s).
619    pub values: Vec<f64>,
620    /// Emission rate of the source density over the domain, in kg/s.
621    pub source: f64,
622    /// Mass entering through boundary faces, in kg/s, nonnegative.
623    pub inflow: f64,
624    /// Mass leaving through boundary faces, in kg/s, nonnegative.
625    pub outflow: f64,
626}
627/// Finite-volume right-hand side `dc/dt` of concentration `c` for face
628/// velocities `u`, cell diffusivities `d` (m2/s, averaged to the faces), the
629/// source density `source` (kg/(m3 s)) and the advection scheme. `inlet`
630/// gives the concentration outside a boundary face, used for inflow
631/// including backflow at an outlet; the solver uses zero. Interior, inlet
632/// and outlet faces carry flux; outlets carry no diffusion.
633pub fn rhs(
634    g: &Grid,
635    c: &[f64],
636    u: &[f64],
637    d: &[f64],
638    source: &[f64],
639    advection: Advection,
640    inlet: impl Fn(&crate::grid::Face) -> f64,
641) -> Rhs {
642    let mut values = Vec::new();
643    let (source, inflow, outflow) = rhs_into(g, c, u, d, source, advection, inlet, &mut values);
644    Rhs {
645        values,
646        source,
647        inflow,
648        outflow,
649    }
650}
651
652/// `rhs` into a reused buffer; returns the source, inflow and outflow rates.
653/// The flux of each face is divided by the cell volume once and applied to
654/// both cells, which is the same value `rhs` computed for each.
655#[allow(clippy::too_many_arguments)]
656pub(crate) fn rhs_into(
657    g: &Grid,
658    c: &[f64],
659    u: &[f64],
660    d: &[f64],
661    source: &[f64],
662    advection: Advection,
663    inlet: impl Fn(&crate::grid::Face) -> f64,
664    v: &mut Vec<f64>,
665) -> (f64, f64, f64) {
666    v.clear();
667    v.extend_from_slice(source);
668    let mut inflow = 0.0;
669    let mut outflow = 0.0;
670    let muscl = advection == Advection::Muscl;
671    for (fi, f) in g.faces.iter().enumerate() {
672        if !matches!(
673            f.kind,
674            FaceKind::Interior | FaceKind::Inlet | FaceKind::Outlet
675        ) {
676            continue;
677        }
678        let cl = f.lo.map(|i| c[i]).unwrap_or_else(|| inlet(f));
679        let cr = f.hi.map(|i| c[i]).unwrap_or_else(|| inlet(f));
680        let donor = if u[fi] >= 0.0 {
681            f.lo.map(|i| {
682                cl + if muscl {
683                    0.5 * slope(g, c, i, f.axis)
684                } else {
685                    0.0
686                }
687            })
688            .unwrap_or(cl)
689        } else {
690            f.hi.map(|i| {
691                cr - if muscl {
692                    0.5 * slope(g, c, i, f.axis)
693                } else {
694                    0.0
695                }
696            })
697            .unwrap_or(cr)
698        };
699        let diffusivity = match (f.lo, f.hi) {
700            (Some(i), Some(j)) => 0.5 * (d[i] + d[j]),
701            (Some(i), None) | (None, Some(i)) => d[i],
702            _ => 0.0,
703        };
704        let diff = if f.kind == FaceKind::Outlet {
705            0.0
706        } else {
707            diffusivity * (cl - cr) / f.distance
708        };
709        let flux = (u[fi] * donor + diff) * f.area;
710        let per_volume = flux / g.volume;
711        if let Some(i) = f.lo {
712            v[i] -= per_volume;
713        }
714        if let Some(i) = f.hi {
715            v[i] += per_volume;
716        }
717        if f.lo.is_none() || f.hi.is_none() {
718            let outward = if f.lo.is_some() { flux } else { -flux };
719            outflow += outward.max(0.0);
720            inflow += (-outward).max(0.0);
721        }
722    }
723    (source.iter().sum::<f64>() * g.volume, inflow, outflow)
724}
725
726/// Add conservative downward settling and absorbing ground/roof fluxes to an
727/// already evaluated gas RHS. Returns additional open-boundary outflow and
728/// deposition rates by surface. Interior settling uses first-order upwind;
729/// the same flux is applied with opposite signs to neighboring fluid cells.
730pub fn particle_terms(
731    case: &Case,
732    g: &Grid,
733    particle: &ParticleBin,
734    concentrations: &[f64],
735    values: &mut [f64],
736) -> (f64, std::collections::BTreeMap<String, f64>) {
737    let settling = particle.settling_speed();
738    let mut outflow = 0.0;
739    let mut deposited = std::collections::BTreeMap::new();
740    for f in &g.faces {
741        if f.axis != 2 {
742            continue;
743        }
744        match f.kind {
745            FaceKind::Interior => {
746                let (Some(lo), Some(hi)) = (f.lo, f.hi) else {
747                    continue;
748                };
749                if lo == hi {
750                    continue; // one-cell periodic axis: exactly zero drift operator
751                }
752                let flux = settling * concentrations[hi] * f.area / g.volume;
753                values[lo] += flux;
754                values[hi] -= flux;
755            }
756            FaceKind::Inlet | FaceKind::Outlet | FaceKind::Slip
757                if case.boundaries.z == Boundary::Open =>
758            {
759                // Downward drift carries zero incremental concentration into the
760                // upper boundary, and removes mass at an open lower boundary.
761                if let (None, Some(hi)) = (f.lo, f.hi) {
762                    let flux = settling * concentrations[hi] * f.area;
763                    values[hi] -= flux / g.volume;
764                    outflow += flux;
765                }
766            }
767            FaceKind::Wall => {
768                if let (None, Some(hi)) = (f.lo, f.hi) {
769                    let (name, extra) =
770                        if f.coord[2] == 0 && case.boundaries.z != Boundary::Periodic {
771                            ("ground", particle.ground_deposition_velocity_m_s)
772                        } else {
773                            ("roof", particle.roof_deposition_velocity_m_s)
774                        };
775                    let flux = (settling + extra) * concentrations[hi] * f.area;
776                    values[hi] -= flux / g.volume;
777                    if flux != 0.0 {
778                        *deposited.entry(name.to_string()).or_insert(0.0) += flux;
779                    }
780                }
781            }
782            _ => {}
783        }
784    }
785    (outflow, deposited)
786}
787
788#[cfg(test)]
789mod tests {
790    use super::*;
791    use crate::case::{Block, Boundary, Case};
792
793    // The gathered-face evaluation must return the bits of `rhs` with linear
794    // upwind and zero inlet values, on open, periodic, masked and RANS grids.
795    #[test]
796    fn fixed_rhs_returns_the_bits_of_rhs() {
797        let canyon: Case =
798            serde_json::from_str(include_str!("../../../cases/canyon/wh1-wind270.json")).unwrap();
799        let mut periodic: Case = serde_json::from_str(include_str!(
800            "../../../cases/verification/periodic-tracer.json"
801        ))
802        .unwrap();
803        periodic.grid.cells = [6, 1, 5];
804        let mut masked = canyon.clone();
805        masked.boundaries.y = Boundary::Periodic;
806        masked.geometry.push(Block {
807            footprint_m: None,
808            id: "extra".into(),
809            min_m: [12.0, 0.0, 0.0],
810            max_m: [13.0, 16.0, 2.0],
811        });
812        for c in [canyon, periodic, masked] {
813            let g = Grid::build(&c).unwrap();
814            let n = g.count();
815            let u: Vec<_> = (0..g.faces.len())
816                .map(|i| (0.37 * i as f64).sin() * 2.0)
817                .collect();
818            let d: Vec<_> = (0..n)
819                .map(|i| 0.01 + 0.005 * (0.11 * i as f64).cos())
820                .collect();
821            let x: Vec<_> = (0..n)
822                .map(|i| {
823                    if g.fluid[i] {
824                        (0.23 * i as f64).cos().abs()
825                    } else {
826                        0.0
827                    }
828                })
829                .collect();
830            let source: Vec<_> = (0..n).map(|i| 1e-3 * (i % 7) as f64).collect();
831            let expected = rhs(&g, &x, &u, &d, &source, Advection::LinearUpwind, |_| 0.0);
832            let mut values = vec![1.0; 3];
833            let (s, inflow, outflow) = FixedRhs::new(&g, &u, &d).eval(&x, &source, &mut values);
834            let bits = |v: &[f64]| v.iter().map(|x| x.to_bits()).collect::<Vec<_>>();
835            assert_eq!(bits(&values), bits(&expected.values), "{}", c.name);
836            assert_eq!(
837                [s, inflow, outflow].map(f64::to_bits),
838                [expected.source, expected.inflow, expected.outflow].map(f64::to_bits)
839            );
840        }
841    }
842}