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, "EXTENDEDKALMANFILTER")
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(
46 name = "StoreInternalVariables",
49 message = "Stockage des variables internes ou intermédiaires du calcul",
51 self.defineRequiredParameter(
52 name = "StoreSupplementaryCalculations",
55 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
56 listval = ["APosterioriCorrelations", "APosterioriCovariance", "APosterioriStandardDeviations", "APosterioriVariances", "BMA", "CurrentState", "CostFunctionJ", "Innovation"]
58 self.defineRequiredParameter( # Pas de type
60 message = "Liste des valeurs de bornes",
63 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
66 # Paramètres de pilotage
67 # ----------------------
68 self.setParameters(Parameters)
70 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):
71 Bounds = self._parameters["Bounds"]
72 logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
75 if self._parameters["EstimationOf"] == "Parameters":
76 self._parameters["StoreInternalVariables"] = True
81 raise ValueError("Background error covariance matrix has to be properly defined!")
83 raise ValueError("Observation error covariance matrix has to be properly defined!")
85 H = HO["Direct"].appliedControledFormTo
87 if self._parameters["EstimationOf"] == "State":
88 M = EM["Direct"].appliedControledFormTo
90 if CM is not None and CM.has_key("Tangent") and U is not None:
91 Cm = CM["Tangent"].asMatrix(Xb)
95 # Nombre de pas identique au nombre de pas d'observations
96 # -------------------------------------------------------
97 if hasattr(Y,"stepnumber"):
98 duration = Y.stepnumber()
102 # Précalcul des inversions de B et R
103 # ----------------------------------
104 if self._parameters["StoreInternalVariables"]:
113 self.StoredVariables["Analysis"].store( Xn.A1 )
114 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
115 self.StoredVariables["APosterioriCovariance"].store( Pn.asfullmatrix(Xn.size) )
118 previousJMinimum = numpy.finfo(float).max
120 for step in range(duration-1):
121 if hasattr(Y,"store"):
122 Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
124 Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
126 Ht = HO["Tangent"].asMatrix(ValueForMethodForm = Xn)
127 Ht = Ht.reshape(Ynpu.size,Xn.size) # ADAO & check shape
128 Ha = HO["Adjoint"].asMatrix(ValueForMethodForm = Xn)
129 Ha = Ha.reshape(Xn.size,Ynpu.size) # ADAO & check shape
131 if self._parameters["EstimationOf"] == "State":
132 Mt = EM["Tangent"].asMatrix(ValueForMethodForm = Xn)
133 Mt = Mt.reshape(Xn.size,Xn.size) # ADAO & check shape
134 Ma = EM["Adjoint"].asMatrix(ValueForMethodForm = Xn)
135 Ma = Ma.reshape(Xn.size,Xn.size) # ADAO & check shape
138 if hasattr(U,"store") and len(U)>1:
139 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
140 elif hasattr(U,"store") and len(U)==1:
141 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
143 Un = numpy.asmatrix(numpy.ravel( U )).T
147 if self._parameters["EstimationOf"] == "State":
148 Xn_predicted = numpy.asmatrix(numpy.ravel( M( (Xn, Un) ) )).T
149 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
150 Cm = Cm.reshape(Xn.size,Un.size) # ADAO & check shape
151 Xn_predicted = Xn_predicted + Cm * Un
152 Pn_predicted = Q + Mt * Pn * Ma
153 elif self._parameters["EstimationOf"] == "Parameters":
154 # --- > Par principe, M = Id, Q = 0
158 if Bounds is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
159 Xn_predicted = numpy.max(numpy.hstack((Xn_predicted,numpy.asmatrix(Bounds)[:,0])),axis=1)
160 Xn_predicted = numpy.min(numpy.hstack((Xn_predicted,numpy.asmatrix(Bounds)[:,1])),axis=1)
162 if self._parameters["EstimationOf"] == "State":
163 d = Ynpu - numpy.asmatrix(numpy.ravel( H( (Xn_predicted, None) ) )).T
164 elif self._parameters["EstimationOf"] == "Parameters":
165 d = Ynpu - numpy.asmatrix(numpy.ravel( H( (Xn_predicted, Un) ) )).T
166 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans H, doublon !
169 _A = R + Ht * Pn_predicted * Ha
170 _u = numpy.linalg.solve( _A , d )
171 Xn = Xn_predicted + Pn_predicted * Ha * _u
172 Kn = Pn_predicted * Ha * (R + Ht * Pn_predicted * Ha).I
173 Pn = Pn_predicted - Kn * Ht * Pn_predicted
175 self.StoredVariables["Analysis"].store( Xn.A1 )
176 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
177 self.StoredVariables["APosterioriCovariance"].store( Pn )
178 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
179 self.StoredVariables["Innovation"].store( numpy.ravel( d.A1 ) )
180 if self._parameters["StoreInternalVariables"]:
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 if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
185 self.StoredVariables["CurrentState"].store( Xn )
186 self.StoredVariables["CostFunctionJb"].store( Jb )
187 self.StoredVariables["CostFunctionJo"].store( Jo )
188 self.StoredVariables["CostFunctionJ" ].store( J )
189 if J < previousJMinimum:
192 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
198 # Stockage supplementaire de l'optimum en estimation de parametres
199 # ----------------------------------------------------------------
200 if self._parameters["EstimationOf"] == "Parameters":
201 self.StoredVariables["Analysis"].store( Xa.A1 )
202 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
203 self.StoredVariables["APosterioriCovariance"].store( covarianceXa )
205 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
206 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
211 # ==============================================================================
212 if __name__ == "__main__":
213 print '\n AUTODIAGNOSTIC \n'