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",
81 self.defineRequiredParameter(
82 name = "StoreInternalVariables",
85 message = "Stockage des variables internes ou intermédiaires du calcul",
88 def run(self, Xb=None, Y=None, H=None, M=None, R=None, B=None, Q=None, Parameters=None):
90 Calcul de l'estimateur 3D-VAR
92 logging.debug("%s Lancement"%self._name)
93 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("Mo")))
95 # Paramètres de pilotage
96 # ----------------------
97 self.setParameters(Parameters)
99 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):
100 Bounds = self._parameters["Bounds"]
101 logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
105 # Correction pour pallier a un bug de TNC sur le retour du Minimum
106 if self._parameters.has_key("Minimizer") is "TNC":
107 self.setParameterValue("StoreInternalVariables",True)
109 # Opérateur d'observation
110 # -----------------------
111 Hm = H["Direct"].appliedTo
112 Ha = H["Adjoint"].appliedInXTo
114 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
115 # ----------------------------------------------------
116 if H["AppliedToX"] is not None and H["AppliedToX"].has_key("HXb"):
117 logging.debug("%s Utilisation de HXb"%self._name)
118 HXb = H["AppliedToX"]["HXb"]
120 logging.debug("%s Calcul de Hm(Xb)"%self._name)
122 HXb = numpy.asmatrix(HXb).flatten().T
124 # Calcul de l'innovation
125 # ----------------------
126 if Y.size != HXb.size:
127 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))
128 if max(Y.shape) != max(HXb.shape):
129 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))
131 logging.debug("%s Innovation d = %s"%(self._name, d))
133 # Précalcul des inversions de B et R
134 # ----------------------------------
137 elif self._parameters["B_scalar"] is not None:
138 BI = 1.0 / self._parameters["B_scalar"]
140 raise ValueError("Background error covariance matrix has to be properly defined!")
144 elif self._parameters["R_scalar"] is not None:
145 RI = 1.0 / self._parameters["R_scalar"]
147 raise ValueError("Observation error covariance matrix has to be properly defined!")
149 # Définition de la fonction-coût
150 # ------------------------------
152 _X = numpy.asmatrix(x).flatten().T
153 logging.debug("%s CostFunction X = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
155 _HX = numpy.asmatrix(_HX).flatten().T
156 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
157 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
158 J = float( Jb ) + float( Jo )
159 logging.debug("%s CostFunction Jb = %s"%(self._name, Jb))
160 logging.debug("%s CostFunction Jo = %s"%(self._name, Jo))
161 logging.debug("%s CostFunction J = %s"%(self._name, J))
162 if self._parameters["StoreInternalVariables"]:
163 self.StoredVariables["CurrentState"].store( _X.A1 )
164 self.StoredVariables["CostFunctionJb"].store( Jb )
165 self.StoredVariables["CostFunctionJo"].store( Jo )
166 self.StoredVariables["CostFunctionJ" ].store( J )
169 def GradientOfCostFunction(x):
170 _X = numpy.asmatrix(x).flatten().T
171 logging.debug("%s GradientOfCostFunction X = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
173 _HX = numpy.asmatrix(_HX).flatten().T
174 GradJb = BI * (_X - Xb)
175 GradJo = - Ha( (_X, RI * (Y - _HX)) )
176 GradJ = numpy.asmatrix( GradJb ).flatten().T + numpy.asmatrix( GradJo ).flatten().T
177 logging.debug("%s GradientOfCostFunction GradJb = %s"%(self._name, numpy.asmatrix( GradJb ).flatten()))
178 logging.debug("%s GradientOfCostFunction GradJo = %s"%(self._name, numpy.asmatrix( GradJo ).flatten()))
179 logging.debug("%s GradientOfCostFunction GradJ = %s"%(self._name, numpy.asmatrix( GradJ ).flatten()))
182 # Point de démarrage de l'optimisation : Xini = Xb
183 # ------------------------------------
184 if type(Xb) is type(numpy.matrix([])):
185 Xini = Xb.A1.tolist()
188 logging.debug("%s Point de démarrage Xini = %s"%(self._name, Xini))
190 # Minimisation de la fonctionnelle
191 # --------------------------------
192 if self._parameters["Minimizer"] == "LBFGSB":
193 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
196 fprime = GradientOfCostFunction,
199 maxfun = self._parameters["MaximumNumberOfSteps"]-1,
200 factr = self._parameters["CostDecrementTolerance"]*1.e14,
201 pgtol = self._parameters["ProjectedGradientTolerance"],
204 nfeval = Informations['funcalls']
205 rc = Informations['warnflag']
206 elif self._parameters["Minimizer"] == "TNC":
207 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
210 fprime = GradientOfCostFunction,
213 maxfun = self._parameters["MaximumNumberOfSteps"],
214 pgtol = self._parameters["ProjectedGradientTolerance"],
215 ftol = self._parameters["CostDecrementTolerance"],
218 elif self._parameters["Minimizer"] == "CG":
219 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
222 fprime = GradientOfCostFunction,
224 maxiter = self._parameters["MaximumNumberOfSteps"],
225 gtol = self._parameters["GradientNormTolerance"],
229 elif self._parameters["Minimizer"] == "NCG":
230 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
233 fprime = GradientOfCostFunction,
235 maxiter = self._parameters["MaximumNumberOfSteps"],
236 avextol = self._parameters["CostDecrementTolerance"],
240 elif self._parameters["Minimizer"] == "BFGS":
241 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
244 fprime = GradientOfCostFunction,
246 maxiter = self._parameters["MaximumNumberOfSteps"],
247 gtol = self._parameters["GradientNormTolerance"],
252 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
254 StepMin = numpy.argmin( self.StoredVariables["CostFunctionJ"].valueserie() )
255 MinJ = self.StoredVariables["CostFunctionJ"].valueserie(step = StepMin)
257 # Correction pour pallier a un bug de TNC sur le retour du Minimum
258 # ----------------------------------------------------------------
259 if self._parameters["StoreInternalVariables"]:
260 Minimum = self.StoredVariables["CurrentState"].valueserie(step = StepMin)
262 logging.debug("%s %s Step of min cost = %s"%(self._name, self._parameters["Minimizer"], StepMin))
263 logging.debug("%s %s Minimum cost = %s"%(self._name, self._parameters["Minimizer"], MinJ))
264 logging.debug("%s %s Minimum state = %s"%(self._name, self._parameters["Minimizer"], Minimum))
265 logging.debug("%s %s Nb of F = %s"%(self._name, self._parameters["Minimizer"], nfeval))
266 logging.debug("%s %s RetCode = %s"%(self._name, self._parameters["Minimizer"], rc))
268 # Obtention de l'analyse
269 # ----------------------
270 Xa = numpy.asmatrix(Minimum).T
271 logging.debug("%s Analyse Xa = %s"%(self._name, Xa))
273 self.StoredVariables["Analysis"].store( Xa.A1 )
274 self.StoredVariables["Innovation"].store( d.A1 )
276 # Calcul de la covariance d'analyse
277 # ---------------------------------
278 if self._parameters["CalculateAPosterioriCovariance"]:
282 _ee = numpy.matrix(numpy.zeros(nb)).T
285 _HmEE = numpy.asmatrix(_HmEE).flatten().T
286 Hessienne.append( ( BI*_ee + Ha((Xa,RI*_HmEE)) ).A1 )
287 Hessienne = numpy.matrix( Hessienne )
289 self.StoredVariables["APosterioriCovariance"].store( A )
291 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("MB")))
292 logging.debug("%s Terminé"%self._name)
296 # ==============================================================================
297 if __name__ == "__main__":
298 print '\n AUTODIAGNOSTIC \n'