1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2010 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"
27 from daCore import BasicObjects, PlatformInfo
28 m = PlatformInfo.SystemUsage()
33 if logging.getLogger().level < 30:
35 message = scipy.optimize.tnc.MSG_ALL
39 message = scipy.optimize.tnc.MSG_NONE
42 # ==============================================================================
43 class ElementaryAlgorithm(BasicObjects.Algorithm):
45 BasicObjects.Algorithm.__init__(self)
47 logging.debug("%s Initialisation"%self._name)
49 def run(self, Xb=None, Y=None, H=None, M=None, R=None, B=None, Q=None, Par=None):
51 Calcul de l'estimateur 3D-VAR
53 logging.debug("%s Lancement"%self._name)
54 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("Mo")))
56 Hm = H["Direct"].appliedTo
57 Ht = H["Adjoint"].appliedInXTo
59 # Utilisation éventuelle d'un vecteur H(Xb) précalculé
60 # ----------------------------------------------------
61 if H["AppliedToX"] is not None and H["AppliedToX"].has_key("HXb"):
62 logging.debug("%s Utilisation de HXb"%self._name)
63 HXb = H["AppliedToX"]["HXb"]
65 logging.debug("%s Calcul de Hm(Xb)"%self._name)
68 # Calcul du préconditionnement
69 # ----------------------------
70 # Bdemi = numpy.linalg.cholesky(B)
72 # Calcul de l'innovation
73 # ----------------------
75 logging.debug("%s Innovation d = %s"%(self._name, d))
77 # Précalcul des inversion appellée dans les fonction-coût et gradient
78 # -------------------------------------------------------------------
82 # Définition de la fonction-coût
83 # ------------------------------
85 _X = numpy.asmatrix(x).flatten().T
86 logging.info("%s CostFunction X = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
88 _HX = numpy.asmatrix(_HX).flatten().T
89 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
90 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
91 J = float( Jb ) + float( Jo )
92 logging.info("%s CostFunction Jb = %s"%(self._name, Jb))
93 logging.info("%s CostFunction Jo = %s"%(self._name, Jo))
94 logging.info("%s CostFunction J = %s"%(self._name, J))
95 self.StoredVariables["CostFunctionJb"].store( Jb )
96 self.StoredVariables["CostFunctionJo"].store( Jo )
97 self.StoredVariables["CostFunctionJ" ].store( J )
100 def GradientOfCostFunction(x):
101 _X = numpy.asmatrix(x).flatten().T
102 logging.info("%s GradientOfCostFunction X = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
104 _HX = numpy.asmatrix(_HX).flatten().T
105 GradJb = BI * (_X - Xb)
106 GradJo = - Ht( (_X, RI * (Y - _HX)) )
107 GradJ = numpy.asmatrix( GradJb ).flatten().T + numpy.asmatrix( GradJo ).flatten().T
108 logging.debug("%s GradientOfCostFunction GradJb = %s"%(self._name, numpy.asmatrix( GradJb ).flatten()))
109 logging.debug("%s GradientOfCostFunction GradJo = %s"%(self._name, numpy.asmatrix( GradJo ).flatten()))
110 logging.debug("%s GradientOfCostFunction GradJ = %s"%(self._name, numpy.asmatrix( GradJ ).flatten()))
111 # self.StoredVariables["GradientOfCostFunctionJb"].store( Jb )
112 # self.StoredVariables["GradientOfCostFunctionJo"].store( Jo )
113 # self.StoredVariables["GradientOfCostFunctionJ" ].store( J )
116 # Point de démarrage de l'optimisation : Xini = Xb
117 # ------------------------------------
118 if type(Xb) is type(numpy.matrix([])):
119 Xini = Xb.A1.tolist()
122 logging.debug("%s Point de démarrage Xini = %s"%(self._name, Xini))
124 # Paramètres de pilotage
125 # ----------------------
126 if Par.has_key("Bounds") and (type(Par["Bounds"]) is type([]) or type(Par["Bounds"]) is type(())) and (len(Par["Bounds"]) > 0):
127 Bounds = Par["Bounds"]
130 MinimizerList = ["LBFGSB","TNC", "CG", "BFGS"]
131 if Par.has_key("Minimizer") and (Par["Minimizer"] in MinimizerList):
132 Minimizer = str( Par["Minimizer"] )
135 logging.debug("%s Minimiseur utilisé = %s"%(self._name, Minimizer))
136 if Par.has_key("MaximumNumberOfSteps") and (Par["MaximumNumberOfSteps"] > -1):
137 maxiter = int( Par["MaximumNumberOfSteps"] )
140 logging.debug("%s Nombre maximal de pas d'optimisation = %s"%(self._name, maxiter))
142 # Minimisation de la fonctionnelle
143 # --------------------------------
144 if Minimizer == "LBFGSB":
145 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
148 fprime = GradientOfCostFunction,
154 logging.debug("%s %s Minimum = %s"%(self._name, Minimizer, Minimum))
155 logging.debug("%s %s Nb of F = %s"%(self._name, Minimizer, Informations['funcalls']))
156 logging.debug("%s %s RetCode = %s"%(self._name, Minimizer, Informations['warnflag']))
157 elif Minimizer == "TNC":
158 Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
161 fprime = GradientOfCostFunction,
167 logging.debug("%s %s Minimum = %s"%(self._name, Minimizer, Minimum))
168 logging.debug("%s %s Nb of F = %s"%(self._name, Minimizer, nfeval))
169 logging.debug("%s %s RetCode = %s"%(self._name, Minimizer, rc))
170 elif Minimizer == "CG":
171 Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
174 fprime = GradientOfCostFunction,
180 logging.debug("%s %s Minimum = %s"%(self._name, Minimizer, Minimum))
181 logging.debug("%s %s Nb of F = %s"%(self._name, Minimizer, nfeval))
182 logging.debug("%s %s RetCode = %s"%(self._name, Minimizer, rc))
183 elif Minimizer == "BFGS":
184 Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
187 fprime = GradientOfCostFunction,
193 logging.debug("%s %s Minimum = %s"%(self._name, Minimizer, Minimum))
194 logging.debug("%s %s Nb of F = %s"%(self._name, Minimizer, nfeval))
195 logging.debug("%s %s RetCode = %s"%(self._name, Minimizer, rc))
197 raise ValueError("Error in Minimizer name: %s"%Minimizer)
199 # Calcul de l'analyse
200 # --------------------
201 Xa = numpy.asmatrix(Minimum).T
202 logging.debug("%s Analyse Xa = %s"%(self._name, Xa))
204 self.StoredVariables["Analysis"].store( Xa.A1 )
205 self.StoredVariables["Innovation"].store( d.A1 )
207 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("MB")))
208 logging.debug("%s Terminé"%self._name)
212 # ==============================================================================
213 if __name__ == "__main__":
214 print '\n AUTODIAGNOSTIC \n'