1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2012 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, PlatformInfo
25 m = PlatformInfo.SystemUsage()
30 if logging.getLogger().level < logging.WARNING:
32 message = scipy.optimize.tnc.MSG_ALL
36 message = scipy.optimize.tnc.MSG_NONE
39 # ==============================================================================
40 class ElementaryAlgorithm(BasicObjects.Algorithm):
42 BasicObjects.Algorithm.__init__(self, "3DVAR")
43 self.defineRequiredParameter(
47 message = "Minimiseur utilisé",
48 listval = ["LBFGSB","TNC", "CG", "NCG", "BFGS"],
50 self.defineRequiredParameter(
51 name = "MaximumNumberOfSteps",
54 message = "Nombre maximal de pas d'optimisation",
57 self.defineRequiredParameter(
58 name = "CostDecrementTolerance",
61 message = "Diminution relative minimale du cout lors de l'arrêt",
63 self.defineRequiredParameter(
64 name = "ProjectedGradientTolerance",
67 message = "Maximum des composantes du gradient projeté lors de l'arrêt",
70 self.defineRequiredParameter(
71 name = "GradientNormTolerance",
74 message = "Maximum des composantes du gradient lors de l'arrêt",
76 self.defineRequiredParameter(
77 name = "StoreInternalVariables",
80 message = "Stockage des variables internes ou intermédiaires du calcul",
82 self.defineRequiredParameter(
83 name = "StoreSupplementaryCalculations",
86 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
87 listval = ["APosterioriCovariance", "BMA", "OMA", "OMB", "Innovation", "SigmaObs2"]
90 def run(self, Xb=None, Y=None, H=None, M=None, R=None, B=None, Q=None, Parameters=None):
92 Calcul de l'estimateur 3D-VAR
94 logging.debug("%s Lancement"%self._name)
95 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
97 # Paramètres de pilotage
98 # ----------------------
99 self.setParameters(Parameters)
101 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):
102 Bounds = self._parameters["Bounds"]
103 logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
107 # Correction pour pallier a un bug de TNC sur le retour du Minimum
108 if self._parameters.has_key("Minimizer") is "TNC":
109 self.setParameterValue("StoreInternalVariables",True)
111 # Opérateur d'observation
112 # -----------------------
113 Hm = H["Direct"].appliedTo
114 Ha = H["Adjoint"].appliedInXTo
116 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
117 # ----------------------------------------------------
118 if H["AppliedToX"] is not None and H["AppliedToX"].has_key("HXb"):
119 logging.debug("%s Utilisation de HXb"%self._name)
120 HXb = H["AppliedToX"]["HXb"]
122 logging.debug("%s Calcul de Hm(Xb)"%self._name)
124 HXb = numpy.asmatrix(HXb).flatten().T
126 # Calcul de l'innovation
127 # ----------------------
128 if Y.size != HXb.size:
129 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))
130 if max(Y.shape) != max(HXb.shape):
131 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))
133 logging.debug("%s Innovation d = %s"%(self._name, d))
135 # Précalcul des inversions de B et R
136 # ----------------------------------
139 elif self._parameters["B_scalar"] is not None:
140 BI = 1.0 / self._parameters["B_scalar"]
142 raise ValueError("Background error covariance matrix has to be properly defined!")
146 elif self._parameters["R_scalar"] is not None:
147 RI = 1.0 / self._parameters["R_scalar"]
149 raise ValueError("Observation error covariance matrix has to be properly defined!")
151 # Définition de la fonction-coût
152 # ------------------------------
154 _X = numpy.asmatrix(x).flatten().T
155 logging.debug("%s CostFunction X = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
157 _HX = numpy.asmatrix(_HX).flatten().T
158 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
159 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
160 J = float( Jb ) + float( Jo )
161 logging.debug("%s CostFunction Jb = %s"%(self._name, Jb))
162 logging.debug("%s CostFunction Jo = %s"%(self._name, Jo))
163 logging.debug("%s CostFunction J = %s"%(self._name, J))
164 if self._parameters["StoreInternalVariables"]:
165 self.StoredVariables["CurrentState"].store( _X.A1 )
166 self.StoredVariables["CostFunctionJb"].store( Jb )
167 self.StoredVariables["CostFunctionJo"].store( Jo )
168 self.StoredVariables["CostFunctionJ" ].store( J )
171 def GradientOfCostFunction(x):
172 _X = numpy.asmatrix(x).flatten().T
173 logging.debug("%s GradientOfCostFunction X = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
175 _HX = numpy.asmatrix(_HX).flatten().T
176 GradJb = BI * (_X - Xb)
177 GradJo = - Ha( (_X, RI * (Y - _HX)) )
178 GradJ = numpy.asmatrix( GradJb ).flatten().T + numpy.asmatrix( GradJo ).flatten().T
179 logging.debug("%s GradientOfCostFunction GradJb = %s"%(self._name, numpy.asmatrix( GradJb ).flatten()))
180 logging.debug("%s GradientOfCostFunction GradJo = %s"%(self._name, numpy.asmatrix( GradJo ).flatten()))
181 logging.debug("%s GradientOfCostFunction GradJ = %s"%(self._name, numpy.asmatrix( GradJ ).flatten()))
184 # Point de démarrage de l'optimisation : Xini = Xb
185 # ------------------------------------
186 if type(Xb) is type(numpy.matrix([])):
187 Xini = Xb.A1.tolist()
190 logging.debug("%s Point de démarrage Xini = %s"%(self._name, Xini))
192 # Minimisation de la fonctionnelle
193 # --------------------------------
194 if self._parameters["Minimizer"] == "LBFGSB":
195 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
198 fprime = GradientOfCostFunction,
201 maxfun = self._parameters["MaximumNumberOfSteps"]-1,
202 factr = self._parameters["CostDecrementTolerance"]*1.e14,
203 pgtol = self._parameters["ProjectedGradientTolerance"],
206 nfeval = Informations['funcalls']
207 rc = Informations['warnflag']
208 elif self._parameters["Minimizer"] == "TNC":
209 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
212 fprime = GradientOfCostFunction,
215 maxfun = self._parameters["MaximumNumberOfSteps"],
216 pgtol = self._parameters["ProjectedGradientTolerance"],
217 ftol = self._parameters["CostDecrementTolerance"],
220 elif self._parameters["Minimizer"] == "CG":
221 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
224 fprime = GradientOfCostFunction,
226 maxiter = self._parameters["MaximumNumberOfSteps"],
227 gtol = self._parameters["GradientNormTolerance"],
231 elif self._parameters["Minimizer"] == "NCG":
232 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
235 fprime = GradientOfCostFunction,
237 maxiter = self._parameters["MaximumNumberOfSteps"],
238 avextol = self._parameters["CostDecrementTolerance"],
242 elif self._parameters["Minimizer"] == "BFGS":
243 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
246 fprime = GradientOfCostFunction,
248 maxiter = self._parameters["MaximumNumberOfSteps"],
249 gtol = self._parameters["GradientNormTolerance"],
254 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
256 StepMin = numpy.argmin( self.StoredVariables["CostFunctionJ"].valueserie() )
257 MinJ = self.StoredVariables["CostFunctionJ"].valueserie(step = StepMin)
259 # Correction pour pallier a un bug de TNC sur le retour du Minimum
260 # ----------------------------------------------------------------
261 if self._parameters["StoreInternalVariables"]:
262 Minimum = self.StoredVariables["CurrentState"].valueserie(step = StepMin)
264 logging.debug("%s %s Step of min cost = %s"%(self._name, self._parameters["Minimizer"], StepMin))
265 logging.debug("%s %s Minimum cost = %s"%(self._name, self._parameters["Minimizer"], MinJ))
266 logging.debug("%s %s Minimum state = %s"%(self._name, self._parameters["Minimizer"], Minimum))
267 logging.debug("%s %s Nb of F = %s"%(self._name, self._parameters["Minimizer"], nfeval))
268 logging.debug("%s %s RetCode = %s"%(self._name, self._parameters["Minimizer"], rc))
270 # Obtention de l'analyse
271 # ----------------------
272 Xa = numpy.asmatrix(Minimum).flatten().T
273 logging.debug("%s Analyse Xa = %s"%(self._name, Xa))
275 self.StoredVariables["Analysis"].store( Xa.A1 )
277 # Calcul de la covariance d'analyse
278 # ---------------------------------
279 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
283 _ee = numpy.matrix(numpy.zeros(nb)).T
286 _HmEE = numpy.asmatrix(_HmEE).flatten().T
287 HessienneI.append( ( BI*_ee + Ha((Xa,RI*_HmEE)) ).A1 )
288 HessienneI = numpy.matrix( HessienneI )
290 if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
292 L = numpy.linalg.cholesky( A )
294 raise ValueError("The 3DVAR a posteriori covariance matrix A is not symmetric positive-definite. Check your B and R a priori covariances.")
295 self.StoredVariables["APosterioriCovariance"].store( A )
297 # Calculs et/ou stockages supplémentaires
298 # ---------------------------------------
299 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
300 self.StoredVariables["Innovation"].store( numpy.asmatrix(d).flatten().A1 )
301 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
302 self.StoredVariables["BMA"].store( numpy.asmatrix(Xb - Xa).flatten().A1 )
303 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
304 self.StoredVariables["OMA"].store( numpy.asmatrix(Y - Hm(Xa)).flatten().A1 )
305 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
306 self.StoredVariables["OMB"].store( numpy.asmatrix(d).flatten().A1 )
307 if "SigmaObs2" in self._parameters["StoreSupplementaryCalculations"]:
308 self.StoredVariables["SigmaObs2"].store( float( (d.T * (Y-Hm(Xa))) / R.trace() ) )
310 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
311 logging.debug("%s Terminé"%self._name)
315 # ==============================================================================
316 if __name__ == "__main__":
317 print '\n AUTODIAGNOSTIC \n'