1#![allow(clippy::needless_range_loop)]
14use crate::{
15 case::*,
16 grid::{FaceKind, Grid},
17 transport,
18};
19use rayon::prelude::*;
20
21pub const C_MU: f64 = 0.09;
23pub const C1: f64 = 1.44;
25pub const C2: f64 = 1.92;
27pub const SIGMA_EPSILON: f64 = 0.4 * 0.4 / ((C2 - C1) * 0.3);
30pub 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#[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#[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}
181fn 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
195pub enum Reconstruction {
196 FirstOrder,
199 SecondOrder,
201 VanAlbada,
203 VanLeer,
205 MonotonizedCentral,
207}
208impl Reconstruction {
209 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 (MomentumAdvection::LimitedUpwind, None) => Some(Self::FirstOrder),
226 }
227 }
228 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
244fn interior(g: &Grid, face: Option<usize>) -> Option<usize> {
246 face.filter(|&j| matches!(g.faces[j].kind, FaceKind::Interior | FaceKind::Outlet))
247}
248
249pub 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
269fn 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 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 let edge_core = |d: usize,
303 d_faces: [Option<usize>; 2],
304 [at_q, above, below, above2]: [Option<usize>; 4]|
305 -> f64 {
306 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 (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 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 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 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
426pub 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 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 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 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}
521pub 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 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 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}
595pub(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 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 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}
669pub 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}