bunsen 0.40.0

bunsen is a batteries included common library for burn
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
#![allow(dead_code)]
//! # LBM D2Q9 World Module

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,
};

/// Introspection trait for [`LBMD2Q9State`]
pub trait LBMMeta {
    /// Returns the shape of the simulation: `[HEIGHT, WIDTH]`.
    fn shape(&self) -> GridShape2D;
}

/// Config for [`LBMD2Q9State`]
///
/// Specifies the `[HEIGHT, WIDTH]` grid shape, at least 3 cells on a side,
/// and the [`RelaxationParam`]. Call `.init(device, rho)` (or
/// [`try_init`](Self::try_init)) to build a relaxed [`LBMD2Q9State`] module
/// ready to be advanced step by step, one step per
/// [`advance_step`](LBMD2Q9State::advance_step). Implements [`LBMMeta`].
#[derive(Config, Debug)]
pub struct LBMD2Q9Config {
    /// The shape of the simulation.
    pub shape: GridShape2D,

    /// Relaxation Param
    #[config(default = "RelaxationParam::Tau(0.5)")]
    pub relaxation: RelaxationParam,
}

impl LBMMeta for LBMD2Q9Config {
    fn shape(&self) -> GridShape2D {
        self.shape
    }
}

impl LBMD2Q9Config {
    /// Initializes a [`LBMD2Q9State`] module.
    ///
    /// The interior is fluid at rest at density `rho`, the outer ring is
    /// empty, and the total mass is recorded as the target the mass
    /// correction holds.
    ///
    /// The fallible half of a `try_x` / `x` pair; the panicking half is
    /// [`init`](Self::init).
    ///
    /// # Errors
    ///
    /// [`Illegal`](crate::errors::BunsenErrorKind::Illegal), with a
    /// [`ConstraintError`] cause, if the grid is under 3 cells on a side,
    /// which leaves no fluid inside the outer ring, or if the relaxation is
    /// out of range ([`RelaxationParam::try_validate`]).
    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);

        // Start off in a relaxed state. The border ring is zero, and it must
        // be: nothing later writes it from outside, and the mass total covers
        // the whole grid.
        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,
        })
    }

    /// Initializes a [`LBMD2Q9State`] module, or panics; the panicking twin
    /// of [`try_init`](Self::try_init).
    ///
    /// # Panics
    ///
    /// With the [`try_init`](Self::try_init) error's message: if the grid is
    /// under 3 cells on a side, or the relaxation is out of range.
    pub fn init(
        self,
        device: &Device,
        rho: f64,
    ) -> LBMD2Q9State {
        self.try_init(device, rho).ok_or_panic()
    }
}

/// Lattice-Boltzmann Fluid Simulation State Module
///
/// Holds the D2Q9 population distribution `[H, W, 3, 3]`, the relaxation field,
/// solid mask, and [`LbmTables`] lattice constants. Construct it from a
/// [`LBMD2Q9Config`] via `.init(device, rho)`, then call
/// [`LBMD2Q9State::advance_step`] to stream, collide, and reflect the fluid one
/// step at a time. Implements [`LBMMeta`].
///
/// The tensors are public, for the caller to edit between steps, and are
/// held bare, not as parameters. The step and the mass correction are
/// described in the [`d2q9`](super) docs.
///
/// Built by [`LBMD2Q9Config`].
#[derive(Module, Debug)]
pub struct LBMD2Q9State {
    /// The grid shape.
    #[module(skip)]
    pub shape: GridShape2D,

    /// The current simulation step.
    pub step_count: u64,

    /// The total mass the mass correction steers toward: the mass `init`
    /// built, until [`save_correct_total_mass`](Self::save_correct_total_mass)
    /// replaces it.
    pub correct_total_mass: f64,

    /// The grid velocity: `[H, W, UY=3, UX=3]`
    /// Here the 0-9 velocity terms are unfolded
    /// into the ``UY`` and ``UX`` dims.
    pub dist: Tensor<4>,

