1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2016 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",
85 listval = ["APosterioriCorrelations", "APosterioriCovariance", "APosterioriStandardDeviations", "APosterioriVariances", "BMA", "CurrentState", "CostFunctionJ", "Innovation"]
87 self.defineRequiredParameter( # Pas de type
89 message = "Liste des valeurs de bornes",
92 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
95 # Paramètres de pilotage
96 # ----------------------
97 self.setParameters(Parameters)
99 if self._parameters.has_key("Bounds") and (type(self._parameters["Bounds"]) is type([]) or type(self._parameters["Bounds"]) is type(())) and (len(self._parameters["Bounds"]) > 0):
100 Bounds = self._parameters["Bounds"]
101 logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
104 if self._parameters["EstimationOf"] == "Parameters":
105 self._parameters["StoreInternalVariables"] = True
108 Alpha = self._parameters["Alpha"]
109 Beta = self._parameters["Beta"]
110 if self._parameters["Kappa"] == 0:
111 if self._parameters["EstimationOf"] == "State":
113 elif self._parameters["EstimationOf"] == "Parameters":
116 Kappa = self._parameters["Kappa"]
117 Lambda = float( Alpha**2 ) * ( L + Kappa ) - L
118 Gamma = math.sqrt( L + Lambda )
123 Ww.append( 1. / (2.*(L + Lambda)) )
125 Wm = numpy.array( Ww )
126 Wm[0] = Lambda / (L + Lambda)
127 Wc = numpy.array( Ww )
128 Wc[0] = Lambda / (L + Lambda) + (1. - Alpha**2 + Beta)
133 raise ValueError("Background error covariance matrix has to be properly defined!")
135 raise ValueError("Observation error covariance matrix has to be properly defined!")
137 H = HO["Direct"].appliedControledFormTo
139 if self._parameters["EstimationOf"] == "State":
140 M = EM["Direct"].appliedControledFormTo
142 if CM is not None and CM.has_key("Tangent") and U is not None:
143 Cm = CM["Tangent"].asMatrix(Xb)
147 # Nombre de pas identique au nombre de pas d'observations
148 # -------------------------------------------------------
149 if hasattr(Y,"stepnumber"):
150 duration = Y.stepnumber()
154 # Précalcul des inversions de B et R
155 # ----------------------------------
156 if self._parameters["StoreInternalVariables"]:
163 if hasattr(B,"asfullmatrix"):
164 Pn = B.asfullmatrix(Xn.size)
168 self.StoredVariables["Analysis"].store( Xn.A1 )
169 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
170 self.StoredVariables["APosterioriCovariance"].store( Pn )
173 previousJMinimum = numpy.finfo(float).max
175 for step in range(duration-1):
176 if hasattr(Y,"store"):
177 Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
179 Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
182 if hasattr(U,"store") and len(U)>1:
183 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
184 elif hasattr(U,"store") and len(U)==1:
185 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
187 Un = numpy.asmatrix(numpy.ravel( U )).T
191 Pndemi = numpy.linalg.cholesky(Pn)
192 Xnp = numpy.hstack([Xn, Xn+Gamma*Pndemi, Xn-Gamma*Pndemi])
195 if Bounds is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
196 for point in range(nbSpts):
197 Xnp[:,point] = numpy.max(numpy.hstack((Xnp[:,point],numpy.asmatrix(Bounds)[:,0])),axis=1)
198 Xnp[:,point] = numpy.min(numpy.hstack((Xnp[:,point],numpy.asmatrix(Bounds)[:,1])),axis=1)
201 for point in range(nbSpts):
202 if self._parameters["EstimationOf"] == "State":
203 XEtnnpi = numpy.asmatrix(numpy.ravel( M( (Xnp[:,point], Un) ) )).T
204 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
205 Cm = Cm.reshape(Xn.size,Un.size) # ADAO & check shape
206 XEtnnpi = XEtnnpi + Cm * Un
207 if Bounds is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
208 XEtnnpi = numpy.max(numpy.hstack((XEtnnpi,numpy.asmatrix(Bounds)[:,0])),axis=1)
209 XEtnnpi = numpy.min(numpy.hstack((XEtnnpi,numpy.asmatrix(Bounds)[:,1])),axis=1)
210 elif self._parameters["EstimationOf"] == "Parameters":
211 # --- > Par principe, M = Id, Q = 0
212 XEtnnpi = Xnp[:,point]
213 XEtnnp.append( XEtnnpi )
214 XEtnnp = numpy.hstack( XEtnnp )
216 Xncm = numpy.matrix( XEtnnp.getA()*numpy.array(Wm) ).sum(axis=1)
218 if Bounds is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
219 Xncm = numpy.max(numpy.hstack((Xncm,numpy.asmatrix(Bounds)[:,0])),axis=1)
220 Xncm = numpy.min(numpy.hstack((Xncm,numpy.asmatrix(Bounds)[:,1])),axis=1)
222 if self._parameters["EstimationOf"] == "State": Pnm = Q
223 elif self._parameters["EstimationOf"] == "Parameters": Pnm = 0.
224 for point in range(nbSpts):
225 Pnm += Wc[i] * (XEtnnp[:,point]-Xncm) * (XEtnnp[:,point]-Xncm).T
227 if self._parameters["EstimationOf"] == "Parameters" and Bounds is not None:
228 Pnmdemi = self._parameters["Reconditioner"] * numpy.linalg.cholesky(Pnm)
230 Pnmdemi = numpy.linalg.cholesky(Pnm)
232 Xnnp = numpy.hstack([Xncm, Xncm+Gamma*Pnmdemi, Xncm-Gamma*Pnmdemi])
234 if Bounds is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
235 for point in range(nbSpts):
236 Xnnp[:,point] = numpy.max(numpy.hstack((Xnnp[:,point],numpy.asmatrix(Bounds)[:,0])),axis=1)
237 Xnnp[:,point] = numpy.min(numpy.hstack((Xnnp[:,point],numpy.asmatrix(Bounds)[:,1])),axis=1)
240 for point in range(nbSpts):
241 if self._parameters["EstimationOf"] == "State":
242 Ynnpi = numpy.asmatrix(numpy.ravel( H( (Xnnp[:,point], None) ) )).T
243 elif self._parameters["EstimationOf"] == "Parameters":
244 Ynnpi = numpy.asmatrix(numpy.ravel( H( (Xnnp[:,point], Un) ) )).T
246 Ynnp = numpy.hstack( Ynnp )
248 Yncm = numpy.matrix( Ynnp.getA()*numpy.array(Wm) ).sum(axis=1)
252 for point in range(nbSpts):
253 Pyyn += Wc[i] * (Ynnp[:,point]-Yncm) * (Ynnp[:,point]-Yncm).T
254 Pxyn += Wc[i] * (Xnnp[:,point]-Xncm) * (Ynnp[:,point]-Yncm).T
257 if self._parameters["EstimationOf"] == "Parameters":
258 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans H, doublon !
263 Pn = Pnm - Kn * Pyyn * Kn.T
265 if Bounds is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
266 Xn = numpy.max(numpy.hstack((Xn,numpy.asmatrix(Bounds)[:,0])),axis=1)
267 Xn = numpy.min(numpy.hstack((Xn,numpy.asmatrix(Bounds)[:,1])),axis=1)
269 self.StoredVariables["Analysis"].store( Xn.A1 )
270 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
271 self.StoredVariables["APosterioriCovariance"].store( Pn )
272 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
273 self.StoredVariables["Innovation"].store( numpy.ravel( d.A1 ) )
274 if self._parameters["StoreInternalVariables"]:
275 Jb = 0.5 * (Xn - Xb).T * BI * (Xn - Xb)
276 Jo = 0.5 * d.T * RI * d
277 J = float( Jb ) + float( Jo )
278 if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
279 self.StoredVariables["CurrentState"].store( Xn )
280 self.StoredVariables["CostFunctionJb"].store( Jb )
281 self.StoredVariables["CostFunctionJo"].store( Jo )
282 self.StoredVariables["CostFunctionJ" ].store( J )
283 if J < previousJMinimum:
286 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
292 # Stockage supplementaire de l'optimum en estimation de parametres
293 # ----------------------------------------------------------------
294 if self._parameters["EstimationOf"] == "Parameters":
295 self.StoredVariables["Analysis"].store( Xa.A1 )
296 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
297 self.StoredVariables["APosterioriCovariance"].store( covarianceXa )
299 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
300 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
305 # ==============================================================================
306 if __name__ == "__main__":
307 print '\n AUTODIAGNOSTIC \n'