Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Kalman Filter #698

Merged
merged 1 commit into from
Sep 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/Locators/BfgsMultilateralizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public bool Locate(Scenario scenario)
if (pos.Length < 3 || _floor.Bounds == null)
{
confidence = 1;
scenario.Location = guess;
scenario.UpdateLocation(guess);
}
else
{
Expand Down Expand Up @@ -77,7 +77,7 @@ public bool Locate(Scenario scenario)
});
var solver = new BfgsBMinimizer(0, 0.25, 0.25, 1000);
var result = solver.FindMinimum(obj, lowerBound, upperBound, initialGuess);
scenario.Location = new Point3D(result.MinimizingPoint[0], result.MinimizingPoint[1], result.MinimizingPoint[2]);
scenario.UpdateLocation(new Point3D(result.MinimizingPoint[0], result.MinimizingPoint[1], result.MinimizingPoint[2]));
scenario.Fixes = pos.Length;
scenario.Error = result.FunctionInfoAtMinimum.Value;
scenario.Iterations = result switch
Expand All @@ -94,7 +94,7 @@ public bool Locate(Scenario scenario)
catch (Exception ex)
{
confidence = 1;
scenario.Location = guess;
scenario.UpdateLocation(guess);
Log.Error("Error finding location for {0}: {1}", _device, ex.Message);
}

