Salome HOME
Improving documentation and naming of estimation
[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", "BMA", "Innovation"]
38             )
39         self.defineRequiredParameter(
40             name     = "EstimationOf",
41             default  = "State",
42             typecast = str,
43             message  = "Estimation d'etat ou de parametres",
44             listval  = ["State", "Parameters"],
45             )
46         self.defineRequiredParameter(
47             name     = "StoreInternalVariables",
48             default  = False,
49             typecast = bool,
50             message  = "Stockage des variables internes ou intermédiaires du calcul",
51             )
52
53     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
54         logging.debug("%s Lancement"%self._name)
55         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
56         #
57         # Paramètres de pilotage
58         # ----------------------
59         self.setParameters(Parameters)
60         #
61         if self._parameters["EstimationOf"] == "Parameters":
62             self._parameters["StoreInternalVariables"] = True
63         #
64         # Opérateurs
65         # ----------
66         if B is None:
67             raise ValueError("Background error covariance matrix has to be properly defined!")
68         if R is None:
69             raise ValueError("Observation error covariance matrix has to be properly defined!")
70         #
71         Ht = HO["Tangent"].asMatrix(Xb)
72         Ha = HO["Adjoint"].asMatrix(Xb)
73         #
74         if self._parameters["EstimationOf"] == "State":
75             Mt = EM["Tangent"].asMatrix(Xb)
76             Ma = EM["Adjoint"].asMatrix(Xb)
77         #
78         if CM is not None and CM.has_key("Tangent") and U is not None:
79             Cm = CM["Tangent"].asMatrix(Xb)
80         else:
81             Cm = None
82         #
83         # Nombre de pas du Kalman identique au nombre de pas d'observations
84         # -----------------------------------------------------------------
85         if hasattr(Y,"stepnumber"):
86             duration = Y.stepnumber()
87         else:
88             duration = 2
89         #
90         # Précalcul des inversions de B et R
91         # ----------------------------------
92         if self._parameters["StoreInternalVariables"]:
93             if B is not None:
94                 BI = B.I
95             elif self._parameters["B_scalar"] is not None:
96                 BI = 1.0 / self._parameters["B_scalar"]
97             #
98             if R is not None:
99                 RI = R.I
100             elif self._parameters["R_scalar"] is not None:
101                 RI = 1.0 / self._parameters["R_scalar"]
102         #
103         # Initialisation
104         # --------------
105         Xn = Xb
106         Pn = B
107         #
108         self.StoredVariables["Analysis"].store( Xn.A1 )
109         if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
110             self.StoredVariables["APosterioriCovariance"].store( Pn )
111             covarianceXa = Pn
112         Xa               = Xn
113         previousJMinimum = numpy.finfo(float).max
114         #
115         for step in range(duration-1):
116             if hasattr(Y,"store"):
117                 Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
118             else:
119                 Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
120             #
121             if U is not None:
122                 if hasattr(U,"store") and len(U)>1:
123                     Un = numpy.asmatrix(numpy.ravel( U[step] )).T
124                 elif hasattr(U,"store") and len(U)==1:
125                     Un = numpy.asmatrix(numpy.ravel( U[0] )).T
126                 else:
127                     Un = numpy.asmatrix(numpy.ravel( U )).T
128             else:
129                 Un = None
130             #
131             if self._parameters["EstimationOf"] == "State":
132                 Xn_predicted = Mt * Xn
133                 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
134                     Xn_predicted = Xn_predicted + Cm * Un
135                 Pn_predicted = Mt * Pn * Ma + Q
136             elif self._parameters["EstimationOf"] == "Parameters":
137                 # --- > Par principe, M = Id, Q = 0
138                 Xn_predicted = Xn
139                 Pn_predicted = Pn
140             #
141             if self._parameters["EstimationOf"] == "State":
142                 d  = Ynpu - Ht * Xn_predicted
143             elif self._parameters["EstimationOf"] == "Parameters":
144                 d  = Ynpu - Ht * Xn_predicted
145                 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans H, doublon !
146                     d = d - Cm * Un
147             #
148             K  = Pn_predicted * Ha * (Ht * Pn_predicted * Ha + R).I
149             Xn = Xn_predicted + K * d
150             Pn = Pn_predicted - K * Ht * Pn_predicted
151             #
152             self.StoredVariables["Analysis"].store( Xn.A1 )
153             if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
154                 self.StoredVariables["APosterioriCovariance"].store( Pn )
155             if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
156                 self.StoredVariables["Innovation"].store( numpy.ravel( d.A1 ) )
157             if self._parameters["StoreInternalVariables"]:
158                 Jb  = 0.5 * (Xn - Xb).T * BI * (Xn - Xb)
159                 Jo  = 0.5 * d.T * RI * d
160                 J   = float( Jb ) + float( Jo )
161                 self.StoredVariables["CurrentState"].store( Xn.A1 )
162                 self.StoredVariables["CostFunctionJb"].store( Jb )
163                 self.StoredVariables["CostFunctionJo"].store( Jo )
164                 self.StoredVariables["CostFunctionJ" ].store( J )
165                 if J < previousJMinimum:
166                     previousJMinimum  = J
167                     Xa                = Xn
168                     if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
169                         covarianceXa  = Pn
170             else:
171                 Xa = Xn
172             #
173         #
174         # Stockage supplementaire de l'optimum en estimation de parametres
175         # ----------------------------------------------------------------
176         if self._parameters["EstimationOf"] == "Parameters":
177             self.StoredVariables["Analysis"].store( Xa.A1 )
178             if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
179                 self.StoredVariables["APosterioriCovariance"].store( covarianceXa )
180         #
181         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
182             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
183         #
184         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
185         logging.debug("%s Terminé"%self._name)
186         #
187         return 0
188
189 # ==============================================================================
190 if __name__ == "__main__":
191     print '\n AUTODIAGNOSTIC \n'