Salome HOME
Updating version and copyright date information
[modules/adao.git] / src / daComposant / daAlgorithms / UnscentedKalmanFilter.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2020 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, math
26
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
29     def __init__(self):
30         BasicObjects.Algorithm.__init__(self, "UNSCENTEDKALMANFILTER")
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     = "Alpha",
47             default  = 1.,
48             typecast = float,
49             message  = "",
50             minval   = 1.e-4,
51             maxval   = 1.,
52             )
53         self.defineRequiredParameter(
54             name     = "Beta",
55             default  = 2,
56             typecast = float,
57             message  = "",
58             )
59         self.defineRequiredParameter(
60             name     = "Kappa",
61             default  = 0,
62             typecast = int,
63             message  = "",
64             maxval   = 2,
65             )
66         self.defineRequiredParameter(
67             name     = "Reconditioner",
68             default  = 1.,
69             typecast = float,
70             message  = "",
71             minval   = 1.e-3,
72             maxval   = 1.e+1,
73             )
74         self.defineRequiredParameter(
75             name     = "StoreInternalVariables",
76             default  = False,
77             typecast = bool,
78             message  = "Stockage des variables internes ou intermédiaires du calcul",
79             )
80         self.defineRequiredParameter(
81             name     = "StoreSupplementaryCalculations",
82             default  = [],
83             typecast = tuple,
84             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
85             listval  = [
86                 "Analysis",
87                 "APosterioriCorrelations",
88                 "APosterioriCovariance",
89                 "APosterioriStandardDeviations",
90                 "APosterioriVariances",
91                 "BMA",
92                 "CostFunctionJ",
93                 "CostFunctionJb",
94                 "CostFunctionJo",
95                 "CurrentState",
96                 "InnovationAtCurrentState",
97                 ]
98             )
99         self.defineRequiredParameter( # Pas de type
100             name     = "Bounds",
101             message  = "Liste des valeurs de bornes",
102             )
103         self.requireInputArguments(
104             mandatory= ("Xb", "Y", "HO", "R", "B" ),
105             optional = ("U", "EM", "CM", "Q"),
106             )
107
108     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
109         self._pre_run(Parameters, Xb, Y, R, B, Q)
110         #
111         if self._parameters["EstimationOf"] == "Parameters":
112             self._parameters["StoreInternalVariables"] = True
113         #
114         L     = Xb.size
115         Alpha = self._parameters["Alpha"]
116         Beta  = self._parameters["Beta"]
117         if self._parameters["Kappa"] == 0:
118             if self._parameters["EstimationOf"] == "State":
119                 Kappa = 0
120             elif self._parameters["EstimationOf"] == "Parameters":
121                 Kappa = 3 - L
122         else:
123             Kappa = self._parameters["Kappa"]
124         Lambda = float( Alpha**2 ) * ( L + Kappa ) - L
125         Gamma  = math.sqrt( L + Lambda )
126         #
127         Ww = []
128         Ww.append( 0. )
129         for i in range(2*L):
130             Ww.append( 1. / (2.*(L + Lambda)) )
131         #
132         Wm = numpy.array( Ww )
133         Wm[0] = Lambda / (L + Lambda)
134         Wc = numpy.array( Ww )
135         Wc[0] = Lambda / (L + Lambda) + (1. - Alpha**2 + Beta)
136         #
137         # Opérateurs
138         # ----------
139         Hm = HO["Direct"].appliedControledFormTo
140         #
141         if self._parameters["EstimationOf"] == "State":
142             Mm = EM["Direct"].appliedControledFormTo
143         #
144         if CM is not None and "Tangent" in CM and U is not None:
145             Cm = CM["Tangent"].asMatrix(Xb)
146         else:
147             Cm = None
148         #
149         # Nombre de pas identique au nombre de pas d'observations
150         # -------------------------------------------------------
151         if hasattr(Y,"stepnumber"):
152             duration = Y.stepnumber()
153         else:
154             duration = 2
155         #
156         # Précalcul des inversions de B et R
157         # ----------------------------------
158         if self._parameters["StoreInternalVariables"] \
159             or self._toStore("CostFunctionJ") \
160             or self._toStore("CostFunctionJb") \
161             or self._toStore("CostFunctionJo"):
162             BI = B.getI()
163             RI = R.getI()
164         #
165         # Initialisation
166         # --------------
167         __n = Xb.size
168         Xn = Xb
169         if hasattr(B,"asfullmatrix"): Pn = B.asfullmatrix(__n)
170         else:                         Pn = B
171         #
172         if len(self.StoredVariables["Analysis"])==0 or not self._parameters["nextStep"]:
173             self.StoredVariables["Analysis"].store( numpy.ravel(Xb) )
174             if self._toStore("APosterioriCovariance"):
175                 self.StoredVariables["APosterioriCovariance"].store( Pn )
176                 covarianceXa = Pn
177         #
178         Xa               = Xb
179         XaMin            = Xb
180         previousJMinimum = numpy.finfo(float).max
181         #
182         for step in range(duration-1):
183             if hasattr(Y,"store"):
184                 Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
185             else:
186                 Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
187             #
188             if U is not None:
189                 if hasattr(U,"store") and len(U)>1:
190                     Un = numpy.asmatrix(numpy.ravel( U[step] )).T
191                 elif hasattr(U,"store") and len(U)==1:
192                     Un = numpy.asmatrix(numpy.ravel( U[0] )).T
193                 else:
194                     Un = numpy.asmatrix(numpy.ravel( U )).T
195             else:
196                 Un = None
197             #
198             Pndemi = numpy.linalg.cholesky(Pn)
199             Xnp = numpy.hstack([Xn, Xn+Gamma*Pndemi, Xn-Gamma*Pndemi])
200             nbSpts = 2*Xn.size+1
201             #
202             if self._parameters["Bounds"] is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
203                 for point in range(nbSpts):
204                     Xnp[:,point] = numpy.max(numpy.hstack((Xnp[:,point],numpy.asmatrix(self._parameters["Bounds"])[:,0])),axis=1)
205                     Xnp[:,point] = numpy.min(numpy.hstack((Xnp[:,point],numpy.asmatrix(self._parameters["Bounds"])[:,1])),axis=1)
206             #
207             XEtnnp = []
208             for point in range(nbSpts):
209                 if self._parameters["EstimationOf"] == "State":
210                     XEtnnpi = numpy.asmatrix(numpy.ravel( Mm( (Xnp[:,point], Un) ) )).T
211                     if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
212                         Cm = Cm.reshape(Xn.size,Un.size) # ADAO & check shape
213                         XEtnnpi = XEtnnpi + Cm * Un
214                     if self._parameters["Bounds"] is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
215                         XEtnnpi = numpy.max(numpy.hstack((XEtnnpi,numpy.asmatrix(self._parameters["Bounds"])[:,0])),axis=1)
216                         XEtnnpi = numpy.min(numpy.hstack((XEtnnpi,numpy.asmatrix(self._parameters["Bounds"])[:,1])),axis=1)
217                 elif self._parameters["EstimationOf"] == "Parameters":
218                     # --- > Par principe, M = Id, Q = 0
219                     XEtnnpi = Xnp[:,point]
220                 XEtnnp.append( XEtnnpi )
221             XEtnnp = numpy.hstack( XEtnnp )
222             #
223             Xncm = numpy.matrix( XEtnnp.getA()*numpy.array(Wm) ).sum(axis=1)
224             #
225             if self._parameters["Bounds"] is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
226                 Xncm = numpy.max(numpy.hstack((Xncm,numpy.asmatrix(self._parameters["Bounds"])[:,0])),axis=1)
227                 Xncm = numpy.min(numpy.hstack((Xncm,numpy.asmatrix(self._parameters["Bounds"])[:,1])),axis=1)
228             #
229             if self._parameters["EstimationOf"] == "State":        Pnm = Q
230             elif self._parameters["EstimationOf"] == "Parameters": Pnm = 0.
231             for point in range(nbSpts):
232                 Pnm += Wc[i] * (XEtnnp[:,point]-Xncm) * (XEtnnp[:,point]-Xncm).T
233             #
234             if self._parameters["EstimationOf"] == "Parameters" and self._parameters["Bounds"] is not None:
235                 Pnmdemi = self._parameters["Reconditioner"] * numpy.linalg.cholesky(Pnm)
236             else:
237                 Pnmdemi = numpy.linalg.cholesky(Pnm)
238             #
239             Xnnp = numpy.hstack([Xncm, Xncm+Gamma*Pnmdemi, Xncm-Gamma*Pnmdemi])
240             #
241             if self._parameters["Bounds"] is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
242                 for point in range(nbSpts):
243                     Xnnp[:,point] = numpy.max(numpy.hstack((Xnnp[:,point],numpy.asmatrix(self._parameters["Bounds"])[:,0])),axis=1)
244                     Xnnp[:,point] = numpy.min(numpy.hstack((Xnnp[:,point],numpy.asmatrix(self._parameters["Bounds"])[:,1])),axis=1)
245             #
246             Ynnp = []
247             for point in range(nbSpts):
248                 if self._parameters["EstimationOf"] == "State":
249                     Ynnpi = numpy.asmatrix(numpy.ravel( Hm( (Xnnp[:,point], None) ) )).T
250                 elif self._parameters["EstimationOf"] == "Parameters":
251                     Ynnpi = numpy.asmatrix(numpy.ravel( Hm( (Xnnp[:,point], Un) ) )).T
252                 Ynnp.append( Ynnpi )
253             Ynnp = numpy.hstack( Ynnp )
254             #
255             Yncm = numpy.matrix( Ynnp.getA()*numpy.array(Wm) ).sum(axis=1)
256             #
257             Pyyn = R
258             Pxyn = 0.
259             for point in range(nbSpts):
260                 Pyyn += Wc[i] * (Ynnp[:,point]-Yncm) * (Ynnp[:,point]-Yncm).T
261                 Pxyn += Wc[i] * (Xnnp[:,point]-Xncm) * (Ynnp[:,point]-Yncm).T
262             #
263             d  = Ynpu - Yncm
264             if self._parameters["EstimationOf"] == "Parameters":
265                 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans H, doublon !
266                     d = d - Cm * Un
267             #
268             Kn = Pxyn * Pyyn.I
269             Xn = Xncm + Kn * d
270             Pn = Pnm - Kn * Pyyn * Kn.T
271             #
272             if self._parameters["Bounds"] is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
273                 Xn = numpy.max(numpy.hstack((Xn,numpy.asmatrix(self._parameters["Bounds"])[:,0])),axis=1)
274                 Xn = numpy.min(numpy.hstack((Xn,numpy.asmatrix(self._parameters["Bounds"])[:,1])),axis=1)
275             Xa = Xn # Pointeurs
276             #
277             # ---> avec analysis
278             self.StoredVariables["Analysis"].store( Xa )
279             if self._toStore("APosterioriCovariance"):
280                 self.StoredVariables["APosterioriCovariance"].store( Pn )
281             # ---> avec current state
282             if self._toStore("InnovationAtCurrentState"):
283                 self.StoredVariables["InnovationAtCurrentState"].store( d )
284             if self._parameters["StoreInternalVariables"] \
285                 or self._toStore("CurrentState"):
286                 self.StoredVariables["CurrentState"].store( Xn )
287             if self._parameters["StoreInternalVariables"] \
288                 or self._toStore("CostFunctionJ") \
289                 or self._toStore("CostFunctionJb") \
290                 or self._toStore("CostFunctionJo"):
291                 Jb  = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
292                 Jo  = float( 0.5 * d.T * RI * d )
293                 J   = Jb + Jo
294                 self.StoredVariables["CostFunctionJb"].store( Jb )
295                 self.StoredVariables["CostFunctionJo"].store( Jo )
296                 self.StoredVariables["CostFunctionJ" ].store( J )
297             if self._parameters["EstimationOf"] == "Parameters" \
298                 and J < previousJMinimum:
299                 previousJMinimum    = J
300                 XaMin               = Xa
301                 if self._toStore("APosterioriCovariance"):
302                     covarianceXaMin = Pn
303         #
304         # Stockage final supplémentaire de l'optimum en estimation de paramètres
305         # ----------------------------------------------------------------------
306         if self._parameters["EstimationOf"] == "Parameters":
307             self.StoredVariables["Analysis"].store( XaMin )
308             if self._toStore("APosterioriCovariance"):
309                 self.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
310             if self._toStore("BMA"):
311                 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
312         #
313         self._post_run(HO)
314         return 0
315
316 # ==============================================================================
317 if __name__ == "__main__":
318     print('\n AUTODIAGNOSTIC\n')