autd3_core/environment/
mod.rs

1use std::f32::consts::PI;
2
3use crate::common::{METER, ULTRASOUND_FREQ};
4
5#[non_exhaustive]
6#[repr(C)]
7#[derive(Debug, Clone, Copy, PartialEq)]
8pub struct Environment {
9    pub sound_speed: f32,
10}
11
12impl Environment {
13    /// Creates a new environment with the default sound speed (340m/s).
14    pub fn new() -> Self {
15        Self {
16            sound_speed: 340.0 * METER,
17        }
18    }
19
20    /// Sets the sound speed of envs from the temperature.
21    ///
22    /// This is equivalent to `Self::set_sound_speed_from_temp_with(t, 1.4, 8.314_463, 28.9647e-3)`.
23    pub fn set_sound_speed_from_temp(&mut self, t: f32) {
24        self.set_sound_speed_from_temp_with(t, 1.4, 8.314_463, 28.9647e-3);
25    }
26
27    /// Sets the sound speed of envs from the temperature `t`, heat capacity ratio `k`, gas constant `r`, and molar mass `m` [kg/mol].
28    pub fn set_sound_speed_from_temp_with(&mut self, t: f32, k: f32, r: f32, m: f32) {
29        self.sound_speed = (k * r * (273.15 + t) / m).sqrt() * METER;
30    }
31
32    /// Gets the wavelength of the ultrasound.
33    #[must_use]
34    pub const fn wavelength(&self) -> f32 {
35        self.sound_speed / ULTRASOUND_FREQ.hz() as f32
36    }
37
38    /// Gets the wavenumber of the ultrasound.
39    #[must_use]
40    pub const fn wavenumber(&self) -> f32 {
41        2.0 * PI * ULTRASOUND_FREQ.hz() as f32 / self.sound_speed
42    }
43}
44
45impl Default for Environment {
46    fn default() -> Self {
47        Self::new()
48    }
49}
50
51#[cfg(test)]
52pub(crate) mod tests {
53    use super::*;
54    use crate::common::mm;
55
56    #[rstest::rstest]
57    #[test]
58    #[case(340.29525e3, 15.)]
59    #[case(343.23497e3, 20.)]
60    #[case(349.04013e3, 30.)]
61    fn set_sound_speed_from_temp(#[case] expected: f32, #[case] temp: f32) {
62        let mut env = Environment::new();
63        env.set_sound_speed_from_temp(temp);
64        approx::assert_abs_diff_eq!(expected * mm, env.sound_speed, epsilon = 1e-3);
65    }
66
67    #[rstest::rstest]
68    #[test]
69    #[case(8.5, 340e3)]
70    #[case(10., 400e3)]
71    fn wavelength(#[case] expect: f32, #[case] c: f32) {
72        let mut env = Environment::new();
73        env.sound_speed = c;
74        approx::assert_abs_diff_eq!(expect, env.wavelength());
75    }
76
77    #[rstest::rstest]
78    #[test]
79    #[case(0.739_198_27, 340e3)]
80    #[case(0.628_318_55, 400e3)]
81    fn wavenumber(#[case] expect: f32, #[case] c: f32) {
82        let mut env = Environment::new();
83        env.sound_speed = c;
84        approx::assert_abs_diff_eq!(expect, env.wavenumber());
85    }
86}