### Install Kalman Filter via Npm Source: https://github.com/piercus/kalman-filter/blob/master/README.md Install the Kalman Filter library using npm. This is the recommended method for Node.js projects. ```sh npm install kalman-filter ``` -------------------------------- ### Instantiate generic linear model with detailed configuration Source: https://github.com/piercus/kalman-filter/blob/master/README.md Manually configures a Kalman filter for a 3D constant-speed model without using 'dynamic.name'. This example demonstrates detailed API usage for initial state mean, covariance, state dimension, transition matrix, and process noise covariance. ```javascript const {KalmanFilter} = require('kalman-filter'); const timeStep = 0.1; const huge = 1e8; const kFilter = new KalmanFilter({ observation: { dimension: 3 }, dynamic: { init: { // We just use random-guessed values here that seems reasonable mean: [[500], [500], [500], [0], [0], [0]], // We init the dynamic model with a huge covariance cause we don't // have any idea where my modeled object before the first observation is located covariance: [ [huge, 0, 0, 0, 0, 0], [0, huge, 0, 0, 0, 0], [0, 0, huge, 0, 0, 0], [0, 0, 0, huge, 0, 0], [0, 0, 0, 0, huge, 0], [0, 0, 0, 0, 0, huge], ], }, // Corresponds to (x, y, z, vx, vy, vz) dimension: 6, // This is a constant-speed model on 3D : [ [Id , timeStep*Id], [0, Id]] transition: [ [1, 0, 0, timeStep, 0, 0], [0, 1, 0, 0, timeStep, 0], [0, 0, 1, 0, 0, timeStep], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1] ], // Diagonal covariance for independant variables // since timeStep = 0.1, // it makes sense to consider speed variance to be ~ timeStep^2 * positionVariance covariance: [1, 1, 1, 0.01, 0.01, 0.01]// equivalent to diag([1, 1, 1, 0.01, 0.01, 0.01]) } }); ``` -------------------------------- ### 1D Smoothing with Kalman Filter Source: https://github.com/piercus/kalman-filter/blob/master/README.md Perform 1D smoothing on a series of observations using the KalmanFilter. This example initializes the filter with default settings. ```js const {KalmanFilter} = require('kalman-filter'); const observations = [0, 0.1, 0.5, 0.2, 3, 4, 2, 1, 2, 3, 5, 6]; // this is creating a smoothing const kFilter = new KalmanFilter(); const res = kFilter.filterAll(observations) ``` -------------------------------- ### Import Kalman Filter in Node.js Source: https://github.com/piercus/kalman-filter/blob/master/README.md Import the KalmanFilter class into your Node.js project after installation. ```js const {KalmanFilter} = require('kalman-filter'); ``` -------------------------------- ### 2D Smoothing with Constant-Speed Model Source: https://github.com/piercus/kalman-filter/blob/master/README.md Perform 2D smoothing using a constant-speed dynamic model. This example configures the filter with both observation dimension and the dynamic model. ```js const {KalmanFilter} = require('kalman-filter'); const observations = [[0, 1], [0.1, 0.5], [0.2, 3], [4, 2], [1, 2]]; const kFilter = new KalmanFilter({ observation: 2, dynamic: 'constant-speed' }); // equivalent to // new KalmanFilter({ // observation: { // name: 'sensor', // sensorDimension: 2 // }, // dynamic: { // name: 'constant-speed' // }, // }); const res = kFilter.filterAll(observations) ``` -------------------------------- ### 2D Smoothing with Kalman Filter Source: https://github.com/piercus/kalman-filter/blob/master/README.md Perform 2D smoothing on a series of 2D observations. This example specifies the sensor dimension for the filter. ```js const {KalmanFilter} = require('kalman-filter'); const observations = [[0, 1], [0.1, 0.5], [0.2, 3], [4, 2], [1, 2]]; const kFilter = new KalmanFilter({observation: 2}); // equivalent to // new KalmanFilter({ // observation: { // name: 'sensor', // sensorDimension: 2 // } // }); const res = kFilter.filterAll(observations) ``` -------------------------------- ### Simple Batch Kalman Filter Usage Source: https://github.com/piercus/kalman-filter/blob/master/README.md Use this for running the Kalman filter once on an entire dataset. ```javascript const observations = [[0, 2], [0.1, 4], [0.5, 9], [0.2, 12]]; // batch kalman filter const results = kFilter.filterAll(observations); ``` -------------------------------- ### Configure Kalman Filter with Dynamic Intervals Source: https://github.com/piercus/kalman-filter/blob/master/README.md Use this snippet to initialize a KalmanFilter with custom functions for observation and dynamic models, allowing for non-uniform time intervals. Ensure 'dT' is a positive number. ```javascript const {KalmanFilter} = require('kalman-filter'); const intervals = [1,1,1,1,2,1,1,1]; const kFilter = new KalmanFilter({ observation: { dimension: 2, /** * @param {State} opts.predicted * @param {Array.} opts.observation * @param {Number} opts.index */ stateProjection: function(opts){ return [ [1, 0, 0, 0], [0, 1, 0, 0] ] }, /** * @param {State} opts.predicted * @param {Array.} opts.observation * @param {Number} opts.index */ covariance: function(opts){ return [ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1] ] } }, dynamic: { dimension: 4, //(x, y, vx, vy) /** * @param {State} opts.previousCorrected * @param {Number} opts.index */ transition: function(opts){ const dT = intervals[opts.index]; if(typeof(dT) !== 'number' || isNaN(dT) || dT <= 0){ throw(new Error('dT should be positive number')) } return [ [1, 0, dT, 0], [0, 1, 0, dT] [0, 0, 1, 0] [0, 0, 0, 1] ] }, /** * @param {State} opts.previousCorrected * @param {Number} opts.index */ covariance: function(opts){ const dT = intervals[opts.index]; if(typeof(dT) !== 'number' || isNaN(dT) || dT <= 0){ throw(new Error('dT should be positive number')) } return [ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1*dT, 0], [0, 0, 0, 1*dT] ] } } }); ``` -------------------------------- ### Configure Custom Observation Matrix Source: https://github.com/piercus/kalman-filter/blob/master/README.md Use this configuration for observations from sensors with different properties or when manually defining the observation model. The `stateProjection` matrix maps the state to the observation space. ```javascript const {KalmanFilter} = require('kalman-filter'); const timeStep = 0.1; const kFilter = new KalmanFilter({ observation: { dimension: 4, stateProjection: [ [1, 0, 0, 0], [0, 1, 0, 0], [1, 0, 0, 0], [0, 1, 0, 0] ], covariance: [3, 4, 0.3, 0.4] }, dynamic: { name: 'constant-speed',// observation.sensorDimension * 2 == state.dimension covariance: [3, 3, 4, 4]// equivalent to diag([3, 3, 4, 4]) } }); ``` -------------------------------- ### Configure 'constant-acceleration' dynamic model for 2D data Source: https://github.com/piercus/kalman-filter/blob/master/README.md Instantiates a Kalman filter with the 'constant-acceleration' dynamic model for 2D observations, including 'timeStep' and 'covariance'. The state dimension is three times the sensor dimension. ```javascript const {KalmanFilter} = require('kalman-filter'); const kFilter = new KalmanFilter({ observation: { sensorDimension: 2, name: 'sensor' }, dynamic: { name: 'constant-acceleration',// observation.sensorDimension * 3 == state.dimension timeStep: 0.1, covariance: [3, 3, 4, 4, 5, 5]// equivalent to diag([3, 3, 4, 4, 5, 5]) } }); ``` -------------------------------- ### Online Kalman Filter Usage Source: https://github.com/piercus/kalman-filter/blob/master/README.md Use this for online filtering where only the forward step is needed. The output of the `filter` method is a State instance. ```javascript // online kalman filter let previousCorrected = null; const results = []; observations.forEach(observation => { previousCorrected = kFilter.filter({previousCorrected, observation}); results.push(previousCorrected.mean); }); ``` -------------------------------- ### Include Kalman Filter in Browser Source: https://github.com/piercus/kalman-filter/blob/master/README.md Include the Kalman Filter library in your browser project by adding the minified JavaScript file. Then, access the KalmanFilter class. ```html ``` -------------------------------- ### Configure 'constant-speed' dynamic model for 3D data Source: https://github.com/piercus/kalman-filter/blob/master/README.md Instantiates a Kalman filter with the 'constant-speed' dynamic model for 3D observations, specifying a 'timeStep' and 'covariance'. The state dimension is twice the sensor dimension. ```javascript const {KalmanFilter} = require('kalman-filter'); const kFilter = new KalmanFilter({ observation: { sensorDimension: 3, name: 'sensor' }, dynamic: { name: 'constant-speed',// observation.sensorDimension * 2 == state.dimension timeStep: 0.1, covariance: [3, 3, 3, 4, 4, 4]// equivalent to diag([3, 3, 3, 4, 4, 4]) } }); ``` -------------------------------- ### Configure 'constant-position' dynamic model for 2D data Source: https://github.com/piercus/kalman-filter/blob/master/README.md Instantiates a Kalman filter with the default 'constant-position' dynamic model for 2D observations. The 'covariance' is set using a diagonal array. ```javascript const {KalmanFilter} = require('kalman-filter'); const kFilter = new KalmanFilter({ observation: { sensorDimension: 2, name: 'sensor' }, dynamic: { name: 'constant-position',// observation.sensorDimension == dynamic.dimension covariance: [3, 4]// equivalent to diag([3, 4]) } }); ``` -------------------------------- ### Batch Forward-Backward Smoothing Source: https://github.com/piercus/kalman-filter/blob/master/README.md Utilize the forward-backward process for batch smoothing operations. ```javascript // batch kalman filter const results = kFilter.filterAll({observations, passMode: 'forward-backward'}); ``` -------------------------------- ### Control UI Elements and Kalman Filter Logic Source: https://github.com/piercus/kalman-filter/blob/master/docs/index.html Manages the visibility of different Kalman filter states (prediction, observation, correction, speed vectors, variances, covariances) and initializes the filter run. Attaches an event listener to a button to display a status message. ```javascript const btn = document.querySelector('button'); const status = { 'predicted': true, 'observation': true, 'corrected': true, 'speedVectors': false, 'variances': true, 'covariances': false }; const removeClass = function(el, className) { el.classList.remove(className); }; const addClass = function(el, className) { el.classList.add(className); }; const showHide = function(id) { const toRemove = status[id] ? id : 'not-'+id; const toAdd = !(status[id]) ? id : 'not-'+id; removeClass(document.getElementById("bikes"), toRemove); addClass(document.getElementById("bikes"), toAdd); status[id] = !(status[id]) } Object.keys(status).forEach(k => { showHide(k) showHide(k) }) const run = function(){ require('bike').run() } // Add event listener to display status messages when the user clicks the "Run Kalman Filter" button document.querySelector('#clickMe').addEventListener('click', function() { document.querySelector('#status').innerHTML = 'Running Kalman Filter...'; }); ``` -------------------------------- ### Configure Sensor Observation Source: https://github.com/piercus/kalman-filter/blob/master/README.md Use this configuration when observations come from multiple sensors with identical properties. The `sensorDimension` and `nSensors` properties define the structure of the input measure. ```javascript const {KalmanFilter} = require('kalman-filter'); const timeStep = 0.1; const kFilter = new KalmanFilter({ observation: { sensorDimension: 2,// observation.dimension == observation.sensorDimension * observation.nSensors nSensors: 2, sensorCovariance: [3, 4], // equivalent to diag([3, 4]) name: 'sensor' }, dynamic: { name: 'constant-speed',// observation.sensorDimension * 2 == state.dimension covariance: [3, 3, 4, 4]// equivalent to diag([3, 3, 4, 4]) } }); ``` -------------------------------- ### Register Custom Observation and Dynamic Models Source: https://github.com/piercus/kalman-filter/blob/master/README.md Register custom observation and dynamic models by providing factory functions. The KalmanFilter constructor accepts these registered models by name. ```javascript const {registerDynamic, KalmanFilter, registerObservation} = require('kalman-filter'); registerObservation('custom-sensor', function(opts1){ // do your stuff return { dimension, stateProjection, covariance } }) registerDynamic('custom-dynamic', function(opts2, observation){ // do your stuff // here you can use the parameter of observation (like observation.dimension) // to build the parameters for dynamic return { dimension, transition, covariance } }) const kFilter = new KalmanFilter({ observation: { name: 'custom-sensor', // ... fields of opts1 }, dynamic: { name: 'custom-dynamic', // ... fields of opts2 } }); ``` -------------------------------- ### Set Kalman Filter Model Parameters Source: https://github.com/piercus/kalman-filter/blob/master/README.md Use ground truth state values to calculate covariance matrices for the Kalman filter. This involves defining ground truth states and corresponding observations, then using the `getCovariance` function. ```javascript const {getCovariance, KalmanFilter} = require('kalman-filter'); // Ground truth values in the dynamic model hidden state const groundTruthStates = [ // here this is (x, vx) [[0, 1.1], [1.1, 1], [2.1, 0.9], [3, 1], [4, 1.2]], // example 1 [[8, 1.1], [9.1, 1], [10.1, 0.9], [11, 1], [12, 1.2]] // example 2 ] // Observations of this values const measures = [ // here this is x only [[0.1], [1.3], [2.4], [2.6], [3.8]], // example 1 [[8.1], [9.3], [10.4], [10.6], [11.8]] // example 2 ]; const kFilter = new KalmanFilter({ observation: { name: 'sensor', sensorDimension: 1 }, dynamic: { name: 'constant-speed' } }) const dynamicCovariance = getCovariance({ measures: groundTruthStates.map(ex => return ex.slice(1) ).reduce((a,b) => a.concat(b)), averages: groundTruthStates.map(ex => return ex.slice(1).map((_, index) => { return kFilter.predict({previousCorrected: ex[index - 1]}).mean; }) ).reduce((a,b) => a.concat(b)) }); const observationCovariance = getCovariance({ measures: measures.reduce((a,b) => a.concat(b)), averages: groundTruthStates.map((a) => a[0]).reduce((a,b) => a.concat(b)) }); ``` -------------------------------- ### JavaScript Status and UI Control for Bouncing Ball Demo Source: https://github.com/piercus/kalman-filter/blob/master/docs/bouncing-ball.html Manages the display status of different Kalman Filter components (prediction, observation, correction, speed vectors, variances, covariances) and controls their visibility. This script is intended to be run in a browser environment. ```javascript const btn = document.querySelector('button'); const status = { 'predicted': true, 'observation': true, 'corrected': true, 'speedVectors': false, 'variances': true, 'covariances': false }; const removeClass = function(el, className) { el.classList.remove(className); }; const addClass = function(el, className) { el.classList.add(className); }; const showHide = function(id) { const toRemove = status[id] ? id : 'not-'+id; const toAdd = !(status[id]) ? id : 'not-'+id; removeClass(document.getElementById("bouncing-ball"), toRemove); addClass(document.getElementById("bouncing-ball"), toAdd); status[id] = !(status[id]) } Object.keys(status).forEach(k => { showHide(k) showHide(k) }) const run = function(){ require('bouncing-ball').run() } ``` -------------------------------- ### Predict/Correct Kalman Filter Usage Source: https://github.com/piercus/kalman-filter/blob/master/README.md For advanced online usage, dissociate the `predict` and `correct` functions. Ensure `previousCorrected` is updated for the next iteration. ```javascript // online kalman filter let previousCorrected = null; const results = []; observations.forEach(observation => { const predicted = kFilter.predict({ previousCorrected }); const correctedState = kFilter.correct({ predicted, observation }); results.push(correctedState.mean); // update the previousCorrected for next loop iteration previousCorrected = correctedState }); console.log(results); ``` -------------------------------- ### Measure Model Precision with Random Data Source: https://github.com/piercus/kalman-filter/blob/master/README.md Assess the precision of a Kalman filter model by comparing its predictions against randomly generated data sequences. This uses the `hasard` library to generate observations and then calculates the total Mahalanobis distance. ```javascript const h = require('hasard') const observationHasard = h.array({value: h.number({type: 'normal'}), size: 2}) const observations = observationHasard.run(200); // online kalman filter let previousCorrected = null; const results = []; observations.forEach(observation => { const predicted = kFilter.predict({ previousCorrected }); const dist = predicted.mahalanobis(measure) previousCorrected = kFilter.correct({ predicted, observation }); distances.push(dist); }); const distance = distances.reduce((d1, d2) => d1 + d2, 0); ``` -------------------------------- ### Measure Model Fit with Mahalanobis Distance Source: https://github.com/piercus/kalman-filter/blob/master/README.md Calculate the Mahalanobis distance to measure how well a Kalman filter model fits a sequence of measurements. This involves iterating through observations, predicting the next state, calculating the distance, and correcting the state. ```javascript const observations = [[0, 2], [0.1, 4], [0.5, 9], [0.2, 12]]; // online kalman filter let previousCorrected = null; const results = []; observations.forEach(observation => { const predicted = kFilter.predict({ previousCorrected }); const dist = predicted.mahalanobis(observation) previousCorrected = kFilter.correct({ predicted, observation }); distances.push(dist); }); const distance = distances.reduce((d1, d2) => d1 + d2, 0); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.