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