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