1 # -*- coding: utf-8 -*-
3 from numpy import array, random
8 Yobs.append([random.normal(Xtrue, 0.1, size=(1,)),])
10 print("Estimation of a constant variable by filtering")
11 print("----------------------------------------------")
12 print(" Noisy measurements acquired on %i time steps"%(len(Yobs)-1,))
14 from adao import adaoBuilder
15 case = adaoBuilder.New('')
17 case.setObservationOperator(Matrix = [1.])
18 case.setObservationError (ScalarSparseMatrix = 0.1**2)
20 case.setEvolutionModel (Matrix = [1.])
21 case.setEvolutionError (ScalarSparseMatrix = 1e-5)
23 case.setAlgorithmParameters(
24 Algorithm="KalmanFilter",
26 "StoreSupplementaryCalculations":[
28 "APosterioriCovariance",
33 Info=" Analyzed state at current observation:",
34 Template='ValuePrinter',
38 XaStep, VaStep = 0., 1.
39 for i in range(1,len(Yobs)):
40 case.setBackground (Vector = "%s"%float(XaStep))
41 case.setBackgroundError (ScalarSparseMatrix = "%s"%float(VaStep))
42 case.setObservation (Vector = Yobs[i])
43 case.execute( nextStep = True )
44 XaStep = case.get("Analysis")[-1]
45 VaStep = case.get("APosterioriCovariance")[-1]
47 Xa = case.get("Analysis")
48 Pa = case.get("APosterioriCovariance")
51 print(" Final a posteriori variance:",Pa[-1])
54 #-------------------------------------------------------------------------------
56 Observations = array([yo[0] for yo in Yobs])
57 Estimates = array([xa[0] for xa in case.get("Analysis")])
58 Variances = array([pa[0,0] for pa in case.get("APosterioriCovariance")])
60 import matplotlib.pyplot as plt
61 plt.rcParams['figure.figsize'] = (10, 4)
64 plt.plot(Observations,'kx',label='Noisy measurements')
65 plt.plot(Estimates,'r-',label='Estimated state')
66 plt.axhline(Xtrue,color='b',label='Truth value')
68 plt.title('Estimate of the state', fontweight='bold')
69 plt.xlabel('Observation step')
71 plt.savefig("simple_KalmanFilter2_state.png")
74 iobs = range(1,len(Observations))
75 plt.plot(iobs,Variances[iobs],label='A posteriori error variance')
76 plt.title('Estimate of the a posteriori error variance', fontweight='bold')
77 plt.xlabel('Observation step')
78 plt.ylabel('$(Voltage)^2$')
79 plt.setp(plt.gca(),'ylim',[0,.01])
80 plt.savefig("simple_KalmanFilter2_variance.png")