1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2016 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
25 import numpy, scipy.optimize
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
30 BasicObjects.Algorithm.__init__(self, "3DVAR")
31 self.defineRequiredParameter(
35 message = "Minimiseur utilisé",
36 listval = ["LBFGSB","TNC", "CG", "NCG", "BFGS"],
38 self.defineRequiredParameter(
39 name = "MaximumNumberOfSteps",
42 message = "Nombre maximal de pas d'optimisation",
45 self.defineRequiredParameter(
46 name = "CostDecrementTolerance",
49 message = "Diminution relative minimale du cout lors de l'arrêt",
51 self.defineRequiredParameter(
52 name = "ProjectedGradientTolerance",
55 message = "Maximum des composantes du gradient projeté lors de l'arrêt",
58 self.defineRequiredParameter(
59 name = "GradientNormTolerance",
62 message = "Maximum des composantes du gradient lors de l'arrêt",
64 self.defineRequiredParameter(
65 name = "StoreInternalVariables",
68 message = "Stockage des variables internes ou intermédiaires du calcul",
70 self.defineRequiredParameter(
71 name = "StoreSupplementaryCalculations",
74 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
75 listval = ["APosterioriCorrelations", "APosterioriCovariance", "APosterioriStandardDeviations", "APosterioriVariances", "BMA", "OMA", "OMB", "CostFunctionJ", "CostFunctionJb", "CostFunctionJo", "CurrentState", "CurrentOptimum", "IndexOfOptimum", "Innovation", "InnovationAtCurrentState", "CostFunctionJAtCurrentOptimum", "SigmaObs2", "MahalanobisConsistency", "SimulationQuantiles", "SimulatedObservationAtBackground", "SimulatedObservationAtCurrentState", "SimulatedObservationAtOptimum", "SimulatedObservationAtCurrentOptimum"]
77 self.defineRequiredParameter(
81 message = "Liste des valeurs de quantiles",
85 self.defineRequiredParameter(
87 typecast = numpy.random.seed,
88 message = "Graine fixée pour le générateur aléatoire",
90 self.defineRequiredParameter(
91 name = "NumberOfSamplesForQuantiles",
94 message = "Nombre d'échantillons simulés pour le calcul des quantiles",
97 self.defineRequiredParameter(
98 name = "SimulationForQuantiles",
101 message = "Type de simulation pour l'estimation des quantiles",
102 listval = ["Linear", "NonLinear"]
104 self.defineRequiredParameter( # Pas de type
106 message = "Liste des valeurs de bornes",
109 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
111 if logging.getLogger().level < logging.WARNING:
112 self.__iprint, self.__disp = 1, 1
113 self.__message = scipy.optimize.tnc.MSG_ALL
115 self.__iprint, self.__disp = -1, 0
116 self.__message = scipy.optimize.tnc.MSG_NONE
118 # Paramètres de pilotage
119 # ----------------------
120 self.setParameters(Parameters)
122 if self._parameters.has_key("Bounds") and (type(self._parameters["Bounds"]) is type([]) or type(self._parameters["Bounds"]) is type(())) and (len(self._parameters["Bounds"]) > 0):
123 Bounds = self._parameters["Bounds"]
124 logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
128 # Correction pour pallier a un bug de TNC sur le retour du Minimum
129 if self._parameters.has_key("Minimizer") == "TNC":
130 self.setParameterValue("StoreInternalVariables",True)
134 Hm = HO["Direct"].appliedTo
135 Ha = HO["Adjoint"].appliedInXTo
137 # Utilisation éventuelle d'un vecteur H(Xb) précalculé (sans cout)
138 # ----------------------------------------------------------------
139 if HO["AppliedToX"] is not None and HO["AppliedToX"].has_key("HXb"):
140 HXb = Hm( Xb, HO["AppliedToX"]["HXb"])
143 HXb = numpy.asmatrix(numpy.ravel( HXb )).T
144 if Y.size != HXb.size:
145 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))
146 if max(Y.shape) != max(HXb.shape):
147 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))
149 # Précalcul des inversions de B et R
150 # ----------------------------------
154 # Définition de la fonction-coût
155 # ------------------------------
157 _X = numpy.asmatrix(numpy.ravel( x )).T
158 if self._parameters["StoreInternalVariables"] or \
159 "CurrentState" in self._parameters["StoreSupplementaryCalculations"] or \
160 "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
161 self.StoredVariables["CurrentState"].store( _X )
163 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
164 _Innovation = Y - _HX
165 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"] or \
166 "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
167 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
168 if "InnovationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
169 self.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
171 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
172 Jo = 0.5 * _Innovation.T * RI * _Innovation
173 J = float( Jb ) + float( Jo )
175 self.StoredVariables["CostFunctionJb"].store( Jb )
176 self.StoredVariables["CostFunctionJo"].store( Jo )
177 self.StoredVariables["CostFunctionJ" ].store( J )
178 if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
179 "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
180 "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
181 "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
182 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
183 if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"]:
184 self.StoredVariables["IndexOfOptimum"].store( IndexMin )
185 if "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
186 self.StoredVariables["CurrentOptimum"].store( self.StoredVariables["CurrentState"][IndexMin] )
187 if "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
188 self.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] )
189 if "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
190 self.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJb"][IndexMin] )
191 self.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJo"][IndexMin] )
192 self.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( self.StoredVariables["CostFunctionJ" ][IndexMin] )
195 def GradientOfCostFunction(x):
196 _X = numpy.asmatrix(numpy.ravel( x )).T
198 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
199 GradJb = BI * (_X - Xb)
200 GradJo = - Ha( (_X, RI * (Y - _HX)) )
201 GradJ = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
204 # Point de démarrage de l'optimisation : Xini = Xb
205 # ------------------------------------
206 Xini = numpy.ravel(Xb)
208 # Minimisation de la fonctionnelle
209 # --------------------------------
210 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
212 if self._parameters["Minimizer"] == "LBFGSB":
213 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
216 fprime = GradientOfCostFunction,
219 maxfun = self._parameters["MaximumNumberOfSteps"]-1,
220 factr = self._parameters["CostDecrementTolerance"]*1.e14,
221 pgtol = self._parameters["ProjectedGradientTolerance"],
222 iprint = self.__iprint,
224 nfeval = Informations['funcalls']
225 rc = Informations['warnflag']
226 elif self._parameters["Minimizer"] == "TNC":
227 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
230 fprime = GradientOfCostFunction,
233 maxfun = self._parameters["MaximumNumberOfSteps"],
234 pgtol = self._parameters["ProjectedGradientTolerance"],
235 ftol = self._parameters["CostDecrementTolerance"],
236 messages = self.__message,
238 elif self._parameters["Minimizer"] == "CG":
239 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
242 fprime = GradientOfCostFunction,
244 maxiter = self._parameters["MaximumNumberOfSteps"],
245 gtol = self._parameters["GradientNormTolerance"],
249 elif self._parameters["Minimizer"] == "NCG":
250 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
253 fprime = GradientOfCostFunction,
255 maxiter = self._parameters["MaximumNumberOfSteps"],
256 avextol = self._parameters["CostDecrementTolerance"],
260 elif self._parameters["Minimizer"] == "BFGS":
261 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
264 fprime = GradientOfCostFunction,
266 maxiter = self._parameters["MaximumNumberOfSteps"],
267 gtol = self._parameters["GradientNormTolerance"],
272 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
274 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
275 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
277 # Correction pour pallier a un bug de TNC sur le retour du Minimum
278 # ----------------------------------------------------------------
279 if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
280 Minimum = self.StoredVariables["CurrentState"][IndexMin]
282 # Obtention de l'analyse
283 # ----------------------
284 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
286 self.StoredVariables["Analysis"].store( Xa.A1 )
288 if "OMA" in self._parameters["StoreSupplementaryCalculations"] or \
289 "SigmaObs2" in self._parameters["StoreSupplementaryCalculations"] or \
290 "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
291 "SimulationQuantiles" in self._parameters["StoreSupplementaryCalculations"]:
292 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
293 HXa = self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
294 elif "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
295 HXa = self.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
299 # Calcul de la covariance d'analyse
300 # ---------------------------------
301 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"] or \
302 "SimulationQuantiles" in self._parameters["StoreSupplementaryCalculations"]:
303 HtM = HO["Tangent"].asMatrix(ValueForMethodForm = Xa)
304 HtM = HtM.reshape(Y.size,Xa.size) # ADAO & check shape
305 HaM = HO["Adjoint"].asMatrix(ValueForMethodForm = Xa)
306 HaM = HaM.reshape(Xa.size,Y.size) # ADAO & check shape
310 _ee = numpy.matrix(numpy.zeros(nb)).T
312 _HtEE = numpy.dot(HtM,_ee)
313 _HtEE = numpy.asmatrix(numpy.ravel( _HtEE )).T
314 HessienneI.append( numpy.ravel( BI*_ee + HaM * (RI * _HtEE) ) )
315 HessienneI = numpy.matrix( HessienneI )
317 if min(A.shape) != max(A.shape):
318 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)))
319 if (numpy.diag(A) < 0).any():
320 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,))
321 if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
323 L = numpy.linalg.cholesky( A )
325 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,))
326 self.StoredVariables["APosterioriCovariance"].store( A )
328 # Calculs et/ou stockages supplémentaires
329 # ---------------------------------------
330 if "Innovation" in self._parameters["StoreSupplementaryCalculations"] or \
331 "OMB" in self._parameters["StoreSupplementaryCalculations"] or \
332 "SigmaObs2" in self._parameters["StoreSupplementaryCalculations"] or \
333 "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"]:
335 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
336 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
337 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
338 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
339 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
340 self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
341 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
342 self.StoredVariables["OMB"].store( numpy.ravel(d) )
343 if "SigmaObs2" in self._parameters["StoreSupplementaryCalculations"]:
344 TraceR = R.trace(Y.size)
345 self.StoredVariables["SigmaObs2"].store( float( (d.T * (numpy.asmatrix(numpy.ravel(Y)).T-numpy.asmatrix(numpy.ravel(HXa)).T)) ) / TraceR )
346 if "MahalanobisConsistency" in self._parameters["StoreSupplementaryCalculations"]:
347 self.StoredVariables["MahalanobisConsistency"].store( float( 2.*MinJ/d.size ) )
348 if "SimulationQuantiles" in self._parameters["StoreSupplementaryCalculations"]:
349 Qtls = map(float, self._parameters["Quantiles"])
350 nech = self._parameters["NumberOfSamplesForQuantiles"]
351 HXa = numpy.matrix(numpy.ravel( HXa )).T
353 for i in range(nech):
354 if self._parameters["SimulationForQuantiles"] == "Linear":
355 dXr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A) - Xa.A1).T
356 dYr = numpy.matrix(numpy.ravel( HtM * dXr )).T
358 elif self._parameters["SimulationForQuantiles"] == "NonLinear":
359 Xr = numpy.matrix(numpy.random.multivariate_normal(Xa.A1,A)).T
360 Yr = numpy.matrix(numpy.ravel( Hm( Xr ) )).T
364 YfQ = numpy.hstack((YfQ,Yr))
367 for quantile in Qtls:
368 if not (0. <= quantile <= 1.): continue
369 indice = int(nech * quantile - 1./nech)
370 if YQ is None: YQ = YfQ[:,indice]
371 else: YQ = numpy.hstack((YQ,YfQ[:,indice]))
372 self.StoredVariables["SimulationQuantiles"].store( YQ )
373 if "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
374 self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
375 if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
376 self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
381 # ==============================================================================
382 if __name__ == "__main__":
383 print '\n AUTODIAGNOSTIC \n'