Salome HOME
Coherence correction for documentation of algorithms
[modules/adao.git] / src / daComposant / daAlgorithms / KalmanFilter.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, "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  = ["APosterioriCorrelations", "APosterioriCovariance", "APosterioriStandardDeviations", "APosterioriVariances", "BMA", "CurrentState", "CostFunctionJ", "CostFunctionJb", "CostFunctionJo", "Innovation"]
50             )
51
52     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
53         self._pre_run()
54         #
55         # Paramètres de pilotage
56         # ----------------------
57         self.setParameters(Parameters)
58         #
59         if self._parameters["EstimationOf"] == "Parameters":
60             self._parameters["StoreInternalVariables"] = True
61         #
62         # Opérateurs
63         # ----------
64         if B is None:
65             raise ValueError("Background error covariance matrix has to be properly defined!")
66         if R is None:
67             raise ValueError("Observation error covariance matrix has to be properly defined!")
68         #
69         Ht = HO["Tangent"].asMatrix(Xb)
70         Ha = HO["Adjoint"].asMatrix(Xb)
71         #
72         if self._parameters["EstimationOf"] == "State":
73             Mt = EM["Tangent"].asMatrix(Xb)
74             Ma = EM["Adjoint"].asMatrix(Xb)
75         #
76         if CM is not None and CM.has_key("Tangent") and U is not None:
77             Cm = CM["Tangent"].asMatrix(Xb)
78         else:
79             Cm = None
80         #
81         # Nombre de pas identique au nombre de pas d'observations
82         # -------------------------------------------------------
83         if hasattr(Y,"stepnumber"):
84             duration = Y.stepnumber()
85         else:
86             duration = 2
87         #
88         # Précalcul des inversions de B et R
89         # ----------------------------------
90         if self._parameters["StoreInternalVariables"]:
91             BI = B.getI()
92             RI = R.getI()
93         #
94         # Initialisation
95         # --------------
96         Xn = Xb
97         Pn = B
98         #
99         self.StoredVariables["Analysis"].store( Xn.A1 )
100         if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
101             self.StoredVariables["APosterioriCovariance"].store( Pn.asfullmatrix(Xn.size) )
102             covarianceXa = Pn
103         Xa               = Xn
104         previousJMinimum = numpy.finfo(float).max
105         #
106         for step in range(duration-1):
107             if hasattr(Y,"store"):
108                 Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
109             else:
110                 Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
111             #
112             if U is not None:
113                 if hasattr(U,"store") and len(U)>1:
114                     Un = numpy.asmatrix(numpy.ravel( U[step] )).T
115                 elif hasattr(U,"store") and len(U)==1:
116                     Un = numpy.asmatrix(numpy.ravel( U[0] )).T
117                 else:
118                     Un = numpy.asmatrix(numpy.ravel( U )).T
119             else:
120                 Un = None
121             #
122             if self._parameters["EstimationOf"] == "State":
123                 Xn_predicted = Mt * Xn
124                 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
125                     Cm = Cm.reshape(Xn.size,Un.size) # ADAO & check shape
126                     Xn_predicted = Xn_predicted + Cm * Un
127                 Pn_predicted = Q + Mt * Pn * Ma
128             elif self._parameters["EstimationOf"] == "Parameters":
129                 # --- > Par principe, M = Id, Q = 0
130                 Xn_predicted = Xn
131                 Pn_predicted = Pn
132             #
133             if self._parameters["EstimationOf"] == "State":
134                 d  = Ynpu - Ht * Xn_predicted
135             elif self._parameters["EstimationOf"] == "Parameters":
136                 d  = Ynpu - Ht * Xn_predicted
137                 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans H, doublon !
138                     d = d - Cm * Un
139             #
140             _A = R + Ht * Pn_predicted * Ha
141             _u = numpy.linalg.solve( _A , d )
142             Xn = Xn_predicted + Pn_predicted * Ha * _u
143             Kn = Pn_predicted * Ha * (R + Ht * Pn_predicted * Ha).I
144             Pn = Pn_predicted - Kn * Ht * Pn_predicted
145             #
146             self.StoredVariables["Analysis"].store( Xn.A1 )
147             if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
148                 self.StoredVariables["APosterioriCovariance"].store( Pn )
149             if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
150                 self.StoredVariables["Innovation"].store( numpy.ravel( d.A1 ) )
151             if self._parameters["StoreInternalVariables"]:
152                 Jb  = 0.5 * (Xn - Xb).T * BI * (Xn - Xb)
153                 Jo  = 0.5 * d.T * RI * d
154                 J   = float( Jb ) + float( Jo )
155                 if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
156                     self.StoredVariables["CurrentState"].store( Xn )
157                 self.StoredVariables["CostFunctionJb"].store( Jb )
158                 self.StoredVariables["CostFunctionJo"].store( Jo )
159                 self.StoredVariables["CostFunctionJ" ].store( J )
160                 if J < previousJMinimum:
161                     previousJMinimum  = J
162                     Xa                = Xn
163                     if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
164                         covarianceXa  = Pn
165             else:
166                 Xa = Xn
167             #
168         #
169         # Stockage supplementaire de l'optimum en estimation de parametres
170         # ----------------------------------------------------------------
171         if self._parameters["EstimationOf"] == "Parameters":
172             self.StoredVariables["Analysis"].store( Xa.A1 )
173             if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
174                 self.StoredVariables["APosterioriCovariance"].store( covarianceXa )
175         #
176         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
177             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
178         #
179         self._post_run(HO)
180         return 0
181
182 # ==============================================================================
183 if __name__ == "__main__":
184     print '\n AUTODIAGNOSTIC \n'