Salome HOME
Correcting date copyright information
[modules/adao.git] / src / daComposant / daAlgorithms / NonLinearLeastSquares.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2012 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 = "NONLINEARLEASTSQUARES"
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 moindres carrés pondérés non linéaires
48         (assimilation variationnelle sans ébauche)
49         """
50         logging.debug("%s Lancement"%self._name)
51         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("Mo")))
52         #
53         # Opérateur d'observation
54         # -----------------------
55         Hm = H["Direct"].appliedTo
56         Ht = H["Adjoint"].appliedInXTo
57         #
58         # Utilisation éventuelle d'un vecteur H(Xb) précalculé
59         # ----------------------------------------------------
60         if H["AppliedToX"] is not None and H["AppliedToX"].has_key("HXb"):
61             logging.debug("%s Utilisation de HXb"%self._name)
62             HXb = H["AppliedToX"]["HXb"]
63         else:
64             logging.debug("%s Calcul de Hm(Xb)"%self._name)
65             HXb = Hm( Xb )
66         HXb = numpy.asmatrix(HXb).flatten().T
67         #
68         # Calcul de l'innovation
69         # ----------------------
70         if Y.size != HXb.size:
71             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))
72         if max(Y.shape) != max(HXb.shape):
73             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         d  = Y - HXb
75         logging.debug("%s Innovation d = %s"%(self._name, d))
76         #
77         # Précalcul des inversions de B et R
78         # ----------------------------------
79         # if B is not None:
80         #     BI = B.I
81         # elif Parameters["B_scalar"] is not None:
82         #     BI = 1.0 / Parameters["B_scalar"]
83         #
84         if R is not None:
85             RI = R.I
86         elif Parameters["R_scalar"] is not None:
87             RI = 1.0 / Parameters["R_scalar"]
88         #
89         # Définition de la fonction-coût
90         # ------------------------------
91         def CostFunction(x):
92             _X  = numpy.asmatrix(x).flatten().T
93             logging.debug("%s CostFunction X  = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
94             _HX = Hm( _X )
95             _HX = numpy.asmatrix(_HX).flatten().T
96             Jb  = 0.
97             Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
98             J   = float( Jb ) + float( Jo )
99             logging.debug("%s CostFunction Jb = %s"%(self._name, Jb))
100             logging.debug("%s CostFunction Jo = %s"%(self._name, Jo))
101             logging.debug("%s CostFunction J  = %s"%(self._name, J))
102             self.StoredVariables["CurrentState"].store( _X.A1 )
103             self.StoredVariables["CostFunctionJb"].store( Jb )
104             self.StoredVariables["CostFunctionJo"].store( Jo )
105             self.StoredVariables["CostFunctionJ" ].store( J )
106             return float( J )
107         #
108         def GradientOfCostFunction(x):
109             _X      = numpy.asmatrix(x).flatten().T
110             logging.debug("%s GradientOfCostFunction X      = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
111             _HX     = Hm( _X )
112             _HX     = numpy.asmatrix(_HX).flatten().T
113             GradJb  = 0.
114             GradJo  = - Ht( (_X, RI * (Y - _HX)) )
115             GradJ   = numpy.asmatrix( GradJb ).flatten().T + numpy.asmatrix( GradJo ).flatten().T
116             logging.debug("%s GradientOfCostFunction GradJb = %s"%(self._name, numpy.asmatrix( GradJb ).flatten()))
117             logging.debug("%s GradientOfCostFunction GradJo = %s"%(self._name, numpy.asmatrix( GradJo ).flatten()))
118             logging.debug("%s GradientOfCostFunction GradJ  = %s"%(self._name, numpy.asmatrix( GradJ  ).flatten()))
119             return GradJ.A1
120         #
121         # Point de démarrage de l'optimisation : Xini = Xb
122         # ------------------------------------
123         if type(Xb) is type(numpy.matrix([])):
124             Xini = Xb.A1.tolist()
125         else:
126             Xini = list(Xb)
127         logging.debug("%s Point de démarrage Xini = %s"%(self._name, Xini))
128         #
129         # Paramètres de pilotage
130         # ----------------------
131         # Potentiels : "Bounds", "Minimizer", "MaximumNumberOfSteps", "ProjectedGradientTolerance", "GradientNormTolerance", "InnerMinimizer"
132         if Parameters.has_key("Bounds") and (type(Parameters["Bounds"]) is type([]) or type(Parameters["Bounds"]) is type(())) and (len(Parameters["Bounds"]) > 0):
133             Bounds = Parameters["Bounds"]
134         else:
135             Bounds = None
136         MinimizerList = ["LBFGSB","TNC", "CG", "NCG", "BFGS"]
137         if Parameters.has_key("Minimizer") and (Parameters["Minimizer"] in MinimizerList):
138             Minimizer = str( Parameters["Minimizer"] )
139         else:
140             Minimizer = "LBFGSB"
141             logging.warning("%s Unknown or undefined minimizer, replaced by the default one \"%s\""%(self._name,Minimizer))
142         logging.debug("%s Minimiseur utilisé = %s"%(self._name, Minimizer))
143         if Parameters.has_key("MaximumNumberOfSteps") and (Parameters["MaximumNumberOfSteps"] > -1):
144             maxiter = int( Parameters["MaximumNumberOfSteps"] )
145         else:
146             maxiter = 15000
147         logging.debug("%s Nombre maximal de pas d'optimisation = %s"%(self._name, str(maxiter)))
148         if Parameters.has_key("CostDecrementTolerance") and (Parameters["CostDecrementTolerance"] > 0):
149             ftol  = float(Parameters["CostDecrementTolerance"])
150             factr = ftol * 1.e14
151         else:
152             ftol  = 1.e-7
153             factr = ftol * 1.e14
154         logging.debug("%s Diminution relative minimale du cout lors de l'arret = %s"%(self._name, str(1./factr)))
155         if Parameters.has_key("ProjectedGradientTolerance") and (Parameters["ProjectedGradientTolerance"] > -1):
156             pgtol = float(Parameters["ProjectedGradientTolerance"])
157         else:
158             pgtol = -1
159         logging.debug("%s Maximum des composantes du gradient projete lors de l'arret = %s"%(self._name, str(pgtol)))
160         if Parameters.has_key("GradientNormTolerance") and (Parameters["GradientNormTolerance"] > -1):
161             gtol = float(Parameters["GradientNormTolerance"])
162         else:
163             gtol = 1.e-05
164         logging.debug("%s Maximum des composantes du gradient lors de l'arret = %s"%(self._name, str(gtol)))
165         InnerMinimizerList = ["CG", "NCG", "BFGS"]
166         if Parameters.has_key("InnerMinimizer") and (Parameters["InnerMinimizer"] in InnerMinimizerList):
167             InnerMinimizer = str( Parameters["InnerMinimizer"] )
168         else:
169             InnerMinimizer = "BFGS"
170         logging.debug("%s Minimiseur interne utilisé = %s"%(self._name, InnerMinimizer))
171         #
172         # Minimisation de la fonctionnelle
173         # --------------------------------
174         if Minimizer == "LBFGSB":
175             Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
176                 func        = CostFunction,
177                 x0          = Xini,
178                 fprime      = GradientOfCostFunction,
179                 args        = (),
180                 bounds      = Bounds,
181                 maxfun      = maxiter-1,
182                 factr       = factr,
183                 pgtol       = pgtol,
184                 iprint      = iprint,
185                 )
186             nfeval = Informations['funcalls']
187             rc     = Informations['warnflag']
188         elif Minimizer == "TNC":
189             Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
190                 func        = CostFunction,
191                 x0          = Xini,
192                 fprime      = GradientOfCostFunction,
193                 args        = (),
194                 bounds      = Bounds,
195                 maxfun      = maxiter,
196                 pgtol       = pgtol,
197                 ftol        = ftol,
198                 messages    = message,
199                 )
200         elif Minimizer == "CG":
201             Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
202                 f           = CostFunction,
203                 x0          = Xini,
204                 fprime      = GradientOfCostFunction,
205                 args        = (),
206                 maxiter     = maxiter,
207                 gtol        = gtol,
208                 disp        = disp,
209                 full_output = True,
210                 )
211         elif Minimizer == "NCG":
212             Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
213                 f           = CostFunction,
214                 x0          = Xini,
215                 fprime      = GradientOfCostFunction,
216                 args        = (),
217                 maxiter     = maxiter,
218                 avextol     = ftol,
219                 disp        = disp,
220                 full_output = True,
221                 )
222         elif Minimizer == "BFGS":
223             Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
224                 f           = CostFunction,
225                 x0          = Xini,
226                 fprime      = GradientOfCostFunction,
227                 args        = (),
228                 maxiter     = maxiter,
229                 gtol        = gtol,
230                 disp        = disp,
231                 full_output = True,
232                 )
233         else:
234             raise ValueError("Error in Minimizer name: %s"%Minimizer)
235         #
236         # Correction pour pallier a un bug de TNC sur le retour du Minimum
237         # ----------------------------------------------------------------
238         StepMin = numpy.argmin( self.StoredVariables["CostFunctionJ"].valueserie() )
239         MinJ    = self.StoredVariables["CostFunctionJ"].valueserie(step = StepMin)
240         Minimum = self.StoredVariables["CurrentState"].valueserie(step = StepMin)
241         #
242         logging.debug("%s %s Step of min cost  = %s"%(self._name, Minimizer, StepMin))
243         logging.debug("%s %s Minimum cost      = %s"%(self._name, Minimizer, MinJ))
244         logging.debug("%s %s Minimum state     = %s"%(self._name, Minimizer, Minimum))
245         logging.debug("%s %s Nb of F           = %s"%(self._name, Minimizer, nfeval))
246         logging.debug("%s %s RetCode           = %s"%(self._name, Minimizer, rc))
247         #
248         # Calcul  de l'analyse
249         # --------------------
250         Xa = numpy.asmatrix(Minimum).T
251         logging.debug("%s Analyse Xa = %s"%(self._name, Xa))
252         #
253         self.StoredVariables["Analysis"].store( Xa.A1 )
254         self.StoredVariables["Innovation"].store( d.A1 )
255         #
256         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("MB")))
257         logging.debug("%s Terminé"%self._name)
258         #
259         return 0
260
261 # ==============================================================================
262 if __name__ == "__main__":
263     print '\n AUTODIAGNOSTIC \n'