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