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

Updated noise handling #147

Open
wants to merge 3 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 7 additions & 20 deletions src/prog_algs/state_estimators/kalman_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,6 @@ class KalmanFilter(state_estimator.StateEstimator):
Starting time (s)
dt : float
time step (s)
Q : List[List[float]]
Process Noise Matrix
R : List[List[float]]
Measurement Noise Matrix

Note:
The Kalman Filter does not support a custom measurement function
Expand All @@ -47,13 +43,11 @@ def __init__(self, model, x0, measurement_eqn : Callable = None, **kwargs):

self.x0 = x0

if 'Q' not in self.parameters:
self.parameters['Q'] = np.diag([1.0e-3 for i in x0.keys()])
if 'R' not in self.parameters:
# Size of what's being measured (not output)
# This is determined by running the measure function on the first state
self.parameters['R'] = np.diag([1.0e-3 for i in range(model.n_outputs)])

if 'Q' in self.parameters:
warn("UKF does not support Q parameter. Instead, set process noise, model.parameters['process_noise']")
if 'R' in self.parameters:
warn("UKF does not support R parameter. Instead, set measurement noise, model.parameters['measurement_noise']")

num_states = len(x0.keys())
num_inputs = model.n_inputs + 1
num_measurements = model.n_outputs
Expand All @@ -72,21 +66,14 @@ def __init__(self, model, x0, measurement_eqn : Callable = None, **kwargs):
if isinstance(x0, dict) or isinstance(x0, model.StateContainer):
warn("Warning: Use UncertainData type if estimating filtering with uncertain data.")
self.filter.x = np.array([[x0[key]] for key in model.states]) # x0.keys()
self.filter.P = self.parameters['Q'] / 10
elif isinstance(x0, UncertainData):
x_mean = x0.mean
self.filter.x = np.array([[x_mean[key]] for key in model.states])

# Reorder covariance to be in same order as model.states
mapping = {i: list(x0.keys()).index(key) for i, key in enumerate(model.states)}
cov = x0.cov # Set covariance in case it has been calculated
mapped_cov = [[cov[mapping[i]][mapping[j]] for j in range(len(cov))] for i in range(len(cov))] # Set covariance based on mapping
self.filter.P = np.array(mapped_cov)
else:
raise TypeError("TypeError: x0 initial state must be of type {{dict, UncertainData}}")

self.filter.Q = self.parameters['Q']
self.filter.R = self.parameters['R']
self.filter.Q = np.diag([0]*len(x0))
self.filter.R = np.diag([0]*len(model.outputs))
self.filter.F = F
self.filter.B = B

Expand Down
30 changes: 14 additions & 16 deletions src/prog_algs/state_estimators/unscented_kalman_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,21 @@
from . import state_estimator
from filterpy import kalman
from numpy import diag, array
from warnings import warn
from ..uncertain_data import MultivariateNormalDist, UncertainData


class UnscentedKalmanFilter(state_estimator.StateEstimator):
"""
An Unscented Kalman Filter (UKF) for state estimation

This class defines logic for performing an unscented kalman filter with a Prognostics Model (see Prognostics Model Package). This filter uses measurement data with noise to generate a state estimate and covariance matrix.

Arguments:
model: A Prognostics Model object
x0: A dictionary of initial state values
measurement_eqn (optional): A function that takes a dictionary of state values and returns a dictionary of measurement values. If not specified, the model's output function is used.

The supported configuration parameters (keyword arguments) for UKF construction are described below:

Constructor Configuration Parameters:
Expand All @@ -22,10 +29,8 @@ class UnscentedKalmanFilter(state_estimator.StateEstimator):
Starting time (s)
dt : float
time step (s)
Q : List[List[float]]
Process Noise Matrix
R : List[List[float]]
Measurement Noise Matrix
R : numpy.ndarray
Measurement noise covariance matrix (n_measurements x n_measurements). Only applicable if using measurement_eqn
"""
default_parameters = {
'alpha': 1,
Expand Down Expand Up @@ -56,16 +61,15 @@ def measure(x):
z = measurement_eqn(x)
return array(list(z.values())).ravel()

if 'Q' not in self.parameters:
self.parameters['Q'] = diag([1.0e-3 for i in x0.keys()])
if 'Q' in self.parameters:
warn("UKF does not support Q parameter. Instead, set process noise, model.parameters['process_noise']")

def state_transition(x, dt):
x = {key: value for (key, value) in zip(x0.keys(), x)}
Q_err = model.parameters['process_noise'].copy()
model.parameters['process_noise'] = dict.fromkeys(Q_err, 0)
z = model.output(x)
model.parameters['process_noise'] = Q_err
x = model.next_state(x, self.__input, dt)
model.parameters['process_noise'] = Q_err
return array(list(x.values())).ravel()

num_states = len(x0.keys())
Expand All @@ -76,20 +80,14 @@ def state_transition(x, dt):
if isinstance(x0, dict) or isinstance(x0, model.StateContainer):
warn("Warning: Use UncertainData type if estimating filtering with uncertain data.")
self.filter.x = array(list(x0.values()))
self.filter.P = self.parameters['Q'] / 10
elif isinstance(x0, UncertainData):
x_mean = x0.mean
self.filter.x = array(list(x_mean.values()))
self.filter.P = x0.cov
else:
raise TypeError("TypeError: x0 initial state must be of type {{dict, UncertainData}}")

if 'R' not in self.parameters:
# Size of what's being measured (not output)
# This is determined by running the measure function on the first state
self.parameters['R'] = diag([1.0e-3 for i in range(len(measure(self.filter.x)))])
self.filter.Q = self.parameters['Q']
self.filter.R = self.parameters['R']
self.filter.P = diag([0]*len(x0))
self.filter.R = diag([0]*len(measure(self.filter.x)))

def estimate(self, t : float, u, z):
"""
Expand Down