1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2021 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",
44 "APosterioriCorrelations",
45 "APosterioriCovariance",
46 "APosterioriStandardDeviations",
47 "APosterioriVariances",
50 "CostFunctionJAtCurrentOptimum",
52 "CostFunctionJbAtCurrentOptimum",
54 "CostFunctionJoAtCurrentOptimum",
58 "MahalanobisConsistency",
61 "SampledStateForQuantiles",
64 "SimulatedObservationAtBackground",
65 "SimulatedObservationAtCurrentOptimum",
66 "SimulatedObservationAtCurrentState",
67 "SimulatedObservationAtOptimum",
68 "SimulationQuantiles",
71 self.defineRequiredParameter(
75 message = "Liste des valeurs de quantiles",
79 self.defineRequiredParameter(
81 typecast = numpy.random.seed,
82 message = "Graine fixée pour le générateur aléatoire",
84 self.defineRequiredParameter(
85 name = "NumberOfSamplesForQuantiles",
88 message = "Nombre d'échantillons simulés pour le calcul des quantiles",
91 self.defineRequiredParameter(
92 name = "SimulationForQuantiles",
95 message = "Type de simulation pour l'estimation des quantiles",
96 listval = ["Linear", "NonLinear"]
98 self.requireInputArguments(
99 mandatory= ("Xb", "Y", "HO", "R", "B"),
101 self.setAttributes(tags=(
107 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
108 self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
110 Hm = HO["Tangent"].asMatrix(Xb)
111 Hm = Hm.reshape(Y.size,Xb.size) # ADAO & check shape
112 Ha = HO["Adjoint"].asMatrix(Xb)
113 Ha = Ha.reshape(Xb.size,Y.size) # ADAO & check shape
114 H = HO["Direct"].appliedTo
116 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
117 # ----------------------------------------------------
118 if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
119 HXb = H( Xb, HO["AppliedInX"]["HXb"])
122 HXb = numpy.asmatrix(numpy.ravel( HXb )).T
123 if Y.size != HXb.size:
124 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))
125 if max(Y.shape) != max(HXb.shape):
126 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))
128 # Précalcul des inversions de B et R
129 # ----------------------------------
133 # Calcul de l'innovation
134 # ----------------------
137 # Calcul de la matrice de gain et de l'analyse
138 # --------------------------------------------
139 if Y.size <= Xb.size:
140 _A = R + numpy.dot(Hm, B * Ha)
141 _u = numpy.linalg.solve( _A , d )
142 Xa = Xb + B * Ha * _u
144 _A = BI + numpy.dot(Ha, RI * Hm)
145 _u = numpy.linalg.solve( _A , numpy.dot(Ha, RI * d) )
147 self.StoredVariables["Analysis"].store( Xa.A1 )
149 # Calcul de la fonction coût
150 # --------------------------
151 if self._parameters["StoreInternalVariables"] or \
152 self._toStore("CostFunctionJ") or self._toStore("CostFunctionJAtCurrentOptimum") or \
153 self._toStore("CostFunctionJb") or self._toStore("CostFunctionJbAtCurrentOptimum") or \
154 self._toStore("CostFunctionJo") or self._toStore("CostFunctionJoAtCurrentOptimum") or \
155 self._toStore("OMA") or \
156 self._toStore("SigmaObs2") or \
157 self._toStore("MahalanobisConsistency") or \
158 self._toStore("SimulatedObservationAtCurrentOptimum") or \
159 self._toStore("SimulatedObservationAtCurrentState") or \
160 self._toStore("SimulatedObservationAtOptimum") or \
161 self._toStore("SimulationQuantiles"):
162 HXa = numpy.matrix(numpy.ravel( H( Xa ) )).T
164 if self._parameters["StoreInternalVariables"] or \
165 self._toStore("CostFunctionJ") or self._toStore("CostFunctionJAtCurrentOptimum") or \
166 self._toStore("CostFunctionJb") or self._toStore("CostFunctionJbAtCurrentOptimum") or \
167 self._toStore("CostFunctionJo") or self._toStore("CostFunctionJoAtCurrentOptimum") or \
168 self._toStore("MahalanobisConsistency"):
169 Jb = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
170 Jo = float( 0.5 * oma.T * RI * oma )
172 self.StoredVariables["CostFunctionJb"].store( Jb )
173 self.StoredVariables["CostFunctionJo"].store( Jo )
174 self.StoredVariables["CostFunctionJ" ].store( J )
175 self.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( Jb )
176 self.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( Jo )
177 self.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( J )
179 # Calcul de la covariance d'analyse
180 # ---------------------------------
181 if self._toStore("APosterioriCovariance") or \
182 self._toStore("SimulationQuantiles"):
183 if (Y.size <= Xb.size): K = B * Ha * (R + numpy.dot(Hm, B * Ha)).I
184 elif (Y.size > Xb.size): K = (BI + numpy.dot(Ha, RI * Hm)).I * Ha * RI
186 if min(A.shape) != max(A.shape):
187 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)))
188 if (numpy.diag(A) < 0).any():
189 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,))
190 if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
192 L = numpy.linalg.cholesky( A )
194 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,))
195 self.StoredVariables["APosterioriCovariance"].store( A )
197 # Calculs et/ou stockages supplémentaires
198 # ---------------------------------------
199 if self._parameters["StoreInternalVariables"] or self._toStore("CurrentState"):
200 self.StoredVariables["CurrentState"].store( numpy.ravel(Xa) )
201 if self._toStore("CurrentOptimum"):
202 self.StoredVariables["CurrentOptimum"].store( numpy.ravel(Xa) )
203 if self._toStore("Innovation"):
204 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
205 if self._toStore("BMA"):
206 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
207 if self._toStore("OMA"):
208 self.StoredVariables["OMA"].store( numpy.ravel(oma) )
209 if self._toStore("OMB"):
210 self.StoredVariables["OMB"].store( numpy.ravel(d) )
211 if self._toStore("SigmaObs2"):
212 TraceR = R.trace(Y.size)
213 self.StoredVariables["SigmaObs2"].store( float( (d.T * (numpy.asmatrix(numpy.ravel(oma)).T)) ) / TraceR )
214 if self._toStore("SigmaBck2"):
215 self.StoredVariables["SigmaBck2"].store( float( (d.T * Hm * (Xa - Xb))/(Hm * B * Hm.T).trace() ) )
216 if self._toStore("MahalanobisConsistency"):
217 self.StoredVariables["MahalanobisConsistency"].store( float( 2.*J/d.size ) )
218 if self._toStore("SimulationQuantiles"):
219 nech = self._parameters["NumberOfSamplesForQuantiles"]
220 HtM = HO["Tangent"].asMatrix(ValueForMethodForm = Xa)
221 HtM = HtM.reshape(Y.size,Xa.size) # ADAO & check shape
224 for i in range(nech):
225 if self._parameters["SimulationForQuantiles"] == "Linear":
226 dXr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A) - Xa.A1).T
227 dYr = numpy.matrix(numpy.ravel( HtM * dXr )).T
229 if selfA._toStore("SampledStateForQuantiles"): Xr = Xa+dXr
230 elif self._parameters["SimulationForQuantiles"] == "NonLinear":
231 Xr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A)).T
232 Yr = numpy.matrix(numpy.ravel( H( Xr ) )).T
235 if selfA._toStore("SampledStateForQuantiles"): EXr = numpy.ravel(Xr)
237 YfQ = numpy.hstack((YfQ,Yr))
238 if selfA._toStore("SampledStateForQuantiles"): EXr = numpy.vstack((EXr,numpy.ravel(Xr)))
241 for quantile in self._parameters["Quantiles"]:
242 if not (0. <= float(quantile) <= 1.): continue
243 indice = int(nech * float(quantile) - 1./nech)
244 if YQ is None: YQ = YfQ[:,indice]
245 else: YQ = numpy.hstack((YQ,YfQ[:,indice]))
246 self.StoredVariables["SimulationQuantiles"].store( YQ )
247 if selfA._toStore("SampledStateForQuantiles"):
248 selfA.StoredVariables["SampledStateForQuantiles"].store( EXr.T )
249 if self._toStore("SimulatedObservationAtBackground"):
250 self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
251 if self._toStore("SimulatedObservationAtCurrentState"):
252 self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(HXa) )
253 if self._toStore("SimulatedObservationAtCurrentOptimum"):
254 self.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( numpy.ravel(HXa) )
255 if self._toStore("SimulatedObservationAtOptimum"):
256 self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
261 # ==============================================================================
262 if __name__ == "__main__":
263 print('\n AUTODIAGNOSTIC\n')