Salome HOME
cd96ea1418a0bee800cb724dc9f0a21911ee8688
[modules/adao.git] / src / daComposant / daAlgorithms / KalmanFilter.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2013 EDF R&D
4 #
5 #  This library is free software; you can redistribute it and/or
6 #  modify it under the terms of the GNU Lesser General Public
7 #  License as published by the Free Software Foundation; either
8 #  version 2.1 of the License.
9 #
10 #  This library is distributed in the hope that it will be useful,
11 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 #  Lesser General Public License for more details.
14 #
15 #  You should have received a copy of the GNU Lesser General Public
16 #  License along with this library; if not, write to the Free Software
17 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18 #
19 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #
21 #  Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
22
23 import logging
24 from daCore import BasicObjects, PlatformInfo
25 m = PlatformInfo.SystemUsage()
26 import numpy
27
28 # ==============================================================================
29 class ElementaryAlgorithm(BasicObjects.Algorithm):
30     def __init__(self):
31         BasicObjects.Algorithm.__init__(self, "KALMANFILTER")
32         self.defineRequiredParameter(
33             name     = "StoreSupplementaryCalculations",
34             default  = [],
35             typecast = tuple,
36             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
37             listval  = ["APosterioriCovariance", "CostFunctionJ", "Innovation"]
38             )
39         self.defineRequiredParameter(
40             name     = "EstimationType",
41             default  = "State",
42             typecast = str,
43             message  = "Estimation d'etat ou de parametres",
44             listval  = ["State", "Parameters"],
45             )
46
47     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
48         logging.debug("%s Lancement"%self._name)
49         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
50         #
51         # Paramètres de pilotage
52         # ----------------------
53         self.setParameters(Parameters)
54         #
55         # Opérateurs
56         # ----------
57         if B is None:
58             raise ValueError("Background error covariance matrix has to be properly defined!")
59         if R is None:
60             raise ValueError("Observation error covariance matrix has to be properly defined!")
61         #
62         Ht = HO["Tangent"].asMatrix(None)
63         Ha = HO["Adjoint"].asMatrix(None)
64         #
65         Mt = EM["Tangent"].asMatrix(None)
66         Ma = EM["Adjoint"].asMatrix(None)
67         #
68         if CM is not None and CM.has_key("Tangent") and U is not None:
69             Cm = CM["Tangent"].asMatrix(None)
70         else:
71             Cm = None
72         #
73         # Nombre de pas du Kalman identique au nombre de pas d'observations
74         # -----------------------------------------------------------------
75         if hasattr(Y,"stepnumber"):
76             duration = Y.stepnumber()
77         else:
78             duration = 2
79         #
80         # Précalcul des inversions de B et R
81         # ----------------------------------
82         if "CostFunctionJ" in self._parameters["StoreSupplementaryCalculations"]:
83             if B is not None:
84                 BI = B.I
85             elif self._parameters["B_scalar"] is not None:
86                 BI = 1.0 / self._parameters["B_scalar"]
87             #
88             if R is not None:
89                 RI = R.I
90             elif self._parameters["R_scalar"] is not None:
91                 RI = 1.0 / self._parameters["R_scalar"]
92         #
93         # Initialisation
94         # --------------
95         Xn = Xb
96         Pn = B
97         self.StoredVariables["Analysis"].store( Xn.A1 )
98         if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
99             self.StoredVariables["APosterioriCovariance"].store( Pn )
100         #
101         for step in range(duration-1):
102             Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
103             #
104             if U is not None:
105                 if hasattr(U,"store") and len(U)>1:
106                     Un = numpy.asmatrix(numpy.ravel( U[step] )).T
107                 elif hasattr(U,"store") and len(U)==1:
108                     Un = numpy.asmatrix(numpy.ravel( U[0] )).T
109                 else:
110                     Un = numpy.asmatrix(numpy.ravel( U )).T
111             else:
112                 Un = None
113             #
114             if self._parameters["EstimationType"] == "State" and Cm is not None and Un is not None:
115                 Xn_predicted = Mt * Xn + Cm * Un
116             else:
117                 Xn_predicted = Mt * Xn
118             Pn_predicted = Mt * Pn * Ma + Q
119             #
120             if self._parameters["EstimationType"] == "Parameters" and Cm is not None and Un is not None:
121                 d  = Ynpu - Ht * Xn_predicted - Cm * Un
122             else:
123                 d  = Ynpu - Ht * Xn_predicted
124             K  = Pn_predicted * Ha * (Ht * Pn_predicted * Ha + R).I
125             Xn = Xn_predicted + K * d
126             Pn = Pn_predicted - K * Ht * Pn_predicted
127             #
128             self.StoredVariables["Analysis"].store( Xn.A1 )
129             if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
130                 self.StoredVariables["Innovation"].store( numpy.ravel( d.A1 ) )
131             if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
132                 self.StoredVariables["APosterioriCovariance"].store( Pn )
133             if "CostFunctionJ" in self._parameters["StoreSupplementaryCalculations"]:
134                 Jb  = 0.5 * (Xn - Xb).T * BI * (Xn - Xb)
135                 Jo  = 0.5 * d.T * RI * d
136                 J   = float( Jb ) + float( Jo )
137                 self.StoredVariables["CostFunctionJb"].store( Jb )
138                 self.StoredVariables["CostFunctionJo"].store( Jo )
139                 self.StoredVariables["CostFunctionJ" ].store( J )
140         #
141         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
142         logging.debug("%s Terminé"%self._name)
143         #
144         return 0
145
146 # ==============================================================================
147 if __name__ == "__main__":
148     print '\n AUTODIAGNOSTIC \n'