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, "BLUE")
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 = ["APosterioriCorrelations", "APosterioriCovariance", "APosterioriStandardDeviations", "APosterioriVariances", "BMA", "OMA", "OMB", "CurrentState", "CostFunctionJ", "CostFunctionJb", "CostFunctionJo", "Innovation", "SigmaBck2", "SigmaObs2", "MahalanobisConsistency", "SimulationQuantiles", "SimulatedObservationAtBackground", "SimulatedObservationAtCurrentState", "SimulatedObservationAtOptimum"]
44 self.defineRequiredParameter(
48 message = "Liste des valeurs de quantiles",
52 self.defineRequiredParameter(
54 typecast = numpy.random.seed,
55 message = "Graine fixée pour le générateur aléatoire",
57 self.defineRequiredParameter(
58 name = "NumberOfSamplesForQuantiles",
61 message = "Nombre d'échantillons simulés pour le calcul des quantiles",
64 self.defineRequiredParameter(
65 name = "SimulationForQuantiles",
68 message = "Type de simulation pour l'estimation des quantiles",
69 listval = ["Linear", "NonLinear"]
72 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
73 self._pre_run(Parameters)
75 Hm = HO["Tangent"].asMatrix(Xb)
76 Hm = Hm.reshape(Y.size,Xb.size) # ADAO & check shape
77 Ha = HO["Adjoint"].asMatrix(Xb)
78 Ha = Ha.reshape(Xb.size,Y.size) # ADAO & check shape
80 # Utilisation éventuelle d'un vecteur H(Xb) précalculé (sans cout)
81 # ----------------------------------------------------------------
82 if HO["AppliedInX"] is not None and "HXb" in HO["AppliedInX"]:
83 HXb = HO["AppliedInX"]["HXb"]
86 HXb = numpy.asmatrix(numpy.ravel( HXb )).T
87 if Y.size != HXb.size:
88 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))
89 if max(Y.shape) != max(HXb.shape):
90 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))
92 # Précalcul des inversions de B et R
93 # ----------------------------------
97 # Calcul de l'innovation
98 # ----------------------
101 # Calcul de la matrice de gain et de l'analyse
102 # --------------------------------------------
103 if Y.size <= Xb.size:
105 _u = numpy.linalg.solve( _A , d )
106 Xa = Xb + B * Ha * _u
108 _A = BI + Ha * RI * Hm
109 _u = numpy.linalg.solve( _A , Ha * RI * d )
111 self.StoredVariables["Analysis"].store( Xa.A1 )
113 # Calcul de la fonction coût
114 # --------------------------
115 if self._parameters["StoreInternalVariables"] or \
116 "CostFunctionJ" in self._parameters["StoreSupplementaryCalculations"] or \
117 "OMA" in self._parameters["StoreSupplementaryCalculations"] or \
118 "SigmaObs2" in self._parameters["StoreSupplementaryCalculations"] or \
119 "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"] or \
120 "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"] or \
121 "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
122 "SimulationQuantiles" in self._parameters["StoreSupplementaryCalculations"]:
125 if self._parameters["StoreInternalVariables"] or \
126 "CostFunctionJ" in self._parameters["StoreSupplementaryCalculations"] or \
127 "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"]:
129 Jb = float( 0.5 * (Xa - Xb).T * BI * (Xa - Xb) )
130 Jo = float( 0.5 * oma.T * RI * oma )
133 self.StoredVariables["CostFunctionJb"].store( Jb )
134 self.StoredVariables["CostFunctionJo"].store( Jo )
135 self.StoredVariables["CostFunctionJ" ].store( J )
137 # Calcul de la covariance d'analyse
138 # ---------------------------------
139 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"] or \
140 "SimulationQuantiles" in self._parameters["StoreSupplementaryCalculations"]:
141 if (Y.size <= Xb.size): K = B * Ha * (R + Hm * B * Ha).I
142 elif (Y.size > Xb.size): K = (BI + Ha * RI * Hm).I * Ha * RI
144 if min(A.shape) != max(A.shape):
145 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)))
146 if (numpy.diag(A) < 0).any():
147 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,))
148 if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
150 L = numpy.linalg.cholesky( A )
152 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,))
153 self.StoredVariables["APosterioriCovariance"].store( A )
155 # Calculs et/ou stockages supplémentaires
156 # ---------------------------------------
157 if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
158 self.StoredVariables["CurrentState"].store( numpy.ravel(Xa) )
159 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
160 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
161 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
162 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
163 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
164 self.StoredVariables["OMA"].store( numpy.ravel(oma) )
165 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
166 self.StoredVariables["OMB"].store( numpy.ravel(d) )
167 if "SigmaObs2" in self._parameters["StoreSupplementaryCalculations"]:
168 TraceR = R.trace(Y.size)
169 self.StoredVariables["SigmaObs2"].store( float( (d.T * (numpy.asmatrix(numpy.ravel(oma)).T)) ) / TraceR )
170 if "SigmaBck2" in self._parameters["StoreSupplementaryCalculations"]:
171 self.StoredVariables["SigmaBck2"].store( float( (d.T * Hm * (Xa - Xb))/(Hm * B * Hm.T).trace() ) )
172 if "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"]:
173 self.StoredVariables["MahalanobisConsistency"].store( float( 2.*J/d.size ) )
174 if "SimulationQuantiles" in self._parameters["StoreSupplementaryCalculations"]:
175 nech = self._parameters["NumberOfSamplesForQuantiles"]
177 for i in range(nech):
178 if self._parameters["SimulationForQuantiles"] == "Linear":
179 dXr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A) - Xa.A1).T
180 dYr = numpy.matrix(numpy.ravel( Hm * dXr )).T
182 elif self._parameters["SimulationForQuantiles"] == "NonLinear":
183 Xr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A)).T
184 Yr = numpy.matrix(numpy.ravel( Hm * Xr )).T
188 YfQ = numpy.hstack((YfQ,Yr))
191 for quantile in self._parameters["Quantiles"]:
192 if not (0. <= float(quantile) <= 1.): continue
193 indice = int(nech * float(quantile) - 1./nech)
194 if YQ is None: YQ = YfQ[:,indice]
195 else: YQ = numpy.hstack((YQ,YfQ[:,indice]))
196 self.StoredVariables["SimulationQuantiles"].store( YQ )
197 if "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
198 self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
199 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
200 self.StoredVariables["SimulatedObservationAtCurrentState"].store( numpy.ravel(HXa) )
201 if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
202 self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
207 # ==============================================================================
208 if __name__ == "__main__":
209 print('\n AUTODIAGNOSTIC \n')