    /// The solid mask: `[H, W]`
    pub solid_mask: Tensor<2, Bool>,

    /// The relaxation field.
    pub omega: Tensor<2>,

    /// Space Constants
    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 {
    /// Returns the device the module is on.
    pub fn device(&self) -> Device {
        self.dist.device()
    }

    /// Returns the datatype of the state.
    pub fn dtype(&self) -> DType {
        self.dist.dtype()
    }

    /// Recasts the datatype of the state.
    pub fn to_dtype(
        self,
        dtype: DType,
    ) -> Self {
        Self {
            dist: self.dist.cast(dtype),
            lbm_tables: self.lbm_tables.to_dtype(dtype),
            ..self
        }
    }

    /// Returns the current simulation step count.
    pub fn step_count(&self) -> u64 {
        self.step_count
    }

    /// Sets the current simulation step count.
    pub fn set_step_count(
        &mut self,
        step: u64,
    ) {
        self.step_count = step;
    }

    /// Resets the simulation step count to zero.
    pub fn reset_step_count(&mut self) {
        self.set_step_count(0)
    }

    /// Returns the mass correction term: the target mass,
    /// `correct_total_mass`, over the current total. The next step scales
    /// the fluid cells' collision result by it.
    ///
    /// # Panics
    ///
    /// If the current total mass is not finite and positive: the distribution
    /// is empty, or it has gone non-finite.
    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
    }

    /// Advances the world simulation by one step: stream, collide (scaled by
    /// [`correction_term`](Self::correction_term)), and reflect off the
    /// solid mask, with the grid's outer ring counted as solid.
    ///
    /// # Panics
    ///
    /// As [`correction_term`](Self::correction_term), or if the backend
    /// fails to sync.
    pub fn advance_step(&mut self) {
        // Everything the step reads from `self` is read here, before the
        // distribution is taken out of `self.dist` for the in-place update.
        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,
            )
        });

        // TODO: better handle of numerical instability.
        // let dist = dist.clone().mask_fill(dist.is_finite().bool_not(), 0.0);

        self.step_count += 1;

        self.device().sync().unwrap();
    }

    /// Returns the current mass of the simm.
    pub fn current_total_mass(&self) -> f64 {
        self.dist.clone().sum().into_scalar()
    }

    /// Makes the current total mass the target the mass correction steers
    /// toward. Call it after changing the mass on purpose; otherwise the
    /// following steps scale the change away.
    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,
        },
        kits::sims::lbm::d2q9::{
            SPEED_OF_SOUND,
            macroscopic_momentum,
        },
        support::testing::{
            DeviceMemoryGuard,
            performance_device,
        },
    };

    const RHO: f64 = SPEED_OF_SOUND / 100.0;

    /// A 16 x 24 world at rest density `RHO`.
    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);

        // The border ring is zero, not whatever the allocator held.
        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);
        }

        // The interior carries `RHO` per cell, and the saved mass is that sum.
        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);

        // A rest-population bump and a wall give the fluid something to do.
        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);

        // Every population is finite.
        let all_finite: bool = world.dist.clone().is_finite().all().into_scalar();
        assert!(all_finite, "the distribution went non-finite");

        // Mass is conserved to float precision, so the correction stays ~1.
        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);

        // The bump has spread: momentum is nonzero somewhere.
        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);

        // What `extract()` leaves behind: an empty distribution.
        let _taken = world.dist.extract();
        let _ = world.correction_term();
    }

    /// A grid under 3 cells on a side has no fluid interior: `init` panics
    /// with the `try_init` error.
    #[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);
    }

    /// `try_init` rejects a grid under 3 cells on a side, or an out-of-range
    /// relaxation, with an `Err`; a 3x3 grid, one fluid cell inside the
    /// outer ring, builds and steps.
    #[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);
    }
}