Skip to main content

cfd_craft/
flow.rs

1//! Momentum and turbulence terms of the flow model: the steady momentum
2//! right-hand side, wall treatment, momentum advection schemes and the
3//! neutral k-epsilon package.
4//!
5//! Velocities are the face-normal components of the staggered grid; k,
6//! epsilon and the eddy viscosity are cell values. Walls and solids enter
7//! through ghost values: no-slip (or moving-wall) reflection for laminar
8//! flow, rough-wall functions with `neutral_rans`, and the equilibrium shear
9//! stress at the top of `ground_open_top`. The coefficients, the wall and
10//! inflow treatment and their limits are documented in the
11//! [flow model card](https://github.com/dietmarwo/CFD-craft/blob/main/docs/model-cards/flow.md).
12// Explicit tensor indices keep the stencil equations readable.
13#![allow(clippy::needless_range_loop)]
14use crate::{
15    case::*,
16    grid::{FaceKind, Grid},
17    transport,
18};
19use rayon::prelude::*;
20
21/// k-epsilon closure coefficient C_mu in nu_t = C_mu k^2 / epsilon.
22pub const C_MU: f64 = 0.09;
23/// Production coefficient C_epsilon1 of the epsilon equation.
24pub const C1: f64 = 1.44;
25/// Destruction coefficient C_epsilon2 of the epsilon equation.
26pub const C2: f64 = 1.92;
27/// Turbulent Prandtl number of epsilon, kappa^2 / ((C2 - C1) sqrt(C_mu)) =
28/// 1.111..., chosen so the inflow log layer is an equilibrium (kappa = 0.4).
29pub const SIGMA_EPSILON: f64 = 0.4 * 0.4 / ((C2 - C1) * 0.3);
30/// Eddy viscosity C_mu k^2 / epsilon in m2/s, per cell; zero in solid cells
31/// and where epsilon is not positive (always without `neutral_rans`, whose
32/// k and epsilon are zero).
33pub fn eddy_viscosity(g: &Grid, k: &[f64], eps: &[f64]) -> Vec<f64> {
34    (0..g.count())
35        .map(|i| {
36            if g.fluid[i] && eps[i] > 0.0 {
37                C_MU * k[i] * k[i] / eps[i]
38            } else {
39                0.0
40            }
41        })
42        .collect()
43}
44pub(crate) fn adjacent_mean(f: &crate::grid::Face, v: &[f64]) -> f64 {
45    match (f.lo, f.hi) {
46        (Some(i), Some(j)) => 0.5 * (v[i] + v[j]),
47        (Some(i), None) | (None, Some(i)) => v[i],
48        _ => 0.0,
49    }
50}
51#[allow(clippy::too_many_arguments)]
52pub(crate) fn wall_ghost(
53    c: &Case,
54    g: &Grid,
55    fi: usize,
56    d: usize,
57    side: isize,
58    u: &[f64],
59    nut: &[f64],
60    cell_u: &[[f64; 3]],
61) -> f64 {
62    ghost_value(c, g, fi, d, side, u[fi], nut, cell_u)
63}
64/// The ghost value of face `fi` beyond direction `d` and `side`, for the face
65/// value `value`. It is affine in `value` with `nut` and `cell_u` held fixed,
66/// which is how the implicit steady iterations read its coefficient.
67#[allow(clippy::too_many_arguments)]
68pub(crate) fn ghost_value(
69    c: &Case,
70    g: &Grid,
71    fi: usize,
72    d: usize,
73    side: isize,
74    value: f64,
75    nut: &[f64],
76    cell_u: &[[f64; 3]],
77) -> f64 {
78    ghost_values(c, g, fi, d, side, [value], nut, cell_u)[0]
79}
80/// `ghost_value` for several face values at once: the boundary branch, the wall
81/// speed and the logarithms are evaluated once, and each value then goes
82/// through the same arithmetic as a single call.
83#[allow(clippy::too_many_arguments)]
84pub(crate) fn ghost_values<const N: usize>(
85    c: &Case,
86    g: &Grid,
87    fi: usize,
88    d: usize,
89    side: isize,
90    values: [f64; N],
91    nut: &[f64],
92    cell_u: &[[f64; 3]],
93) -> [f64; N] {
94    let f = &g.faces[fi];
95    let at_domain = if side < 0 {
96        f.center[d] < g.dx[d]
97    } else {
98        f.center[d] > c.domain.size_m[d] - g.dx[d]
99    };
100    let bc = c.boundaries.at(d);
101    if at_domain && matches!(bc, Boundary::Slip) {
102        return values;
103    }
104    if at_domain && bc == Boundary::Open {
105        let speed = c.flow.vector(f.center[2])[d] * side as f64;
106        return if speed < -1e-12 {
107            let inflow = c.flow.vector(f.center[2])[f.axis];
108            values.map(|value| 2.0 * inflow - value)
109        } else {
110            values
111        };
112    }
113    if c.flow.rans() {
114        if d == 2 && side > 0 && at_domain && bc == Boundary::GroundOpenTop {
115            let v = c.flow.vector(c.domain.size_m[2]);
116            let speed = (v[0] * v[0] + v[1] * v[1]).sqrt();
117            let stress = c.flow.ustar().powi(2) * v[f.axis] / speed.max(1e-30);
118            let mu = c.flow.viscosity() + adjacent_mean(f, nut);
119            return values.map(|value| value + stress * g.dx[d] / mu);
120        }
121        let i = f.lo.or(f.hi).unwrap();
122        let velocity = cell_u[i];
123        let speed = (0..3)
124            .filter(|a| *a != d)
125            .map(|a| velocity[a].powi(2))
126            .sum::<f64>()
127            .sqrt();
128        if let Flow::NeutralRans { roughness_m, .. } = &c.flow {
129            let z = 0.5 * g.dx[d];
130            let z0 = if d == 2 && side < 0 && at_domain {
131                *roughness_m
132            } else {
133                c.building_roughness_m
134                    .unwrap_or_else(|| roughness_m.min(0.001 * g.dx[d]))
135            };
136            let us = 0.4 * speed / ((z + z0) / z0).ln();
137            let mu = c.flow.viscosity() + adjacent_mean(f, nut);
138            return values.map(|value| {
139                let stress = us * us * value / speed.max(1e-30);
140                value - stress * g.dx[d] / mu
141            });
142        }
143    }
144    let target = if at_domain {
145        c.moving_walls
146            .iter()
147            .find(|w| w.axis == d && w.upper == (side > 0))
148            .map(|w| w.velocity_m_s[f.axis])
149            .unwrap_or(0.0)
150    } else {
151        0.0
152    };
153    values.map(|value| 2.0 * target - value)
154}
155#[allow(clippy::too_many_arguments)]
156fn sample(
157    c: &Case,
158    g: &Grid,
159    fi: usize,
160    d: usize,
161    side: isize,
162    neighbor: Option<usize>,
163    u: &[f64],
164    nut: &[f64],
165    cell_u: &[[f64; 3]],
166) -> f64 {
167    let f = &g.faces[fi];
168    if let Some(j) = neighbor {
169        if matches!(g.faces[j].kind, FaceKind::Wall | FaceKind::Blocked) && d != f.axis {
170            wall_ghost(c, g, fi, d, side, u, nut, cell_u)
171        } else {
172            u[j]
173        }
174    } else {
175        if d == f.axis {
176            return u[fi];
177        }
178        wall_ghost(c, g, fi, d, side, u, nut, cell_u)
179    }
180}
181// Reuse topology within this cell evaluation; no persistent mutable-grid cache.
182fn cell_neighbors(g: &Grid, i: usize) -> [[usize; 2]; 3] {
183    std::array::from_fn(|d| {
184        [
185            transport::neighbor(g, i, d, 0).unwrap_or(i),
186            transport::neighbor(g, i, d, 1).unwrap_or(i),
187        ]
188    })
189}
190
191/// Face reconstruction of the transported momentum component on a momentum
192/// control-volume face, phi_f = phi_U + s(a, b) / 2 with a = phi_U - phi_UU and
193/// b = phi_D - phi_U (van Leer's MUSCL, Sweby's limiter notation). Division-free.
194#[derive(Clone, Copy, Debug, PartialEq, Eq)]
195pub enum Reconstruction {
196    /// s = 0: flux-form first-order upwind. A test control only; it is not the
197    /// production donor-cell scheme, which uses the advective form.
198    FirstOrder,
199    /// s = a: unlimited second-order upwind.
200    SecondOrder,
201    /// s = ab(a + b)/(a^2 + b^2) where ab > 0, else 0.
202    VanAlbada,
203    /// s = 2ab/(a + b) where ab > 0, else 0.
204    VanLeer,
205    /// s = sign(b) min(2|a|, |a + b|/2, 2|b|) where ab > 0, else 0.
206    MonotonizedCentral,
207}
208impl Reconstruction {
209    /// The flux-form reconstruction selected by the case numerics, or `None`
210    /// for the default donor-cell scheme, which uses the advective form.
211    pub fn of(numerics: &Numerics) -> Option<Self> {
212        match (numerics.momentum_advection, numerics.momentum_limiter) {
213            (MomentumAdvection::DonorCell, _) => None,
214            (MomentumAdvection::SecondOrderUpwind, _) => Some(Self::SecondOrder),
215            (MomentumAdvection::LimitedUpwind, Some(MomentumLimiter::VanAlbada)) => {
216                Some(Self::VanAlbada)
217            }
218            (MomentumAdvection::LimitedUpwind, Some(MomentumLimiter::VanLeer)) => {
219                Some(Self::VanLeer)
220            }
221            (MomentumAdvection::LimitedUpwind, Some(MomentumLimiter::MonotonizedCentral)) => {
222                Some(Self::MonotonizedCentral)
223            }
224            // Rejected by case validation (CFD-E037).
225            (MomentumAdvection::LimitedUpwind, None) => Some(Self::FirstOrder),
226        }
227    }
228    /// The limited slope s(a, b) of the reconstruction phi_f = phi_U +
229    /// s(a, b)/2, with a = phi_U - phi_UU and b = phi_D - phi_U.
230    pub fn slope(self, a: f64, b: f64) -> f64 {
231        match self {
232            Self::FirstOrder => 0.0,
233            Self::SecondOrder => a,
234            _ if a * b <= 0.0 => 0.0,
235            Self::VanAlbada => a * b * (a + b) / (a * a + b * b),
236            Self::VanLeer => 2.0 * a * b / (a + b),
237            Self::MonotonizedCentral => {
238                b.signum() * (2.0 * a.abs()).min(0.5 * (a + b).abs()).min(2.0 * b.abs())
239            }
240        }
241    }
242}
243
244// A face that carries a real interior velocity sample for the momentum stencil.
245fn interior(g: &Grid, face: Option<usize>) -> Option<usize> {
246    face.filter(|&j| matches!(g.faces[j].kind, FaceKind::Interior | FaceKind::Outlet))
247}
248
249/// Conservative flux-form advection of the face-normal velocities on the
250/// staggered grid (Harlow and Welch; Morinishi et al. 1998). Each momentum control
251/// volume is centered on its face. The advecting velocity on a control-volume face
252/// is the classic MAC average of the two face velocities that meet there, and the
253/// transported component is reconstructed upwind with `reconstruction`. Every
254/// control-volume face flux is a function of that face alone, so the two momentum
255/// cells that share it see the same value and the fluxes telescope. Walls and
256/// solids use the viscous ghost values for the near samples; where the far-upwind
257/// sample is not an interior face, the face falls back to first order (s = 0).
258/// Returns -div(u u_a) on interior faces and zero elsewhere.
259pub fn flux_form_advection(
260    c: &Case,
261    g: &Grid,
262    u: &[f64],
263    nut: &[f64],
264    reconstruction: Reconstruction,
265) -> Vec<f64> {
266    flux_form_advection_with(c, g, u, nut, &g.cell_velocity(u), reconstruction)
267}
268
269// Each control-volume face flux is evaluated once and shared by the two momentum
270// cells that meet there: center fluxes per fluid cell and axis, edge fluxes per
271// a-face and direction d ≠ a (the edge above the face in d). The arithmetic of
272// every flux is unchanged, so the result is bit-identical to evaluating each
273// flux from both sides.
274fn flux_form_advection_with(
275    c: &Case,
276    g: &Grid,
277    u: &[f64],
278    nut: &[f64],
279    cell_u: &[[f64; 3]],
280    reconstruction: Reconstruction,
281) -> Vec<f64> {
282    // Flux through the control-volume face at the center of cell `cell`, between
283    // the a-faces L (below) and H (above) of that cell.
284    let center_flux = |a: usize, cell: usize| -> f64 {
285        let [lo, hi] = g.cell_faces[cell][a];
286        let advecting = 0.5 * (u[lo] + u[hi]);
287        let (up, down, far) = if advecting >= 0.0 {
288            (lo, hi, g.faces[lo].lo.map(|k| g.cell_faces[k][a][0]))
289        } else {
290            (hi, lo, g.faces[hi].hi.map(|k| g.cell_faces[k][a][1]))
291        };
292        let s = match interior(g, far) {
293            Some(far) => reconstruction.slope(u[up] - u[far], u[down] - u[up]),
294            None => 0.0,
295        };
296        advecting * (u[up] + 0.5 * s)
297    };
298    // Flux through the control-volume face between the a-face at q (L, below in d)
299    // and the a-face at q + e_d (H). Either may be missing or a wall face. The
300    // faces it needs, as `face_at` finds them: the d-faces at q + e_d and
301    // q + e_d − e_a, and the a-faces at q, q + e_d, q − e_d and q + 2e_d.
302    let edge_core = |d: usize,
303                     d_faces: [Option<usize>; 2],
304                     [at_q, above, below, above2]: [Option<usize>; 4]|
305     -> f64 {
306        // At an outlet's momentum cell only the inside cell's d-face exists; its
307        // velocity is extrapolated (zero gradient) to the outer half.
308        let advecting = match d_faces {
309            [Some(d0), Some(d1)] => 0.5 * (u[d0] + u[d1]),
310            [Some(d0), None] | [None, Some(d0)] => u[d0],
311            [None, None] => return 0.0,
312        };
313        let low = interior(g, at_q);
314        let high = interior(g, above);
315        let value = |own: Option<usize>, other: Option<usize>, side: isize| -> Option<f64> {
316            match (own, other) {
317                (Some(j), _) => Some(u[j]),
318                // The missing sample is the neighbor of `other` on this side.
319                (None, Some(j)) => Some(wall_ghost(c, g, j, d, side, u, nut, cell_u)),
320                (None, None) => None,
321            }
322        };
323        let (Some(phi_low), Some(phi_high)) = (value(low, high, -1), value(high, low, 1)) else {
324            return 0.0;
325        };
326        let (phi_up, phi_down, far) = if advecting >= 0.0 {
327            (phi_low, phi_high, low.and(interior(g, below)))
328        } else {
329            (phi_high, phi_low, high.and(interior(g, above2)))
330        };
331        let s = match far {
332            Some(far) => reconstruction.slope(phi_up - u[far], phi_down - phi_up),
333            None => 0.0,
334        };
335        advecting * (phi_up + 0.5 * s)
336    };
337    let edge_flux = |a: usize, d: usize, q: [isize; 3]| -> f64 {
338        let at = |axis: usize, offset: [isize; 3]| {
339            g.face_at(c, axis, std::array::from_fn(|k| q[k] + offset[k]))
340        };
341        let shift = |k: isize, back_a: isize| {
342            let mut o = [0; 3];
343            o[d] = k;
344            o[a] += back_a;
345            o
346        };
347        edge_core(
348            d,
349            [at(d, shift(1, 0)), at(d, shift(1, -1))],
350            [
351                at(a, [0; 3]),
352                at(a, shift(1, 0)),
353                at(a, shift(-1, 0)),
354                at(a, shift(2, 0)),
355            ],
356        )
357    };
358    let neighbor_faces = g.neighbor_faces(c);
359    let edge_faces = g.edge_faces(c);
360    let centers: Vec<[f64; 3]> = (0..g.count())
361        .into_par_iter()
362        .map(|cell| {
363            if g.fluid[cell] {
364                std::array::from_fn(|a| center_flux(a, cell))
365            } else {
366                [0.0; 3]
367            }
368        })
369        .collect();
370    // The edge above each a-face in d, from the cached face tables (the same
371    // faces `edge_flux` would look up).
372    let edges: Vec<[f64; 3]> = g
373        .faces
374        .par_iter()
375        .enumerate()
376        .map(|(fi, f)| {
377            std::array::from_fn(|d| {
378                if d == f.axis {
379                    0.0
380                } else {
381                    let [below, above] = neighbor_faces[fi][d];
382                    let above2 = above.and_then(|j| neighbor_faces[j][d][1]);
383                    edge_core(d, edge_faces[fi][d], [Some(fi), above, below, above2])
384                }
385            })
386        })
387        .collect();
388    g.faces
389        .par_iter()
390        .enumerate()
391        .map(|(fi, f)| {
392            if !matches!(f.kind, FaceKind::Interior | FaceKind::Outlet) {
393                return 0.0;
394            }
395            let a = f.axis;
396            let q = f.coord.map(|v| v as isize);
397            let mut rhs = 0.0;
398            for d in 0..3 {
399                let (low, high) = if d == a {
400                    // Outlet closure: the outer half of an outlet's momentum cell
401                    // advects with the outlet velocity and a zero-gradient value
402                    // (s = 0); an inflow face is prescribed and has no equation.
403                    let outer = u[fi] * u[fi];
404                    (
405                        f.lo.map_or(outer, |cell| centers[cell][a]),
406                        f.hi.map_or(outer, |cell| centers[cell][a]),
407                    )
408                } else {
409                    let mut below = q;
410                    below[d] -= 1;
411                    // The edge below is the edge above the a-face below, when that
412                    // face exists (face_at wraps periodic axes the same way).
413                    let low = match neighbor_faces[fi][d][0] {
414                        Some(j) => edges[j][d],
415                        None => edge_flux(a, d, below),
416                    };
417                    (low, edges[fi][d])
418                };
419                rhs -= (high - low) / g.dx[d];
420            }
421            rhs
422        })
423        .collect()
424}
425
426/// The steady momentum right-hand side on every face (zero on faces without an
427/// equation). `nut` enters only with `neutral_rans`; laminar flow has none.
428pub fn momentum_rhs(c: &Case, g: &Grid, u: &[f64], nut: &[f64]) -> Vec<f64> {
429    let reconstruction = Reconstruction::of(&c.numerics);
430    let cell_u = g.cell_velocity(u);
431    let canopy_drag = crate::vegetation::face_drag(c, g, u);
432    let advection = reconstruction.map(|r| flux_form_advection_with(c, g, u, nut, &cell_u, r));
433    // Remaining variable-viscosity symmetric-stress term:
434    // div(mu grad(u)^T)_a = sum_d (d_d mu)(d_a u_d), for divergence-free flow.
435    let mut cross = vec![[0.0; 3]; g.count()];
436    if c.flow.rans() {
437        for i in 0..g.count() {
438            if !g.fluid[i] {
439                continue;
440            }
441            let neighbors = cell_neighbors(g, i);
442            for a in 0..3 {
443                for d in 0..3 {
444                    let [im, ip] = neighbors[d];
445                    let [jm, jp] = neighbors[a];
446                    cross[i][a] += (nut[ip] - nut[im]) / (2.0 * g.dx[d])
447                        * (cell_u[jp][d] - cell_u[jm][d])
448                        / (2.0 * g.dx[a]);
449                }
450            }
451        }
452    }
453    let neighbor_faces = g.neighbor_faces(c);
454    let nu = c.flow.viscosity();
455    let rans = c.flow.rans();
456    let mean: Vec<f64> = if rans {
457        g.faces.iter().map(|f| adjacent_mean(f, nut)).collect()
458    } else {
459        Vec::new()
460    };
461    g.faces
462        .par_iter()
463        .enumerate()
464        .map(|(fi, f)| {
465            if !matches!(f.kind, FaceKind::Interior | FaceKind::Outlet) {
466                return 0.0;
467            }
468            let velocity = std::array::from_fn::<_, 3, _>(|a| match (f.lo, f.hi) {
469                (Some(i), Some(j)) => 0.5 * (cell_u[i][a] + cell_u[j][a]),
470                (Some(i), None) | (None, Some(i)) => cell_u[i][a],
471                _ => 0.0,
472            });
473            let mut rhs = advection.as_ref().map_or(0.0, |adv| adv[fi]);
474            for d in 0..3 {
475                let [lo_face, hi_face] = neighbor_faces[fi][d];
476                let lo = sample(c, g, fi, d, -1, lo_face, u, nut, &cell_u);
477                let hi = sample(c, g, fi, d, 1, hi_face, u, nut, &cell_u);
478                // Donor-cell momentum, direct second-order viscous stencil on the staggered grid.
479                if advection.is_none() {
480                    rhs -= velocity[d]
481                        * if velocity[d] >= 0.0 {
482                            (u[fi] - lo) / g.dx[d]
483                        } else {
484                            (hi - u[fi]) / g.dx[d]
485                        };
486                }
487                // Variable-viscosity flux includes the derivative of the eddy viscosity.
488                // Laminar: nut is zero, so every face viscosity is exactly nu.
489                let mu = nu + if rans { mean[fi] } else { 0.0 };
490                let mut mu_lo = mu;
491                let mut mu_hi = mu;
492                if rans {
493                    for (neighbor, dst) in [(lo_face, &mut mu_lo), (hi_face, &mut mu_hi)] {
494                        if let Some(j) = neighbor
495                            && g.faces[j].kind == FaceKind::Interior
496                        {
497                            *dst = 0.5 * (mu + nu + mean[j]);
498                        }
499                    }
500                }
501                rhs += (mu_hi * (hi - u[fi]) - mu_lo * (u[fi] - lo)) / (g.dx[d] * g.dx[d]);
502            }
503            if let Flow::Laminar {
504                acceleration_m_s2, ..
505            } = &c.flow
506            {
507                rhs += acceleration_m_s2[f.axis];
508            }
509            rhs += match (f.lo, f.hi) {
510                (Some(i), Some(j)) => 0.5 * (cross[i][f.axis] + cross[j][f.axis]),
511                (Some(i), None) | (None, Some(i)) => cross[i][f.axis],
512                _ => 0.0,
513            };
514            if !canopy_drag.is_empty() {
515                rhs -= canopy_drag[fi] * u[fi];
516            }
517            rhs
518        })
519        .collect()
520}
521/// Turbulence production per cell in m2/s3, `2 nu_t S:S` from the cell
522/// velocity gradients, and the algebraic wall epsilon of wall-adjacent cells.
523///
524/// With `neutral_rans`, a cell with wall faces takes the mean wall-function
525/// production and dissipation over those faces instead (the second vector is
526/// `Some(epsilon)` there and `None` elsewhere). `u` are face velocities,
527/// `nut` the eddy viscosity and `k` the turbulent kinetic energy.
528pub fn production(
529    c: &Case,
530    g: &Grid,
531    u: &[f64],
532    nut: &[f64],
533    k: &[f64],
534) -> (Vec<f64>, Vec<Option<f64>>) {
535    let v = g.cell_velocity(u);
536    let mut p = vec![0.0; g.count()];
537    let mut eps_wall = vec![None; g.count()];
538    for i in 0..g.count() {
539        if !g.fluid[i] {
540            continue;
541        }
542        let neighbors = cell_neighbors(g, i);
543        let mut grad = [[0.0; 3]; 3];
544        for a in 0..3 {
545            for d in 0..3 {
546                let lo = v[neighbors[d][0]][a];
547                let hi = v[neighbors[d][1]][a];
548                grad[a][d] = (hi - lo) / (2.0 * g.dx[d]);
549            }
550        }
551        p[i] = nut[i]
552            * (0..3)
553                .flat_map(|a| (0..3).map(move |d| 0.5 * (grad[a][d] + grad[d][a]).powi(2)))
554                .sum::<f64>();
555        if let Flow::NeutralRans { roughness_m, .. } = &c.flow {
556            // A cell with several wall faces (a canyon floor corner) averages the wall
557            // production and dissipation over those faces, with equal weights.
558            let (mut p_sum, mut eps_sum, mut walls) = (0.0, 0.0, 0usize);
559            for d in 0..3 {
560                for side in 0..2 {
561                    let f = &g.faces[g.cell_faces[i][d][side]];
562                    if f.kind != FaceKind::Wall {
563                        continue;
564                    }
565                    let speed = (0..3)
566                        .filter(|a| *a != d)
567                        .map(|a| v[i][a].powi(2))
568                        .sum::<f64>()
569                        .sqrt();
570                    let ground = d == 2 && side == 0 && f.center[2] == 0.0;
571                    let z0 = if ground {
572                        *roughness_m
573                    } else {
574                        c.building_roughness_m
575                            .unwrap_or_else(|| roughness_m.min(0.001 * g.dx[d]))
576                    };
577                    let distance = 0.5 * g.dx[d] + z0;
578                    let us = 0.4 * speed / (distance / z0).ln();
579                    // High-Re wall epsilon follows k, including stagnating wall cells.
580                    // Using wall speed cubed here would collapse epsilon while k stays finite.
581                    let ep = C_MU.powf(0.75) * k[i].max(1e-14).powf(1.5) / (0.4 * distance);
582                    p_sum += us * us * C_MU.powf(0.25) * k[i].max(1e-14).sqrt() / (0.4 * distance);
583                    eps_sum += ep.max(1e-14);
584                    walls += 1;
585                }
586            }
587            if walls > 0 {
588                p[i] = p_sum / walls as f64;
589                eps_wall[i] = Some(eps_sum / walls as f64);
590            }
591        }
592    }
593    (p, eps_wall)
594}
595/// The k and epsilon transport parts of the turbulence equations, and the
596/// terms they need: production, wall epsilon and the diffusivities.
597pub(crate) struct TurbulenceTerms {
598    pub(crate) canopy: Option<crate::vegetation::TurbulenceSources>,
599    pub(crate) production: Vec<f64>,
600    pub(crate) wall_epsilon: Vec<Option<f64>>,
601    pub(crate) dk: Vec<f64>,
602    pub(crate) de: Vec<f64>,
603    pub(crate) k_transport: Vec<f64>,
604    pub(crate) e_transport: Vec<f64>,
605    /// Coefficient of k (or epsilon) in the upper-boundary diffusion term of
606    /// each cell, so the transport parts' linear operators can include it.
607    pub(crate) k_top: Vec<f64>,
608    pub(crate) e_top: Vec<f64>,
609}
610pub(crate) fn turbulence_terms(
611    c: &Case,
612    g: &Grid,
613    u: &[f64],
614    k: &[f64],
615    eps: &[f64],
616) -> TurbulenceTerms {
617    let nut = eddy_viscosity(g, k, eps);
618    let (p, walls) = production(c, g, u, &nut, k);
619    let zeros = vec![0.0; g.count()];
620    let dk: Vec<_> = nut.iter().map(|n| c.flow.viscosity() + n).collect();
621    let de: Vec<_> = nut
622        .iter()
623        .map(|n| c.flow.viscosity() + n / SIGMA_EPSILON)
624        .collect();
625    let mut kr = transport::rhs(g, k, u, &dk, &zeros, Advection::LinearUpwind, |f| {
626        c.flow.turbulence(f.center[2]).0
627    });
628    let mut er = transport::rhs(g, eps, u, &de, &zeros, Advection::LinearUpwind, |f| {
629        c.flow.turbulence(f.center[2]).1
630    });
631    let mut k_top = vec![0.0; g.count()];
632    let mut e_top = vec![0.0; g.count()];
633    // The equilibrium ABL has nonzero epsilon diffusion at the upper boundary.
634    // Zero-gradient epsilon there destroys horizontal homogeneity.
635    for f in &g.faces {
636        if f.axis == 2
637            && f.hi.is_none()
638            && f.kind == FaceKind::Slip
639            && c.boundaries.z == Boundary::GroundOpenTop
640        {
641            let i = f.lo.unwrap();
642            let (kb, eb) = c.flow.turbulence(c.domain.size_m[2]);
643            let nb = C_MU * kb * kb / eb;
644            kr.values[i] += 0.5 * (dk[i] + c.flow.viscosity() + nb) * (kb - k[i]) / f.distance
645                * f.area
646                / g.volume;
647            er.values[i] += 0.5 * (de[i] + c.flow.viscosity() + nb / SIGMA_EPSILON) * (eb - eps[i])
648                / f.distance
649                * f.area
650                / g.volume;
651            k_top[i] -= 0.5 * (dk[i] + c.flow.viscosity() + nb) / f.distance * f.area / g.volume;
652            e_top[i] -= 0.5 * (de[i] + c.flow.viscosity() + nb / SIGMA_EPSILON) / f.distance
653                * f.area
654                / g.volume;
655        }
656    }
657    TurbulenceTerms {
658        canopy: crate::vegetation::turbulence(c, g, u, k, eps),
659        production: p,
660        wall_epsilon: walls,
661        dk,
662        de,
663        k_transport: kr.values,
664        e_transport: er.values,
665        k_top,
666        e_top,
667    }
668}
669/// One explicit k-epsilon update of size `dt` on the face velocities `u`, in
670/// place, with implicit destruction terms and the algebraic wall epsilon.
671///
672/// Returns the number of fluid cells whose new k or epsilon fell below the
673/// 1e-14 floor and were raised to it; any such event fails the numerical
674/// checks. A nonfinite update stores NaN, which the state check then
675/// rejects. With `dt = 0`, as after the initial projection, k and epsilon
676/// change only by the wall epsilon and the floor.
677pub fn turbulence_step(
678    c: &Case,
679    g: &Grid,
680    u: &[f64],
681    k: &mut [f64],
682    eps: &mut [f64],
683    dt: f64,
684) -> usize {
685    let TurbulenceTerms {
686        canopy,
687        production: p,
688        wall_epsilon: walls,
689        k_transport,
690        e_transport,
691        ..
692    } = turbulence_terms(c, g, u, k, eps);
693    let mut floors = 0;
694    for i in 0..g.count() {
695        if !g.fluid[i] {
696            continue;
697        }
698        let oldk = k[i].max(1e-14);
699        let olde = eps[i].max(1e-14);
700        let (nk, ne) = if let Some(canopy) = &canopy {
701            (
702                (k[i] + dt * (k_transport[i] + p[i] + canopy.k_source[i]))
703                    / (1.0 + dt * (olde / oldk + canopy.k_sink[i])),
704                (eps[i] + dt * (e_transport[i] + C1 * p[i] * olde / oldk + canopy.e_source[i]))
705                    / (1.0 + dt * (C2 * olde / oldk + canopy.e_sink[i])),
706            )
707        } else {
708            (
709                (k[i] + dt * (k_transport[i] + p[i])) / (1.0 + dt * olde / oldk),
710                (eps[i] + dt * (e_transport[i] + C1 * p[i] * olde / oldk))
711                    / (1.0 + dt * C2 * olde / oldk),
712            )
713        };
714        if !nk.is_finite() || !ne.is_finite() {
715            k[i] = f64::NAN;
716            eps[i] = f64::NAN;
717            continue;
718        }
719        if nk < 1e-14 || ne < 1e-14 {
720            floors += 1;
721        }
722        k[i] = nk.max(1e-14);
723        eps[i] = walls[i]
724            .map(|v| v * (k[i] / oldk).powf(1.5))
725            .unwrap_or(ne.max(1e-14));
726    }
727    floors
728}