### Multi-Rate Sensor Fusion Example Setup Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Sets up a distributed information filter for multi-rate sensor fusion. This example initializes the filter with a state dimension suitable for fusing data from sensors with different update rates (e.g., GPS, IMU, Camera). ```rust /// Demonstrate multi-rate sensing fn multi_rate_example() { println!("\\n\\nMulti-Rate Sensor Fusion Example"); println!("================================="); // Different sensor types with different update rates // - GPS: 1 Hz (slow, accurate position) // - IMU: 100 Hz (fast, acceleration) // - Camera: 10 Hz (medium, position) let mut dif = DistributedInformationFilter::::new(6); / ``` -------------------------------- ### Metrics Server Example (Prometheus) Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html This example requires the 'prometheus-metrics' feature to be enabled. It initializes the metrics system, runs a Kalman filter simulation in a separate thread, and exposes metrics on http://localhost:9090/metrics. ```Rust #[cfg(not(feature = \"prometheus-metrics\"))] fn main() { eprintln!(\"This example requires the prometheus-metrics feature.\"); eprintln!(\"Run with: cargo run --example metrics_server --features prometheus-metrics\"); } #[cfg(feature = \"prometheus-metrics\")] fn main() { use kalman_filter::KalmanFilterBuilder; use std::thread; use std::time::Duration; use std::net::TcpListener; // Initialize metrics system kalman_filter::metrics::init(); println!(\"Metrics system initialized\"); // Create a thread to run filters and generate metrics thread::spawn(|| { // Create a simple 2D position-velocity Kalman filter let mut kf = KalmanFilterBuilder::new(2, 1) .initial_state(vec![0.0, 0.0]) .initial_covariance(vec![1.0, 0.0, 0.0, 1.0]) .transition_matrix(vec![1.0, 1.0, 0.0, 1.0]) // dt = 1.0 .process_noise(vec![0.001, 0.0, 0.0, 0.001]) .observation_matrix(vec![1.0, 0.0]) // observe position only .measurement_noise(vec![0.1]) .build() .expect(\"Failed to build Kalman filter\"); println!(\"Running Kalman filter simulation...\"); // Simulate continuous operation let mut time: f64 = 0.0; loop { // Predict step kf.predict(); // Generate synthetic measurement (true position with noise) let true_position = time; // Simple noise generation without rand dependency let noise = ((time.sin() * 100.0) % 1.0 - 0.5) * 0.2; let measurement = vec![true_position + noise]; // Update step if let Err(e) = kf.update(&measurement) { eprintln!(\"Update failed: {:?}\", e); } time += 1.0; // Sleep to simulate real-time operation thread::sleep(Duration::from_millis(100)); if time as i32 % 10 == 0 { println!(\"Processed {} steps, state: {:?}\", time as i32, kf.state()); } } }); // Start HTTP server for metrics endpoint let listener = TcpListener::bind("127.0.0.1:9090") .expect(\"Failed to bind to port 9090\"); println!(\"Metrics server listening on http://localhost:9090/metrics\"); println!(\"Use Ctrl+C to stop the server\"); for stream in listener.incoming() { match stream { Ok(stream) => { handle_request(stream); } Err(e) => { eprintln!(\"Connection failed: {}\", e); } } } } ``` -------------------------------- ### Run Cargo Examples Source: https://github.com/destenson/kalman-filter-rs/blob/master/README.md Commands to run the example applications included with the Kalman filter library. These examples showcase different functionalities like 1D tracking, sensor networks, and logging. ```bash # Simple 1D tracking cargo run --example simple_1d # Sensor network with Information Filter cargo run --example if_sensor_network # Logging demonstration RUST_LOG=debug cargo run --example logging_demo ``` -------------------------------- ### High-Dimensional System Example (Rust) Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Demonstrates a 6D nonlinear system using the Cubature Kalman Filter (CKF). This example highlights CKF's stability in high-dimensional scenarios. Note that CKF does not require Jacobians. ```rust struct HighDimensionalSystem; impl NonlinearSystem for HighDimensionalSystem { fn state_transition(&self, state: &[f64], _control: Option<&[f64]>, dt: f64) -> Vec { // Coupled nonlinear dynamics vec![ state[0] + state[3] * dt + 0.01 * state[0] * state[1] * dt, state[1] + state[4] * dt + 0.01 * state[1] * state[2] * dt, state[2] + state[5] * dt + 0.01 * state[2] * state[0] * dt, state[3] * (1.0 - 0.1 * dt) + 0.05 * state[4].sin() * dt, state[4] * (1.0 - 0.1 * dt) + 0.05 * state[5].sin() * dt, state[5] * (1.0 - 0.1 * dt) + 0.05 * state[3].sin() * dt, ] } fn measurement(&self, state: &[f64]) -> Vec { // Nonlinear measurements of positions vec![ (state[0].powi(2) + state[1].powi(2)).sqrt(), // Distance from origin in XY (state[1].powi(2) + state[2].powi(2)).sqrt(), // Distance from origin in YZ state[0] + state[1] + state[2], // Sum of positions ] } fn state_jacobian(&self, _state: &[f64], _control: Option<&[f64]>, _dt: f64) -> Vec { unreachable!("CKF doesn't need Jacobians") } fn measurement_jacobian(&self, _state: &[f64]) -> Vec { unreachable!("CKF doesn't need Jacobians") } fn state_dim(&self) -> usize { 6 } fn measurement_dim(&self) -> usize { 3 } } fn main() { println!("=== CKF High-Dimensional System Example ===\\n\n"); let system = HighDimensionalSystem; // Initial 6D state: [x, y, z, vx, vy, vz] let initial_state = vec![1.0, 0.5, -0.5, 0.1, 0.2, -0.1]; // Initial covariance (6x6 identity scaled) let mut initial_covariance = vec![0.0; 36]; for i in 0..6 { initial_covariance[i * 6 + i] = 0.1; } // Process noise (6x6 diagonal) let mut process_noise = vec![0.0; 36]; for i in 0..3 { process_noise[i * 6 + i] = } ``` -------------------------------- ### Legacy Kalman Filter API Example Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Demonstrates the usage of the legacy Kalman filter API. Run with `cargo run --example legacy --features legacy`. ```rust #! Legacy API example //! Run with: cargo run --example legacy --features legacy use kalman_filter::legacy::KalmanFilter; fn main() { let mut kf = KalmanFilter::new(2, 1, 0); kf.transition_matrix(&[1.0, 1.0, 0.0, 1.0]); kf.measurement_matrix(&[1.0, 0.0]); kf.process_noise_cov(&[1e-5, 0.0, 0.0, 1e-5]); kf.measurement_noise_cov(&[0.1]); kf.error_cov_post(&[1.0, 0.0, 0.0, 1.0]); kf.state_post(&[10.0, 0.0]); let sys_time = std::time::SystemTime::now(); for i in 0..10000 { kf.predict(None); kf.correct(&[i as f32 + 0.1]); } println!("{}", sys_time.elapsed().unwrap().subsec_nanos()); } ``` -------------------------------- ### Unscented Kalman Filter Builder Example Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Demonstrates building an Unscented Kalman Filter with specified parameters. Ensure all required parameters are set before building. ```rust let ukf = UnscentedKalmanFilterBuilder::new(system) .initial_state(vec![0.0, 1.0]) .initial_covariance(vec![1.0, 0.0, 0.0, 1.0]) .process_noise(vec![0.01, 0.0, 0.0, 0.01]) .measurement_noise(vec![0.1]) .dt(0.1) .alpha(0.001) .beta(2.0) .kappa(0.0) .build() .unwrap(); assert_eq!(ukf.state().len(), 2); assert_eq!(ukf.covariance().len(), 4); ``` -------------------------------- ### Extended Kalman Filter Builder Example Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Demonstrates how to construct an Extended Kalman Filter using the builder pattern. Requires a custom NonlinearSystem implementation. ```rust use kalman_filter::builders::ExtendedKalmanFilterBuilder; use kalman_filter::NonlinearSystem; # struct MySystem; # impl NonlinearSystem for MySystem { # fn state_dim(&self) -> usize { 2 } # fn measurement_dim(&self) -> usize { 1 } # fn state_transition(&self, x: &[f64], u: Option<&[f64]>, dt: f64) -> Vec { vec![0.0; 2] } # fn measurement(&self, x: &[f64]) -> Vec { vec![0.0] } # fn state_jacobian(&self, x: &[f64], u: Option<&[f64]>, dt: f64) -> Vec { vec![0.0; 4] } # fn measurement_jacobian(&self, x: &[f64]) -> Vec { vec![0.0; 2] } # } let system = MySystem; let ekf = ExtendedKalmanFilterBuilder::new(system) .initial_state(vec![0.0, 0.0]) .initial_covariance(vec![1.0, 0.0, 0.0, 1.0]) .process_noise(vec![0.01, 0.0, 0.0, 0.01]) .measurement_noise(vec![0.1]) .dt(0.01) .build() .unwrap(); ``` -------------------------------- ### InformationFilterBuilder Example Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Demonstrates how to construct an Information Filter using the builder pattern. Requires specifying dimensions and various matrices/vectors. ```rust use kalman_filter::builders::InformationFilterBuilder; let if_filter = InformationFilterBuilder::new(2, 1) .initial_information_matrix(vec![1.0, 0.0, 0.0, 1.0]) .initial_information_vector(vec![0.0, 0.0]) .state_transition_matrix(vec![1.0, 0.1, 0.0, 1.0]) .process_noise(vec![0.01, 0.0, 0.0, 0.01]) .observation_matrix(vec![1.0, 0.0]) .measurement_noise(vec![0.1]) .build() .unwrap(); ``` -------------------------------- ### Extended Kalman Filter (EKF) Example Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Demonstrates the Extended Kalman Filter for a nonlinear system like a pendulum. Requires implementing the NonlinearSystem trait. ```rust //! Extended Kalman Filter (EKF) implementation //! //! The Extended Kalman Filter linearizes non-linear models around the current estimate //! using Jacobian matrices. It extends the linear Kalman filter to handle nonlinear //! state transition and measurement functions. //! //! # Theory //! //! For a nonlinear system: //! - State transition: x_k+1 = f(x_k, u_k) + w_k //! - Measurement: z_k = h(x_k) + v_k //! //! The EKF linearizes these functions using Jacobians: //! - F_k = ∂f/∂x evaluated at x̂_k //! - H_k = ∂h/∂x evaluated at x̂_k|k-1 //! //! # Example //! //! ```no_run //! use kalman_filter::{ExtendedKalmanFilter, NonlinearSystem, KalmanScalar}; //! //! struct PendulumSystem; //! //! impl NonlinearSystem for PendulumSystem { //! fn state_transition(&self, state: &[f64], _control: Option<&[f64]>, dt: f64) -> Vec { //! let theta = state[0]; //! let theta_dot = state[1]; //! let g = 9.81; //! let l = 1.0; //! vec![ //! theta + theta_dot * dt, //! theta_dot - (g / l) * theta.sin() * dt, //! ] //! } //! //! fn measurement(&self, state: &[f64]) -> Vec { // Measure angle only //! vec![state[0]] //! } //! //! fn state_jacobian(&self, state: &[f64], _control: Option<&[f64]>, dt: f64) -> Vec { //! let theta = state[0]; //! let g = 9.81; //! let l = 1.0; //! vec![ //! 1.0, dt, //! -(g / l) * theta.cos() * dt, 1.0, //! ] //! } //! //! fn measurement_jacobian(&self, _state: &[f64]) -> Vec { //! vec![1.0, 0.0] //! } //! //! fn state_dim(&self) -> usize { 2 } //! fn measurement_dim(&self) -> usize { 1 } //! } //! ``` ``` -------------------------------- ### Kalman Filter Prediction and Update Example Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Demonstrates the basic usage of the Kalman Filter for prediction and update steps. Ensure the filter is initialized before use. ```rust hybrid.predict().unwrap(); hybrid.update(&[1.0]).unwrap(); let state = hybrid.get_state().unwrap(); assert!(state[0] > 0.0); ``` -------------------------------- ### Cubature Kalman Filter Builder Example Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Shows how to construct a Cubature Kalman Filter using its builder. This is useful for systems where the state transition is non-linear. ```rust let ckf = CubatureKalmanFilterBuilder::new(system) .initial_state(vec![0.0, 1.0]) .initial_covariance(vec![1.0, 0.0, 0.0, 1.0]) .process_noise(vec![0.01, 0.0, 0.0, 0.01]) .measurement_noise(vec![0.1]) .dt(0.1) .build() .unwrap(); assert_eq!(ckf.state().len(), 2); assert_eq!(ckf.covariance().len(), 4); ``` -------------------------------- ### Scheduler Execution Environment Setup Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Configures the scheduler's execution environment, including message channels for asynchronous operations and performance timing. ```javascript if("undefined"===typeof window||"function"!==typeof MessageChannel){var A=null,qa=null,ra=function(){if(null!==A)try{var a=q();A(!0,a);A=null}catch(b){throw setTimeout(ra,0),b;}};var q= function(){return Date.now()-La};var z=function(a){null!==A?setTimeout(z,0,a):(A=a,setTimeout(ra,0))};var G=function(a,b){qa=setTimeout(a,b)};var V=function(){clearTimeout(qa)};var W=function(){return!1}}else{var Y=window.performance,sa=window.Date,Ma=window.setTimeout,Na=window.clearTimeout;if("object"===typeof Y&&"function"===typeof Y.now)q=function(){return Y.now()};else{var Oa=sa.now();q=function(){return sa.now()-Oa}};var J=!1,K=null,Z=-1,ta=5,ua=0;W=function(){return q()>=ua};f=function(){};X=function(a){0>a||125::new(2, 1); // Plant model: integrator with noise kf.x = vec![0.0, 0.0]; kf.P = vec![1.0, 0.0, 0.0, 1.0]; kf.F = vec![1.0, 1.0, 0.0, 1.0]; // Discrete integrator kf.H = vec![1.0, 0.0]; // Measure position kf.Q = vec![0.01, 0.01, 0.01, 0.02]; // Process noise kf.R = vec![1.0]; // Measurement noise // Run a few steps let measurements = vec![0.5, 1.0, 1.5, 2.0, 2.5]; for &z in &measurements { kf.predict(); kf.update(&vec![z]).unwrap(); } // Should track the ramping input assert!(kf.x[0] > 1.5 && kf.x[0] < 3.0, "Position estimate out of range"); assert!(kf.x[1] > 0.3 && kf.x[1] < 0.7, "Velocity estimate out of range"); } ``` -------------------------------- ### Test MATLAB Example Integration Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Validates the Kalman filter implementation against a known example from MATLAB's documentation. This test ensures compatibility and correctness for a 2D integrator system. ```rust // Test with known MATLAB example #["test"] fn test_matlab_example() { // Example from MATLAB documentation // https://www.mathworks.com/help/control/ref/kalman.html let mut kf = KalmanFilter::::new(2, 1); // Plant model: integrator with noise kf.x = vec![0.0, 0.0]; kf.P = vec![1.0, 0.0, 0.0, 1.0]; kf.F = vec![1.0, 1.0, 0.0, 1.0]; // Discrete integrator kf.H = vec![1.0, 0.0]; // Measure position kf.Q = vec![0.01, 0.01, 0.01, 0.02]; // Process noise kf.R = vec![1.0]; // Measurement noise // Run a few steps let measurements = vec![0.5, 1.0, 1.5, 2.0, 2.5]; for &z in &measurements { kf.predict(); kf.update(&vec![z]).unwrap(); } // Should track the ramping input assert!(kf.x[0] > 1.5 && kf.x[0] < 3.0, "Position estimate out of range"); assert!(kf.x[1] > 0.3 && kf.x[1] < 0.7, "Velocity estimate out of range"); } } ``` -------------------------------- ### Kalman Filter Builder Example Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Demonstrates creating a simple 1D Kalman filter using the builder pattern. Ensure all necessary parameters like initial state, covariance, matrices, and noise are provided before building. ```rust //! # Kalman Filter Implementation //! //! This crate provides a Kalman filter implementation for state estimation //! in linear dynamic systems. The Kalman filter is an optimal recursive //! estimator that combines predictions from a system model with measurements //! to estimate the true state of a system. //! //! ## Features //! //! - Linear Kalman filter with predict and update steps //! - Dynamic dimension support without external dependencies //! - Support for both f32 and f64 precision //! - Builder pattern for easy initialization //! - Extended Kalman Filter (EKF) support (future) //! - Unscented Kalman Filter (UKF) support (future) //! //! ## Example //! //! ``` //! use kalman_filter::KalmanFilterBuilder; //! //! // Create a simple 1D Kalman filter using the builder //! let mut kf = KalmanFilterBuilder::new(1, 1) //! .initial_state(vec![0.0]) //! .initial_covariance(vec![1.0]) //! .transition_matrix(vec![1.0]) //! .process_noise(vec![0.001]) //! .observation_matrix(vec![1.0]) //! .measurement_noise(vec![0.1]) //! .build() //! .unwrap(); //! //! // Predict step //! kf.predict(); //! //! // Update with measurement //! kf.update(&[1.0]).unwrap(); //! ``` #![allow(unused, non_snake_case)] // DO NOT CHANGE pub mod builder; pub mod builders; pub mod ensemble; pub mod error; pub mod extended; pub mod filter; pub mod information; pub mod logging; #[cfg(feature = "prometheus-metrics")] pub mod metrics; pub mod particle; ``` -------------------------------- ### Kalman Filter Metrics Server Example Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Example of exposing Kalman filter metrics via an HTTP endpoint for Prometheus scraping. Requires the `prometheus-metrics` feature. Access metrics at `http://localhost:9090/metrics`. ```rust #[cfg(not(feature = "prometheus-metrics"))] fn main() { eprintln!("This example requires the prometheus-metrics feature."); eprintln!("Run with: cargo run --example metrics_server --features prometheus-metrics"); } #[cfg(feature = "prometheus-metrics")] fn main() { use kalman_filter::KalmanFilterBuilder; use std::thread; use std::time::Duration; use std::net::TcpListener; // Initialize metrics system kalman_filter::metrics::init(); println!("Metrics system initialized"); // Create a thread to run filters and generate metrics thread::spawn(|| { // Create a simple 2D position-velocity Kalman filter let mut kf = KalmanFilterBuilder::new(2, 1) .initial_state(vec![0.0, 0.0]) .initial_covariance(vec![1.0, 0.0, 0.0, 1.0]) .transition_matrix(vec![1.0, 1.0, 0.0, 1.0]) // dt = 1.0 .process_noise(vec![0.001, 0.0, 0.0, 0.001]) .observation_matrix(vec![1.0, 0.0]) // observe position only .measurement_noise(vec![0.1]) .build() .expect("Failed to build Kalman filter"); println!("Running Kalman filter simulation..."); // Simulate continuous operation let mut time: f64 = 0.0; loop { // Predict step kf.predict(); // Generate synthetic measurement (true position with noise) let true_position = time; // Simple noise generation without rand dependency let noise = ((time.sin() * 100.0) % 1.0 - 0.5) * 0.2; let measurement = vec![true_position + noise]; // Update step if let Err(e) = kf.update(&measurement) { eprintln!("Update failed: {:?}", e); } time += 1.0; // Sleep to simulate real-time operation thread::sleep(Duration::from_millis(100)); if time as i32 % 10 == 0 { println!("Processed {} steps, state: {:?}", time as i32, kf.state()); } } }); // Start HTTP server for metrics endpoint let listener = TcpListener::bind("127.0.0.1:9090") .expect("Failed to bind to port 9090"); println!("Metrics server listening on http://localhost:9090/metrics"); println!("Use Ctrl+C to stop the server"); for stream in listener.incoming() { match stream { Ok(stream) => { handle_request(stream); } Err(e) => { eprintln!("Connection failed: {}", e); } } } } #[cfg(feature = "prometheus-metrics")] fn handle_request(mut stream: std::net::TcpStream) { use prometheus_client::encoding::text::encode; use std::io::{Read, Write}; // Read the request (we only care about the path) let mut buffer = [0; 1024]; if let Err(e) = stream.read(&mut buffer) { eprintln!("Failed to read request: {}", e); return; } let request = String::from_utf8_lossy(&buffer); // Check if this is a request for /metrics if request.starts_with("GET /metrics") { // Get the metrics registry let registry = kalman_filter::metrics::registry(); // Encode metrics in Prometheus text format let mut buffer = String::new(); if let Err(e) = encode(&mut buffer, registry) { eprintln!("Failed to encode metrics: {}", e); let response = format!( "HTTP/1.1 500 Internal Server Error\r\n\r\n Content-Type: text/plain\r\n\r\n Content-Length: {} \n\r\n Failed to encode metrics", "Failed to encode metrics".len() ); let _ = stream.write_all(response.as_bytes()); return; } // Send HTTP response with metrics let response = format!( "HTTP/1.1 200 OK\r\n" ); let _ = stream.write_all(response.as_bytes()); } } ``` -------------------------------- ### Basic Kalman Filter Example Source: https://github.com/destenson/kalman-filter-rs/blob/master/README.md Demonstrates creating and using a basic 2D Kalman Filter for position and velocity tracking. Requires initialization of state, covariance, transition, process noise, observation, and measurement noise. ```rust use kalman_filters::KalmanFilterBuilder; // Create a 2D position/velocity tracker let mut kf = KalmanFilterBuilder::new(2, 1) // 2 states, 1 measurement .initial_state(vec![0.0, 0.0]) // position, velocity .initial_covariance(vec![ 1.0, 0.0, 0.0, 1.0, ]) .transition_matrix(vec![ 1.0, 0.1, // position += velocity * dt 0.0, 1.0, // velocity unchanged ]) .process_noise(vec![ 0.001, 0.0, 0.0, 0.001, ]) .observation_matrix(vec![1.0, 0.0]) // measure position only .measurement_noise(vec![0.1]) .build() .unwrap(); // Prediction step kf.predict(); // Update with measurement kf.update(&[1.5]).unwrap(); let state = kf.state(); println!("Position: {:.2}, Velocity: {:.2}", state[0], state[1]); ``` -------------------------------- ### Particle Filter Builder Example (Rust) Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Demonstrates how to construct a Particle Filter using the builder pattern. Ensure all necessary parameters like initial mean, standard deviation, noise levels, and time step are provided. ```rust use kalman_filter::builders::ParticleFilterBuilder; let pf = ParticleFilterBuilder::new(2, 100) .initial_mean(vec![0.0, 0.0]) .initial_std(vec![1.0, 1.0]) .process_noise_std(vec![0.1, 0.1]) .measurement_noise_std(vec![0.5]) .dt(0.01) .build() .unwrap(); ``` -------------------------------- ### Simple 1D Kalman Filter Example (Vec-based) Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Tracks a 1D position with noisy measurements using a constant velocity model and standard Rust Vec for matrices. Use 'cargo run --example simple_1d'. ```rust //! Simple 1D Kalman filter example\n//! \n//! This example demonstrates tracking a 1D position with noisy measurements.\n//! The system models constant velocity motion where:\n//! - State: [position, velocity]\n//! - Measurement: position only\n//!\n//! This example works with both Vec-based and nalgebra implementations.\n//! Use `cargo run --example simple_1d` for Vec-based\n//! Use `cargo run --example simple_1d --features nalgebra` for nalgebra-based\n#![allow(unused, non_snake_case)]\n\nuse rand::Rng;\n\n#[cfg(not(feature = \"nalgebra\"))]\nuse kalman_filter::{KalmanFilter, KalmanFilterBuilder};\n\n#[cfg(feature = \"nalgebra\")]\nuse kalman_filter::StaticKalmanFilter;\n#[cfg(feature = \"nalgebra\")]\nuse nalgebra::{SMatrix, SVector};\n\n#[cfg(not(feature = \"nalgebra\"))]\nfn main() {\n println!(\"Simple 1D Kalman Filter Example (Vec-based)\");\n println!(\"============================================\");\n \n // Time step\n let dt = 0.1;\n \n // Create state transition matrix (constant velocity model)\n // [position_new] = [1 dt] * [position_old]\n // [velocity_new] [0 1 ] [velocity_old]\n let f = vec![ 1.0, dt, 0.0, 1.0, ];\n \n // Initial state: position = 0, velocity = 1 m/s\n let x0 = vec![0.0, 1.0];\n \n // Initial covariance (uncertainty)\n let p0 = vec![ 1.0, 0.0, 0.0, 1.0, ];\n \n // Process noise (how much the system can change randomly)\n let q = vec![ 0.001, 0.0, 0.0, 0.001, ];\n \n // Observation matrix (we only measure position)\n let h = vec![1.0, 0.0];\n \n // Measurement noise\n let r = vec![0.1];\n \n // Build the Kalman filter\n let mut kf = KalmanFilterBuilder::::new(2, 1)\n .initial_state(x0)\n .initial_covariance(p0)\n .transition_matrix(f)\n .process_noise(q)\n .observation_matrix(h)\n .measurement_noise(r)\n .build()\n .expect(\"Failed to build Kalman filter\");\n \n // Simulate true system and noisy measurements\n let mut rng = rand::thread_rng();\n let true_velocity = 1.0;\n let measurement_noise_std = 0.3;\n \n println!(\"\\nTime | True Pos | Measured | Estimated | Est. Vel\");\n println!(\"-----|----------|----------|-----------|----------\");\n \n for step in 0..50 {\n let t = step as f64 * dt;\n let true_position = true_velocity * t;\n \n // Generate noisy measurement\n let noise = rng.gen_range(-measurement_noise_std..measurement_noise_std);\n let measured_position = true_position + noise;\n \n // Kalman filter predict step\n kf.predict();\n \n // Kalman filter update step\n kf.update(&[measured_position]).expect(\"Update failed\");\n \n // Get estimated state\n let state = kf.state();\n let estimated_position = state[0];\n let estimated_velocity = state[1];\n \n // Print results every 10 steps\n if step % 10 == 0 {\n println!(\n \"{ :4.1} | {:8.3} | {:8.3} | {:9.3} | {:8.3}\",\n t, true_position, measured_position, estimated_position, estimated_velocity\n );\n }\n }\n \n println!(\"\\nFinal state covariance:\");\n let p = kf.covariance();\n println!(\"Position variance: {:.6}\", p[0]);\n println!(\"Velocity variance: {:.6}\", p[3]);\n \n println!(\"\\nThe Kalman filter successfully tracked the position and\");\n println!(\"estimated the velocity from noisy position measurements.\");\n}\n\n#[cfg(feature = \"nalgebra\")]\nfn main() {\n println!(\"Simple 1D Kalman Filter Example (nalgebra-based)\");\n println!(\"=================================================\");\n \n // Time step\n let dt = 0.1;\n \n // Create state transition matrix (constant velocity model)\n let F = SMatrix::::from_row_slice(&[ 1.0, dt, 0.0, 1.0, ]);\n \n // Initial state: position = 0, velocity = 1 m/s\n let x0 = SVector::::from([0.0, 1.0]);\n \n // Initial covariance (uncertainty)\n let P0 = SMatrix::::from_row_slice(&[ 1.0, 0.0, 0.0, 1.0, ]);\n \n // Process noise (how much the system can change randomly)\n let Q = SMatrix::::from_row_slice(&[ 0.001, 0.0, 0.0, 0.001, ]);\n \n // Observation matrix (we only measure position)\n let H = SMatrix::::from_row_slice(&[ 1.0, 0.0, ]);\n ``` -------------------------------- ### EKF Initialization and Basic Usage Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Demonstrates initializing an Extended Kalman Filter with a PendulumSystem and performing a basic prediction and update cycle. Asserts that the state has been updated correctly. ```rust let system = PendulumSystem { g: 9.81, l: 1.0 }; let initial_state = vec![0.1, 0.0]; let initial_covariance = vec![0.01, 0.0, 0.0, 0.01]; let process_noise = vec![0.001, 0.0, 0.0, 0.001]; let measurement_noise = vec![0.01]; let mut ekf = ExtendedKalmanFilter::new( system, initial_state, initial_covariance, process_noise, measurement_noise, 0.01, ) .unwrap(); ekf.predict(); ekf.update(&[0.09]).unwrap(); // Check that state has been updated assert!((ekf.state()[0] - 0.1).abs() < 0.05); ``` -------------------------------- ### Information Filter Builder Example Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Demonstrates building an Information Filter using its builder pattern. Requires initial information vector and state transition matrix. ```rust let if_filter = InformationFilterBuilder::new(vec![1.0, 0.0, 0.0, 1.0]) .initial_information_vector(vec![0.0, 0.0]) .state_transition_matrix(vec![1.0, 0.1, 0.0, 1.0]) .process_noise(vec![0.01, 0.0, 0.0, 0.01]) .observation_matrix(vec![1.0, 0.0]) .measurement_noise(vec![0.1]) .build() .unwrap(); let state = if_filter.get_state().unwrap(); assert_eq!(state.len(), 2); ``` -------------------------------- ### Get Covariance Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Recovers and returns the current covariance matrix of the state estimate. ```APIDOC ## get_covariance ### Description Retrieves the current covariance matrix associated with the state estimate. The covariance matrix represents the uncertainty in the state estimate. ### Method `pub fn get_covariance(&self) -> KalmanResult>` ### Response #### Success Response (Vec) A vector of type `T` representing the flattened covariance matrix. #### Error Response (KalmanError) - `CovarianceRecoveryError`: If the covariance matrix cannot be recovered from the internal information state. ``` -------------------------------- ### Kalman Filter Builder Initialization (Rust) Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Demonstrates how to construct a Kalman filter using the builder pattern. Specifies dimensions, initial state, covariance, transition matrix, process noise, observation matrix, and measurement noise. ```Rust use kalman_filter::KalmanFilterBuilder; let kf = KalmanFilterBuilder::::new(2, 1) // 2 states, 1 measurement .initial_state(vec![0.0, 0.0]) .initial_covariance(vec![1.0, 0.0, 0.0, 1.0]) .transition_matrix(vec![1.0, 1.0, 0.0, 1.0]) .process_noise(vec![0.01, 0.0, 0.0, 0.01]) .observation_matrix(vec![1.0, 0.0]) .measurement_noise(vec![0.1]) .build() .unwrap(); ``` -------------------------------- ### Get State Estimate Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Recovers and returns the current state estimate of the system. ```APIDOC ## get_state ### Description Retrieves the current state estimate of the Kalman filter. This is the filter's best guess of the system's state based on the measurements and model. ### Method `pub fn get_state(&self) -> KalmanResult>` ### Response #### Success Response (Vec) A vector of type `T` representing the current state estimate. #### Error Response (KalmanError) - `StateRecoveryError`: If the state estimate cannot be recovered from the internal information state. ``` -------------------------------- ### Initialize Cubature Kalman Filter (Rust) Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Demonstrates the initialization of a Cubature Kalman Filter for a 2D nonlinear system. Ensure the system, initial state, covariances, and noise parameters are correctly defined. ```rust {\n let system = NonlinearSystem2D;\n\n let initial_state = vec![1.0, 0.0];\n let initial_covariance = vec![0.1, 0.0, 0.0, 0.1];\n let process_noise = vec![0.01, 0.0, 0.0, 0.01];\n let measurement_noise = vec![0.1];\n\n let ckf = CubatureKalmanFilter::new(\n system,\n initial_state,\n initial_covariance,\n process_noise,\n measurement_noise,\n 0.01,\n )\n .unwrap();\n\n // Check cubature weight is 1/(2n) = 1/4 for 2D system\n assert!((ckf.weight - 0.25).abs() < 1e-10);\n } ``` -------------------------------- ### Get Current State Covariance Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Retrieves the current state covariance matrix. ```APIDOC ## Covariance ### Description Retrieves the current state covariance matrix. ### Method `covariance` ### Parameters None ### Request Example ```rust let current_covariance = ekf.covariance(); ``` ### Response #### Success Response (&[T]) Returns a slice representing the current state covariance matrix. #### Response Example ```rust &[0.01, 0.0, 0.0, 0.01] // Example covariance matrix ``` ``` -------------------------------- ### Static Kalman Filter Initialization and Basic Cycle Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Demonstrates the initialization and a basic predict-update cycle of a static Kalman Filter. Ensure correct matrix dimensions for initialization. ```rust let x = SVector::\u003cf64, 1\u003e::from(\[\[0.0\]\]);\n let P = SMatrix::\u003cf64, 1, 1\u003e::from(\[\[1.0\]\]);\n let F = SMatrix::\u003cf64, 1, 1\u003e::from(\[\[1.0\]\]);\n let Q = SMatrix::\u003cf64, 1, 1\u003e::from(\[\[0.001\]\]);\n let H = SMatrix::\u003cf64, 1, 1\u003e::from(\[\[1.0\]\]);\n let R = SMatrix::\u003cf64, 1, 1\u003e::from(\[\[0.1\]\]);\n\n let mut kf = StaticKalmanFilter::new(x, P, F, Q, H, R);\n\n // Predict\n kf.predict();\n assert!((kf.state().get(0).unwrap() - 0.0).abs() < 1e-10);\n\n // Update with measurement\n let z = SVector::\u003cf64, 1\u003e::from(\[1.0\]);\n kf.update(&z).unwrap();\n\n // State should have moved toward measurement\n assert!(kf.state().get(0).unwrap() > 0.0);\n assert!(kf.state().get(0).unwrap() < 1.0); ``` -------------------------------- ### Get Current State Estimate Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Retrieves the current state estimate of the system. ```APIDOC ## State ### Description Retrieves the current state estimate of the system. ### Method `state` ### Parameters None ### Request Example ```rust let current_state = ekf.state(); ``` ### Response #### Success Response (&[T]) Returns a slice representing the current state vector. #### Response Example ```rust &[0.1, 0.0] // Example state vector ``` ``` -------------------------------- ### Get Current State Estimate Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Retrieves the current state estimate from the Kalman filter. ```rust pub fn state(&self) -> &[T] { &self.x } ``` -------------------------------- ### Information Filter Builder Example Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Demonstrates building an Information Filter using initial information matrix and vector. This filter works with the information form of the state-space model. ```rust let if_filter = InformationFilterBuilder::new(2, 1) .initial_information_matrix(vec![1.0, 0.0, 0.0, 1.0]) .initial_information_vector(vec![0.0, 0.0]) .state_transition_matrix(vec![1.0, 0.1, 0.0, 1.0]) .process_noise(vec![0.01, 0.0, 0.0, 0.01]) .observation_matrix(vec![1.0, 0.0]) .measurement_noise(vec![0.1]) .build() .unwrap(); let state = if_filter.get_state().unwrap(); assert_eq!(state.len(), 2); ``` -------------------------------- ### Get Current State Covariance Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Returns a reference to the current state covariance matrix. ```rust /// Get current state covariance pub fn covariance(&self) -> &[T] { &self.P } ``` -------------------------------- ### Ensemble Kalman Filter Builder Example Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Illustrates the creation of an Ensemble Kalman Filter, suitable for high-dimensional systems. Key parameters include ensemble size and inflation factor. ```rust let enkf = EnsembleKalmanFilterBuilder::new(system) .initial_mean(vec![0.0, 1.0]) .initial_spread(vec![1.0, 1.0]) .ensemble_size(50) .process_noise(vec![0.01, 0.0, 0.0, 0.01]) .measurement_noise(vec![0.1]) .dt(0.1) .inflation_factor(1.05) .build() .unwrap(); assert_eq!(enkf.mean().len(), 2); assert_eq!(enkf.ensemble_size, 50); ``` -------------------------------- ### Get Current State Estimate Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Returns a reference to the current state estimate vector. ```rust /// Get current state estimate pub fn state(&self) -> &[T] { &self.x } ``` -------------------------------- ### Get Current State Covariance Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Returns a reference to the current state covariance matrix. ```rust pub fn covariance(&self) -> &[T] { &self.P } ``` -------------------------------- ### Get Current State Estimate Source: https://github.com/destenson/kalman-filter-rs/blob/master/tarpaulin-report.html Returns a reference to the current state estimate vector. ```rust pub fn state(&self) -> &[T] { &self.x } ```