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, Parameters=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)
67 HXb = numpy.asmatrix(HXb).flatten().T
69 # Calcul du préconditionnement
70 # ----------------------------
71 # Bdemi = numpy.linalg.cholesky(B)
73 # Calcul de l'innovation
74 # ----------------------
76 logging.debug("%s Innovation d = %s"%(self._name, d))
78 # Précalcul des inversion appellée dans les fonction-coût et gradient
79 # -------------------------------------------------------------------
83 # Définition de la fonction-coût
84 # ------------------------------
86 _X = numpy.asmatrix(x).flatten().T
87 logging.info("%s CostFunction X = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
89 _HX = numpy.asmatrix(_HX).flatten().T
90 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
91 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
92 J = float( Jb ) + float( Jo )
93 logging.info("%s CostFunction Jb = %s"%(self._name, Jb))
94 logging.info("%s CostFunction Jo = %s"%(self._name, Jo))
95 logging.info("%s CostFunction J = %s"%(self._name, J))
96 self.StoredVariables["CurrentState"].store( _X.A1 )
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()))
115 # Point de démarrage de l'optimisation : Xini = Xb
116 # ------------------------------------
117 if type(Xb) is type(numpy.matrix([])):
118 Xini = Xb.A1.tolist()
121 logging.debug("%s Point de démarrage Xini = %s"%(self._name, Xini))
123 # Paramètres de pilotage
124 # ----------------------
125 if Parameters.has_key("Bounds") and (type(Parameters["Bounds"]) is type([]) or type(Parameters["Bounds"]) is type(())) and (len(Parameters["Bounds"]) > 0):
126 Bounds = Parameters["Bounds"]
129 MinimizerList = ["LBFGSB","TNC", "CG", "BFGS"]
130 if Parameters.has_key("Minimizer") and (Parameters["Minimizer"] in MinimizerList):
131 Minimizer = str( Parameters["Minimizer"] )
134 logging.debug("%s Minimiseur utilisé = %s"%(self._name, Minimizer))
135 if Parameters.has_key("MaximumNumberOfSteps") and (Parameters["MaximumNumberOfSteps"] > -1):
136 maxiter = int( Parameters["MaximumNumberOfSteps"] )
139 logging.debug("%s Nombre maximal de pas d'optimisation = %s"%(self._name, maxiter))
141 # Minimisation de la fonctionnelle
142 # --------------------------------
143 if Minimizer == "LBFGSB":
144 Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
147 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'