KalmanFilters
- Kalman Filter (KF)
- Extended Kalman Filter (EKF)
- Ensemble Kalmen Filter (EnKF)
- Ensemble Transform Kalman Filter (ETKF)
- Local Ensemble Transform Kalman Filter (LETKF)
Main File
KF_Plot.py
Code
KF_Plot.py
import numpy as np
import matplotlib.pyplot as plt
import scipy as sp
from matplotlib.widgets import Slider
class KF:
def __init__(self, dim_x:int, dim_y:int, x0, P, M, Q, R, H):
"""
Kalman Filter
Use forecast(), forward(), and analyze()
@param:
dim_x (int): dimension of X (m)
dim_y (int): dimension of Observation Y (j)
x0 (numpy.ndarray): Initial x (mean) mx1
P (numpy.ndarray): P Covariance mxm
M (numpy.ndarray): M Model Matrix mxm
Q (numpy.ndarray): Q Covariance of the model error mxm
R (numpy.ndarray): R Covariance of the observation error jxj
H (numpy.ndarray): H Observation Matrix jxm
"""
if ((dim_x,1) != x0.shape):
raise ValueError("Wrong dimension (X0)")
self.filterType = "KF"
self.dim_x = dim_x # dimension of x (m)
self.dim_y = dim_y # dimension of Observation Y (j)
self.x = x0 # Initial X (mean) mx1
self.P = P # P (Covariance) mxm
self.M = M # M (Model Matrix) mxm
self.Q = Q # Q (Covariance of the model error) mxm
self.R = R # R (Covariance of the observation error) jxj
self.H = H # H (Observation Matrix) jxm
self.Xm = x0 # without KF (process X only with M)
self.X_cStack = x0 # collection of x (mxk, k = number of steps)
self.Xm_cStack = x0 # collection of Xm (mxk)
self.RMSDList = [] # root mean squared deviation List
self.PList = [] # covariance List
def forecast(self):
"""
Forecast X and P
Also save Xm to compare with the estimate
"""
self.x = self.M @ self.x
self.P = self.M @ self.P @ self.M.T + self.Q
self.Xm = self.M @ self.Xm
self.Xm_cStack = np.column_stack((self.Xm_cStack, self.Xm))
def forward(self):
"""Forward X with M"""
self.forecast()
self.X_cStack = np.column_stack((self.X_cStack, self.x))
def analyze(self, y):
"""
Analyze X and P
y (numpy.ndarray): Observation of the true state with observation error
y = H X_t + mu where (mu ~ N(0,R))
"""
if (self.dim_y != y.shape[0]):
raise ValueError("Wrong dimension (Y)")
K = self.P @ self.H.T @ np.linalg.inv(self.H @ self.P @ self.H.T + self.R) # Kalman Gain Matrix
self.x = K @ (y - self.H @ self.x) + self.x # analysis ensemble mean
self.P = (np.eye(self.dim_x) - K @ self.H) @ self.P # analysis covariance
self.PList.append(self.P) # save analysis covariance
self.X_cStack = np.column_stack((self.X_cStack, self.x))
def get_xk(self, m):
"""
return row m of X_cStack as a list
m (int): row index
"""
return list(self.X_cStack[m,:])
def RMSD(self, X, X_true):
"""
Return final Root Mean Squared Deviation
X (numpy.ndarray): Column Stacked X
X_true (numpy.ndarray): Column Stacked True States
"""
return np.sqrt(np.sum((np.sum(X, axis=0) - np.sum(X_true, axis=0))**2)/X.shape[1])
def RMSDSave(self, X, X_true):
"""
Save current RMSD
X (numpy.ndarray): Column Stacked X
X_true (numpy.ndarray): Column Stacked True States
"""
X_Length = X.shape[1]
X_true = X_true[:,np.arange(X_Length)]
self.RMSDList.append(self.RMSD(X, X_true))
def plot_RMSD(self, filters=[], show=True):
"""
plot evolution of Root Mean Squared Deviation.
Need to run RMSDSave in the loop.
filters (list, optional): addition filter to compare, Defaults to [].
show (boolean, optional): execute plt.show() if True. Defaults to True.
"""
plt.figure()
plt.plot(self.RMSDList, label=self.filterType)
if (len(filters) > 0):
for filter in filters:
plt.plot(filter.RMSDList, label=filter.filterType)
plt.legend(loc="best")
if show:
plt.show()
def plot_all(self, x_true=np.array([[]]),
has_obs=[], Ys=np.array([[]]), titles=[], plotXm = True,
show=True, rmsd=True, filters=[], cov=False):
"""
Plot each element (x_i) from X in 2D graph (value vs k)
@param:
x_true (numpy.ndarray, optional): Column stacked true states. Defaults to np.array([[]]).
has_obs (int list, optional): One integer element 'i' represents x_i from X has observations. Defaults to [].
Ys (numpy.ndarray, optional): ColumnStacked observations. Must be ascending order. Defaults to
提示:代码过长已自动截断
Requirements
Open
numpy
pip install numpy
matplotlib
pip install matplotlib
scipy
pip install scipy
tqdm
pip install tqdmd
Template
KF_Template.py
Code
from KF_Plot import *
from tqdm import tqdm
"""
KF_Plot Twin Experiment Template
replace "<>" for user's model
add more steps or features if needed
See examples and KF_Plot.py for more details
"""
"""Variables and Operators Set Up"""
k = "<int>" # number of steps
m = "<int>" # dimension of X
j = "<int>" # dimension of Y
dt = "<float>" # time step
# x is mx1 vector
def M(x): # Model Operator
"<>"
return "<>" # must return mx1 vector
def H(x): # Observation Operator
"<>"
return "<>" # must return jxm vector
def H_j(x): # Jacobian of H if H is non-linear
"<>"
return "<>" # must return jxm vector
Q = "<mxm matrix>" # Model error
R = "<jxj matrix>" # Observation Error
# true states
# starting point
xt0 = "<mx1> vector"
xt = xt0
Ys = np.array([np.inf]*j) # observations
# This is initial observation. Observations will be stacked columnwise
c = "<int>" # observation Frequency
for i in range(k): # generate True State
x = M(xt[:,-1])
xt = np.column_stack((xt,x))
P = "<mxm matrix>" # initial Covariance
e = np.random.multivariate_normal([0, 0, 0], P, size=(1)).T # initial error
X0 = xt0 + e # initial X
filter = "<Kalman Filter>"
# ex) etkf = ETKF(m, j, X0, P, enM, R, enH, n=10)
# Use correct forecast, analyze, forward. Check the prefixes ex) etforward() != forward()
for i in tqdm(range(k),desc="Filtering"):
if i % c == 0:
#"<filter.forecast()>"
y = np.random.multivariate_normal(H(xt[:,i+1]).T, R).reshape((j,1)) # observations with error
#"<filter.analyze(y)>"
Ys = np.column_stack((Ys, y))
else:
#<"filter.forward()>"
Ys = np.column_stack((Ys, np.array([np.inf]*j)))
# filter.RMSDSave(filter.X_cStack, xt)
# "<filter.plot_all(...)>"
# "<filter.plot_RMSD()>"
Lorenz 63 Example
used file:
ETKF_Example2_Lorenz-63.py

评论