Skip to content

Commit d3c4f36

Browse files
committed
1d kalman filter
1 parent 32341df commit d3c4f36

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

src/Vector/KalmanFilter.php

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
<?php
2+
3+
namespace Phperf\Pipeline\Vector;
4+
5+
class KalmanFilter implements VectorProcessor
6+
{
7+
/** @var float|int Process noise (how variable data is expected to come) */
8+
public $processNoise;
9+
/** @var float|int Measurement noise (how strong is ) */
10+
public $measurementNoise;
11+
12+
public $stateVector;
13+
public $controlVector;
14+
public $measurementVector;
15+
public $cov;
16+
public $x;
17+
18+
19+
/**
20+
* Create 1-dimensional kalman filter
21+
* @param float|int $processNoise Process noise
22+
* @param float|int $measurementNoise Measurement noise
23+
* @param float|int $stateVector State vector
24+
* @param float|int $controlVector Control vector
25+
* @param float|int $measurementVector Measurement vector
26+
* @param $cov
27+
* @param $x
28+
*/
29+
function __construct($processNoise = 1, $measurementNoise = 1, $stateVector = 1, $controlVector = 0, $measurementVector = 1, $cov = null, $x = null)
30+
{
31+
$this->processNoise = $processNoise; // noise power desirable
32+
$this->measurementNoise = $measurementNoise; // noise power estimated
33+
34+
$this->stateVector = $stateVector;
35+
$this->controlVector = $controlVector;
36+
$this->measurementVector = $measurementVector;
37+
38+
$this->cov = $cov;
39+
$this->x = $x; // estimated signal without noise
40+
}
41+
42+
/**
43+
* Filter a new value
44+
* @param float $value Measurement
45+
* @param float|int $u Control
46+
* @return float
47+
*/
48+
function value($value, $u = 0)
49+
{
50+
if (null === $this->x) {
51+
$this->x = (1 / $this->measurementVector) * $value;
52+
$this->cov = (1 / $this->measurementVector) * $this->measurementNoise * (1 / $this->measurementVector);
53+
} else {
54+
// Compute prediction
55+
$predX = ($this->stateVector * $this->x) + ($this->controlVector * $u);
56+
$predCov = (($this->stateVector * $this->cov) * $this->stateVector) + $this->processNoise;
57+
58+
// Kalman gain
59+
$K = $predCov * $this->measurementVector *
60+
(1 / (($this->measurementVector * $predCov * $this->measurementVector) + $this->measurementNoise));
61+
62+
// Correction
63+
$this->x = $predX + $K * ($value - ($this->measurementVector * $predX));
64+
$this->cov = $predCov - ($K * $this->measurementVector * $predCov);
65+
}
66+
67+
return $this->x;
68+
}
69+
}

0 commit comments

Comments
 (0)