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):
91 logging.debug("%s Lancement"%self._name)
92 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
94 # Paramètres de pilotage
95 # ----------------------
96 self.setParameters(Parameters)
98 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):
99 Bounds = self._parameters["Bounds"]
100 logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
104 # Correction pour pallier a un bug de TNC sur le retour du Minimum
105 if self._parameters.has_key("Minimizer") is "TNC":
106 self.setParameterValue("StoreInternalVariables",True)
108 # Opérateur d'observation
109 # -----------------------
110 Hm = H["Direct"].appliedTo
111 Ha = H["Adjoint"].appliedInXTo
113 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
114 # ----------------------------------------------------
115 if H["AppliedToX"] is not None and H["AppliedToX"].has_key("HXb"):
116 HXb = H["AppliedToX"]["HXb"]
119 HXb = numpy.asmatrix(numpy.ravel( HXb )).T
121 # Calcul de l'innovation
122 # ----------------------
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))
129 # Précalcul des inversions de B et R
130 # ----------------------------------
133 elif self._parameters["B_scalar"] is not None:
134 BI = 1.0 / self._parameters["B_scalar"]
136 raise ValueError("Background error covariance matrix has to be properly defined!")
140 elif self._parameters["R_scalar"] is not None:
141 RI = 1.0 / self._parameters["R_scalar"]
143 raise ValueError("Observation error covariance matrix has to be properly defined!")
145 # Définition de la fonction-coût
146 # ------------------------------
148 _X = numpy.asmatrix(numpy.ravel( x )).T
150 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
151 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
152 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
153 J = float( Jb ) + float( Jo )
154 if self._parameters["StoreInternalVariables"]:
155 self.StoredVariables["CurrentState"].store( _X.A1 )
156 self.StoredVariables["CostFunctionJb"].store( Jb )
157 self.StoredVariables["CostFunctionJo"].store( Jo )
158 self.StoredVariables["CostFunctionJ" ].store( J )
161 def GradientOfCostFunction(x):
162 _X = numpy.asmatrix(numpy.ravel( x )).T
164 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
165 GradJb = BI * (_X - Xb)
166 GradJo = - Ha( (_X, RI * (Y - _HX)) )
167 GradJ = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
170 # Point de démarrage de l'optimisation : Xini = Xb
171 # ------------------------------------
172 if type(Xb) is type(numpy.matrix([])):
173 Xini = Xb.A1.tolist()
177 # Minimisation de la fonctionnelle
178 # --------------------------------
179 if self._parameters["Minimizer"] == "LBFGSB":
180 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
183 fprime = GradientOfCostFunction,
186 maxfun = self._parameters["MaximumNumberOfSteps"]-1,
187 factr = self._parameters["CostDecrementTolerance"]*1.e14,
188 pgtol = self._parameters["ProjectedGradientTolerance"],
191 nfeval = Informations['funcalls']
192 rc = Informations['warnflag']
193 elif self._parameters["Minimizer"] == "TNC":
194 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
197 fprime = GradientOfCostFunction,
200 maxfun = self._parameters["MaximumNumberOfSteps"],
201 pgtol = self._parameters["ProjectedGradientTolerance"],
202 ftol = self._parameters["CostDecrementTolerance"],
205 elif self._parameters["Minimizer"] == "CG":
206 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
209 fprime = GradientOfCostFunction,
211 maxiter = self._parameters["MaximumNumberOfSteps"],
212 gtol = self._parameters["GradientNormTolerance"],
216 elif self._parameters["Minimizer"] == "NCG":
217 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
220 fprime = GradientOfCostFunction,
222 maxiter = self._parameters["MaximumNumberOfSteps"],
223 avextol = self._parameters["CostDecrementTolerance"],
227 elif self._parameters["Minimizer"] == "BFGS":
228 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
231 fprime = GradientOfCostFunction,
233 maxiter = self._parameters["MaximumNumberOfSteps"],
234 gtol = self._parameters["GradientNormTolerance"],
239 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
241 StepMin = numpy.argmin( self.StoredVariables["CostFunctionJ"].valueserie() )
242 MinJ = self.StoredVariables["CostFunctionJ"].valueserie(step = StepMin)
244 # Correction pour pallier a un bug de TNC sur le retour du Minimum
245 # ----------------------------------------------------------------
246 if self._parameters["StoreInternalVariables"]:
247 Minimum = self.StoredVariables["CurrentState"].valueserie(step = StepMin)
249 # Obtention de l'analyse
250 # ----------------------
251 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
253 self.StoredVariables["Analysis"].store( Xa.A1 )
255 # Calcul de la covariance d'analyse
256 # ---------------------------------
257 if "APosterioriCovariance" in self._parameters["StoreSupplementaryCalculations"]:
258 Ht = H["Tangent"].asMatrix(ValueForMethodForm = Xa)
259 Ht = Ht.reshape(-1,len(Xa.A1)) # ADAO
263 _ee = numpy.matrix(numpy.zeros(nb)).T
266 _HtEE = numpy.asmatrix(numpy.ravel( _HtEE )).T
267 HessienneI.append( ( BI*_ee + Ha((Xa,RI*_HtEE)) ).A1 )
268 HessienneI = numpy.matrix( HessienneI )
269 if numpy.alltrue(numpy.isfinite( HessienneI )):
272 raise ValueError("The 3DVAR a posteriori covariance matrix A can not be calculated. Your problem is perhaps too non-linear?")
273 if logging.getLogger().level < logging.WARNING: # La verification n'a lieu qu'en debug
275 L = numpy.linalg.cholesky( A )
277 raise ValueError("The 3DVAR a posteriori covariance matrix A is not symmetric positive-definite. Check your B and R a priori covariances.")
278 self.StoredVariables["APosterioriCovariance"].store( A )
280 # Calculs et/ou stockages supplémentaires
281 # ---------------------------------------
282 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
283 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
284 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
285 self.StoredVariables["BMA"].store( numpy.ravel(Xb - Xa) )
286 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
287 self.StoredVariables["OMA"].store( numpy.ravel(Y - Hm(Xa)) )
288 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
289 self.StoredVariables["OMB"].store( numpy.ravel(d) )
290 if "SigmaObs2" in self._parameters["StoreSupplementaryCalculations"]:
291 self.StoredVariables["SigmaObs2"].store( float( (d.T * (Y-Hm(Xa))) / R.trace() ) )
293 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
294 logging.debug("%s Terminé"%self._name)
298 # ==============================================================================
299 if __name__ == "__main__":
300 print '\n AUTODIAGNOSTIC \n'