1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2011 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)
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 3D-VAR
49 logging.debug("%s Lancement"%self._name)
50 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("Mo")))
52 # Opérateur d'observation
53 # -----------------------
54 Hm = H["Direct"].appliedTo
55 Ht = H["Adjoint"].appliedInXTo
57 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
58 # ----------------------------------------------------
59 if H["AppliedToX"] is not None and H["AppliedToX"].has_key("HXb"):
60 logging.debug("%s Utilisation de HXb"%self._name)
61 HXb = H["AppliedToX"]["HXb"]
63 logging.debug("%s Calcul de Hm(Xb)"%self._name)
65 HXb = numpy.asmatrix(HXb).flatten().T
67 # Calcul de l'innovation
68 # ----------------------
69 if Y.size != HXb.size:
70 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))
71 if max(Y.shape) != max(HXb.shape):
72 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))
74 logging.debug("%s Innovation d = %s"%(self._name, d))
76 # Précalcul des inversion appellée dans les fonction-coût et gradient
77 # -------------------------------------------------------------------
80 elif Parameters["B_scalar"] is not None:
81 BI = 1.0 / Parameters["B_scalar"]
85 elif Parameters["R_scalar"] is not None:
86 RI = 1.0 / Parameters["R_scalar"]
88 # Définition de la fonction-coût
89 # ------------------------------
91 _X = numpy.asmatrix(x).flatten().T
92 logging.info("%s CostFunction X = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
94 _HX = numpy.asmatrix(_HX).flatten().T
95 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
96 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
97 J = float( Jb ) + float( Jo )
98 logging.info("%s CostFunction Jb = %s"%(self._name, Jb))
99 logging.info("%s CostFunction Jo = %s"%(self._name, Jo))
100 logging.info("%s CostFunction J = %s"%(self._name, J))
101 self.StoredVariables["CurrentState"].store( _X.A1 )
102 self.StoredVariables["CostFunctionJb"].store( Jb )
103 self.StoredVariables["CostFunctionJo"].store( Jo )
104 self.StoredVariables["CostFunctionJ" ].store( J )
107 def GradientOfCostFunction(x):
108 _X = numpy.asmatrix(x).flatten().T
109 logging.info("%s GradientOfCostFunction X = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
111 _HX = numpy.asmatrix(_HX).flatten().T
112 GradJb = BI * (_X - Xb)
113 GradJo = - Ht( (_X, RI * (Y - _HX)) )
114 GradJ = numpy.asmatrix( GradJb ).flatten().T + numpy.asmatrix( GradJo ).flatten().T
115 logging.debug("%s GradientOfCostFunction GradJb = %s"%(self._name, numpy.asmatrix( GradJb ).flatten()))
116 logging.debug("%s GradientOfCostFunction GradJo = %s"%(self._name, numpy.asmatrix( GradJo ).flatten()))
117 logging.debug("%s GradientOfCostFunction GradJ = %s"%(self._name, numpy.asmatrix( GradJ ).flatten()))
120 # Point de démarrage de l'optimisation : Xini = Xb
121 # ------------------------------------
122 if type(Xb) is type(numpy.matrix([])):
123 Xini = Xb.A1.tolist()
126 logging.debug("%s Point de démarrage Xini = %s"%(self._name, Xini))
128 # Paramètres de pilotage
129 # ----------------------
130 # Potentiels : "Bounds", "Minimizer", "MaximumNumberOfSteps", "ProjectedGradientTolerance", "GradientNormTolerance", "InnerMinimizer"
131 if Parameters.has_key("Bounds") and (type(Parameters["Bounds"]) is type([]) or type(Parameters["Bounds"]) is type(())) and (len(Parameters["Bounds"]) > 0):
132 Bounds = Parameters["Bounds"]
135 MinimizerList = ["LBFGSB","TNC", "CG", "NCG", "BFGS"]
136 if Parameters.has_key("Minimizer") and (Parameters["Minimizer"] in MinimizerList):
137 Minimizer = str( Parameters["Minimizer"] )
140 logging.warning("%s Unknown or undefined minimizer, replaced by the default one \"%s\""%(self._name,Minimizer))
141 logging.debug("%s Minimiseur utilisé = %s"%(self._name, Minimizer))
142 if Parameters.has_key("MaximumNumberOfSteps") and (Parameters["MaximumNumberOfSteps"] > -1):
143 maxiter = int( Parameters["MaximumNumberOfSteps"] )
146 logging.debug("%s Nombre maximal de pas d'optimisation = %s"%(self._name, str(maxiter)))
147 if Parameters.has_key("CostDecrementTolerance") and (Parameters["CostDecrementTolerance"] > 0):
148 ftol = float(Parameters["CostDecrementTolerance"])
153 logging.debug("%s Diminution relative minimale du cout lors de l'arret = %s"%(self._name, str(1./factr)))
154 if Parameters.has_key("ProjectedGradientTolerance") and (Parameters["ProjectedGradientTolerance"] > -1):
155 pgtol = float(Parameters["ProjectedGradientTolerance"])
158 logging.debug("%s Maximum des composantes du gradient projete lors de l'arret = %s"%(self._name, str(pgtol)))
159 if Parameters.has_key("GradientNormTolerance") and (Parameters["GradientNormTolerance"] > -1):
160 gtol = float(Parameters["GradientNormTolerance"])
163 logging.debug("%s Maximum des composantes du gradient lors de l'arret = %s"%(self._name, str(gtol)))
164 InnerMinimizerList = ["CG", "NCG", "BFGS"]
165 if Parameters.has_key("InnerMinimizer") and (Parameters["InnerMinimizer"] in InnerMinimizerList):
166 InnerMinimizer = str( Parameters["InnerMinimizer"] )
168 InnerMinimizer = "BFGS"
169 logging.debug("%s Minimiseur interne utilisé = %s"%(self._name, InnerMinimizer))
171 # Minimisation de la fonctionnelle
172 # --------------------------------
173 if Minimizer == "LBFGSB":
174 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
177 fprime = GradientOfCostFunction,
185 nfeval = Informations['funcalls']
186 rc = Informations['warnflag']
187 elif Minimizer == "TNC":
188 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
191 fprime = GradientOfCostFunction,
199 elif Minimizer == "CG":
200 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
203 fprime = GradientOfCostFunction,
210 elif Minimizer == "NCG":
211 Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
214 fprime = GradientOfCostFunction,
221 elif Minimizer == "BFGS":
222 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
225 fprime = GradientOfCostFunction,
233 raise ValueError("Error in Minimizer name: %s"%Minimizer)
235 # Correction pour pallier a un bug de TNC sur le retour du Minimum
236 # ----------------------------------------------------------------
237 StepMin = numpy.argmin( self.StoredVariables["CostFunctionJ"].valueserie() )
238 MinJ = self.StoredVariables["CostFunctionJ"].valueserie(step = StepMin)
239 Minimum = self.StoredVariables["CurrentState"].valueserie(step = StepMin)
241 logging.debug("%s %s Step of min cost = %s"%(self._name, Minimizer, StepMin))
242 logging.debug("%s %s Minimum cost = %s"%(self._name, Minimizer, MinJ))
243 logging.debug("%s %s Minimum state = %s"%(self._name, Minimizer, Minimum))
244 logging.debug("%s %s Nb of F = %s"%(self._name, Minimizer, nfeval))
245 logging.debug("%s %s RetCode = %s"%(self._name, Minimizer, rc))
247 # Calcul de l'analyse
248 # --------------------
249 Xa = numpy.asmatrix(Minimum).T
250 logging.debug("%s Analyse Xa = %s"%(self._name, Xa))
252 self.StoredVariables["Analysis"].store( Xa.A1 )
253 self.StoredVariables["Innovation"].store( d.A1 )
255 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("MB")))
256 logging.debug("%s Terminé"%self._name)
260 # ==============================================================================
261 if __name__ == "__main__":
262 print '\n AUTODIAGNOSTIC \n'