1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2009 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
22 Algorithme variationnel statique (3D-VAR)
24 __author__ = "Jean-Philippe ARGAUD - Mars 2009"
26 import sys ; sys.path.insert(0, "../daCore")
28 from daCore import Persistence
29 from daCore.BasicObjects import Algorithm
30 from daCore import PlatformInfo ; m = PlatformInfo.SystemUsage()
35 if logging.getLogger().level < 30:
37 message = scipy.optimize.tnc.MSG_ALL
41 message = scipy.optimize.tnc.MSG_NONE
44 # ==============================================================================
45 class ElementaryAlgorithm(Algorithm):
47 Algorithm.__init__(self)
49 logging.debug("%s Initialisation"%self._name)
51 def run(self, Xb=None, Y=None, H=None, M=None, R=None, B=None, Q=None, Par=None):
53 Calcul de l'estimateur 3D-VAR
55 logging.debug("%s Lancement"%self._name)
56 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("Mo")))
58 Hm = H["Direct"].appliedTo
59 Ht = H["Adjoint"].appliedInXTo
61 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
62 # ----------------------------------------------------
63 if H["AppliedToX"] is not None and H["AppliedToX"].has_key("HXb"):
64 logging.debug("%s Utilisation de HXb"%self._name)
65 HXb = H["AppliedToX"]["HXb"]
67 logging.debug("%s Calcul de Hm(Xb)"%self._name)
70 # Calcul du préconditionnement
71 # ----------------------------
72 # Bdemi = numpy.linalg.cholesky(B)
74 # Calcul de l'innovation
75 # ----------------------
77 logging.debug("%s Innovation d = %s"%(self._name, d))
79 # Précalcul des inversion appellée dans les fonction-coût et gradient
80 # -------------------------------------------------------------------
84 # Définition de la fonction-coût
85 # ------------------------------
87 _X = numpy.asmatrix(x).flatten().T
88 logging.info("%s CostFunction X = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
90 _HX = numpy.asmatrix(_HX).flatten().T
91 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
92 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
93 J = float( Jb ) + float( Jo )
94 logging.info("%s CostFunction Jb = %s"%(self._name, Jb))
95 logging.info("%s CostFunction Jo = %s"%(self._name, Jo))
96 logging.info("%s CostFunction J = %s"%(self._name, J))
97 self.StoredVariables["CostFunctionJb"].store( Jb )
98 self.StoredVariables["CostFunctionJo"].store( Jo )
99 self.StoredVariables["CostFunctionJ" ].store( J )
102 def GradientOfCostFunction(x):
103 _X = numpy.asmatrix(x).flatten().T
104 logging.info("%s GradientOfCostFunction X = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
106 _HX = numpy.asmatrix(_HX).flatten().T
107 GradJb = BI * (_X - Xb)
108 GradJo = - Ht( (_X, RI * (Y - _HX)) )
109 GradJ = numpy.asmatrix( GradJb ).flatten().T + numpy.asmatrix( GradJo ).flatten().T
110 logging.debug("%s GradientOfCostFunction GradJb = %s"%(self._name, numpy.asmatrix( GradJb ).flatten()))
111 logging.debug("%s GradientOfCostFunction GradJo = %s"%(self._name, numpy.asmatrix( GradJo ).flatten()))
112 logging.debug("%s GradientOfCostFunction GradJ = %s"%(self._name, numpy.asmatrix( GradJ ).flatten()))
113 # self.StoredVariables["GradientOfCostFunctionJb"].store( Jb )
114 # self.StoredVariables["GradientOfCostFunctionJo"].store( Jo )
115 # self.StoredVariables["GradientOfCostFunctionJ" ].store( J )
118 # Point de démarrage de l'optimisation : Xini = Xb
119 # ------------------------------------
120 if type(Xb) is type(numpy.matrix([])):
121 Xini = Xb.A1.tolist()
124 logging.debug("%s Point de démarrage Xini = %s"%(self._name, Xini))
126 # Paramètres de pilotage
127 # ----------------------
128 if Par.has_key("Bounds") and (type(Par["Bounds"]) is type([]) or type(Par["Bounds"]) is type(())) and (len(Par["Bounds"]) > 0):
129 Bounds = Par["Bounds"]
132 MinimizerList = ["LBFGSB","TNC", "CG", "BFGS"]
133 if Par.has_key("Minimizer") and (Par["Minimizer"] in MinimizerList):
134 Minimizer = str( Par["Minimizer"] )
137 logging.debug("%s Minimiseur utilisé = %s"%(self._name, Minimizer))
138 if Par.has_key("MaximumNumberOfSteps") and (Par["MaximumNumberOfSteps"] > -1):
139 maxiter = int( Par["MaximumNumberOfSteps"] )
142 logging.debug("%s Nombre maximal de pas d'optimisation = %s"%(self._name, maxiter))
144 # Minimisation de la fonctionnelle
145 # --------------------------------
146 if Minimizer == "LBFGSB":
147 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
150 fprime = GradientOfCostFunction,
156 logging.debug("%s %s Minimum = %s"%(self._name, Minimizer, Minimum))
157 logging.debug("%s %s Nb of F = %s"%(self._name, Minimizer, Informations['funcalls']))
158 logging.debug("%s %s RetCode = %s"%(self._name, Minimizer, Informations['warnflag']))
159 elif Minimizer == "TNC":
160 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
163 fprime = GradientOfCostFunction,
169 logging.debug("%s %s Minimum = %s"%(self._name, Minimizer, Minimum))
170 logging.debug("%s %s Nb of F = %s"%(self._name, Minimizer, nfeval))
171 logging.debug("%s %s RetCode = %s"%(self._name, Minimizer, rc))
172 elif Minimizer == "CG":
173 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
176 fprime = GradientOfCostFunction,
182 logging.debug("%s %s Minimum = %s"%(self._name, Minimizer, Minimum))
183 logging.debug("%s %s Nb of F = %s"%(self._name, Minimizer, nfeval))
184 logging.debug("%s %s RetCode = %s"%(self._name, Minimizer, rc))
185 elif Minimizer == "BFGS":
186 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
189 fprime = GradientOfCostFunction,
195 logging.debug("%s %s Minimum = %s"%(self._name, Minimizer, Minimum))
196 logging.debug("%s %s Nb of F = %s"%(self._name, Minimizer, nfeval))
197 logging.debug("%s %s RetCode = %s"%(self._name, Minimizer, rc))
199 raise ValueError("Error in Minimizer name: %s"%Minimizer)
201 # Calcul de l'analyse
202 # --------------------
203 Xa = numpy.asmatrix(Minimum).T
204 logging.debug("%s Analyse Xa = %s"%(self._name, Xa))
206 self.StoredVariables["Analysis"].store( Xa.A1 )
207 self.StoredVariables["Innovation"].store( d.A1 )
209 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("MB")))
210 logging.debug("%s Terminé"%self._name)
214 # ==============================================================================
215 if __name__ == "__main__":
216 print '\n AUTODIAGNOSTIC \n'