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