Salome HOME
Correst warning when using default Minimizer
[modules/adao.git] / src / daComposant / daAlgorithms / 3DVAR.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2011  EDF R&D
4 #
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.
9 #
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.
14 #
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
18 #
19 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #
21
22 import logging
23 from daCore import BasicObjects, PlatformInfo
24 m = PlatformInfo.SystemUsage()
25
26 import numpy
27 import scipy.optimize
28
29 if logging.getLogger().level < 30:
30     iprint  = 1
31     message = scipy.optimize.tnc.MSG_ALL
32     disp    = 1
33 else:
34     iprint  = -1
35     message = scipy.optimize.tnc.MSG_NONE
36     disp    = 0
37
38 # ==============================================================================
39 class ElementaryAlgorithm(BasicObjects.Algorithm):
40     def __init__(self):
41         BasicObjects.Algorithm.__init__(self)
42         self._name = "3DVAR"
43         logging.debug("%s Initialisation"%self._name)
44
45     def run(self, Xb=None, Y=None, H=None, M=None, R=None, B=None, Q=None, Parameters=None):
46         """
47         Calcul de l'estimateur 3D-VAR
48         """
49         logging.debug("%s Lancement"%self._name)
50         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("Mo")))
51         #
52         # Opérateur d'observation
53         # -----------------------
54         Hm = H["Direct"].appliedTo
55         Ht = H["Adjoint"].appliedInXTo
56         #
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"]
62         else:
63             logging.debug("%s Calcul de Hm(Xb)"%self._name)
64             HXb = Hm( Xb )
65         HXb = numpy.asmatrix(HXb).flatten().T
66         #
67         # Calcul de l'innovation
68         # ----------------------
69         d  = Y - HXb
70         logging.debug("%s Innovation d = %s"%(self._name, d))
71         #
72         # Précalcul des inversion appellée dans les fonction-coût et gradient
73         # -------------------------------------------------------------------
74         BI = B.I
75         RI = R.I
76         #
77         # Définition de la fonction-coût
78         # ------------------------------
79         def CostFunction(x):
80             _X  = numpy.asmatrix(x).flatten().T
81             logging.info("%s CostFunction X  = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
82             _HX = Hm( _X )
83             _HX = numpy.asmatrix(_HX).flatten().T
84             Jb  = 0.5 * (_X - Xb).T * BI * (_X - Xb)
85             Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
86             J   = float( Jb ) + float( Jo )
87             logging.info("%s CostFunction Jb = %s"%(self._name, Jb))
88             logging.info("%s CostFunction Jo = %s"%(self._name, Jo))
89             logging.info("%s CostFunction J  = %s"%(self._name, J))
90             self.StoredVariables["CurrentState"].store( _X.A1 )
91             self.StoredVariables["CostFunctionJb"].store( Jb )
92             self.StoredVariables["CostFunctionJo"].store( Jo )
93             self.StoredVariables["CostFunctionJ" ].store( J )
94             return float( J )
95         #
96         def GradientOfCostFunction(x):
97             _X      = numpy.asmatrix(x).flatten().T
98             logging.info("%s GradientOfCostFunction X      = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
99             _HX     = Hm( _X )
100             _HX     = numpy.asmatrix(_HX).flatten().T
101             GradJb  = BI * (_X - Xb)
102             GradJo  = - Ht( (_X, RI * (Y - _HX)) )
103             GradJ   = numpy.asmatrix( GradJb ).flatten().T + numpy.asmatrix( GradJo ).flatten().T
104             logging.debug("%s GradientOfCostFunction GradJb = %s"%(self._name, numpy.asmatrix( GradJb ).flatten()))
105             logging.debug("%s GradientOfCostFunction GradJo = %s"%(self._name, numpy.asmatrix( GradJo ).flatten()))
106             logging.debug("%s GradientOfCostFunction GradJ  = %s"%(self._name, numpy.asmatrix( GradJ  ).flatten()))
107             return GradJ.A1
108         #
109         # Point de démarrage de l'optimisation : Xini = Xb
110         # ------------------------------------
111         if type(Xb) is type(numpy.matrix([])):
112             Xini = Xb.A1.tolist()
113         else:
114             Xini = list(Xb)
115         logging.debug("%s Point de démarrage Xini = %s"%(self._name, Xini))
116         #
117         # Paramètres de pilotage
118         # ----------------------
119         # Potentiels : "Bounds", "Minimizer", "MaximumNumberOfSteps", "ProjectedGradientTolerance", "GradientNormTolerance", "InnerMinimizer"
120         if Parameters.has_key("Bounds") and (type(Parameters["Bounds"]) is type([]) or type(Parameters["Bounds"]) is type(())) and (len(Parameters["Bounds"]) > 0):
121             Bounds = Parameters["Bounds"]
122         else:
123             Bounds = None
124         MinimizerList = ["LBFGSB","TNC", "CG", "NCG", "BFGS"]
125         if Parameters.has_key("Minimizer") and (Parameters["Minimizer"] in MinimizerList):
126             Minimizer = str( Parameters["Minimizer"] )
127         else:
128             Minimizer = "LBFGSB"
129             logging.warning("%s Unknown or undefined minimizer, replaced by the default one \"%s\""%(self._name,Minimizer))
130         logging.debug("%s Minimiseur utilisé = %s"%(self._name, Minimizer))
131         if Parameters.has_key("MaximumNumberOfSteps") and (Parameters["MaximumNumberOfSteps"] > -1):
132             maxiter = int( Parameters["MaximumNumberOfSteps"] )
133         else:
134             maxiter = 15000
135         logging.debug("%s Nombre maximal de pas d'optimisation = %s"%(self._name, str(maxiter)))
136         if Parameters.has_key("CostDecrementTolerance") and (Parameters["CostDecrementTolerance"] > 0):
137             ftol  = float(Parameters["CostDecrementTolerance"])
138             factr = 1./ftol
139         else:
140             ftol  = 1.e-7
141             factr = 1./ftol
142         logging.debug("%s Diminution relative minimale du cout lors de l'arret = %s"%(self._name, str(1./factr)))
143         if Parameters.has_key("ProjectedGradientTolerance") and (Parameters["ProjectedGradientTolerance"] > -1):
144             pgtol = float(Parameters["ProjectedGradientTolerance"])
145         else:
146             pgtol = -1
147         logging.debug("%s Maximum des composantes du gradient projete lors de l'arret = %s"%(self._name, str(pgtol)))
148         if Parameters.has_key("GradientNormTolerance") and (Parameters["GradientNormTolerance"] > -1):
149             gtol = float(Parameters["GradientNormTolerance"])
150         else:
151             gtol = 1.e-05
152         logging.debug("%s Maximum des composantes du gradient lors de l'arret = %s"%(self._name, str(gtol)))
153         InnerMinimizerList = ["CG", "NCG", "BFGS"]
154         if Parameters.has_key("InnerMinimizer") and (Parameters["InnerMinimizer"] in InnerMinimizerList):
155             InnerMinimizer = str( Parameters["Minimizer"] )
156         else:
157             InnerMinimizer = "BFGS"
158         logging.debug("%s Minimiseur interne utilisé = %s"%(self._name, InnerMinimizer))
159         logging.debug("%s Norme du gradient lors de l'arret = %s"%(self._name, str(gtol)))
160         #
161         # Minimisation de la fonctionnelle
162         # --------------------------------
163         if Minimizer == "LBFGSB":
164             Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
165                 func        = CostFunction,
166                 x0          = Xini,
167                 fprime      = GradientOfCostFunction,
168                 args        = (),
169                 bounds      = Bounds,
170                 maxfun      = maxiter,
171                 factr       = factr,
172                 pgtol       = pgtol,
173                 iprint      = iprint,
174                 )
175             nfeval = Informations['funcalls']
176             rc     = Informations['warnflag']
177         elif Minimizer == "TNC":
178             Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
179                 func        = CostFunction,
180                 x0          = Xini,
181                 fprime      = GradientOfCostFunction,
182                 args        = (),
183                 bounds      = Bounds,
184                 maxfun      = maxiter,
185                 pgtol       = pgtol,
186                 ftol        = ftol,
187                 messages    = message,
188                 )
189         elif Minimizer == "CG":
190             Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
191                 f           = CostFunction,
192                 x0          = Xini,
193                 fprime      = GradientOfCostFunction,
194                 args        = (),
195                 maxiter     = maxiter,
196                 gtol        = gtol,
197                 disp        = disp,
198                 full_output = True,
199                 )
200         elif Minimizer == "NCG":
201             Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
202                 f           = CostFunction,
203                 x0          = Xini,
204                 fprime      = GradientOfCostFunction,
205                 args        = (),
206                 maxiter     = maxiter,
207                 avextol     = ftol,
208                 disp        = disp,
209                 full_output = True,
210                 )
211         elif Minimizer == "BFGS":
212             Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
213                 f           = CostFunction,
214                 x0          = Xini,
215                 fprime      = GradientOfCostFunction,
216                 args        = (),
217                 maxiter     = maxiter,
218                 gtol        = gtol,
219                 disp        = disp,
220                 full_output = True,
221                 )
222         else:
223             raise ValueError("Error in Minimizer name: %s"%Minimizer)
224         #
225         # Correction pour pallier a un bug de TNC sur le retour du Minimum
226         # ----------------------------------------------------------------
227         StepMin = numpy.argmin( self.StoredVariables["CostFunctionJ"].valueserie() )
228         MinJ    = self.StoredVariables["CostFunctionJ"].valueserie(step = StepMin)
229         Minimum = self.StoredVariables["CurrentState"].valueserie(step = StepMin)
230         #
231         logging.debug("%s %s Step of min cost  = %s"%(self._name, Minimizer, StepMin))
232         logging.debug("%s %s Minimum cost      = %s"%(self._name, Minimizer, MinJ))
233         logging.debug("%s %s Minimum state     = %s"%(self._name, Minimizer, Minimum))
234         logging.debug("%s %s Nb of F           = %s"%(self._name, Minimizer, nfeval))
235         logging.debug("%s %s RetCode           = %s"%(self._name, Minimizer, rc))
236         #
237         # Calcul  de l'analyse
238         # --------------------
239         Xa = numpy.asmatrix(Minimum).T
240         logging.debug("%s Analyse Xa = %s"%(self._name, Xa))
241         #
242         self.StoredVariables["Analysis"].store( Xa.A1 )
243         self.StoredVariables["Innovation"].store( d.A1 )
244         #
245         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("MB")))
246         logging.debug("%s Terminé"%self._name)
247         #
248         return 0
249
250 # ==============================================================================
251 if __name__ == "__main__":
252     print '\n AUTODIAGNOSTIC \n'