1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2017 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", "CostFunctionJb", "CostFunctionJo", "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):
64 self._pre_run(Parameters)
66 if self._parameters["EstimationOf"] == "Parameters":
67 self._parameters["StoreInternalVariables"] = True
72 raise ValueError("Background error covariance matrix has to be properly defined!")
74 raise ValueError("Observation error covariance matrix has to be properly defined!")
76 H = HO["Direct"].appliedControledFormTo
78 if self._parameters["EstimationOf"] == "State":
79 M = EM["Direct"].appliedControledFormTo
81 if CM is not None and "Tangent" in CM and U is not None:
82 Cm = CM["Tangent"].asMatrix(Xb)
86 # Nombre de pas identique au nombre de pas d'observations
87 # -------------------------------------------------------
88 if hasattr(Y,"stepnumber"):
89 duration = Y.stepnumber()
93 # Précalcul des inversions de B et R
94 # ----------------------------------
95 if self._parameters["StoreInternalVariables"]:
104 self.StoredVariables["Analysis"].store( Xn.A1 )
105 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
106 self.StoredVariables["APosterioriCovariance"].store( Pn.asfullmatrix(Xn.size) )
109 previousJMinimum = numpy.finfo(float).max
111 for step in range(duration-1):
112 if hasattr(Y,"store"):
113 Ynpu = numpy.asmatrix(numpy.ravel( Y[step+1] )).T
115 Ynpu = numpy.asmatrix(numpy.ravel( Y )).T
117 Ht = HO["Tangent"].asMatrix(ValueForMethodForm = Xn)
118 Ht = Ht.reshape(Ynpu.size,Xn.size) # ADAO & check shape
119 Ha = HO["Adjoint"].asMatrix(ValueForMethodForm = Xn)
120 Ha = Ha.reshape(Xn.size,Ynpu.size) # ADAO & check shape
122 if self._parameters["EstimationOf"] == "State":
123 Mt = EM["Tangent"].asMatrix(ValueForMethodForm = Xn)
124 Mt = Mt.reshape(Xn.size,Xn.size) # ADAO & check shape
125 Ma = EM["Adjoint"].asMatrix(ValueForMethodForm = Xn)
126 Ma = Ma.reshape(Xn.size,Xn.size) # ADAO & check shape
129 if hasattr(U,"store") and len(U)>1:
130 Un = numpy.asmatrix(numpy.ravel( U[step] )).T
131 elif hasattr(U,"store") and len(U)==1:
132 Un = numpy.asmatrix(numpy.ravel( U[0] )).T
134 Un = numpy.asmatrix(numpy.ravel( U )).T
138 if self._parameters["EstimationOf"] == "State":
139 Xn_predicted = numpy.asmatrix(numpy.ravel( M( (Xn, Un) ) )).T
140 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans M, doublon !
141 Cm = Cm.reshape(Xn.size,Un.size) # ADAO & check shape
142 Xn_predicted = Xn_predicted + Cm * Un
143 Pn_predicted = Q + Mt * Pn * Ma
144 elif self._parameters["EstimationOf"] == "Parameters":
145 # --- > Par principe, M = Id, Q = 0
149 if self._parameters["Bounds"] is not None and self._parameters["ConstrainedBy"] == "EstimateProjection":
150 Xn_predicted = numpy.max(numpy.hstack((Xn_predicted,numpy.asmatrix(self._parameters["Bounds"])[:,0])),axis=1)
151 Xn_predicted = numpy.min(numpy.hstack((Xn_predicted,numpy.asmatrix(self._parameters["Bounds"])[:,1])),axis=1)
153 if self._parameters["EstimationOf"] == "State":
154 d = Ynpu - numpy.asmatrix(numpy.ravel( H( (Xn_predicted, None) ) )).T
155 elif self._parameters["EstimationOf"] == "Parameters":
156 d = Ynpu - numpy.asmatrix(numpy.ravel( H( (Xn_predicted, Un) ) )).T
157 if Cm is not None and Un is not None: # Attention : si Cm est aussi dans H, doublon !
160 _A = R + Ht * Pn_predicted * Ha
161 _u = numpy.linalg.solve( _A , d )
162 Xn = Xn_predicted + Pn_predicted * Ha * _u
163 Kn = Pn_predicted * Ha * (R + Ht * Pn_predicted * Ha).I
164 Pn = Pn_predicted - Kn * Ht * Pn_predicted
166 self.StoredVariables["Analysis"].store( Xn.A1 )
167 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
168 self.StoredVariables["APosterioriCovariance"].store( Pn )
169 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
170 self.StoredVariables["Innovation"].store( numpy.ravel( d.A1 ) )
171 if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
172 self.StoredVariables["CurrentState"].store( Xn )
173 if self._parameters["StoreInternalVariables"] \
174 or "CostFunctionJ" in self._parameters["StoreSupplementaryCalculations"] \
175 or "CostFunctionJb" in self._parameters["StoreSupplementaryCalculations"] \
176 or "CostFunctionJo" in self._parameters["StoreSupplementaryCalculations"]:
177 Jb = 0.5 * (Xn - Xb).T * BI * (Xn - Xb)
178 Jo = 0.5 * d.T * RI * d
179 J = float( Jb ) + float( Jo )
180 self.StoredVariables["CostFunctionJb"].store( Jb )
181 self.StoredVariables["CostFunctionJo"].store( Jo )
182 self.StoredVariables["CostFunctionJ" ].store( J )
183 if J < previousJMinimum:
186 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
192 # Stockage supplementaire de l'optimum en estimation de parametres
193 # ----------------------------------------------------------------
194 if self._parameters["EstimationOf"] == "Parameters":
195 self.StoredVariables["Analysis"].store( Xa.A1 )
196 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
197 self.StoredVariables["APosterioriCovariance"].store( covarianceXa )
199 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
200 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
205 # ==============================================================================
206 if __name__ == "__main__":
207 print('\n AUTODIAGNOSTIC \n')