Expand Down
8 changes: 4 additions & 4 deletions src/Locators/GaussNewtonMultilateralizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public bool Locate(Scenario scenario)
if (pos.Length < 3 || _floor.Bounds == null)
{
confidence = 1;
scenario.Location = guess;
scenario.UpdateLocation(guess);
}
else
{
Expand All @@ -67,7 +67,7 @@ public bool Locate(Scenario scenario)
var gaussNewton = new GaussNewton(pos, ranges, lowerBound, upperBound);
var result = gaussNewton.FindPosition(initialGuess);

scenario.Location = new Point3D(result.X, result.Y, result.Z);
scenario.UpdateLocation(new Point3D(result.X, result.Y, result.Z));
scenario.Fixes = pos.Length;
scenario.Error = pos.Select((p, i) => Math.Pow(Error(result.ToPoint3D(), p.ToPoint3D(), ranges[i]), 2)).Average();
scenario.Iterations = gaussNewton.Iterations;
Expand All @@ -81,12 +81,12 @@ public bool Locate(Scenario scenario)
{
scenario.ReasonForExit = ExitCondition.ExceedIterations;
confidence = 1;
scenario.Location = guess;
scenario.UpdateLocation(guess);
}
catch (Exception ex)
{
confidence = 0;
scenario.Location = new Point3D();
scenario.UpdateLocation(new Point3D());
Log.Error("Error finding location for {0}: {1}", _device, ex.Message);
}

Expand Down
4 changes: 2 additions & 2 deletions src/Locators/IterativeCentroidMultilateralizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public bool Locate(Scenario scenario)
scenario.Error = CalculateError(centroid, original);
scenario.Confidence = 1;
scenario.ReasonForExit = ExitCondition.LackOfProgress;
scenario.Location = new Point3D(centroid[0], centroid[1], centroid[2]);
scenario.UpdateLocation(new Point3D(centroid[0], centroid[1], centroid[2]));
scenario.Room = floor.Rooms.Values.FirstOrDefault(a => a.Polygon?.EnclosesPoint(scenario.Location.ToPoint2D()) ?? false);
return Math.Abs(scenario.Location.DistanceTo(scenario.LastLocation)) >= 0.1;
}
Expand All @@ -65,7 +65,7 @@ public bool Locate(Scenario scenario)
var err = CalculateError(centroid, original);
scenario.Error = err;
scenario.Confidence = Math.Clamp((10000 - (int?)Math.Ceiling(100 * err)) ?? 0, 0, 100);
scenario.Location = new Point3D(centroid[0], centroid[1], centroid[2]);
scenario.UpdateLocation(new Point3D(centroid[0], centroid[1], centroid[2]));
scenario.Room = floor.Rooms.Values.FirstOrDefault(a => a.Polygon?.EnclosesPoint(scenario.Location.ToPoint2D()) ?? false);
return Math.Abs(scenario.Location.DistanceTo(scenario.LastLocation)) >= 0.1;
}
Expand Down
8 changes: 4 additions & 4 deletions src/Locators/MLEMultilateralizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ double Error(IList<double> x, DeviceToNode dn)
if (pos.Length < 3 || floor.Bounds == null)
{
confidence = 1;
scenario.Location = guess;
scenario.UpdateLocation(guess);
}
else
{
Expand Down Expand Up @@ -84,7 +84,7 @@ double Error(IList<double> x, DeviceToNode dn)
var solver = new NelderMeadSimplex(1e-7, 10000);
var result = solver.FindMinimum(obj, initialGuess, initialPerturbation);
var minimizingPoint = result.MinimizingPoint.PointwiseMinimum(upperBound).PointwiseMaximum(lowerBound);
scenario.Location = new Point3D(minimizingPoint[0], minimizingPoint[1], minimizingPoint[2]);
scenario.UpdateLocation(new Point3D(minimizingPoint[0], minimizingPoint[1], minimizingPoint[2]));
scenario.Scale = minimizingPoint[3];
scenario.Fixes = pos.Length;
scenario.Error = result.FunctionInfoAtMinimum.Value;
Expand All @@ -103,12 +103,12 @@ double Error(IList<double> x, DeviceToNode dn)
{
scenario.ReasonForExit = ExitCondition.ExceedIterations;
confidence = 1;
scenario.Location = guess;
scenario.UpdateLocation(guess);
}
catch (Exception ex)
{
confidence = 0;
scenario.Location = new Point3D();
scenario.UpdateLocation(new Point3D());
Log.Error("Error finding location for {0}: {1}", device, ex.Message);
}

Expand Down
6 changes: 3 additions & 3 deletions src/Locators/MultiFloorMultilateralizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public bool Locate(Scenario scenario)
scenario.Scale ?? 1.0
});
var result = solver.FindMinimum(obj, init);
scenario.Location = new Point3D(result.MinimizingPoint[0], result.MinimizingPoint[1], result.MinimizingPoint[2]);
scenario.UpdateLocation(new Point3D(result.MinimizingPoint[0], result.MinimizingPoint[1], result.MinimizingPoint[2]));
scenario.Scale = result.MinimizingPoint[3];
scenario.Fixes = pos.Count;
scenario.Minimum = nodes.Min(a => (double?) a.Distance);
Expand All @@ -73,14 +73,14 @@ public bool Locate(Scenario scenario)
{
confidence = 1;
scenario.Scale = 1;
scenario.Location = guess;
scenario.UpdateLocation(guess);
}
}
catch (Exception ex)
{
confidence = 1;
scenario.Scale = 1;
scenario.Location = guess;
scenario.UpdateLocation(guess);
Log.Error("Error finding location for {0}: {1}", _device, ex.Message);
}
}
Expand Down
8 changes: 4 additions & 4 deletions src/Locators/NelderMeadMultilateralizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public bool Locate(Scenario scenario)
if (pos.Length < 3 || floor.Bounds == null)
{
confidence = 1;
scenario.Location = guess;
scenario.UpdateLocation(guess);
}
else
{
Expand Down Expand Up @@ -73,7 +73,7 @@ public bool Locate(Scenario scenario)
var solver = new NelderMeadSimplex(1e-7, 10000);
var result = solver.FindMinimum(obj, initialGuess, initialPerturbation);
var minimizingPoint = result.MinimizingPoint.PointwiseMinimum(upperBound).PointwiseMaximum(lowerBound);
scenario.Location = new Point3D(minimizingPoint[0], minimizingPoint[1], minimizingPoint[2]);
scenario.UpdateLocation(new Point3D(minimizingPoint[0], minimizingPoint[1], minimizingPoint[2]));
scenario.Scale = minimizingPoint[3];
scenario.Fixes = pos.Length;
scenario.Error = result.FunctionInfoAtMinimum.Value;
Expand All @@ -92,12 +92,12 @@ public bool Locate(Scenario scenario)
{
scenario.ReasonForExit = ExitCondition.ExceedIterations;
confidence = 1;
scenario.Location = guess;
scenario.UpdateLocation(guess);
}
catch (Exception ex)
{
confidence = 0;
scenario.Location = new Point3D();
scenario.UpdateLocation(new Point3D());
Log.Error("Error finding location for {0}: {1}", device, ex.Message);
}

Expand Down
80 changes: 78 additions & 2 deletions src/Models/Scenario.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using MathNet.Numerics.Optimization;
using MathNet.Spatial.Euclidean;
using Newtonsoft.Json;
using MathNet.Numerics.LinearAlgebra;

namespace ESPresense.Models;

Expand All @@ -14,7 +15,7 @@ public class Scenario(Config? config, ILocate locator, string? name)
public int? Confidence { get; set; }
public double? Minimum { get; set; }
[JsonIgnore] public Point3D LastLocation { get; set; }
public Point3D Location { get; set; }
public Point3D Location { private set; get; }
public double? Scale { get; set; }
public int? Fixes { get; set; }
public string? Name { get; } = name;
Expand All @@ -26,8 +27,83 @@ public class Scenario(Config? config, ILocate locator, string? name)
public DateTime? LastHit { get; set; }
public double Probability { get; set; } = 1.0;

// Kalman filter properties
private Matrix<double>? _kalmanStateEstimate;
private Matrix<double>? _kalmanErrorCovariance;
private const double ProcessNoise = 0.01;
private const double MeasurementNoise = 0.1;
private Matrix<double>? _F; // State transition matrix
private Matrix<double>? _H; // Measurement matrix
private Matrix<double>? _Q; // Process noise covariance
private Matrix<double>? _R; // Measurement noise covariance

public bool Locate()
{
return Locator.Locate(this);
}
}

