Salome HOME
Compatibility fix for algorithm output variables clarity
[modules/adao.git] / src / daComposant / daAlgorithms / ExtendedKalmanFilter.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2019 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  = [
57                 "APosterioriCorrelations",
58                 "APosterioriCovariance",
59                 "APosterioriStandardDeviations",
60                 "APosterioriVariances",
61                 "BMA",
62                 "CurrentState",
63                 "CostFunctionJ",
64                 "CostFunctionJb",
65                 "CostFunctionJo",
66                 "Innovation",
67                 "PredictedState",
68                 ]
69             )
70         self.defineRequiredParameter( # Pas de type
71             name     = "Bounds",
72             message  = "Liste des valeurs de bornes",
73             )
74         self.requireInputArguments(
75             mandatory= ("Xb", "Y", "HO", "R", "B" ),
76             optional = ("U", "EM", "CM", "Q"),
77             )
78
79     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
80         self._pre_run(Parameters, Xb, Y, R, B, Q)
81         #
82         if self._parameters["EstimationOf"] == "Parameters":
83             self._parameters["StoreInternalVariables"] = True
84         #
85         # Opérateurs
86         # ----------
87         Hm = HO["Direct"].appliedControledFormTo
88         #
89         if self._parameters["EstimationOf"] == "State":
90             Mm = EM["Direct"].appliedControledFormTo
91         #
92         if CM is not None and "Tangent" in CM and U is not None:
93             Cm = CM["Tangent"].asMatrix(Xb)
94         else:
95             Cm = None
96         #
97         # Nombre de pas identique au nombre de pas d'observations
98         # -------------------------------------------------------
99         if hasattr(Y,"stepnumber"):
100             duration = Y.stepnumber()
101         else:
102             duration = 2
103         #
104         # Précalcul des inversions de B et R
105         # ----------------------------------
106         if self._parameters["StoreInternalVariables"] \
107             or self._toStore("CostFunctionJ") \
108             or self._toStore("CostFunctionJb") \
109             or self._toStore("CostFunctionJo"):
110             BI = B.getI()
111             RI = R.getI()
112         #
113         # Initialisation
114         # --------------
115         Xn = Xb
116         Pn = B
117         #
118         self.StoredVariables["Analysis"].store( Xn.A1 )
119         if self._toStore("APosterioriCovariance"):
120             self.StoredVariables["APosterioriCovariance"].store( Pn.asfullmatrix(Xn.size) )
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( Mm( (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 = Q + Mt * Pn * Ma
158             elif self._parameters["EstimationOf"] == "Parameters":
159                 # --- > Par principe, M = Id, Q = 0
160                 Xn_predicted = Xn
161                 Pn_predicted = Pn
162             #
163             if self._parameters["Bounds"] is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
164                 Xn_predicted = numpy.max(numpy.hstack((Xn_predicted,numpy.asmatrix(self._parameters["Bounds"])[:,0])),axis=1)
165                 Xn_predicted = numpy.min(numpy.hstack((Xn_predicted,numpy.asmatrix(self._parameters["Bounds"])[:,1])),axis=1)
166             #
167             if self._parameters["EstimationOf"] == "State":
168                 d  = Ynpu - numpy.asmatrix(numpy.ravel( Hm( (Xn_predicted, None) ) )).T
169             elif self._parameters["EstimationOf"] == "Parameters":
170                 d  = Ynpu - numpy.asmatrix(numpy.ravel( Hm( (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             _A = R + numpy.dot(Ht, Pn_predicted * Ha)
175             _u = numpy.linalg.solve( _A , d )
176             Xn = Xn_predicted + Pn_predicted * Ha * _u
177             Kn = Pn_predicted * Ha * (R + numpy.dot(Ht, Pn_predicted * Ha)).I
178             Pn = Pn_predicted - Kn * Ht * Pn_predicted
179             #
180             self.StoredVariables["Analysis"].store( Xn.A1 )
181             if self._toStore("APosterioriCovariance"):
182                 self.StoredVariables["APosterioriCovariance"].store( Pn )
183             if self._toStore("Innovation"):
184                 self.StoredVariables["Innovation"].store( numpy.ravel( d.A1 ) )
185             if self._parameters["StoreInternalVariables"] \
186                 or self._toStore("CurrentState"):
187                 self.StoredVariables["CurrentState"].store( Xn )
188             if self._parameters["StoreInternalVariables"] \
189                 or self._toStore("PredictedState"):
190                 self.StoredVariables["PredictedState"].store( Xn_predicted )
191             if self._parameters["StoreInternalVariables"] \
192                 or self._toStore("CostFunctionJ") \
193                 or self._toStore("CostFunctionJb") \
194                 or self._toStore("CostFunctionJo"):
195                 Jb  = 0.5 * (Xn - Xb).T * BI * (Xn - Xb)
196                 Jo  = 0.5 * d.T * RI * d
197                 J   = float( Jb ) + float( Jo )
198                 self.StoredVariables["CostFunctionJb"].store( Jb )
199                 self.StoredVariables["CostFunctionJo"].store( Jo )
200                 self.StoredVariables["CostFunctionJ" ].store( J )
201                 if J < previousJMinimum:
202                     previousJMinimum  = J
203                     Xa                = Xn
204                     if self._toStore("APosterioriCovariance"):
205                         covarianceXa  = Pn
206             else:
207                 Xa = Xn
208             #
209         #
210         # Stockage supplementaire de l'optimum en estimation de parametres
211         # ----------------------------------------------------------------
212         if self._parameters["EstimationOf"] == "Parameters":
213             self.StoredVariables["Analysis"].store( Xa.A1 )
214             if self._toStore("APosterioriCovariance"):
215                 self.StoredVariables["APosterioriCovariance"].store( covarianceXa )
216         #
217         if self._toStore("BMA"):
218             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
219         #
220         self._post_run(HO)
221         return 0
222
223 # ==============================================================================
224 if __name__ == "__main__":
225     print('\n AUTODIAGNOSTIC \n')