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)
42 self._name = "NONLINEARLEASTSQUARES"
43 logging.debug("%s Initialisation"%self._name)
45 def run(self, Xb=None, Y=None, H=None, M=None, R=None, B=None, Q=None, Parameters=None):
47 Calcul de l'estimateur moindres carrés pondérés non linéaires
48 (assimilation variationnelle sans ébauche)
50 logging.debug("%s Lancement"%self._name)
51 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("Mo")))
53 # Opérateur d'observation
54 # -----------------------
55 Hm = H["Direct"].appliedTo
56 Ht = H["Adjoint"].appliedInXTo
58 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
59 # ----------------------------------------------------
60 if H["AppliedToX"] is not None and H["AppliedToX"].has_key("HXb"):
61 logging.debug("%s Utilisation de HXb"%self._name)
62 HXb = H["AppliedToX"]["HXb"]
64 logging.debug("%s Calcul de Hm(Xb)"%self._name)
66 HXb = numpy.asmatrix(HXb).flatten().T
68 # Calcul de l'innovation
69 # ----------------------
70 if Y.size != HXb.size:
71 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))
72 if max(Y.shape) != max(HXb.shape):
73 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))
75 logging.debug("%s Innovation d = %s"%(self._name, d))
77 # Précalcul des inversions de B et R
78 # ----------------------------------
81 # elif Parameters["B_scalar"] is not None:
82 # BI = 1.0 / Parameters["B_scalar"]
86 elif Parameters["R_scalar"] is not None:
87 RI = 1.0 / Parameters["R_scalar"]
89 # Définition de la fonction-coût
90 # ------------------------------
92 _X = numpy.asmatrix(x).flatten().T
93 logging.debug("%s CostFunction X = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
95 _HX = numpy.asmatrix(_HX).flatten().T
97 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
98 J = float( Jb ) + float( Jo )
99 logging.debug("%s CostFunction Jb = %s"%(self._name, Jb))
100 logging.debug("%s CostFunction Jo = %s"%(self._name, Jo))
101 logging.debug("%s CostFunction J = %s"%(self._name, J))
102 self.StoredVariables["CurrentState"].store( _X.A1 )
103 self.StoredVariables["CostFunctionJb"].store( Jb )
104 self.StoredVariables["CostFunctionJo"].store( Jo )
105 self.StoredVariables["CostFunctionJ" ].store( J )
108 def GradientOfCostFunction(x):
109 _X = numpy.asmatrix(x).flatten().T
110 logging.debug("%s GradientOfCostFunction X = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
112 _HX = numpy.asmatrix(_HX).flatten().T
114 GradJo = - Ht( (_X, RI * (Y - _HX)) )
115 GradJ = numpy.asmatrix( GradJb ).flatten().T + numpy.asmatrix( GradJo ).flatten().T
116 logging.debug("%s GradientOfCostFunction GradJb = %s"%(self._name, numpy.asmatrix( GradJb ).flatten()))
117 logging.debug("%s GradientOfCostFunction GradJo = %s"%(self._name, numpy.asmatrix( GradJo ).flatten()))
118 logging.debug("%s GradientOfCostFunction GradJ = %s"%(self._name, numpy.asmatrix( GradJ ).flatten()))
121 # Point de démarrage de l'optimisation : Xini = Xb
122 # ------------------------------------
123 if type(Xb) is type(numpy.matrix([])):
124 Xini = Xb.A1.tolist()
127 logging.debug("%s Point de démarrage Xini = %s"%(self._name, Xini))
129 # Paramètres de pilotage
130 # ----------------------
131 # Potentiels : "Bounds", "Minimizer", "MaximumNumberOfSteps", "ProjectedGradientTolerance", "GradientNormTolerance", "InnerMinimizer"
132 if Parameters.has_key("Bounds") and (type(Parameters["Bounds"]) is type([]) or type(Parameters["Bounds"]) is type(())) and (len(Parameters["Bounds"]) > 0):
133 Bounds = Parameters["Bounds"]
136 MinimizerList = ["LBFGSB","TNC", "CG", "NCG", "BFGS"]
137 if Parameters.has_key("Minimizer") and (Parameters["Minimizer"] in MinimizerList):
138 Minimizer = str( Parameters["Minimizer"] )
141 logging.warning("%s Unknown or undefined minimizer, replaced by the default one \"%s\""%(self._name,Minimizer))
142 logging.debug("%s Minimiseur utilisé = %s"%(self._name, Minimizer))
143 if Parameters.has_key("MaximumNumberOfSteps") and (Parameters["MaximumNumberOfSteps"] > -1):
144 maxiter = int( Parameters["MaximumNumberOfSteps"] )
147 logging.debug("%s Nombre maximal de pas d'optimisation = %s"%(self._name, str(maxiter)))
148 if Parameters.has_key("CostDecrementTolerance") and (Parameters["CostDecrementTolerance"] > 0):
149 ftol = float(Parameters["CostDecrementTolerance"])
154 logging.debug("%s Diminution relative minimale du cout lors de l'arret = %s"%(self._name, str(1./factr)))
155 if Parameters.has_key("ProjectedGradientTolerance") and (Parameters["ProjectedGradientTolerance"] > -1):
156 pgtol = float(Parameters["ProjectedGradientTolerance"])
159 logging.debug("%s Maximum des composantes du gradient projete lors de l'arret = %s"%(self._name, str(pgtol)))
160 if Parameters.has_key("GradientNormTolerance") and (Parameters["GradientNormTolerance"] > -1):
161 gtol = float(Parameters["GradientNormTolerance"])
164 logging.debug("%s Maximum des composantes du gradient lors de l'arret = %s"%(self._name, str(gtol)))
165 InnerMinimizerList = ["CG", "NCG", "BFGS"]
166 if Parameters.has_key("InnerMinimizer") and (Parameters["InnerMinimizer"] in InnerMinimizerList):
167 InnerMinimizer = str( Parameters["InnerMinimizer"] )
169 InnerMinimizer = "BFGS"
170 logging.debug("%s Minimiseur interne utilisé = %s"%(self._name, InnerMinimizer))
172 # Minimisation de la fonctionnelle
173 # --------------------------------
174 if Minimizer == "LBFGSB":
175 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
178 fprime = GradientOfCostFunction,
186 nfeval = Informations['funcalls']
187 rc = Informations['warnflag']
188 elif Minimizer == "TNC":
189 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
192 fprime = GradientOfCostFunction,
200 elif Minimizer == "CG":
201 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
204 fprime = GradientOfCostFunction,
211 elif Minimizer == "NCG":
212 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
215 fprime = GradientOfCostFunction,
222 elif Minimizer == "BFGS":
223 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
226 fprime = GradientOfCostFunction,
234 raise ValueError("Error in Minimizer name: %s"%Minimizer)
236 # Correction pour pallier a un bug de TNC sur le retour du Minimum
237 # ----------------------------------------------------------------
238 StepMin = numpy.argmin( self.StoredVariables["CostFunctionJ"].valueserie() )
239 MinJ = self.StoredVariables["CostFunctionJ"].valueserie(step = StepMin)
240 Minimum = self.StoredVariables["CurrentState"].valueserie(step = StepMin)
242 logging.debug("%s %s Step of min cost = %s"%(self._name, Minimizer, StepMin))
243 logging.debug("%s %s Minimum cost = %s"%(self._name, Minimizer, MinJ))
244 logging.debug("%s %s Minimum state = %s"%(self._name, Minimizer, Minimum))
245 logging.debug("%s %s Nb of F = %s"%(self._name, Minimizer, nfeval))
246 logging.debug("%s %s RetCode = %s"%(self._name, Minimizer, rc))
248 # Calcul de l'analyse
249 # --------------------
250 Xa = numpy.asmatrix(Minimum).T
251 logging.debug("%s Analyse Xa = %s"%(self._name, Xa))
253 self.StoredVariables["Analysis"].store( Xa.A1 )
254 self.StoredVariables["Innovation"].store( d.A1 )
256 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("MB")))
257 logging.debug("%s Terminé"%self._name)
261 # ==============================================================================
262 if __name__ == "__main__":
263 print '\n AUTODIAGNOSTIC \n'