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