Salome HOME
Minor improvement of debug informations
[modules/adao.git] / src / daComposant / daAlgorithms / KalmanFilter.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2014 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     = "EstimationOf",
34             default  = "State",
35             typecast = str,
36             message  = "Estimation d'etat ou de parametres",
37             listval  = ["State", "Parameters"],
38             )
39         self.defineRequiredParameter(
40             name     = "StoreInternalVariables",
41             default  = False,
42             typecast = bool,
43             message  = "Stockage des variables internes ou intermédiaires du calcul",
44             )
45         self.defineRequiredParameter(
46             name     = "StoreSupplementaryCalculations",
47             default  = [],
48             typecast = tuple,
49             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
50             listval  = ["APosterioriCovariance", "BMA", "Innovation"]
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             BI = B.getI()
94             RI = R.getI()
95         #
96         # Initialisation
97         # --------------
98         Xn = Xb
99         Pn = B
100         #
101         self.StoredVariables["Analysis"].store( Xn.A1 )
102         if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
103             self.StoredVariables["APosterioriCovariance"].store( Pn )
104             covarianceXa = Pn
105         Xa               = Xn
106         previousJMinimum = numpy.finfo(float).max
107         #
108         for step in range(duration-1):
109             if hasattr(Y,"store"):
110                 Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
111             else:
112                 Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
113             #
114             if U is not None:
115                 if hasattr(U,"store") and len(U)>1:
116                     Un = numpy.asmatrix(numpy.ravel( U[step] )).T
117                 elif hasattr(U,"store") and len(U)==1:
118                     Un = numpy.asmatrix(numpy.ravel( U[0] )).T
119                 else:
120                     Un = numpy.asmatrix(numpy.ravel( U )).T
121             else:
122                 Un = None
123             #
124             if self._parameters["EstimationOf"] == "State":
125                 Xn_predicted = Mt * Xn
126                 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
127                     Cm = Cm.reshape(Xn.size,Un.size) # ADAO & check shape
128                     Xn_predicted = Xn_predicted + Cm * Un
129                 Pn_predicted = Q + Mt * Pn * Ma
130             elif self._parameters["EstimationOf"] == "Parameters":
131                 # --- > Par principe, M = Id, Q = 0
132                 Xn_predicted = Xn
133                 Pn_predicted = Pn
134             #
135             if self._parameters["EstimationOf"] == "State":
136                 d  = Ynpu - Ht * Xn_predicted
137             elif self._parameters["EstimationOf"] == "Parameters":
138                 d  = Ynpu - Ht * Xn_predicted
139                 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans H, doublon !
140                     d = d - Cm * Un
141             #
142             Kn = Pn_predicted * Ha * (R + Ht * Pn_predicted * Ha).I
143             Xn = Xn_predicted + Kn * d
144             Pn = Pn_predicted - Kn * Ht * Pn_predicted
145             #
146             self.StoredVariables["Analysis"].store( Xn.A1 )
147             if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
148                 self.StoredVariables["APosterioriCovariance"].store( Pn )
149             if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
150                 self.StoredVariables["Innovation"].store( numpy.ravel( d.A1 ) )
151             if self._parameters["StoreInternalVariables"]:
152                 Jb  = 0.5 * (Xn - Xb).T * BI * (Xn - Xb)
153                 Jo  = 0.5 * d.T * RI * d
154                 J   = float( Jb ) + float( Jo )
155                 self.StoredVariables["CurrentState"].store( Xn )
156                 self.StoredVariables["CostFunctionJb"].store( Jb )
157                 self.StoredVariables["CostFunctionJo"].store( Jo )
158                 self.StoredVariables["CostFunctionJ" ].store( J )
159                 if J < previousJMinimum:
160                     previousJMinimum  = J
161                     Xa                = Xn
162                     if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
163                         covarianceXa  = Pn
164             else:
165                 Xa = Xn
166             #
167         #
168         # Stockage supplementaire de l'optimum en estimation de parametres
169         # ----------------------------------------------------------------
170         if self._parameters["EstimationOf"] == "Parameters":
171             self.StoredVariables["Analysis"].store( Xa.A1 )
172             if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
173                 self.StoredVariables["APosterioriCovariance"].store( covarianceXa )
174         #
175         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
176             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
177         #
178         logging.debug("%s Nombre d'évaluation(s) de l'opérateur d'observation direct/tangent/adjoint.: %i/%i/%i"%(self._name, HO["Direct"].nbcalls(0),HO["Tangent"].nbcalls(0),HO["Adjoint"].nbcalls(0)))
179         logging.debug("%s Nombre d'appels au cache d'opérateur d'observation direct/tangent/adjoint..: %i/%i/%i"%(self._name, HO["Direct"].nbcalls(3),HO["Tangent"].nbcalls(3),HO["Adjoint"].nbcalls(3)))
180         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
181         logging.debug("%s Terminé"%self._name)
182         #
183         return 0
184
185 # ==============================================================================
186 if __name__ == "__main__":
187     print '\n AUTODIAGNOSTIC \n'