Salome HOME
Compatibility fix for algorithm output variables clarity
[modules/adao.git] / src / daComposant / daAlgorithms / KalmanFilter.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, "KALMANFILTER")
31         self.defineRequiredParameter(
32             name     = "EstimationOf",
33             default  = "State",
34             typecast = str,
35             message  = "Estimation d'etat ou de parametres",
36             listval  = ["State", "Parameters"],
37             )
38         self.defineRequiredParameter(
39             name     = "StoreInternalVariables",
40             default  = False,
41             typecast = bool,
42             message  = "Stockage des variables internes ou intermédiaires du calcul",
43             )
44         self.defineRequiredParameter(
45             name     = "StoreSupplementaryCalculations",
46             default  = [],
47             typecast = tuple,
48             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
49             listval  = [
50                 "APosterioriCorrelations",
51                 "APosterioriCovariance",
52                 "APosterioriStandardDeviations",
53                 "APosterioriVariances",
54                 "BMA",
55                 "CurrentState",
56                 "CostFunctionJ",
57                 "CostFunctionJb",
58                 "CostFunctionJo",
59                 "Innovation",
60                 "PredictedState",
61                 ]
62             )
63         self.requireInputArguments(
64             mandatory= ("Xb", "Y", "HO", "R", "B" ),
65             optional = ("U", "EM", "CM", "Q"),
66             )
67
68     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
69         self._pre_run(Parameters, Xb, Y, R, B, Q)
70         #
71         if self._parameters["EstimationOf"] == "Parameters":
72             self._parameters["StoreInternalVariables"] = True
73         #
74         # Opérateurs
75         # ----------
76         Ht = HO["Tangent"].asMatrix(Xb)
77         Ha = HO["Adjoint"].asMatrix(Xb)
78         #
79         if self._parameters["EstimationOf"] == "State":
80             Mt = EM["Tangent"].asMatrix(Xb)
81             Ma = EM["Adjoint"].asMatrix(Xb)
82         #
83         if CM is not None and "Tangent" in CM and U is not None:
84             Cm = CM["Tangent"].asMatrix(Xb)
85         else:
86             Cm = None
87         #
88         # Nombre de pas identique au nombre de pas d'observations
89         # -------------------------------------------------------
90         if hasattr(Y,"stepnumber"):
91             duration = Y.stepnumber()
92         else:
93             duration = 2
94         #
95         # Précalcul des inversions de B et R
96         # ----------------------------------
97         if self._parameters["StoreInternalVariables"] \
98             or self._toStore("CostFunctionJ") \
99             or self._toStore("CostFunctionJb") \
100             or self._toStore("CostFunctionJo"):
101             BI = B.getI()
102             RI = R.getI()
103         #
104         # Initialisation
105         # --------------
106         Xn = Xb
107         Pn = B
108         #
109         self.StoredVariables["Analysis"].store( Xn.A1 )
110         if self._toStore("APosterioriCovariance"):
111             self.StoredVariables["APosterioriCovariance"].store( Pn.asfullmatrix(Xn.size) )
112             covarianceXa = Pn
113         Xa               = Xn
114         previousJMinimum = numpy.finfo(float).max
115         #
116         for step in range(duration-1):
117             if hasattr(Y,"store"):
118                 Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
119             else:
120                 Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
121             #
122             if U is not None:
123                 if hasattr(U,"store") and len(U)>1:
124                     Un = numpy.asmatrix(numpy.ravel( U[step] )).T
125                 elif hasattr(U,"store") and len(U)==1:
126                     Un = numpy.asmatrix(numpy.ravel( U[0] )).T
127                 else:
128                     Un = numpy.asmatrix(numpy.ravel( U )).T
129             else:
130                 Un = None
131             #
132             if self._parameters["EstimationOf"] == "State":
133                 Xn_predicted = Mt * Xn
134                 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
135                     Cm = Cm.reshape(Xn.size,Un.size) # ADAO & check shape
136                     Xn_predicted = Xn_predicted + Cm * Un
137                 Pn_predicted = Q + Mt * Pn * Ma
138             elif self._parameters["EstimationOf"] == "Parameters":
139                 # --- > Par principe, M = Id, Q = 0
140                 Xn_predicted = Xn
141                 Pn_predicted = Pn
142             #
143             if self._parameters["EstimationOf"] == "State":
144                 d  = Ynpu - Ht * Xn_predicted
145             elif self._parameters["EstimationOf"] == "Parameters":
146                 d  = Ynpu - Ht * Xn_predicted
147                 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans H, doublon !
148                     d = d - Cm * Un
149             #
150             _A = R + numpy.dot(Ht, Pn_predicted * Ha)
151             _u = numpy.linalg.solve( _A , d )
152             Xn = Xn_predicted + Pn_predicted * Ha * _u
153             Kn = Pn_predicted * Ha * (R + numpy.dot(Ht, Pn_predicted * Ha)).I
154             Pn = Pn_predicted - Kn * Ht * Pn_predicted
155             #
156             self.StoredVariables["Analysis"].store( Xn.A1 )
157             if self._toStore("APosterioriCovariance"):
158                 self.StoredVariables["APosterioriCovariance"].store( Pn )
159             if self._toStore("Innovation"):
160                 self.StoredVariables["Innovation"].store( numpy.ravel( d.A1 ) )
161             if self._parameters["StoreInternalVariables"] \
162                 or self._toStore("CurrentState"):
163                 self.StoredVariables["CurrentState"].store( Xn )
164             if self._parameters["StoreInternalVariables"] \
165                 or self._toStore("PredictedState"):
166                 self.StoredVariables["PredictedState"].store( Xn_predicted )
167             if self._parameters["StoreInternalVariables"] \
168                 or self._toStore("CostFunctionJ") \
169                 or self._toStore("CostFunctionJb") \
170                 or self._toStore("CostFunctionJo"):
171                 Jb  = 0.5 * (Xn - Xb).T * BI * (Xn - Xb)
172                 Jo  = 0.5 * d.T * RI * d
173                 J   = float( Jb ) + float( Jo )
174                 self.StoredVariables["CostFunctionJb"].store( Jb )
175                 self.StoredVariables["CostFunctionJo"].store( Jo )
176                 self.StoredVariables["CostFunctionJ" ].store( J )
177                 if J < previousJMinimum:
178                     previousJMinimum  = J
179                     Xa                = Xn
180                     if self._toStore("APosterioriCovariance"):
181                         covarianceXa  = Pn
182             else:
183                 Xa = Xn
184             #
185         #
186         # Stockage supplementaire de l'optimum en estimation de parametres
187         # ----------------------------------------------------------------
188         if self._parameters["EstimationOf"] == "Parameters":
189             self.StoredVariables["Analysis"].store( Xa.A1 )
190             if self._toStore("APosterioriCovariance"):
191                 self.StoredVariables["APosterioriCovariance"].store( covarianceXa )
192         #
193         if self._toStore("BMA"):
194             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
195         #
196         self._post_run(HO)
197         return 0
198
199 # ==============================================================================
200 if __name__ == "__main__":
201     print('\n AUTODIAGNOSTIC \n')