Salome HOME
49ae71bae3c98683e2f2d95b9a911ae44b5765e0
[modules/adao.git] / src / daComposant / daAlgorithms / ExtendedKalmanFilter.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, "EXTENDEDKALMANFILTER")
32         self.defineRequiredParameter(
33             name     = "ConstrainedBy",
34             default  = "EstimateProjection",
35             typecast = str,
36             message  = "Prise en compte des contraintes",
37             listval  = ["EstimateProjection"],
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         self.defineRequiredParameter(
53             name     = "StoreSupplementaryCalculations",
54             default  = [],
55             typecast = tuple,
56             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
57             listval  = ["APosterioriCovariance", "BMA", "Innovation"]
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             BI = B.getI()
104             RI = R.getI()
105         #
106         # Initialisation
107         # --------------
108         Xn = Xb
109         Pn = B
110         #
111         self.StoredVariables["Analysis"].store( Xn.A1 )
112         if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
113             self.StoredVariables["APosterioriCovariance"].store( Pn )
114             covarianceXa = Pn
115         Xa               = Xn
116         previousJMinimum = numpy.finfo(float).max
117         #
118         for step in range(duration-1):
119             if hasattr(Y,"store"):
120                 Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
121             else:
122                 Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
123             #
124             Ht = HO["Tangent"].asMatrix(ValueForMethodForm = Xn)
125             Ht = Ht.reshape(Ynpu.size,Xn.size) # ADAO & check shape
126             Ha = HO["Adjoint"].asMatrix(ValueForMethodForm = Xn)
127             Ha = Ha.reshape(Xn.size,Ynpu.size) # ADAO & check shape
128             #
129             if self._parameters["EstimationOf"] == "State":
130                 Mt = EM["Tangent"].asMatrix(ValueForMethodForm = Xn)
131                 Mt = Mt.reshape(Xn.size,Xn.size) # ADAO & check shape
132                 Ma = EM["Adjoint"].asMatrix(ValueForMethodForm = Xn)
133                 Ma = Ma.reshape(Xn.size,Xn.size) # ADAO & check shape
134             #
135             if U is not None:
136                 if hasattr(U,"store") and len(U)>1:
137                     Un = numpy.asmatrix(numpy.ravel( U[step] )).T
138                 elif hasattr(U,"store") and len(U)==1:
139                     Un = numpy.asmatrix(numpy.ravel( U[0] )).T
140                 else:
141                     Un = numpy.asmatrix(numpy.ravel( U )).T
142             else:
143                 Un = None
144             #
145             if self._parameters["EstimationOf"] == "State":
146                 Xn_predicted = numpy.asmatrix(numpy.ravel( M( (Xn, Un) ) )).T
147                 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
148                     Cm = Cm.reshape(Xn.size,Un.size) # ADAO & check shape
149                     Xn_predicted = Xn_predicted + Cm * Un
150                 Pn_predicted = Q + Mt * Pn * Ma
151             elif self._parameters["EstimationOf"] == "Parameters":
152                 # --- > Par principe, M = Id, Q = 0
153                 Xn_predicted = Xn
154                 Pn_predicted = Pn
155             #
156             if Bounds is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
157                 Xn_predicted = numpy.max(numpy.hstack((Xn_predicted,numpy.asmatrix(Bounds)[:,0])),axis=1)
158                 Xn_predicted = numpy.min(numpy.hstack((Xn_predicted,numpy.asmatrix(Bounds)[:,1])),axis=1)
159             #
160             if self._parameters["EstimationOf"] == "State":
161                 d  = Ynpu - numpy.asmatrix(numpy.ravel( H( (Xn_predicted, None) ) )).T
162             elif self._parameters["EstimationOf"] == "Parameters":
163                 d  = Ynpu - numpy.asmatrix(numpy.ravel( H( (Xn_predicted, Un) ) )).T
164                 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans H, doublon !
165                     d = d - Cm * Un
166             #
167             Kn = Pn_predicted * Ha * (R + Ht * Pn_predicted * Ha).I
168             Xn = Xn_predicted + Kn * d
169             Pn = Pn_predicted - Kn * Ht * Pn_predicted
170             #
171             self.StoredVariables["Analysis"].store( Xn.A1 )
172             if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
173                 self.StoredVariables["APosterioriCovariance"].store( Pn )
174             if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
175                 self.StoredVariables["Innovation"].store( numpy.ravel( d.A1 ) )
176             if self._parameters["StoreInternalVariables"]:
177                 Jb  = 0.5 * (Xn - Xb).T * BI * (Xn - Xb)
178                 Jo  = 0.5 * d.T * RI * d
179                 J   = float( Jb ) + float( Jo )
180                 self.StoredVariables["CurrentState"].store( Xn )
181                 self.StoredVariables["CostFunctionJb"].store( Jb )
182                 self.StoredVariables["CostFunctionJo"].store( Jo )
183                 self.StoredVariables["CostFunctionJ" ].store( J )
184                 if J < previousJMinimum:
185                     previousJMinimum  = J
186                     Xa                = Xn
187                     if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
188                         covarianceXa  = Pn
189             else:
190                 Xa = Xn
191             #
192         #
193         # Stockage supplementaire de l'optimum en estimation de parametres
194         # ----------------------------------------------------------------
195         if self._parameters["EstimationOf"] == "Parameters":
196             self.StoredVariables["Analysis"].store( Xa.A1 )
197             if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
198                 self.StoredVariables["APosterioriCovariance"].store( covarianceXa )
199         #
200         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
201             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
202         #
203         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]))
204         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
205         logging.debug("%s Terminé"%self._name)
206         #
207         return 0
208
209 # ==============================================================================
210 if __name__ == "__main__":
211     print '\n AUTODIAGNOSTIC \n'