1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2014 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, "EXTENDEDBLUE")
31 self.defineRequiredParameter(
32 name = "StoreInternalVariables",
35 message = "Stockage des variables internes ou intermédiaires du calcul",
37 self.defineRequiredParameter(
38 name = "StoreSupplementaryCalculations",
41 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
42 listval = ["APosterioriCovariance", "BMA", "OMA", "OMB", "Innovation", "SigmaBck2", "SigmaObs2", "MahalanobisConsistency", "SimulationQuantiles"]
44 self.defineRequiredParameter(
48 message = "Liste des valeurs de quantiles",
50 self.defineRequiredParameter(
52 typecast = numpy.random.seed,
53 message = "Graine fixée pour le générateur aléatoire",
55 self.defineRequiredParameter(
56 name = "NumberOfSamplesForQuantiles",
59 message = "Nombre d'échantillons simulés pour le calcul des quantiles",
62 self.defineRequiredParameter(
63 name = "SimulationForQuantiles",
66 message = "Type de simulation pour l'estimation des quantiles",
67 listval = ["Linear", "NonLinear"]
70 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
73 # Paramètres de pilotage
74 # ----------------------
75 self.setParameters(Parameters)
77 # Opérateur d'observation
78 # -----------------------
79 Hm = HO["Tangent"].asMatrix(Xb)
80 Hm = Hm.reshape(Y.size,Xb.size) # ADAO & check shape
81 Ha = HO["Adjoint"].asMatrix(Xb)
82 Ha = Ha.reshape(Xb.size,Y.size) # ADAO & check shape
83 H = HO["Direct"].appliedTo
85 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
86 # ----------------------------------------------------
87 if HO["AppliedToX"] is not None and HO["AppliedToX"].has_key("HXb"):
88 HXb = HO["AppliedToX"]["HXb"]
91 HXb = numpy.asmatrix(numpy.ravel( HXb )).T
93 # Précalcul des inversions de B et R
94 # ----------------------------------
98 # Calcul de l'innovation
99 # ----------------------
100 if Y.size != HXb.size:
101 raise ValueError("The size %i of observations Y and %i of observed calculation H(X) are different, they have to be identical."%(Y.size,HXb.size))
102 if max(Y.shape) != max(HXb.shape):
103 raise ValueError("The shapes %s of observations Y and %s of observed calculation H(X) are different, they have to be identical."%(Y.shape,HXb.shape))
106 # Calcul de la matrice de gain et de l'analyse
107 # --------------------------------------------
108 if Y.size <= Xb.size:
109 if Y.size > 100: # len(R)
111 _u = numpy.linalg.solve( _A , d )
112 Xa = Xb + B * Ha * _u
114 K = B * Ha * (R + Hm * B * Ha).I
117 if Y.size > 100: # len(R)
118 _A = BI + Ha * RI * Hm
119 _u = numpy.linalg.solve( _A , Ha * RI * d )
122 K = (BI + Ha * RI * Hm).I * Ha * RI
124 self.StoredVariables["Analysis"].store( Xa.A1 )
126 # Calcul de la fonction coût
127 # --------------------------
128 if self._parameters["StoreInternalVariables"] or \
129 "OMA" in self._parameters["StoreSupplementaryCalculations"] or \
130 "SigmaObs2" in self._parameters["StoreSupplementaryCalculations"] or \
131 "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"] or \
132 "SimulationQuantiles" in self._parameters["StoreSupplementaryCalculations"]:
133 HXa = numpy.matrix(numpy.ravel( H( Xa ) )).T
135 if self._parameters["StoreInternalVariables"] or \
136 "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"]:
137 Jb = 0.5 * (Xa - Xb).T * BI * (Xa - Xb)
138 Jo = 0.5 * oma.T * RI * oma
139 J = float( Jb ) + float( Jo )
140 self.StoredVariables["CostFunctionJb"].store( Jb )
141 self.StoredVariables["CostFunctionJo"].store( Jo )
142 self.StoredVariables["CostFunctionJ" ].store( J )
144 # Calcul de la covariance d'analyse
145 # ---------------------------------
146 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"] or \
147 "SimulationQuantiles" in self._parameters["StoreSupplementaryCalculations"]:
148 if (Y.size <= Xb.size) and (Y.size > 100): K = B * Ha * (R + Hm * B * Ha).I
149 elif (Y.size > Xb.size) and (Y.size > 100): K = (BI + Ha * RI * Hm).I * Ha * RI
150 else: pass # K deja calcule
152 if min(A.shape) != max(A.shape):
153 raise ValueError("The %s a posteriori covariance matrix A is of shape %s, despites it has to be a squared matrix. There is an error in the observation operator, please check it."%(self._name,str(A.shape)))
154 if (numpy.diag(A) < 0).any():
155 raise ValueError("The %s a posteriori covariance matrix A has at least one negative value on its diagonal. There is an error in the observation operator, please check it."%(self._name,))
156 if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
158 L = numpy.linalg.cholesky( A )
160 raise ValueError("The %s a posteriori covariance matrix A is not symmetric positive-definite. Please check your a priori covariances and your observation operator."%(self._name,))
161 self.StoredVariables["APosterioriCovariance"].store( A )
163 # Calculs et/ou stockages supplémentaires
164 # ---------------------------------------
165 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
166 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
167 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
168 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
169 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
170 self.StoredVariables["OMA"].store( numpy.ravel(oma) )
171 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
172 self.StoredVariables["OMB"].store( numpy.ravel(d) )
173 if "SigmaObs2" in self._parameters["StoreSupplementaryCalculations"]:
174 TraceR = R.trace(Y.size)
175 self.StoredVariables["SigmaObs2"].store( float( (d.T * (numpy.asmatrix(numpy.ravel(oma)).T)) ) / TraceR )
176 if "SigmaBck2" in self._parameters["StoreSupplementaryCalculations"]:
177 self.StoredVariables["SigmaBck2"].store( float( (d.T * Hm * (Xa - Xb))/(Hm * B * Hm.T).trace() ) )
178 if "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"]:
179 self.StoredVariables["MahalanobisConsistency"].store( float( 2.*J/d.size ) )
180 if "SimulationQuantiles" in self._parameters["StoreSupplementaryCalculations"]:
181 Qtls = self._parameters["Quantiles"]
182 nech = self._parameters["NumberOfSamplesForQuantiles"]
183 HtM = HO["Tangent"].asMatrix(ValueForMethodForm = Xa)
184 HtM = HtM.reshape(Y.size,Xa.size) # ADAO & check shape
186 for i in range(nech):
187 if self._parameters["SimulationForQuantiles"] == "Linear":
188 dXr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A) - Xa.A1).T
189 dYr = numpy.matrix(numpy.ravel( HtM * dXr )).T
191 elif self._parameters["SimulationForQuantiles"] == "NonLinear":
192 Xr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A)).T
193 Yr = numpy.matrix(numpy.ravel( H( Xr ) )).T
197 YfQ = numpy.hstack((YfQ,Yr))
200 for quantile in Qtls:
201 if not (0. <= quantile <= 1.): continue
202 indice = int(nech * quantile - 1./nech)
203 if YQ is None: YQ = YfQ[:,indice]
204 else: YQ = numpy.hstack((YQ,YfQ[:,indice]))
205 self.StoredVariables["SimulationQuantiles"].store( YQ )
210 # ==============================================================================
211 if __name__ == "__main__":
212 print '\n AUTODIAGNOSTIC \n'