#![allow(dead_code)]
use burn::{
Tensor,
config::Config,
module::Module,
prelude::{
Bool,
s,
},
tensor::{
DType,
Device,
},
};
use super::{
LbmTables,
RelaxationParam,
bgk_collision,
outflow_clipping_stream,
with_spherical_reflection,
};
use crate::{
burner::{
module::HasDType,
tensor::TensorOpExt,
},
errors::{
BunsenError,
BunsenResult,
ConstraintError,
WithOkOrPanic,
},
support::geometry::GridShape2D,
};
pub trait LBMMeta {
fn shape(&self) -> GridShape2D;
}
#[derive(Config, Debug)]
pub struct LBMD2Q9Config {
pub shape: GridShape2D,
#[config(default = "RelaxationParam::Tau(0.5)")]
pub relaxation: RelaxationParam,
}
impl LBMMeta for LBMD2Q9Config {
fn shape(&self) -> GridShape2D {
self.shape
}
}
impl LBMD2Q9Config {
pub fn try_init(
self,
device: &Device,
rho: f64,
) -> BunsenResult<LBMD2Q9State> {
let height = self.shape.height;
let width = self.shape.width;
for (field, value) in [("shape.height", height), ("shape.width", width)] {
if value < 3 {
return Err(BunsenError::from(ConstraintError::out_of_range(
"LBMD2Q9Config",
field,
value,
"[3, +inf)",
))
.with_details(format!(
"an LBM grid needs at least 3 cells on a side, for a fluid \
interior inside its outer ring; got height {height}, width {width}"
)));
}
}
self.relaxation.try_validate()?;
let solid_mask = Tensor::<2>::zeros([height, width], device).bool();
let lbm_tables = LbmTables::init(device);
let state = Tensor::<4>::zeros([height, width, 3, 3], device).slice_assign(
s![1..-1, 1..-1],
lbm_tables
.w()
.unsqueeze::<4>()
.expand([height - 2, width - 2, 3, 3])
* rho,
);
let total_mass = state.clone().sum().into_scalar();
let omega = Tensor::<2>::ones([height, width], device) * self.relaxation.as_omega_value();
Ok(LBMD2Q9State {
shape: self.shape,
step_count: 0,
dist: state,
correct_total_mass: total_mass,
solid_mask,
lbm_tables,
omega,
})
}
pub fn init(
self,
device: &Device,
rho: f64,
) -> LBMD2Q9State {
self.try_init(device, rho).ok_or_panic()
}
}
#[derive(Module, Debug)]
pub struct LBMD2Q9State {
#[module(skip)]
pub shape: GridShape2D,
pub step_count: u64,
pub correct_total_mass: f64,
pub dist: Tensor<4>,
pub solid_mask: Tensor<2, Bool>,
pub omega: Tensor<2>,
pub lbm_tables: LbmTables,
}
impl LBMMeta for LBMD2Q9State {
fn shape(&self) -> GridShape2D {
self.shape
}
}
impl HasDType for LBMD2Q9State {
fn dtype(&self) -> DType {
self.dist.dtype()
}
}
impl LBMD2Q9State {
pub fn device(&self) -> Device {
self.dist.device()
}
pub fn dtype(&self) -> DType {
self.dist.dtype()
}
pub fn to_dtype(
self,
dtype: DType,
) -> Self {
Self {
dist: self.dist.cast(dtype),
lbm_tables: self.lbm_tables.to_dtype(dtype),
..self
}
}
pub fn step_count(&self) -> u64 {
self.step_count
}
pub fn set_step_count(
&mut self,
step: u64,
) {
self.step_count = step;
}
pub fn reset_step_count(&mut self) {
self.set_step_count(0)
}
pub fn correction_term(&self) -> f64 {
let current = self.current_total_mass();
assert!(
current.is_finite() && current > 0.0,
"degenerate total mass {current}: the distribution is empty or non-finite"
);
self.correct_total_mass / current
}
pub fn advance_step(&mut self) {
let correction = self.correction_term();
let omega = self.omega.clone();
let lbm_tables = &self.lbm_tables;
let solid_mask = self
.solid_mask
.clone()
.slice_fill(s![0, ..], true)
.slice_fill(s![-1, ..], true)
.slice_fill(s![.., 0], true)
.slice_fill(s![.., -1], true);
self.dist.replace_with(|dist| {
let stream_phase = outflow_clipping_stream(dist);
with_spherical_reflection(
stream_phase.clone(),
bgk_collision(stream_phase, omega, Some(correction), lbm_tables),
solid_mask,
)
});
self.step_count += 1;
self.device().sync().unwrap();
}
pub fn current_total_mass(&self) -> f64 {
self.dist.clone().sum().into_scalar()
}
pub fn save_correct_total_mass(&mut self) {
self.correct_total_mass = self.current_total_mass();
}
}
#[cfg(test)]
mod tests {
use serial_test::serial;
use super::*;
use crate::{
errors::{
BunsenErrorKind,
testing::ErrorMatcher,
},
sims::lbm::d2q9::{
SPEED_OF_SOUND,
macroscopic_momentum,
},
support::testing::{
DeviceMemoryGuard,
performance_device,
},
};
const RHO: f64 = SPEED_OF_SOUND / 100.0;
fn small_world(device: &Device) -> LBMD2Q9State {
LBMD2Q9Config::new(GridShape2D {
width: 24,
height: 16,
})
.with_relaxation(RelaxationParam::Tau(0.9))
.init(device, RHO)
}
#[test]
#[serial]
fn test_init_fills_the_interior_only() {
let device = performance_device();
let _memory = DeviceMemoryGuard::new(&device);
let world = small_world(&device);
assert_eq!(world.dist.dims(), [16, 24, 3, 3]);
assert_eq!(world.step_count(), 0);
for ring in [
world.dist.clone().slice(s![0]),
world.dist.clone().slice(s![-1]),
world.dist.clone().slice(s![.., 0]),
world.dist.clone().slice(s![.., -1]),
] {
let total: f64 = ring.abs().sum().into_scalar();
assert_eq!(total, 0.0);
}
let expected_mass = 14.0 * 22.0 * RHO;
let mass = world.current_total_mass();
assert!(
(mass - expected_mass).abs() <= 1e-4 * expected_mass,
"mass {mass} != {expected_mass}"
);
assert!((world.correct_total_mass - mass).abs() <= 1e-4 * expected_mass);
assert!((world.correction_term() - 1.0).abs() <= 1e-6);
}
#[test]
#[serial]
fn test_advance_step_conserves_mass_and_stays_finite() {
let device = performance_device();
let _memory = DeviceMemoryGuard::new(&device);
let mut world = small_world(&device);
world.dist = world.dist.slice_fill(s![5, 7, 1, 1], 5.0 * RHO);
world.solid_mask = world.solid_mask.slice_fill(s![10, 4..12], true);
world.save_correct_total_mass();
let initial_mass = world.correct_total_mass;
for _ in 0..20 {
world.advance_step();
}
assert_eq!(world.step_count(), 20);
let all_finite: bool = world.dist.clone().is_finite().all().into_scalar();
assert!(all_finite, "the distribution went non-finite");
let mass = world.current_total_mass();
assert!(
(mass - initial_mass).abs() <= 1e-4 * initial_mass,
"mass drifted: {mass} vs {initial_mass}"
);
assert!((world.correction_term() - 1.0).abs() <= 1e-4);
let max_momentum: f64 = macroscopic_momentum(world.dist.clone(), world.lbm_tables.e_vec())
.abs()
.max()
.into_scalar();
assert!(max_momentum > 0.0);
}
#[test]
#[serial]
#[should_panic(expected = "degenerate total mass")]
fn test_correction_term_rejects_a_degenerate_mass() {
let device = performance_device();
let _memory = DeviceMemoryGuard::new(&device);
let mut world = small_world(&device);
let _taken = world.dist.extract();
let _ = world.correction_term();
}
#[test]
#[serial]
#[should_panic(expected = "at least 3 cells on a side")]
fn test_init_rejects_a_grid_under_3() {
let device = performance_device();
let _memory = DeviceMemoryGuard::new(&device);
let _ = LBMD2Q9Config::new(GridShape2D {
width: 8,
height: 1,
})
.init(&device, RHO);
}
#[test]
#[serial]
fn test_try_init_rejects_bad_configs() {
let device = performance_device();
let _memory = DeviceMemoryGuard::new(&device);
for (height, width) in [(0, 8), (1, 8), (2, 8), (8, 2), (2, 2)] {
let result = LBMD2Q9Config::new(GridShape2D { width, height }).try_init(&device, RHO);
ErrorMatcher::kind(BunsenErrorKind::Illegal)
.has_cause::<ConstraintError>()
.details_contains("at least 3 cells on a side")
.assert_err(&result);
}
let result = LBMD2Q9Config::new(GridShape2D::square(8))
.with_relaxation(RelaxationParam::Tau(0.49))
.try_init(&device, RHO);
ErrorMatcher::kind(BunsenErrorKind::Illegal)
.message_contains("RelaxationParam.tau")
.assert_err(&result);
let mut world = LBMD2Q9Config::new(GridShape2D::square(3))
.with_relaxation(RelaxationParam::Tau(0.9))
.try_init(&device, RHO)
.unwrap();
world.advance_step();
assert_eq!(world.step_count(), 1);
}
}