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