]> SALOME platform Git repositories - modules/adao.git/blob - src/daComposant/daAlgorithms/NonLinearLeastSquares.py
Salome HOME
Adding Levenberg-Marquardt algorithm
[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 #  Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
22
23 import logging
24 from daCore import BasicObjects, PlatformInfo
25 m = PlatformInfo.SystemUsage()
26
27 import numpy
28 import scipy.optimize
29
30 if logging.getLogger().level < logging.WARNING:
31     iprint  = 1
32     message = scipy.optimize.tnc.MSG_ALL
33     disp    = 1
34 else:
35     iprint  = -1
36     message = scipy.optimize.tnc.MSG_NONE
37     disp    = 0
38
39 # ==============================================================================
40 class ElementaryAlgorithm(BasicObjects.Algorithm):
41     def __init__(self):
42         BasicObjects.Algorithm.__init__(self, "NONLINEARLEASTSQUARES")
43         self.defineRequiredParameter(
44             name     = "Minimizer",
45             default  = "LBFGSB",
46             typecast = str,
47             message  = "Minimiseur utilisé",
48             listval  = ["LBFGSB","TNC", "CG", "NCG", "BFGS", "LM"],
49             )
50         self.defineRequiredParameter(
51             name     = "MaximumNumberOfSteps",
52             default  = 15000,
53             typecast = int,
54             message  = "Nombre maximal de pas d'optimisation",
55             minval   = -1,
56             )
57         self.defineRequiredParameter(
58             name     = "CostDecrementTolerance",
59             default  = 1.e-7,
60             typecast = float,
61             message  = "Diminution relative minimale du cout lors de l'arrêt",
62             )
63         self.defineRequiredParameter(
64             name     = "ProjectedGradientTolerance",
65             default  = -1,
66             typecast = float,
67             message  = "Maximum des composantes du gradient projeté lors de l'arrêt",
68             minval   = -1,
69             )
70         self.defineRequiredParameter(
71             name     = "GradientNormTolerance",
72             default  = 1.e-05,
73             typecast = float,
74             message  = "Maximum des composantes du gradient lors de l'arrêt",
75             )
76         self.defineRequiredParameter(
77             name     = "StoreInternalVariables",
78             default  = False,
79             typecast = bool,
80             message  = "Stockage des variables internes ou intermédiaires du calcul",
81             )
82         self.defineRequiredParameter(
83             name     = "StoreSupplementaryCalculations",
84             default  = [],
85             typecast = tuple,
86             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
87             listval  = ["BMA", "OMA", "OMB", "Innovation"]
88             )
89
90     def run(self, Xb=None, Y=None, H=None, M=None, R=None, B=None, Q=None, Parameters=None):
91         """
92         Calcul de l'estimateur moindres carrés pondérés non linéaires
93         (assimilation variationnelle sans ébauche)
94         """
95         logging.debug("%s Lancement"%self._name)
96         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
97         #
98         # Paramètres de pilotage
99         # ----------------------
100         self.setParameters(Parameters)
101         #
102         if self._parameters.has_key("Bounds") and (type(self._parameters["Bounds"]) is type([]) or type(self._parameters["Bounds"]) is type(())) and (len(self._parameters["Bounds"]) > 0):
103             Bounds = self._parameters["Bounds"]
104             logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
105         else:
106             Bounds = None
107         #
108         # Correction pour pallier a un bug de TNC sur le retour du Minimum
109         if self._parameters.has_key("Minimizer") is "TNC":
110             self.setParameterValue("StoreInternalVariables",True)
111         #
112         # Opérateur d'observation
113         # -----------------------
114         Hm = H["Direct"].appliedTo
115         Ha = H["Adjoint"].appliedInXTo
116         #
117         # Utilisation éventuelle d'un vecteur H(Xb) précalculé
118         # ----------------------------------------------------
119         if H["AppliedToX"] is not None and H["AppliedToX"].has_key("HXb"):
120             logging.debug("%s Utilisation de HXb"%self._name)
121             HXb = H["AppliedToX"]["HXb"]
122         else:
123             logging.debug("%s Calcul de Hm(Xb)"%self._name)
124             HXb = Hm( Xb )
125         HXb = numpy.asmatrix(HXb).flatten().T
126         #
127         # Calcul de l'innovation
128         # ----------------------
129         if Y.size != HXb.size:
130             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))
131         if max(Y.shape) != max(HXb.shape):
132             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))
133         d  = Y - HXb
134         logging.debug("%s Innovation d = %s"%(self._name, d))
135         #
136         # Précalcul des inversions de B et R
137         # ----------------------------------
138         # if B is not None:
139         #     BI = B.I
140         # elif self._parameters["B_scalar"] is not None:
141         #     BI = 1.0 / self._parameters["B_scalar"]
142         # else:
143         #     raise ValueError("Background error covariance matrix has to be properly defined!")
144         #
145         if R is not None:
146             RI = R.I
147             if self._parameters["Minimizer"] == "LM":
148                 RdemiI = numpy.linalg.cholesky(R).I
149         elif self._parameters["R_scalar"] is not None:
150             RI = 1.0 / self._parameters["R_scalar"]
151             if self._parameters["Minimizer"] == "LM":
152                 import math
153                 RdemiI = 1.0 / math.sqrt( self._parameters["R_scalar"] )
154         else:
155             raise ValueError("Observation error covariance matrix has to be properly defined!")
156         #
157         # Définition de la fonction-coût
158         # ------------------------------
159         def CostFunction(x):
160             _X  = numpy.asmatrix(x).flatten().T
161             logging.debug("%s CostFunction X  = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
162             _HX = Hm( _X )
163             _HX = numpy.asmatrix(_HX).flatten().T
164             Jb  = 0.
165             Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
166             J   = float( Jb ) + float( Jo )
167             logging.debug("%s CostFunction Jb = %s"%(self._name, Jb))
168             logging.debug("%s CostFunction Jo = %s"%(self._name, Jo))
169             logging.debug("%s CostFunction J  = %s"%(self._name, J))
170             if self._parameters["StoreInternalVariables"]:
171                 self.StoredVariables["CurrentState"].store( _X.A1 )
172             self.StoredVariables["CostFunctionJb"].store( Jb )
173             self.StoredVariables["CostFunctionJo"].store( Jo )
174             self.StoredVariables["CostFunctionJ" ].store( J )
175             return J
176         #
177         def GradientOfCostFunction(x):
178             _X      = numpy.asmatrix(x).flatten().T
179             logging.debug("%s GradientOfCostFunction X      = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
180             _HX     = Hm( _X )
181             _HX     = numpy.asmatrix(_HX).flatten().T
182             GradJb  = 0.
183             GradJo  = - Ha( (_X, RI * (Y - _HX)) )
184             GradJ   = numpy.asmatrix( GradJb ).flatten().T + numpy.asmatrix( GradJo ).flatten().T
185             logging.debug("%s GradientOfCostFunction GradJb = %s"%(self._name, numpy.asmatrix( GradJb ).flatten()))
186             logging.debug("%s GradientOfCostFunction GradJo = %s"%(self._name, numpy.asmatrix( GradJo ).flatten()))
187             logging.debug("%s GradientOfCostFunction GradJ  = %s"%(self._name, numpy.asmatrix( GradJ  ).flatten()))
188             return GradJ.A1
189         #
190         def CostFunctionLM(x):
191             _X  = numpy.asmatrix(x).flatten().T
192             logging.debug("%s CostFunction X  = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
193             _HX = Hm( _X )
194             _HX = numpy.asmatrix(_HX).flatten().T
195             Jb  = 0.
196             Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
197             J   = float( Jb ) + float( Jo )
198             logging.debug("%s CostFunction Jb = %s"%(self._name, Jb))
199             logging.debug("%s CostFunction Jo = %s"%(self._name, Jo))
200             logging.debug("%s CostFunction J  = %s"%(self._name, J))
201             if self._parameters["StoreInternalVariables"]:
202                 self.StoredVariables["CurrentState"].store( _X.A1 )
203             self.StoredVariables["CostFunctionJb"].store( Jb )
204             self.StoredVariables["CostFunctionJo"].store( Jo )
205             self.StoredVariables["CostFunctionJ" ].store( J )
206             #
207             return numpy.asmatrix( RdemiI*(Y - _HX) ).flatten().A1
208         #
209         def GradientOfCostFunctionLM(x):
210             _X      = numpy.asmatrix(x).flatten().T
211             logging.debug("%s GradientOfCostFunction X      = %s"%(self._name, numpy.asmatrix( _X ).flatten()))
212             _HX     = Hm( _X )
213             _HX     = numpy.asmatrix(_HX).flatten().T
214             GradJb  = 0.
215             GradJo  = - Ha( (_X, RI * (Y - _HX)) )
216             GradJ   = numpy.asmatrix( GradJb ).flatten().T + numpy.asmatrix( GradJo ).flatten().T
217             logging.debug("%s GradientOfCostFunction GradJb = %s"%(self._name, numpy.asmatrix( GradJb ).flatten()))
218             logging.debug("%s GradientOfCostFunction GradJo = %s"%(self._name, numpy.asmatrix( GradJo ).flatten()))
219             logging.debug("%s GradientOfCostFunction GradJ  = %s"%(self._name, numpy.asmatrix( GradJ  ).flatten()))
220             return - RdemiI*H["Tangent"].asMatrix( _X )
221         #
222         # Point de démarrage de l'optimisation : Xini = Xb
223         # ------------------------------------
224         if type(Xb) is type(numpy.matrix([])):
225             Xini = Xb.A1.tolist()
226         else:
227             Xini = list(Xb)
228         logging.debug("%s Point de démarrage Xini = %s"%(self._name, Xini))
229         #
230         # Minimisation de la fonctionnelle
231         # --------------------------------
232         if self._parameters["Minimizer"] == "LBFGSB":
233             Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
234                 func        = CostFunction,
235                 x0          = Xini,
236                 fprime      = GradientOfCostFunction,
237                 args        = (),
238                 bounds      = Bounds,
239                 maxfun      = self._parameters["MaximumNumberOfSteps"]-1,
240                 factr       = self._parameters["CostDecrementTolerance"]*1.e14,
241                 pgtol       = self._parameters["ProjectedGradientTolerance"],
242                 iprint      = iprint,
243                 )
244             nfeval = Informations['funcalls']
245             rc     = Informations['warnflag']
246         elif self._parameters["Minimizer"] == "TNC":
247             Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
248                 func        = CostFunction,
249                 x0          = Xini,
250                 fprime      = GradientOfCostFunction,
251                 args        = (),
252                 bounds      = Bounds,
253                 maxfun      = self._parameters["MaximumNumberOfSteps"],
254                 pgtol       = self._parameters["ProjectedGradientTolerance"],
255                 ftol        = self._parameters["CostDecrementTolerance"],
256                 messages    = message,
257                 )
258         elif self._parameters["Minimizer"] == "CG":
259             Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
260                 f           = CostFunction,
261                 x0          = Xini,
262                 fprime      = GradientOfCostFunction,
263                 args        = (),
264                 maxiter     = self._parameters["MaximumNumberOfSteps"],
265                 gtol        = self._parameters["GradientNormTolerance"],
266                 disp        = disp,
267                 full_output = True,
268                 )
269         elif self._parameters["Minimizer"] == "NCG":
270             Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
271                 f           = CostFunction,
272                 x0          = Xini,
273                 fprime      = GradientOfCostFunction,
274                 args        = (),
275                 maxiter     = self._parameters["MaximumNumberOfSteps"],
276                 avextol     = self._parameters["CostDecrementTolerance"],
277                 disp        = disp,
278                 full_output = True,
279                 )
280         elif self._parameters["Minimizer"] == "BFGS":
281             Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
282                 f           = CostFunction,
283                 x0          = Xini,
284                 fprime      = GradientOfCostFunction,
285                 args        = (),
286                 maxiter     = self._parameters["MaximumNumberOfSteps"],
287                 gtol        = self._parameters["GradientNormTolerance"],
288                 disp        = disp,
289                 full_output = True,
290                 )
291         elif self._parameters["Minimizer"] == "LM":
292             Minimum, cov_x, infodict, mesg, rc = scipy.optimize.leastsq(
293                 func        = CostFunctionLM,
294                 x0          = Xini,
295                 Dfun        = GradientOfCostFunctionLM,
296                 args        = (),
297                 ftol        = self._parameters["CostDecrementTolerance"],
298                 maxfev      = self._parameters["MaximumNumberOfSteps"],
299                 gtol        = self._parameters["GradientNormTolerance"],
300                 full_output = True,
301                 )
302             nfeval = infodict['nfev']
303         else:
304             raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
305         #
306         StepMin = numpy.argmin( self.StoredVariables["CostFunctionJ"].valueserie() )
307         MinJ    = self.StoredVariables["CostFunctionJ"].valueserie(step = StepMin)
308         #
309         # Correction pour pallier a un bug de TNC sur le retour du Minimum
310         # ----------------------------------------------------------------
311         if self._parameters["StoreInternalVariables"]:
312             Minimum = self.StoredVariables["CurrentState"].valueserie(step = StepMin)
313         #
314         logging.debug("%s %s Step of min cost  = %s"%(self._name, self._parameters["Minimizer"], StepMin))
315         logging.debug("%s %s Minimum cost      = %s"%(self._name, self._parameters["Minimizer"], MinJ))
316         logging.debug("%s %s Minimum state     = %s"%(self._name, self._parameters["Minimizer"], Minimum))
317         logging.debug("%s %s Nb of F           = %s"%(self._name, self._parameters["Minimizer"], nfeval))
318         logging.debug("%s %s RetCode           = %s"%(self._name, self._parameters["Minimizer"], rc))
319         #
320         # Obtention de l'analyse
321         # ----------------------
322         Xa = numpy.asmatrix(Minimum).flatten().T
323         logging.debug("%s Analyse Xa = %s"%(self._name, Xa))
324         #
325         self.StoredVariables["Analysis"].store( Xa.A1 )
326         #
327         # Calculs et/ou stockages supplémentaires
328         # ---------------------------------------
329         if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
330             self.StoredVariables["Innovation"].store( numpy.asmatrix(d).flatten().A1 )
331         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
332             self.StoredVariables["BMA"].store( numpy.asmatrix(Xb - Xa).flatten().A1 )
333         if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
334             self.StoredVariables["OMA"].store( numpy.asmatrix(Y - Hm(Xa)).flatten().A1 )
335         if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
336             self.StoredVariables["OMB"].store( numpy.asmatrix(d).flatten().A1 )
337         #
338         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
339         logging.debug("%s Terminé"%self._name)
340         #
341         return 0
342
343 # ==============================================================================
344 if __name__ == "__main__":
345     print '\n AUTODIAGNOSTIC \n'