public void UpdateLocation(Point3D newLocation)
{
if (_kalmanStateEstimate == null || _kalmanErrorCovariance == null)
{
InitializeKalmanFilter(newLocation);
}

var dt = (DateTime.UtcNow - (LastHit ?? DateTime.UtcNow)).TotalSeconds;
LastHit = DateTime.UtcNow;

UpdateStateTransitionMatrix(dt);

// Predict
_kalmanStateEstimate = _F! * _kalmanStateEstimate!;
_kalmanErrorCovariance = _F * _kalmanErrorCovariance! * _F.Transpose() + _Q!;

// Update
var y = Matrix<double>.Build.DenseOfArray(new double[,] {
{ newLocation.X }, { newLocation.Y }, { newLocation.Z }
}) - _H! * _kalmanStateEstimate;

var S = _H * _kalmanErrorCovariance * _H.Transpose() + _R!;
var K = _kalmanErrorCovariance * _H.Transpose() * S.Inverse();

_kalmanStateEstimate += K * y;
_kalmanErrorCovariance = (Matrix<double>.Build.DenseIdentity(6) - K * _H) * _kalmanErrorCovariance;

// Update Location
Location = new Point3D(
_kalmanStateEstimate[0, 0],
_kalmanStateEstimate[1, 0],
_kalmanStateEstimate[2, 0]
);
}

private void InitializeKalmanFilter(Point3D initialLocation)
{
_kalmanStateEstimate = Matrix<double>.Build.DenseOfArray(new double[,] {
{ initialLocation.X }, { initialLocation.Y }, { initialLocation.Z },
{ 0 }, { 0 }, { 0 }
});
_kalmanErrorCovariance = Matrix<double>.Build.DenseDiagonal(6, 6, 1);

_H = Matrix<double>.Build.DenseOfArray(new double[,] {
{ 1, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 0, 0 }
});

_Q = Matrix<double>.Build.DenseDiagonal(6, 6, ProcessNoise);
_R = Matrix<double>.Build.DenseDiagonal(3, 3, MeasurementNoise);
}

private void UpdateStateTransitionMatrix(double dt)
{
_F = Matrix<double>.Build.DenseOfArray(new double[,] {
{ 1, 0, 0, dt, 0, 0 },
{ 0, 1, 0, 0, dt, 0 },
{ 0, 0, 1, 0, 0, dt },
{ 0, 0, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 1, 0 },
{ 0, 0, 0, 0, 0, 1 }
});
}
}
Loading