filters.py
Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 # Copyright (c) 2013, Oregon State University
00003 # All rights reserved.
00004 
00005 # Redistribution and use in source and binary forms, with or without
00006 # modification, are permitted provided that the following conditions are met:
00007 #     * Redistributions of source code must retain the above copyright
00008 #       notice, this list of conditions and the following disclaimer.
00009 #     * Redistributions in binary form must reproduce the above copyright
00010 #       notice, this list of conditions and the following disclaimer in the
00011 #       documentation and/or other materials provided with the distribution.
00012 #     * Neither the name of the Oregon State University nor the
00013 #       names of its contributors may be used to endorse or promote products
00014 #       derived from this software without specific prior written permission.
00015 
00016 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
00017 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
00018 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
00019 # DISCLAIMED. IN NO EVENT SHALL OREGON STATE UNIVERSITY BE LIABLE FOR ANY
00020 # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
00021 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
00022 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
00023 # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00024 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
00025 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00026 
00027 # Author Dan Lazewatsky/lazewatd@engr.orst.edu
00028 
00029 from collections import deque
00030 import numpy as np
00031 import cv
00032 
00033 class MeanFilter(object):
00034         def __init__(self, window_size=3):
00035                 self.window_size = window_size
00036                 self.observations = deque([], window_size)
00037         def observation(self, obs):
00038                 self.observations.append(obs)
00039                 weights = range(len(self.observations), 0, -1)
00040                 return np.int32(np.average(self.observations, axis=0, weights=weights)).tolist()
00041 
00042 class KalmanFilter(object):
00043         initialized = False
00044         def __init__(self, cov, dynam_params, measure_params, control_params=0):
00045                 self.kf = cv.CreateKalman(dynam_params, measure_params, control_params)
00046                 cv.SetIdentity(self.kf.measurement_matrix, cv.RealScalar(1))
00047                 self.set_cov(cv.fromarray(cov))
00048 
00049         def set_cov(self, cov):
00050                 cov = np.float32(cov)
00051                 cv.Copy(cv.fromarray(cov), self.kf.measurement_noise_cov)
00052                 assert np.all(cov == np.asarray(self.kf.measurement_noise_cov)), "Covariance matrix didn't get set"
00053                 
00054         def set_control(self, cont):
00055                 cont = np.float32(cont)
00056                 cv.Copy(cv.fromarray(cont), self.kf.control_matrix)
00057                 assert np.all(cont == np.asarray(self.kf.control_matrix)), "Control matrix didn't get set"
00058                 
00059         def observation(self, meas):
00060                 meas = np.float32([meas])
00061                 if not self.initialized:
00062                         cv.Copy(cv.fromarray(meas.T.copy()), self.kf.state_post)
00063                         cv.Copy(cv.fromarray(meas.T.copy()), self.kf.state_pre)
00064                         self.initialized = True
00065                 if self.kf.CP == 0:
00066                         cv.KalmanPredict(self.kf)
00067                 corrected = np.asarray(cv.KalmanCorrect(self.kf, cv.fromarray(meas.T.copy())))
00068                 return corrected.T[0].copy()
00069                 
00070         def control(self, signal):
00071                 signal = np.float32([signal])
00072                 if not self.initialized:
00073                         return np.zeros(1,self.kf.DP)
00074                 predicted = np.asarray(cv.KalmanPredict(self.kf, cv.fromarray(signal.T.copy())))
00075                 return predicted.T[0].copy()
00076 
00077 
00078 if __name__ == '__main__':
00079         def make_obs(x):
00080                 #gt = np.array([np.sin(x/75.0), np.cos(x/75.0)])*100
00081                 gt = [x,x]
00082                 # gt = [ 2361.90541702 + x,     352.84006879 + x ]
00083                 # noise = np.random.multivariate_normal((0,0), cov)
00084                 # return gt, gt+noise
00085                 return gt, np.random.multivariate_normal(gt, cov)
00086         
00087         import matplotlib.pyplot as plt
00088         # cov = np.matrix([[ 4.1208e3, 2.3380e3], [-5.3681,     1.9369e3]])
00089         cov = np.ones((2,2))*100
00090         f = KalmanFilter(cov, 2, 2, 2)
00091         f.set_control(cv.fromarray(np.matrix([[1.0,0.0],[0.0,1.0]])))
00092         print np.asarray(f.kf.control_matrix)
00093 
00094         observations = []
00095         filtered = []
00096         gts = []
00097         
00098         for gt, obs in (make_obs(x) for x in xrange(0,100,1)):
00099                 gts.append(gt)
00100                 # print obs
00101                 observations.append(obs)
00102                 
00103                 corrected = f.observation(obs)
00104                 # filtered.append(corrected)
00105                 predicted = f.control([1,0])
00106                 filtered.append(corrected)
00107         
00108         observations = np.array(observations)
00109         filtered = np.array(filtered)
00110         gts = np.array(gts)
00111         # print observations.std(0), filtered.std(0)
00112         plt.clf()
00113         plt.plot(observations[:,0])
00114         plt.hold(True)
00115         plt.plot(filtered[:,0])
00116         plt.legend(['obs', 'filtered'])
00117         plt.show()


rosmouse
Author(s): Daniel Lazewatsky
autogenerated on Mon Oct 6 2014 00:22:57