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, "NONLINEARLEASTSQUARES")
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 = ["BMA", "OMA", "OMB", "Innovation"]
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 moindres carrés pondérés non linéaires
93 (assimilation variationnelle sans ébauche)
95 logging.debug("%s Lancement"%self._name)
96 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
98 # Paramètres de pilotage
99 # ----------------------
100 self.setParameters(Parameters)
102 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):
103 Bounds = self._parameters["Bounds"]
104 logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
108 # Correction pour pallier a un bug de TNC sur le retour du Minimum
109 if self._parameters.has_key("Minimizer") is "TNC":
110 self.setParameterValue("StoreInternalVariables",True)
112 # Opérateur d'observation
113 # -----------------------
114 Hm = H["Direct"].appliedTo
115 Ha = H["Adjoint"].appliedInXTo
117 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
118 # ----------------------------------------------------
119 if H["AppliedToX"] is not None and H["AppliedToX"].has_key("HXb"):
120 logging.debug("%s Utilisation de HXb"%self._name)
121 HXb = H["AppliedToX"]["HXb"]
123 logging.debug("%s Calcul de Hm(Xb)"%self._name)
125 HXb = numpy.asmatrix(HXb).flatten().T
127 # Calcul de l'innovation
128 # ----------------------
129 if Y.size != HXb.size:
130 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))
131 if max(Y.shape) != max(HXb.shape):
132 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))
134 logging.debug("%s Innovation d = %s"%(self._name, d))
136 # Précalcul des inversions de B et R
137 # ----------------------------------
140 # elif self._parameters["B_scalar"] is not None:
141 # BI = 1.0 / self._parameters["B_scalar"]
143 # raise ValueError("Background error covariance matrix has to be properly defined!")
147 elif self._parameters["R_scalar"] is not None:
148 RI = 1.0 / self._parameters["R_scalar"]
150 raise ValueError("Observation error covariance matrix has to be properly defined!")
152 # Définition de la fonction-coût
153 # ------------------------------
155 _X = numpy.asmatrix(x).flatten().T
156 logging.debug("%s CostFunction X = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
158 _HX = numpy.asmatrix(_HX).flatten().T
160 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
161 J = float( Jb ) + float( Jo )
162 logging.debug("%s CostFunction Jb = %s"%(self._name, Jb))
163 logging.debug("%s CostFunction Jo = %s"%(self._name, Jo))
164 logging.debug("%s CostFunction J = %s"%(self._name, J))
165 if self._parameters["StoreInternalVariables"]:
166 self.StoredVariables["CurrentState"].store( _X.A1 )
167 self.StoredVariables["CostFunctionJb"].store( Jb )
168 self.StoredVariables["CostFunctionJo"].store( Jo )
169 self.StoredVariables["CostFunctionJ" ].store( J )
172 def GradientOfCostFunction(x):
173 _X = numpy.asmatrix(x).flatten().T
174 logging.debug("%s GradientOfCostFunction X = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
176 _HX = numpy.asmatrix(_HX).flatten().T
178 GradJo = - Ha( (_X, RI * (Y - _HX)) )
179 GradJ = numpy.asmatrix( GradJb ).flatten().T + numpy.asmatrix( GradJo ).flatten().T
180 logging.debug("%s GradientOfCostFunction GradJb = %s"%(self._name, numpy.asmatrix( GradJb ).flatten()))
181 logging.debug("%s GradientOfCostFunction GradJo = %s"%(self._name, numpy.asmatrix( GradJo ).flatten()))
182 logging.debug("%s GradientOfCostFunction GradJ = %s"%(self._name, numpy.asmatrix( GradJ ).flatten()))
185 # Point de démarrage de l'optimisation : Xini = Xb
186 # ------------------------------------
187 if type(Xb) is type(numpy.matrix([])):
188 Xini = Xb.A1.tolist()
191 logging.debug("%s Point de démarrage Xini = %s"%(self._name, Xini))
193 # Minimisation de la fonctionnelle
194 # --------------------------------
195 if self._parameters["Minimizer"] == "LBFGSB":
196 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
199 fprime = GradientOfCostFunction,
202 maxfun = self._parameters["MaximumNumberOfSteps"]-1,
203 factr = self._parameters["CostDecrementTolerance"]*1.e14,
204 pgtol = self._parameters["ProjectedGradientTolerance"],
207 nfeval = Informations['funcalls']
208 rc = Informations['warnflag']
209 elif self._parameters["Minimizer"] == "TNC":
210 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
213 fprime = GradientOfCostFunction,
216 maxfun = self._parameters["MaximumNumberOfSteps"],
217 pgtol = self._parameters["ProjectedGradientTolerance"],
218 ftol = self._parameters["CostDecrementTolerance"],
221 elif self._parameters["Minimizer"] == "CG":
222 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
225 fprime = GradientOfCostFunction,
227 maxiter = self._parameters["MaximumNumberOfSteps"],
228 gtol = self._parameters["GradientNormTolerance"],
232 elif self._parameters["Minimizer"] == "NCG":
233 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
236 fprime = GradientOfCostFunction,
238 maxiter = self._parameters["MaximumNumberOfSteps"],
239 avextol = self._parameters["CostDecrementTolerance"],
243 elif self._parameters["Minimizer"] == "BFGS":
244 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
247 fprime = GradientOfCostFunction,
249 maxiter = self._parameters["MaximumNumberOfSteps"],
250 gtol = self._parameters["GradientNormTolerance"],
255 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
257 StepMin = numpy.argmin( self.StoredVariables["CostFunctionJ"].valueserie() )
258 MinJ = self.StoredVariables["CostFunctionJ"].valueserie(step = StepMin)
260 # Correction pour pallier a un bug de TNC sur le retour du Minimum
261 # ----------------------------------------------------------------
262 if self._parameters["StoreInternalVariables"]:
263 Minimum = self.StoredVariables["CurrentState"].valueserie(step = StepMin)
265 logging.debug("%s %s Step of min cost = %s"%(self._name, self._parameters["Minimizer"], StepMin))
266 logging.debug("%s %s Minimum cost = %s"%(self._name, self._parameters["Minimizer"], MinJ))
267 logging.debug("%s %s Minimum state = %s"%(self._name, self._parameters["Minimizer"], Minimum))
268 logging.debug("%s %s Nb of F = %s"%(self._name, self._parameters["Minimizer"], nfeval))
269 logging.debug("%s %s RetCode = %s"%(self._name, self._parameters["Minimizer"], rc))
271 # Obtention de l'analyse
272 # ----------------------
273 Xa = numpy.asmatrix(Minimum).flatten().T
274 logging.debug("%s Analyse Xa = %s"%(self._name, Xa))
276 self.StoredVariables["Analysis"].store( Xa.A1 )
278 # Calculs et/ou stockages supplémentaires
279 # ---------------------------------------
280 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
281 self.StoredVariables["Innovation"].store( numpy.asmatrix(d).flatten().A1 )
282 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
283 self.StoredVariables["BMA"].store( numpy.asmatrix(Xb - Xa).flatten().A1 )
284 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
285 self.StoredVariables["OMA"].store( numpy.asmatrix(Y - Hm(Xa)).flatten().A1 )
286 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
287 self.StoredVariables["OMB"].store( numpy.asmatrix(d).flatten().A1 )
289 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
290 logging.debug("%s Terminé"%self._name)
294 # ==============================================================================
295 if __name__ == "__main__":
296 print '\n AUTODIAGNOSTIC \n'