# Here is a graphic demo for fitKCA.

```
# fitKCA by MLdP on 02/22/2014 <[email protected]>
# Kinetic Component Analysis
# demo by Hayek
import numpy as np
from pykalman import KalmanFilter
#-----------------------------------------------
def fitKCA(t,z,q,fwd=0):
'''
Inputs:
t: Iterable with time indices
z: Iterable with measurements
q: Scalar that multiplies the seed states covariance
fwd: number of steps to forecast (optional, default=0)
Output:
x[0]: smoothed state means of position velocity and acceleration
x[1]: smoothed state covar of position velocity and acceleration
Dependencies: numpy, pykalman
'''
#1) Set up matrices A,H and a seed for Q
h=(t[-1]-t[0])/t.shape[0]
A=np.array([[1,h,.5*h**2],
[0,1,h],
[0,0,1]])
Q=q*np.eye(A.shape[0])
#2) Apply the filter
kf=KalmanFilter(transition_matrices=A,transition_covariance=Q)
#3) EM estimates
kf=kf.em(z)
#4) Smooth
x_mean,x_covar=kf.smooth(z)
#5) Forecast
for fwd_ in range(fwd):
x_mean_,x_covar_=kf.filter_update(filtered_state_mean=x_mean[-1], \
filtered_state_covariance=x_covar[-1])
x_mean=np.append(x_mean,x_mean_.reshape(1,-1),axis=0)
x_covar_=np.expand_dims(x_covar_,axis=0)
x_covar=np.append(x_covar,x_covar_,axis=0)
#6) Std series
x_std=(x_covar[:,0,0]**.5).reshape(-1,1)
for i in range(1,x_covar.shape[1]):
x_std_=x_covar[:,i,i]**.5
x_std=np.append(x_std,x_std_.reshape(-1,1),axis=1)
return x_mean,x_std,x_covar
def demo_KCA( ):
""" By Hayek """
from numpy import zeros
from numpy.random import rand
import matplotlib.pyplot as plt
N_K = 100
t = zeros( N_K )
z = zeros( [ N_K, 3 ] )
for k in range( N_K ):
t[ k ] = k
z[ k, : ] = [ 0.005 * k ** 2 + 0.05 * k + 0.5 + 10 * rand(1)[0],
0.01 * k + 0.05, 0.01 ]
# Second order ploynoimial, its vel and acc; sth like x_mean.
x_mean, x_std, x_covar = fitKCA( t, z[ :, 0 ], 1 )
fig = plt.figure( )
ax1 = fig.add_axes( [0.1, 0.1, 0.8, 0.8] )
l_0, l_1 = ax1.plot(
np.arange( N_K ), z[ :, 0 ], 'r' ,
np.arange( N_K ), x_mean[ :, 0 ], 'g' )
fig.legend( ( l_0, l_1 ),
( u'Noised second order ploynoimial',
u'After Kalman filter' ),
'upper left' )
if __name__ == "__main__":
demo_KCA( )
```