1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2019 EDF R&D
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.
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.
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
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
24 from daCore import BasicObjects
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
30 BasicObjects.Algorithm.__init__(self, "UNSCENTEDKALMANFILTER")
31 self.defineRequiredParameter(
32 name = "ConstrainedBy",
33 default = "EstimateProjection",
35 message = "Prise en compte des contraintes",
36 listval = ["EstimateProjection"],
38 self.defineRequiredParameter(
39 name = "EstimationOf",
42 message = "Estimation d'etat ou de parametres",
43 listval = ["State", "Parameters"],
45 self.defineRequiredParameter(
53 self.defineRequiredParameter(
59 self.defineRequiredParameter(
66 self.defineRequiredParameter(
67 name = "Reconditioner",
74 self.defineRequiredParameter(
75 name = "StoreInternalVariables",
78 message = "Stockage des variables internes ou intermédiaires du calcul",
80 self.defineRequiredParameter(
81 name = "StoreSupplementaryCalculations",
84 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
87 "APosterioriCorrelations",
88 "APosterioriCovariance",
89 "APosterioriStandardDeviations",
90 "APosterioriVariances",
96 "InnovationAtCurrentState",
99 self.defineRequiredParameter( # Pas de type
101 message = "Liste des valeurs de bornes",
103 self.requireInputArguments(
104 mandatory= ("Xb", "Y", "HO", "R", "B" ),
105 optional = ("U", "EM", "CM", "Q"),
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)
111 if self._parameters["EstimationOf"] == "Parameters":
112 self._parameters["StoreInternalVariables"] = True
115 Alpha = self._parameters["Alpha"]
116 Beta = self._parameters["Beta"]
117 if self._parameters["Kappa"] == 0:
118 if self._parameters["EstimationOf"] == "State":
120 elif self._parameters["EstimationOf"] == "Parameters":
123 Kappa = self._parameters["Kappa"]
124 Lambda = float( Alpha**2 ) * ( L + Kappa ) - L
125 Gamma = math.sqrt( L + Lambda )
130 Ww.append( 1. / (2.*(L + Lambda)) )
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)
139 Hm = HO["Direct"].appliedControledFormTo
141 if self._parameters["EstimationOf"] == "State":
142 Mm = EM["Direct"].appliedControledFormTo
144 if CM is not None and "Tangent" in CM and U is not None:
145 Cm = CM["Tangent"].asMatrix(Xb)
149 # Nombre de pas identique au nombre de pas d'observations
150 # -------------------------------------------------------
151 if hasattr(Y,"stepnumber"):
152 duration = Y.stepnumber()
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"):
168 if hasattr(B,"asfullmatrix"): Pn = B.asfullmatrix(Xn.size)
171 self.StoredVariables["Analysis"].store( Xn.A1 )
172 if self._toStore("APosterioriCovariance"):
173 self.StoredVariables["APosterioriCovariance"].store( Pn )
176 previousJMinimum = numpy.finfo(float).max
178 for step in range(duration-1):
179 if hasattr(Y,"store"):
180 Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
182 Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
185 if hasattr(U,"store") and len(U)>1:
186 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
187 elif hasattr(U,"store") and len(U)==1:
188 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
190 Un = numpy.asmatrix(numpy.ravel( U )).T
194 Pndemi = numpy.linalg.cholesky(Pn)
195 Xnp = numpy.hstack([Xn, Xn+Gamma*Pndemi, Xn-Gamma*Pndemi])
198 if self._parameters["Bounds"] is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
199 for point in range(nbSpts):
200 Xnp[:,point] = numpy.max(numpy.hstack((Xnp[:,point],numpy.asmatrix(self._parameters["Bounds"])[:,0])),axis=1)
201 Xnp[:,point] = numpy.min(numpy.hstack((Xnp[:,point],numpy.asmatrix(self._parameters["Bounds"])[:,1])),axis=1)
204 for point in range(nbSpts):
205 if self._parameters["EstimationOf"] == "State":
206 XEtnnpi = numpy.asmatrix(numpy.ravel( Mm( (Xnp[:,point], Un) ) )).T
207 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
208 Cm = Cm.reshape(Xn.size,Un.size) # ADAO & check shape
209 XEtnnpi = XEtnnpi + Cm * Un
210 if self._parameters["Bounds"] is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
211 XEtnnpi = numpy.max(numpy.hstack((XEtnnpi,numpy.asmatrix(self._parameters["Bounds"])[:,0])),axis=1)
212 XEtnnpi = numpy.min(numpy.hstack((XEtnnpi,numpy.asmatrix(self._parameters["Bounds"])[:,1])),axis=1)
213 elif self._parameters["EstimationOf"] == "Parameters":
214 # --- > Par principe, M = Id, Q = 0
215 XEtnnpi = Xnp[:,point]
216 XEtnnp.append( XEtnnpi )
217 XEtnnp = numpy.hstack( XEtnnp )
219 Xncm = numpy.matrix( XEtnnp.getA()*numpy.array(Wm) ).sum(axis=1)
221 if self._parameters["Bounds"] is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
222 Xncm = numpy.max(numpy.hstack((Xncm,numpy.asmatrix(self._parameters["Bounds"])[:,0])),axis=1)
223 Xncm = numpy.min(numpy.hstack((Xncm,numpy.asmatrix(self._parameters["Bounds"])[:,1])),axis=1)
225 if self._parameters["EstimationOf"] == "State": Pnm = Q
226 elif self._parameters["EstimationOf"] == "Parameters": Pnm = 0.
227 for point in range(nbSpts):
228 Pnm += Wc[i] * (XEtnnp[:,point]-Xncm) * (XEtnnp[:,point]-Xncm).T
230 if self._parameters["EstimationOf"] == "Parameters" and self._parameters["Bounds"] is not None:
231 Pnmdemi = self._parameters["Reconditioner"] * numpy.linalg.cholesky(Pnm)
233 Pnmdemi = numpy.linalg.cholesky(Pnm)
235 Xnnp = numpy.hstack([Xncm, Xncm+Gamma*Pnmdemi, Xncm-Gamma*Pnmdemi])
237 if self._parameters["Bounds"] is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
238 for point in range(nbSpts):
239 Xnnp[:,point] = numpy.max(numpy.hstack((Xnnp[:,point],numpy.asmatrix(self._parameters["Bounds"])[:,0])),axis=1)
240 Xnnp[:,point] = numpy.min(numpy.hstack((Xnnp[:,point],numpy.asmatrix(self._parameters["Bounds"])[:,1])),axis=1)
243 for point in range(nbSpts):
244 if self._parameters["EstimationOf"] == "State":
245 Ynnpi = numpy.asmatrix(numpy.ravel( Hm( (Xnnp[:,point], None) ) )).T
246 elif self._parameters["EstimationOf"] == "Parameters":
247 Ynnpi = numpy.asmatrix(numpy.ravel( Hm( (Xnnp[:,point], Un) ) )).T
249 Ynnp = numpy.hstack( Ynnp )
251 Yncm = numpy.matrix( Ynnp.getA()*numpy.array(Wm) ).sum(axis=1)
255 for point in range(nbSpts):
256 Pyyn += Wc[i] * (Ynnp[:,point]-Yncm) * (Ynnp[:,point]-Yncm).T
257 Pxyn += Wc[i] * (Xnnp[:,point]-Xncm) * (Ynnp[:,point]-Yncm).T
260 if self._parameters["EstimationOf"] == "Parameters":
261 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans H, doublon !
266 Pn = Pnm - Kn * Pyyn * Kn.T
268 if self._parameters["Bounds"] is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
269 Xn = numpy.max(numpy.hstack((Xn,numpy.asmatrix(self._parameters["Bounds"])[:,0])),axis=1)
270 Xn = numpy.min(numpy.hstack((Xn,numpy.asmatrix(self._parameters["Bounds"])[:,1])),axis=1)
274 self.StoredVariables["Analysis"].store( Xa )
275 if self._toStore("APosterioriCovariance"):
276 self.StoredVariables["APosterioriCovariance"].store( Pn )
277 # ---> avec current state
278 if self._toStore("InnovationAtCurrentState"):
279 self.StoredVariables["InnovationAtCurrentState"].store( d )
280 if self._parameters["StoreInternalVariables"] \
281 or self._toStore("CurrentState"):
282 self.StoredVariables["CurrentState"].store( Xn )
283 if self._parameters["StoreInternalVariables"] \
284 or self._toStore("CostFunctionJ") \
285 or self._toStore("CostFunctionJb") \
286 or self._toStore("CostFunctionJo"):
287 Jb = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
288 Jo = float( 0.5 * d.T * RI * d )
290 self.StoredVariables["CostFunctionJb"].store( Jb )
291 self.StoredVariables["CostFunctionJo"].store( Jo )
292 self.StoredVariables["CostFunctionJ" ].store( J )
293 if self._parameters["EstimationOf"] == "Parameters" \
294 and J < previousJMinimum:
297 if self._toStore("APosterioriCovariance"):
300 # Stockage final supplémentaire de l'optimum en estimation de paramètres
301 # ----------------------------------------------------------------------
302 if self._parameters["EstimationOf"] == "Parameters":
303 self.StoredVariables["Analysis"].store( XaMin )
304 if self._toStore("APosterioriCovariance"):
305 self.StoredVariables["APosterioriCovariance"].store( covarianceXaMin )
306 if self._toStore("BMA"):
307 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(XaMin) )
312 # ==============================================================================
313 if __name__ == "__main__":
314 print('\n AUTODIAGNOSTIC\n')