Salome HOME
Python 3 compatibility improvement (UTF-8) and data interface changes
[modules/adao.git] / src / daComposant / daAlgorithms / ExtendedKalmanFilter.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2017 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", "CostFunctionJb", "CostFunctionJo", "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(Parameters)
65         #
66         if self._parameters["EstimationOf"] == "Parameters":
67             self._parameters["StoreInternalVariables"] = True
68         #
69         # Opérateurs
70         # ----------
71         if B is None:
72             raise ValueError("Background error covariance matrix has to be properly defined!")
73         if R is None:
74             raise ValueError("Observation error covariance matrix has to be properly defined!")
75         #
76         H = HO["Direct"].appliedControledFormTo
77         #
78         if self._parameters["EstimationOf"] == "State":
79             M = EM["Direct"].appliedControledFormTo
80         #
81         if CM is not None and "Tangent" in CM and U is not None:
82             Cm = CM["Tangent"].asMatrix(Xb)
83         else:
84             Cm = None
85         #
86         # Nombre de pas identique au nombre de pas d'observations
87         # -------------------------------------------------------
88         if hasattr(Y,"stepnumber"):
89             duration = Y.stepnumber()
90         else:
91             duration = 2
92         #
93         # Précalcul des inversions de B et R
94         # ----------------------------------
95         if self._parameters["StoreInternalVariables"]:
96             BI = B.getI()
97             RI = R.getI()
98         #
99         # Initialisation
100         # --------------
101         Xn = Xb
102         Pn = B
103         #
104         self.StoredVariables["Analysis"].store( Xn.A1 )
105         if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
106             self.StoredVariables["APosterioriCovariance"].store( Pn.asfullmatrix(Xn.size) )
107             covarianceXa = Pn
108         Xa               = Xn
109         previousJMinimum = numpy.finfo(float).max
110         #
111         for step in range(duration-1):
112             if hasattr(Y,"store"):
113                 Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
114             else:
115                 Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
116             #
117             Ht = HO["Tangent"].asMatrix(ValueForMethodForm = Xn)
118             Ht = Ht.reshape(Ynpu.size,Xn.size) # ADAO & check shape
119             Ha = HO["Adjoint"].asMatrix(ValueForMethodForm = Xn)
120             Ha = Ha.reshape(Xn.size,Ynpu.size) # ADAO & check shape
121             #
122             if self._parameters["EstimationOf"] == "State":
123                 Mt = EM["Tangent"].asMatrix(ValueForMethodForm = Xn)
124                 Mt = Mt.reshape(Xn.size,Xn.size) # ADAO & check shape
125                 Ma = EM["Adjoint"].asMatrix(ValueForMethodForm = Xn)
126                 Ma = Ma.reshape(Xn.size,Xn.size) # ADAO & check shape
127             #
128             if U is not None:
129                 if hasattr(U,"store") and len(U)>1:
130                     Un = numpy.asmatrix(numpy.ravel( U[step] )).T
131                 elif hasattr(U,"store") and len(U)==1:
132                     Un = numpy.asmatrix(numpy.ravel( U[0] )).T
133                 else:
134                     Un = numpy.asmatrix(numpy.ravel( U )).T
135             else:
136                 Un = None
137             #
138             if self._parameters["EstimationOf"] == "State":
139                 Xn_predicted = numpy.asmatrix(numpy.ravel( M( (Xn, Un) ) )).T
140                 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
141                     Cm = Cm.reshape(Xn.size,Un.size) # ADAO & check shape
142                     Xn_predicted = Xn_predicted + Cm * Un
143                 Pn_predicted = Q + Mt * Pn * Ma
144             elif self._parameters["EstimationOf"] == "Parameters":
145                 # --- > Par principe, M = Id, Q = 0
146                 Xn_predicted = Xn
147                 Pn_predicted = Pn
148             #
149             if self._parameters["Bounds"] is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
150                 Xn_predicted = numpy.max(numpy.hstack((Xn_predicted,numpy.asmatrix(self._parameters["Bounds"])[:,0])),axis=1)
151                 Xn_predicted = numpy.min(numpy.hstack((Xn_predicted,numpy.asmatrix(self._parameters["Bounds"])[:,1])),axis=1)
152             #
153             if self._parameters["EstimationOf"] == "State":
154                 d  = Ynpu - numpy.asmatrix(numpy.ravel( H( (Xn_predicted, None) ) )).T
155             elif self._parameters["EstimationOf"] == "Parameters":
156                 d  = Ynpu - numpy.asmatrix(numpy.ravel( H( (Xn_predicted, Un) ) )).T
157                 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans H, doublon !
158                     d = d - Cm * Un
159             #
160             _A = R + Ht * Pn_predicted * Ha
161             _u = numpy.linalg.solve( _A , d )
162             Xn = Xn_predicted + Pn_predicted * Ha * _u
163             Kn = Pn_predicted * Ha * (R + Ht * Pn_predicted * Ha).I
164             Pn = Pn_predicted - Kn * Ht * Pn_predicted
165             #
166             self.StoredVariables["Analysis"].store( Xn.A1 )
167             if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
168                 self.StoredVariables["APosterioriCovariance"].store( Pn )
169             if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
170                 self.StoredVariables["Innovation"].store( numpy.ravel( d.A1 ) )
171             if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
172                 self.StoredVariables["CurrentState"].store( Xn )
173             if self._parameters["StoreInternalVariables"] \
174                 or "CostFunctionJ" in self._parameters["StoreSupplementaryCalculations"] \
175                 or "CostFunctionJb" in self._parameters["StoreSupplementaryCalculations"] \
176                 or "CostFunctionJo" in self._parameters["StoreSupplementaryCalculations"]:
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["CostFunctionJb"].store( Jb )
181                 self.StoredVariables["CostFunctionJo"].store( Jo )
182                 self.StoredVariables["CostFunctionJ" ].store( J )
183                 if J < previousJMinimum:
184                     previousJMinimum  = J
185                     Xa                = Xn
186                     if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
187                         covarianceXa  = Pn
188             else:
189                 Xa = Xn
190             #
191         #
192         # Stockage supplementaire de l'optimum en estimation de parametres
193         # ----------------------------------------------------------------
194         if self._parameters["EstimationOf"] == "Parameters":
195             self.StoredVariables["Analysis"].store( Xa.A1 )
196             if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
197                 self.StoredVariables["APosterioriCovariance"].store( covarianceXa )
198         #
199         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
200             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
201         #
202         self._post_run(HO)
203         return 0
204
205 # ==============================================================================
206 if __name__ == "__main__":
207     print('\n AUTODIAGNOSTIC \n')