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
23 from daCore import BasicObjects, PlatformInfo
24 m = PlatformInfo.SystemUsage()
29 if logging.getLogger().level < 30:
31 message = scipy.optimize.tnc.MSG_ALL
35 message = scipy.optimize.tnc.MSG_NONE
38 # ==============================================================================
39 class ElementaryAlgorithm(BasicObjects.Algorithm):
41 BasicObjects.Algorithm.__init__(self, "3DVAR")
42 self.defineRequiredParameter(
46 message = "Minimiseur utilisé",
47 listval = ["LBFGSB","TNC", "CG", "NCG", "BFGS"],
49 self.defineRequiredParameter(
50 name = "MaximumNumberOfSteps",
53 message = "Nombre maximal de pas d'optimisation",
56 self.defineRequiredParameter(
57 name = "CostDecrementTolerance",
60 message = "Diminution relative minimale du cout lors de l'arrêt",
62 self.defineRequiredParameter(
63 name = "ProjectedGradientTolerance",
66 message = "Maximum des composantes du gradient projeté lors de l'arrêt",
69 self.defineRequiredParameter(
70 name = "GradientNormTolerance",
73 message = "Maximum des composantes du gradient lors de l'arrêt",
75 self.defineRequiredParameter(
76 name = "CalculateAPosterioriCovariance",
79 message = "Calcul de la covariance a posteriori",
82 def run(self, Xb=None, Y=None, H=None, M=None, R=None, B=None, Q=None, Parameters=None):
84 Calcul de l'estimateur 3D-VAR
86 logging.debug("%s Lancement"%self._name)
87 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("Mo")))
89 # Paramètres de pilotage
90 # ----------------------
91 self.setParameters(Parameters)
93 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):
94 Bounds = self._parameters["Bounds"]
95 logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
99 # Opérateur d'observation
100 # -----------------------
101 Hm = H["Direct"].appliedTo
102 Ha = H["Adjoint"].appliedInXTo
104 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
105 # ----------------------------------------------------
106 if H["AppliedToX"] is not None and H["AppliedToX"].has_key("HXb"):
107 logging.debug("%s Utilisation de HXb"%self._name)
108 HXb = H["AppliedToX"]["HXb"]
110 logging.debug("%s Calcul de Hm(Xb)"%self._name)
112 HXb = numpy.asmatrix(HXb).flatten().T
114 # Calcul de l'innovation
115 # ----------------------
116 if Y.size != HXb.size:
117 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))
118 if max(Y.shape) != max(HXb.shape):
119 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))
121 logging.debug("%s Innovation d = %s"%(self._name, d))
123 # Précalcul des inversions de B et R
124 # ----------------------------------
127 elif self._parameters["B_scalar"] is not None:
128 BI = 1.0 / self._parameters["B_scalar"]
130 raise ValueError("Background error covariance matrix has to be properly defined!")
134 elif self._parameters["R_scalar"] is not None:
135 RI = 1.0 / self._parameters["R_scalar"]
137 raise ValueError("Observation error covariance matrix has to be properly defined!")
139 # Définition de la fonction-coût
140 # ------------------------------
142 _X = numpy.asmatrix(x).flatten().T
143 logging.debug("%s CostFunction X = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
145 _HX = numpy.asmatrix(_HX).flatten().T
146 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
147 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
148 J = float( Jb ) + float( Jo )
149 logging.debug("%s CostFunction Jb = %s"%(self._name, Jb))
150 logging.debug("%s CostFunction Jo = %s"%(self._name, Jo))
151 logging.debug("%s CostFunction J = %s"%(self._name, J))
152 self.StoredVariables["CurrentState"].store( _X.A1 )
153 self.StoredVariables["CostFunctionJb"].store( Jb )
154 self.StoredVariables["CostFunctionJo"].store( Jo )
155 self.StoredVariables["CostFunctionJ" ].store( J )
158 def GradientOfCostFunction(x):
159 _X = numpy.asmatrix(x).flatten().T
160 logging.debug("%s GradientOfCostFunction X = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
162 _HX = numpy.asmatrix(_HX).flatten().T
163 GradJb = BI * (_X - Xb)
164 GradJo = - Ha( (_X, RI * (Y - _HX)) )
165 GradJ = numpy.asmatrix( GradJb ).flatten().T + numpy.asmatrix( GradJo ).flatten().T
166 logging.debug("%s GradientOfCostFunction GradJb = %s"%(self._name, numpy.asmatrix( GradJb ).flatten()))
167 logging.debug("%s GradientOfCostFunction GradJo = %s"%(self._name, numpy.asmatrix( GradJo ).flatten()))
168 logging.debug("%s GradientOfCostFunction GradJ = %s"%(self._name, numpy.asmatrix( GradJ ).flatten()))
171 # Point de démarrage de l'optimisation : Xini = Xb
172 # ------------------------------------
173 if type(Xb) is type(numpy.matrix([])):
174 Xini = Xb.A1.tolist()
177 logging.debug("%s Point de démarrage Xini = %s"%(self._name, Xini))
179 # Minimisation de la fonctionnelle
180 # --------------------------------
181 if self._parameters["Minimizer"] == "LBFGSB":
182 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
185 fprime = GradientOfCostFunction,
188 maxfun = self._parameters["MaximumNumberOfSteps"]-1,
189 factr = self._parameters["CostDecrementTolerance"]*1.e14,
190 pgtol = self._parameters["ProjectedGradientTolerance"],
193 nfeval = Informations['funcalls']
194 rc = Informations['warnflag']
195 elif self._parameters["Minimizer"] == "TNC":
196 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
199 fprime = GradientOfCostFunction,
202 maxfun = self._parameters["MaximumNumberOfSteps"],
203 pgtol = self._parameters["ProjectedGradientTolerance"],
204 ftol = self._parameters["CostDecrementTolerance"],
207 elif self._parameters["Minimizer"] == "CG":
208 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
211 fprime = GradientOfCostFunction,
213 maxiter = self._parameters["MaximumNumberOfSteps"],
214 gtol = self._parameters["GradientNormTolerance"],
218 elif self._parameters["Minimizer"] == "NCG":
219 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
222 fprime = GradientOfCostFunction,
224 maxiter = self._parameters["MaximumNumberOfSteps"],
225 avextol = self._parameters["CostDecrementTolerance"],
229 elif self._parameters["Minimizer"] == "BFGS":
230 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
233 fprime = GradientOfCostFunction,
235 maxiter = self._parameters["MaximumNumberOfSteps"],
236 gtol = self._parameters["GradientNormTolerance"],
241 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
243 # Correction pour pallier a un bug de TNC sur le retour du Minimum
244 # ----------------------------------------------------------------
245 StepMin = numpy.argmin( self.StoredVariables["CostFunctionJ"].valueserie() )
246 MinJ = self.StoredVariables["CostFunctionJ"].valueserie(step = StepMin)
247 Minimum = self.StoredVariables["CurrentState"].valueserie(step = StepMin)
249 logging.debug("%s %s Step of min cost = %s"%(self._name, self._parameters["Minimizer"], StepMin))
250 logging.debug("%s %s Minimum cost = %s"%(self._name, self._parameters["Minimizer"], MinJ))
251 logging.debug("%s %s Minimum state = %s"%(self._name, self._parameters["Minimizer"], Minimum))
252 logging.debug("%s %s Nb of F = %s"%(self._name, self._parameters["Minimizer"], nfeval))
253 logging.debug("%s %s RetCode = %s"%(self._name, self._parameters["Minimizer"], rc))
255 # Obtention de l'analyse
256 # ----------------------
257 Xa = numpy.asmatrix(Minimum).T
258 logging.debug("%s Analyse Xa = %s"%(self._name, Xa))
260 self.StoredVariables["Analysis"].store( Xa.A1 )
261 self.StoredVariables["Innovation"].store( d.A1 )
263 # Calcul de la covariance d'analyse
264 # ---------------------------------
265 if self._parameters["CalculateAPosterioriCovariance"]:
269 ee = numpy.matrix(numpy.zeros(nb)).T
271 Hessienne.append( ( BI*ee + Ha((Xa,RI*Hm(ee))) ).A1 )
272 Hessienne = numpy.matrix( Hessienne )
274 self.StoredVariables["APosterioriCovariance"].store( A )
276 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("MB")))
277 logging.debug("%s Terminé"%self._name)
281 # ==============================================================================
282 if __name__ == "__main__":
283 print '\n AUTODIAGNOSTIC \n'