Add design persistence, world rendering, metrics overlay and logs
M3: STL/OBJ import with mesh validation, mass/COM/inertia, material database, RON scene with content-addressed blobs and v0->v1 migration. M4: deterministic heightmap terrain, trimesh colliders, wgpu renderer with instancing and depth, winit app with 1 kHz physics, fly camera, on-screen metrics overlay and per-frame CSV/dev logs. Docs: UI, logging, network and headless CLI plans.
This commit is contained in:
parent
79928b645b
commit
93075ab1fd
107 changed files with 14785 additions and 46 deletions
35
crates/sensors/src/delay.rs
Normal file
35
crates/sensors/src/delay.rs
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
//! A fixed-length FIFO that models the transport delay of a sensor bus.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
/// A FIFO of `steps` samples.
|
||||
///
|
||||
/// The queue starts filled with `initial`, so the first `steps` calls to
|
||||
/// [`Delay::push`] report that value while the queue drains.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Delay<T> {
|
||||
initial: T,
|
||||
queue: VecDeque<T>,
|
||||
}
|
||||
|
||||
impl<T: Clone> Delay<T> {
|
||||
/// A delay of `steps` samples, reporting `initial` until the queue fills.
|
||||
pub fn new(steps: usize, initial: T) -> Self {
|
||||
Self {
|
||||
initial: initial.clone(),
|
||||
queue: core::iter::repeat_n(initial, steps).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pushes a new sample and returns the one measured `steps` samples ago, or the
|
||||
/// new sample itself when the delay is zero.
|
||||
pub fn push(&mut self, value: T) -> T {
|
||||
if self.queue.is_empty() {
|
||||
return value;
|
||||
}
|
||||
self.queue.push_back(value);
|
||||
self.queue
|
||||
.pop_front()
|
||||
.unwrap_or_else(|| self.initial.clone())
|
||||
}
|
||||
}
|
||||
|
|
@ -1 +1,139 @@
|
|||
//! fabrilis-sensors :: encoder - stub (see docs/ARCHITECTURE.md)
|
||||
//! Quadrature encoder model: quantization, bias, noise and transport delay.
|
||||
//!
|
||||
//! A full revolution is split into `2^resolution_bits` counts. The sensor quantizes
|
||||
//! the true angle, adds a constant bias and Gaussian noise, and reports the result
|
||||
//! through a FIFO delay, so a controller sees the past, not the present.
|
||||
|
||||
use fabrilis_core::math;
|
||||
use fabrilis_core::rng::Rng;
|
||||
use fabrilis_core::units::Radians;
|
||||
|
||||
use crate::delay::Delay;
|
||||
use crate::noise::Noise;
|
||||
|
||||
/// One full revolution, rad.
|
||||
const FULL_TURN: f64 = math::TAU;
|
||||
|
||||
/// Smallest accepted `resolution_bits`; one bit still gives two counts per revolution.
|
||||
const MIN_BITS: u8 = 1;
|
||||
|
||||
/// Largest accepted `resolution_bits`; `2^31` counts per revolution fits `u32` and `i64`.
|
||||
const MAX_BITS: u8 = 31;
|
||||
|
||||
/// Encoder parameters.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct EncoderConfig {
|
||||
/// Counts per revolution is `2^resolution_bits`; must be in `1..=31`.
|
||||
pub resolution_bits: u8,
|
||||
/// Standard deviation of the Gaussian noise, rad.
|
||||
pub noise_sigma: f64,
|
||||
/// Constant measurement offset, rad.
|
||||
pub bias: f64,
|
||||
/// Transport delay in samples.
|
||||
pub delay_steps: usize,
|
||||
}
|
||||
|
||||
impl Default for EncoderConfig {
|
||||
/// A 12-bit encoder without noise, bias or delay.
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
resolution_bits: 12,
|
||||
noise_sigma: 0.0,
|
||||
bias: 0.0,
|
||||
delay_steps: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why an [`Encoder`] could not be created.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum EncoderError {
|
||||
/// The bit count is outside `1..=31`, so the count grid is unusable.
|
||||
ResolutionOutOfRange(u8),
|
||||
}
|
||||
|
||||
impl core::fmt::Display for EncoderError {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
Self::ResolutionOutOfRange(bits) => write!(
|
||||
f,
|
||||
"encoder resolution of {bits} bits is outside {MIN_BITS}..={MAX_BITS}"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for EncoderError {}
|
||||
|
||||
/// An angle encoder with quantization, noise, bias and delay.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Encoder {
|
||||
resolution_bits: u8,
|
||||
counts: u64,
|
||||
noise: Noise,
|
||||
bias: f64,
|
||||
delay: Delay<Radians>,
|
||||
rng: Rng,
|
||||
}
|
||||
|
||||
impl Encoder {
|
||||
/// Creates an encoder, or reports an unusable resolution.
|
||||
pub fn new(config: EncoderConfig, seed: u64) -> Result<Self, EncoderError> {
|
||||
let bits = config.resolution_bits;
|
||||
if !(MIN_BITS..=MAX_BITS).contains(&bits) {
|
||||
return Err(EncoderError::ResolutionOutOfRange(bits));
|
||||
}
|
||||
Ok(Self {
|
||||
resolution_bits: bits,
|
||||
counts: 1u64 << bits,
|
||||
noise: Noise::new(config.noise_sigma),
|
||||
bias: config.bias,
|
||||
delay: Delay::new(config.delay_steps, Radians::ZERO),
|
||||
rng: Rng::new(seed),
|
||||
})
|
||||
}
|
||||
|
||||
/// Declared resolution in bits.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn resolution_bits(&self) -> u8 {
|
||||
self.resolution_bits
|
||||
}
|
||||
|
||||
/// Counts per full revolution, `2^resolution_bits`.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn counts_per_revolution(&self) -> u64 {
|
||||
self.counts
|
||||
}
|
||||
|
||||
/// Measures `true_angle`.
|
||||
///
|
||||
/// The angle is quantized to the nearest count, ties round up (towards `+∞`), and
|
||||
/// the count is wrapped modulo `2^resolution_bits`, so the quantized angle always
|
||||
/// lies in `[0, TAU)`. Bias and noise are added after quantization, then the value
|
||||
/// goes through the delay FIFO. Non-finite input is measured as `0` rad.
|
||||
///
|
||||
/// Until the FIFO fills, the reported value is the initial `0` rad.
|
||||
pub fn sample(&mut self, true_angle: Radians) -> Radians {
|
||||
let quantized = self.quantize(true_angle);
|
||||
let biased = quantized.get() + self.bias;
|
||||
let measured = Radians(self.noise.apply(biased, &mut self.rng));
|
||||
self.delay.push(measured)
|
||||
}
|
||||
|
||||
fn quantize(&self, angle: Radians) -> Radians {
|
||||
let counts = self.counts as f64;
|
||||
let step = FULL_TURN / counts;
|
||||
let scaled = angle.get() / step;
|
||||
if !scaled.is_finite() {
|
||||
return Radians::ZERO;
|
||||
}
|
||||
// Ties round up; `floor` and `rem_euclid` are exact IEEE operations.
|
||||
let count = (scaled + 0.5).floor().rem_euclid(counts);
|
||||
Radians(count * step)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
|
|
|||
176
crates/sensors/src/encoder/tests.rs
Normal file
176
crates/sensors/src/encoder/tests.rs
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
use fabrilis_core::math;
|
||||
use fabrilis_core::units::Radians;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Counts per revolution for the small test encoder.
|
||||
const COUNTS: f64 = 1024.0;
|
||||
|
||||
/// One count of the test encoder, rad.
|
||||
const STEP: f64 = math::TAU / COUNTS;
|
||||
|
||||
fn quiet() -> EncoderConfig {
|
||||
EncoderConfig {
|
||||
resolution_bits: 10,
|
||||
noise_sigma: 0.0,
|
||||
bias: 0.0,
|
||||
delay_steps: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn build(config: EncoderConfig) -> Encoder {
|
||||
Encoder::new(config, 42).expect("test resolution is valid")
|
||||
}
|
||||
|
||||
/// An angle that sits exactly on the count grid.
|
||||
fn grid(count: f64) -> Radians {
|
||||
Radians::new(count * STEP)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_an_unusable_resolution() {
|
||||
let zero = Encoder::new(
|
||||
EncoderConfig {
|
||||
resolution_bits: 0,
|
||||
..quiet()
|
||||
},
|
||||
1,
|
||||
);
|
||||
assert_eq!(zero.err(), Some(EncoderError::ResolutionOutOfRange(0)));
|
||||
let wide = Encoder::new(
|
||||
EncoderConfig {
|
||||
resolution_bits: 32,
|
||||
..quiet()
|
||||
},
|
||||
1,
|
||||
);
|
||||
assert_eq!(wide.err(), Some(EncoderError::ResolutionOutOfRange(32)));
|
||||
for bits in [1, 12, 31] {
|
||||
let encoder = Encoder::new(
|
||||
EncoderConfig {
|
||||
resolution_bits: bits,
|
||||
..quiet()
|
||||
},
|
||||
1,
|
||||
);
|
||||
assert!(encoder.is_ok(), "bits {bits}");
|
||||
}
|
||||
assert_eq!(build(quiet()).counts_per_revolution(), 1024);
|
||||
assert_eq!(build(quiet()).resolution_bits(), 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quiet_encoder_passes_grid_angles_through_bitwise() {
|
||||
let mut encoder = build(quiet());
|
||||
for count in [0.0, 1.0, 3.0, 512.0, 1023.0] {
|
||||
let angle = grid(count);
|
||||
assert_eq!(
|
||||
encoder.sample(angle).get().to_bits(),
|
||||
angle.get().to_bits(),
|
||||
"count {count}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quantization_snaps_to_the_nearest_count() {
|
||||
let mut encoder = build(quiet());
|
||||
let cases = [
|
||||
(3.4, 3.0),
|
||||
(3.49, 3.0),
|
||||
(3.5, 4.0),
|
||||
(3.6, 4.0),
|
||||
(-0.4, 0.0),
|
||||
(-0.5, 0.0),
|
||||
(-0.6, 1023.0),
|
||||
];
|
||||
for (input, expected) in cases {
|
||||
let measured = encoder.sample(Radians::new(input * STEP));
|
||||
assert_eq!(
|
||||
measured.get().to_bits(),
|
||||
grid(expected).get().to_bits(),
|
||||
"input {input} count"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_turn_wraps_to_zero() {
|
||||
let mut encoder = build(quiet());
|
||||
let measured = encoder.sample(Radians::new(math::TAU));
|
||||
assert_eq!(measured.get().to_bits(), 0.0_f64.to_bits());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_finite_angle_is_measured_as_zero() {
|
||||
let mut encoder = build(quiet());
|
||||
assert_eq!(
|
||||
encoder.sample(Radians::new(f64::INFINITY)).get().to_bits(),
|
||||
0.0_f64.to_bits()
|
||||
);
|
||||
assert_eq!(
|
||||
encoder.sample(Radians::new(f64::NAN)).get().to_bits(),
|
||||
0.0_f64.to_bits()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bias_shifts_the_quantized_angle() {
|
||||
let mut encoder = build(EncoderConfig {
|
||||
bias: STEP,
|
||||
..quiet()
|
||||
});
|
||||
assert_eq!(
|
||||
encoder.sample(Radians::ZERO).get().to_bits(),
|
||||
STEP.to_bits()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delay_reports_the_sample_from_n_steps_ago() {
|
||||
let mut encoder = build(EncoderConfig {
|
||||
delay_steps: 3,
|
||||
..quiet()
|
||||
});
|
||||
let mut measured = Vec::new();
|
||||
for count in [10.0, 20.0, 30.0, 40.0, 50.0] {
|
||||
measured.push(encoder.sample(grid(count)));
|
||||
}
|
||||
let expected = [grid(0.0), grid(0.0), grid(0.0), grid(10.0), grid(20.0)];
|
||||
for (value, want) in measured.iter().zip(expected) {
|
||||
assert_eq!(value.get().to_bits(), want.get().to_bits());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_seed_repeats_and_different_seeds_differ() {
|
||||
let noisy = EncoderConfig {
|
||||
noise_sigma: 0.01,
|
||||
delay_steps: 2,
|
||||
..quiet()
|
||||
};
|
||||
let mut a = Encoder::new(noisy, 7).expect("test resolution is valid");
|
||||
let mut b = Encoder::new(noisy, 7).expect("test resolution is valid");
|
||||
let mut c = Encoder::new(noisy, 8).expect("test resolution is valid");
|
||||
let mut differs = false;
|
||||
for step in 0..50 {
|
||||
let angle = grid(f64::from(step) * 7.0);
|
||||
let (first, repeated, other) = (a.sample(angle), b.sample(angle), c.sample(angle));
|
||||
assert_eq!(first.get().to_bits(), repeated.get().to_bits());
|
||||
differs |= first.get().to_bits() != other.get().to_bits();
|
||||
}
|
||||
assert!(differs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_stays_finite_over_many_samples() {
|
||||
let mut encoder = build(EncoderConfig {
|
||||
noise_sigma: 10.0,
|
||||
delay_steps: 4,
|
||||
..quiet()
|
||||
});
|
||||
for step in 0..10_000 {
|
||||
let measured = encoder.sample(Radians::new(f64::from(step) * 1e-3));
|
||||
assert!(measured.get().is_finite(), "step {step}");
|
||||
}
|
||||
}
|
||||
|
|
@ -1 +1,137 @@
|
|||
//! fabrilis-sensors :: imu - stub (see docs/ARCHITECTURE.md)
|
||||
//! Inertial measurement unit: a gyro and an accelerometer with noise, bias and delay.
|
||||
//!
|
||||
//! The model is deliberately minimal: no magnetometer and no sensor fusion, so the
|
||||
//! caller supplies the true orientation and receives a perturbed measurement of it.
|
||||
//! Noise applies to every output component, bias to the measured vectors, and the
|
||||
//! whole sample goes through a FIFO.
|
||||
|
||||
use fabrilis_core::rng::Rng;
|
||||
use fabrilis_core::units::RadiansPerSecond;
|
||||
use fabrilis_core::vec::{Quat, Vec3};
|
||||
|
||||
use crate::delay::Delay;
|
||||
use crate::noise::Noise;
|
||||
|
||||
/// IMU parameters.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct ImuConfig {
|
||||
/// Standard deviation of the Gaussian noise, applied to every output component.
|
||||
///
|
||||
/// Orientation components are dimensionless, angular velocity is in rad/s and
|
||||
/// acceleration in m/s², so one sigma serves all three at modest accuracy.
|
||||
pub noise_sigma: f64,
|
||||
/// Constant additive offset of angular velocity and acceleration, per component.
|
||||
///
|
||||
/// Orientation carries no bias: a constant quaternion offset is not a rotation.
|
||||
pub bias: f64,
|
||||
/// Transport delay in samples.
|
||||
pub delay_steps: usize,
|
||||
}
|
||||
|
||||
impl Default for ImuConfig {
|
||||
/// An IMU without noise, bias or delay.
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
noise_sigma: 0.0,
|
||||
bias: 0.0,
|
||||
delay_steps: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One IMU measurement, expressed in the body frame.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct ImuSample {
|
||||
/// Measured orientation of the body in the world frame.
|
||||
pub orientation: Quat,
|
||||
/// Measured angular velocity, rad/s.
|
||||
pub angular_velocity: Vec3,
|
||||
/// Measured proper acceleration, m/s².
|
||||
pub acceleration: Vec3,
|
||||
}
|
||||
|
||||
impl ImuSample {
|
||||
/// The value reported until the delay FIFO fills.
|
||||
pub const AT_REST: Self = Self {
|
||||
orientation: Quat::IDENTITY,
|
||||
angular_velocity: Vec3::ZERO,
|
||||
acceleration: Vec3::ZERO,
|
||||
};
|
||||
}
|
||||
|
||||
/// A gyro and an accelerometer with noise, bias and delay.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Imu {
|
||||
noise: Noise,
|
||||
bias: f64,
|
||||
delay: Delay<ImuSample>,
|
||||
rng: Rng,
|
||||
}
|
||||
|
||||
impl Imu {
|
||||
/// Creates an IMU; every configuration is valid.
|
||||
#[must_use]
|
||||
pub fn new(config: ImuConfig, seed: u64) -> Self {
|
||||
Self {
|
||||
noise: Noise::new(config.noise_sigma),
|
||||
bias: config.bias,
|
||||
delay: Delay::new(config.delay_steps, ImuSample::AT_REST),
|
||||
rng: Rng::new(seed),
|
||||
}
|
||||
}
|
||||
|
||||
/// Measures one instant of the true state.
|
||||
///
|
||||
/// The gyro models a single body axis: the scalar `angular_velocity` is the rate
|
||||
/// about body Z, and X and Y measure only noise and bias. Orientation components
|
||||
/// are perturbed independently and renormalized, but only when noise is enabled,
|
||||
/// so a noise-free IMU reproduces the input bit for bit.
|
||||
///
|
||||
/// Until the FIFO fills, the reported sample is [`ImuSample::AT_REST`].
|
||||
pub fn sample(
|
||||
&mut self,
|
||||
true_orientation: Quat,
|
||||
angular_velocity: RadiansPerSecond,
|
||||
acceleration: Vec3,
|
||||
) -> ImuSample {
|
||||
let noise = self.noise;
|
||||
let bias = self.bias;
|
||||
let rng = &mut self.rng;
|
||||
let orientation = measured_orientation(true_orientation, noise, rng);
|
||||
let rate = Vec3::new(0.0, 0.0, angular_velocity.get());
|
||||
let measured = ImuSample {
|
||||
orientation,
|
||||
angular_velocity: measured_vec3(rate, noise, bias, rng),
|
||||
acceleration: measured_vec3(acceleration, noise, bias, rng),
|
||||
};
|
||||
self.delay.push(measured)
|
||||
}
|
||||
}
|
||||
|
||||
fn measured_orientation(true_orientation: Quat, noise: Noise, rng: &mut Rng) -> Quat {
|
||||
if noise.is_zero() {
|
||||
return true_orientation;
|
||||
}
|
||||
let q = Quat::new(
|
||||
true_orientation.w + noise.sample(rng),
|
||||
true_orientation.x + noise.sample(rng),
|
||||
true_orientation.y + noise.sample(rng),
|
||||
true_orientation.z + noise.sample(rng),
|
||||
);
|
||||
q.normalize().unwrap_or(true_orientation)
|
||||
}
|
||||
|
||||
fn measured_vec3(true_value: Vec3, noise: Noise, bias: f64, rng: &mut Rng) -> Vec3 {
|
||||
Vec3::new(
|
||||
measured_component(true_value.x, noise, bias, rng),
|
||||
measured_component(true_value.y, noise, bias, rng),
|
||||
measured_component(true_value.z, noise, bias, rng),
|
||||
)
|
||||
}
|
||||
|
||||
fn measured_component(true_value: f64, noise: Noise, bias: f64, rng: &mut Rng) -> f64 {
|
||||
bias + noise.apply(true_value, rng)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
|
|
|||
139
crates/sensors/src/imu/tests.rs
Normal file
139
crates/sensors/src/imu/tests.rs
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
use fabrilis_core::units::RadiansPerSecond;
|
||||
use fabrilis_core::vec::{Quat, Vec3};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn quiet() -> ImuConfig {
|
||||
ImuConfig {
|
||||
noise_sigma: 0.0,
|
||||
bias: 0.0,
|
||||
delay_steps: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn truth() -> (Quat, RadiansPerSecond, Vec3) {
|
||||
(
|
||||
Quat::IDENTITY,
|
||||
RadiansPerSecond::new(0.75),
|
||||
Vec3::new(1.5, -2.25, 9.81),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_quiet_imu_reproduces_the_true_state_bitwise() {
|
||||
let mut imu = Imu::new(quiet(), 21);
|
||||
let (orientation, rate, acceleration) = truth();
|
||||
let sample = imu.sample(orientation, rate, acceleration);
|
||||
assert_eq!(sample.orientation, orientation);
|
||||
assert_eq!(sample.angular_velocity.x, 0.0);
|
||||
assert_eq!(sample.angular_velocity.y, 0.0);
|
||||
assert_eq!(sample.angular_velocity.z.to_bits(), rate.get().to_bits());
|
||||
assert_eq!(sample.acceleration.x.to_bits(), acceleration.x.to_bits());
|
||||
assert_eq!(sample.acceleration.y.to_bits(), acceleration.y.to_bits());
|
||||
assert_eq!(sample.acceleration.z.to_bits(), acceleration.z.to_bits());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delay_reports_the_rest_sample_until_the_queue_fills() {
|
||||
let mut imu = Imu::new(
|
||||
ImuConfig {
|
||||
delay_steps: 2,
|
||||
..quiet()
|
||||
},
|
||||
3,
|
||||
);
|
||||
let (orientation, rate, acceleration) = truth();
|
||||
assert_eq!(
|
||||
imu.sample(orientation, rate, acceleration),
|
||||
ImuSample::AT_REST
|
||||
);
|
||||
assert_eq!(
|
||||
imu.sample(orientation, rate, acceleration),
|
||||
ImuSample::AT_REST
|
||||
);
|
||||
let delayed = imu.sample(orientation, rate, acceleration);
|
||||
assert_eq!(delayed.orientation, orientation);
|
||||
assert_eq!(delayed.angular_velocity.z.to_bits(), rate.get().to_bits());
|
||||
assert_eq!(delayed.acceleration.z.to_bits(), acceleration.z.to_bits());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bias_offsets_angular_velocity_and_acceleration() {
|
||||
let mut imu = Imu::new(
|
||||
ImuConfig {
|
||||
bias: 0.5,
|
||||
..quiet()
|
||||
},
|
||||
4,
|
||||
);
|
||||
let (orientation, rate, acceleration) = truth();
|
||||
let sample = imu.sample(orientation, rate, acceleration);
|
||||
assert_eq!(sample.angular_velocity.x, 0.5);
|
||||
assert_eq!(
|
||||
sample.angular_velocity.z.to_bits(),
|
||||
(0.5 + rate.get()).to_bits()
|
||||
);
|
||||
assert_eq!(
|
||||
sample.acceleration.x.to_bits(),
|
||||
(0.5 + acceleration.x).to_bits()
|
||||
);
|
||||
assert_eq!(sample.orientation, orientation);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_zero_rate_lands_on_the_z_axis_only() {
|
||||
let mut imu = Imu::new(quiet(), 5);
|
||||
let (_, rate, acceleration) = truth();
|
||||
let sample = imu.sample(Quat::IDENTITY, rate, acceleration);
|
||||
assert_eq!(sample.angular_velocity, Vec3::new(0.0, 0.0, rate.get()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_seed_repeats_and_different_seeds_differ() {
|
||||
let noisy = ImuConfig {
|
||||
noise_sigma: 0.01,
|
||||
bias: 0.001,
|
||||
delay_steps: 1,
|
||||
};
|
||||
let mut a = Imu::new(noisy, 6);
|
||||
let mut b = Imu::new(noisy, 6);
|
||||
let mut c = Imu::new(noisy, 7);
|
||||
let (orientation, rate, acceleration) = truth();
|
||||
let mut differs = false;
|
||||
for _ in 0..50 {
|
||||
let first = a.sample(orientation, rate, acceleration);
|
||||
let repeated = b.sample(orientation, rate, acceleration);
|
||||
let other = c.sample(orientation, rate, acceleration);
|
||||
assert_eq!(
|
||||
first.acceleration.z.to_bits(),
|
||||
repeated.acceleration.z.to_bits()
|
||||
);
|
||||
assert_eq!(
|
||||
first.orientation.w.to_bits(),
|
||||
repeated.orientation.w.to_bits()
|
||||
);
|
||||
differs |= first.acceleration.z.to_bits() != other.acceleration.z.to_bits();
|
||||
}
|
||||
assert!(differs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_stays_finite_and_the_orientation_stays_normalized() {
|
||||
let mut imu = Imu::new(
|
||||
ImuConfig {
|
||||
noise_sigma: 0.05,
|
||||
bias: 0.1,
|
||||
delay_steps: 3,
|
||||
},
|
||||
8,
|
||||
);
|
||||
let (orientation, rate, acceleration) = truth();
|
||||
for step in 0..10_000 {
|
||||
let sample = imu.sample(orientation, rate, acceleration);
|
||||
let norm = sample.orientation.norm_squared();
|
||||
assert!((norm - 1.0).abs() < 1e-12, "step {step}: norm {norm}");
|
||||
assert!(sample.orientation.w.is_finite(), "step {step}");
|
||||
assert!(sample.angular_velocity.is_finite(), "step {step}");
|
||||
assert!(sample.acceleration.is_finite(), "step {step}");
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
//! IMU, encoders, current sensors: noise, bias, delay, sampling
|
||||
mod delay;
|
||||
pub mod encoder;
|
||||
pub mod imu;
|
||||
pub mod noise;
|
||||
|
|
|
|||
|
|
@ -1 +1,69 @@
|
|||
//! fabrilis-sensors :: noise - stub (see docs/ARCHITECTURE.md)
|
||||
//! Additive white Gaussian noise for sensor models.
|
||||
//!
|
||||
//! Sampling uses the Box-Muller transform over the seeded [`Rng`], so a sequence is
|
||||
//! identical on every platform (docs/DETERMINISM.md). A zero sigma returns exactly
|
||||
//! `0.0` and does not touch the generator, which lets a noise-free sensor reproduce
|
||||
//! its input bit for bit.
|
||||
|
||||
use fabrilis_core::math;
|
||||
use fabrilis_core::rng::Rng;
|
||||
|
||||
/// Gaussian noise with standard deviation `sigma`, in the units of the measured value.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Noise {
|
||||
sigma: f64,
|
||||
}
|
||||
|
||||
impl Noise {
|
||||
/// Creates a noise source with standard deviation `sigma`.
|
||||
///
|
||||
/// A negative, zero or non-finite `sigma` disables the noise; the sign of `sigma`
|
||||
/// carries no meaning here.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn new(sigma: f64) -> Self {
|
||||
let sigma = if sigma.is_finite() && sigma > 0.0 {
|
||||
sigma
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
Self { sigma }
|
||||
}
|
||||
|
||||
/// The standard deviation in the units of the measured value.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn sigma(self) -> f64 {
|
||||
self.sigma
|
||||
}
|
||||
|
||||
/// True when this source adds nothing and leaves the generator untouched.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn is_zero(self) -> bool {
|
||||
self.sigma == 0.0
|
||||
}
|
||||
|
||||
/// One sample from a normal distribution with mean `0.0` and standard deviation
|
||||
/// `sigma`.
|
||||
///
|
||||
/// A zero sigma returns exactly `0.0` and does not advance `rng`.
|
||||
pub fn sample(self, rng: &mut Rng) -> f64 {
|
||||
if self.sigma == 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
// `u1` lies in `(0, 1]`, so the logarithm stays finite, and `u2` in `[0, 1)`.
|
||||
let u1 = 1.0 - rng.next_f64();
|
||||
let u2 = rng.next_f64();
|
||||
let radius = math::sqrt(-2.0 * math::ln(u1));
|
||||
self.sigma * radius * math::cos(math::TAU * u2)
|
||||
}
|
||||
|
||||
/// `value` with one noise sample added.
|
||||
pub fn apply(self, value: f64, rng: &mut Rng) -> f64 {
|
||||
value + self.sample(rng)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
|
|
|||
74
crates/sensors/src/noise/tests.rs
Normal file
74
crates/sensors/src/noise/tests.rs
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
use fabrilis_core::rng::Rng;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn zero_sigma_returns_zero_and_keeps_the_generator_untouched() {
|
||||
let mut rng = Rng::new(5);
|
||||
assert_eq!(Noise::new(0.0).sample(&mut rng), 0.0);
|
||||
let mut reference = Rng::new(5);
|
||||
assert_eq!(rng.next_u64(), reference.next_u64());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_sigma_passes_the_value_through_bitwise() {
|
||||
let mut rng = Rng::new(6);
|
||||
let value = -1.234_567_890_123e-7;
|
||||
let measured = Noise::new(0.0).apply(value, &mut rng);
|
||||
assert_eq!(measured.to_bits(), value.to_bits());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_and_non_finite_sigma_disable_the_noise() {
|
||||
assert_eq!(Noise::new(-1.0).sigma(), 0.0);
|
||||
assert_eq!(Noise::new(f64::NAN).sigma(), 0.0);
|
||||
assert_eq!(Noise::new(f64::INFINITY).sigma(), 0.0);
|
||||
assert!(Noise::new(-1.0).is_zero());
|
||||
assert_eq!(Noise::new(0.5).sigma(), 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn samples_are_finite_and_match_the_sigma() {
|
||||
let sigma = 0.25;
|
||||
let noise = Noise::new(sigma);
|
||||
let mut rng = Rng::new(17);
|
||||
let count = 100_000_u32;
|
||||
let mut sum = 0.0;
|
||||
let mut sum_squared = 0.0;
|
||||
for _ in 0..count {
|
||||
let value = noise.sample(&mut rng);
|
||||
assert!(value.is_finite(), "{value}");
|
||||
sum += value;
|
||||
sum_squared += value * value;
|
||||
}
|
||||
let n = f64::from(count);
|
||||
let mean = sum / n;
|
||||
let variance = sum_squared / n - mean * mean;
|
||||
assert!(mean.abs() < 0.01, "mean {mean}");
|
||||
assert!(
|
||||
(variance - sigma * sigma).abs() < 0.005,
|
||||
"variance {variance}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_seed_repeats_the_sequence() {
|
||||
let noise = Noise::new(0.5);
|
||||
let mut a = Rng::new(3);
|
||||
let mut b = Rng::new(3);
|
||||
for _ in 0..100 {
|
||||
assert_eq!(
|
||||
noise.sample(&mut a).to_bits(),
|
||||
noise.sample(&mut b).to_bits()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_seeds_differ() {
|
||||
let noise = Noise::new(1.0);
|
||||
let mut a = Rng::new(1);
|
||||
let mut b = Rng::new(2);
|
||||
let differs = (0..8).any(|_| noise.sample(&mut a).to_bits() != noise.sample(&mut b).to_bits());
|
||||
assert!(differs);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue