1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2018 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",
43 "APosterioriCorrelations",
44 "APosterioriCovariance",
45 "APosterioriStandardDeviations",
46 "APosterioriVariances",
57 "MahalanobisConsistency",
58 "SimulationQuantiles",
59 "SimulatedObservationAtBackground",
60 "SimulatedObservationAtCurrentState",
61 "SimulatedObservationAtOptimum",
64 self.defineRequiredParameter(
68 message = "Liste des valeurs de quantiles",
72 self.defineRequiredParameter(
74 typecast = numpy.random.seed,
75 message = "Graine fixée pour le générateur aléatoire",
77 self.defineRequiredParameter(
78 name = "NumberOfSamplesForQuantiles",
81 message = "Nombre d'échantillons simulés pour le calcul des quantiles",
84 self.defineRequiredParameter(
85 name = "SimulationForQuantiles",
88 message = "Type de simulation pour l'estimation des quantiles",
89 listval = ["Linear", "NonLinear"]
91 self.requireInputArguments(
92 mandatory= ("Xb", "Y", "HO", "R", "B"),
95 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
96 self._pre_run(Parameters, Xb, Y, R, B, Q)
98 Hm = HO["Tangent"].asMatrix(Xb)
99 Hm = Hm.reshape(Y.size,Xb.size) # ADAO & check shape
100 Ha = HO["Adjoint"].asMatrix(Xb)
101 Ha = Ha.reshape(Xb.size,Y.size) # ADAO & check shape
102 H = HO["Direct"].appliedTo
104 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
105 # ----------------------------------------------------
106 if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
107 HXb = H( Xb, HO["AppliedInX"]["HXb"])
110 HXb = numpy.asmatrix(numpy.ravel( HXb )).T
111 if Y.size != HXb.size:
112 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))
113 if max(Y.shape) != max(HXb.shape):
114 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))
116 # Précalcul des inversions de B et R
117 # ----------------------------------
121 # Calcul de l'innovation
122 # ----------------------
125 # Calcul de la matrice de gain et de l'analyse
126 # --------------------------------------------
127 if Y.size <= Xb.size:
129 _u = numpy.linalg.solve( _A , d )
130 Xa = Xb + B * Ha * _u
132 _A = BI + Ha * RI * Hm
133 _u = numpy.linalg.solve( _A , Ha * RI * d )
135 self.StoredVariables["Analysis"].store( Xa.A1 )
137 # Calcul de la fonction coût
138 # --------------------------
139 if self._parameters["StoreInternalVariables"] or \
140 "CostFunctionJ" in self._parameters["StoreSupplementaryCalculations"] or \
141 "OMA" in self._parameters["StoreSupplementaryCalculations"] or \
142 "SigmaObs2" in self._parameters["StoreSupplementaryCalculations"] or \
143 "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"] or \
144 "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"] or \
145 "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
146 "SimulationQuantiles" in self._parameters["StoreSupplementaryCalculations"]:
147 HXa = numpy.matrix(numpy.ravel( H( Xa ) )).T
149 if self._parameters["StoreInternalVariables"] or \
150 "CostFunctionJ" in self._parameters["StoreSupplementaryCalculations"] or \
151 "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"]:
152 Jb = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
153 Jo = float( 0.5 * oma.T * RI * oma )
155 self.StoredVariables["CostFunctionJb"].store( Jb )
156 self.StoredVariables["CostFunctionJo"].store( Jo )
157 self.StoredVariables["CostFunctionJ" ].store( J )
159 # Calcul de la covariance d'analyse
160 # ---------------------------------
161 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"] or \
162 "SimulationQuantiles" in self._parameters["StoreSupplementaryCalculations"]:
163 if (Y.size <= Xb.size): K = B * Ha * (R + Hm * B * Ha).I
164 elif (Y.size > Xb.size): K = (BI + Ha * RI * Hm).I * Ha * RI
166 if min(A.shape) != max(A.shape):
167 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)))
168 if (numpy.diag(A) < 0).any():
169 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,))
170 if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
172 L = numpy.linalg.cholesky( A )
174 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,))
175 self.StoredVariables["APosterioriCovariance"].store( A )
177 # Calculs et/ou stockages supplémentaires
178 # ---------------------------------------
179 if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
180 self.StoredVariables["CurrentState"].store( numpy.ravel(Xa) )
181 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
182 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
183 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
184 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
185 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
186 self.StoredVariables["OMA"].store( numpy.ravel(oma) )
187 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
188 self.StoredVariables["OMB"].store( numpy.ravel(d) )
189 if "SigmaObs2" in self._parameters["StoreSupplementaryCalculations"]:
190 TraceR = R.trace(Y.size)
191 self.StoredVariables["SigmaObs2"].store( float( (d.T * (numpy.asmatrix(numpy.ravel(oma)).T)) ) / TraceR )
192 if "SigmaBck2" in self._parameters["StoreSupplementaryCalculations"]:
193 self.StoredVariables["SigmaBck2"].store( float( (d.T * Hm * (Xa - Xb))/(Hm * B * Hm.T).trace() ) )
194 if "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"]:
195 self.StoredVariables["MahalanobisConsistency"].store( float( 2.*J/d.size ) )
196 if "SimulationQuantiles" in self._parameters["StoreSupplementaryCalculations"]:
197 nech = self._parameters["NumberOfSamplesForQuantiles"]
198 HtM = HO["Tangent"].asMatrix(ValueForMethodForm = Xa)
199 HtM = HtM.reshape(Y.size,Xa.size) # ADAO & check shape
201 for i in range(nech):
202 if self._parameters["SimulationForQuantiles"] == "Linear":
203 dXr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A) - Xa.A1).T
204 dYr = numpy.matrix(numpy.ravel( HtM * dXr )).T
206 elif self._parameters["SimulationForQuantiles"] == "NonLinear":
207 Xr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A)).T
208 Yr = numpy.matrix(numpy.ravel( H( Xr ) )).T
212 YfQ = numpy.hstack((YfQ,Yr))
215 for quantile in self._parameters["Quantiles"]:
216 if not (0. <= float(quantile) <= 1.): continue
217 indice = int(nech * float(quantile) - 1./nech)
218 if YQ is None: YQ = YfQ[:,indice]
219 else: YQ = numpy.hstack((YQ,YfQ[:,indice]))
220 self.StoredVariables["SimulationQuantiles"].store( YQ )
221 if "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
222 self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
223 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
224 self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(HXa) )
225 if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
226 self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
231 # ==============================================================================
232 if __name__ == "__main__":
233 print('\n AUTODIAGNOSTIC \n')