Salome HOME
Improving and simplifying result variables access methods
[modules/adao.git] / src / daComposant / daAlgorithms / NonLinearLeastSquares.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2013 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, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
91         logging.debug("%s Lancement"%self._name)
92         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
93         #
94         # Paramètres de pilotage
95         # ----------------------
96         self.setParameters(Parameters)
97         #
98         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):
99             Bounds = self._parameters["Bounds"]
100             logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
101         else:
102             Bounds = None
103         #
104         # Correction pour pallier a un bug de TNC sur le retour du Minimum
105         if self._parameters.has_key("Minimizer") is "TNC":
106             self.setParameterValue("StoreInternalVariables",True)
107         #
108         # Opérateur d'observation
109         # -----------------------
110         Hm = HO["Direct"].appliedTo
111         Ha = HO["Adjoint"].appliedInXTo
112         #
113         # Utilisation éventuelle d'un vecteur H(Xb) précalculé
114         # ----------------------------------------------------
115         if HO["AppliedToX"] is not None and HO["AppliedToX"].has_key("HXb"):
116             HXb = HO["AppliedToX"]["HXb"]
117         else:
118             HXb = Hm( Xb )
119         HXb = numpy.asmatrix(numpy.ravel( HXb )).T
120         #
121         # Calcul de l'innovation
122         # ----------------------
123         if Y.size != HXb.size:
124             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))
125         if max(Y.shape) != max(HXb.shape):
126             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))
127         d  = Y - HXb
128         #
129         # Précalcul des inversions de B et R
130         # ----------------------------------
131         # if B is not None:
132         #     BI = B.I
133         # elif self._parameters["B_scalar"] is not None:
134         #     BI = 1.0 / self._parameters["B_scalar"]
135         # else:
136         #     raise ValueError("Background error covariance matrix has to be properly defined!")
137         #
138         if R is not None:
139             RI = R.I
140             if self._parameters["Minimizer"] == "LM":
141                 RdemiI = numpy.linalg.cholesky(R).I
142         elif self._parameters["R_scalar"] is not None:
143             RI = 1.0 / self._parameters["R_scalar"]
144             if self._parameters["Minimizer"] == "LM":
145                 import math
146                 RdemiI = 1.0 / math.sqrt( self._parameters["R_scalar"] )
147         else:
148             raise ValueError("Observation error covariance matrix has to be properly defined!")
149         #
150         # Définition de la fonction-coût
151         # ------------------------------
152         def CostFunction(x):
153             _X  = numpy.asmatrix(numpy.ravel( x )).T
154             _HX = Hm( _X )
155             _HX = numpy.asmatrix(numpy.ravel( _HX )).T
156             Jb  = 0.
157             Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
158             J   = float( Jb ) + float( Jo )
159             if self._parameters["StoreInternalVariables"]:
160                 self.StoredVariables["CurrentState"].store( _X.A1 )
161             self.StoredVariables["CostFunctionJb"].store( Jb )
162             self.StoredVariables["CostFunctionJo"].store( Jo )
163             self.StoredVariables["CostFunctionJ" ].store( J )
164             return J
165         #
166         def GradientOfCostFunction(x):
167             _X      = numpy.asmatrix(numpy.ravel( x )).T
168             _HX     = Hm( _X )
169             _HX     = numpy.asmatrix(numpy.ravel( _HX )).T
170             GradJb  = 0.
171             GradJo  = - Ha( (_X, RI * (Y - _HX)) )
172             GradJ   = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
173             return GradJ.A1
174         #
175         def CostFunctionLM(x):
176             _X  = numpy.asmatrix(numpy.ravel( x )).T
177             _HX = Hm( _X )
178             _HX = numpy.asmatrix(numpy.ravel( _HX )).T
179             Jb  = 0.
180             Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
181             J   = float( Jb ) + float( Jo )
182             if self._parameters["StoreInternalVariables"]:
183                 self.StoredVariables["CurrentState"].store( _X.A1 )
184             self.StoredVariables["CostFunctionJb"].store( Jb )
185             self.StoredVariables["CostFunctionJo"].store( Jo )
186             self.StoredVariables["CostFunctionJ" ].store( J )
187             #
188             return numpy.ravel( RdemiI*(Y - _HX) )
189         #
190         def GradientOfCostFunctionLM(x):
191             _X      = numpy.asmatrix(numpy.ravel( x )).T
192             _HX     = Hm( _X )
193             _HX     = numpy.asmatrix(numpy.ravel( _HX )).T
194             GradJb  = 0.
195             GradJo  = - Ha( (_X, RI * (Y - _HX)) )
196             GradJ   = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
197             return - RdemiI*HO["Tangent"].asMatrix( _X )
198         #
199         # Point de démarrage de l'optimisation : Xini = Xb
200         # ------------------------------------
201         if type(Xb) is type(numpy.matrix([])):
202             Xini = Xb.A1.tolist()
203         else:
204             Xini = list(Xb)
205         #
206         # Minimisation de la fonctionnelle
207         # --------------------------------
208         nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
209         #
210         if self._parameters["Minimizer"] == "LBFGSB":
211             Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
212                 func        = CostFunction,
213                 x0          = Xini,
214                 fprime      = GradientOfCostFunction,
215                 args        = (),
216                 bounds      = Bounds,
217                 maxfun      = self._parameters["MaximumNumberOfSteps"]-1,
218                 factr       = self._parameters["CostDecrementTolerance"]*1.e14,
219                 pgtol       = self._parameters["ProjectedGradientTolerance"],
220                 iprint      = iprint,
221                 )
222             nfeval = Informations['funcalls']
223             rc     = Informations['warnflag']
224         elif self._parameters["Minimizer"] == "TNC":
225             Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
226                 func        = CostFunction,
227                 x0          = Xini,
228                 fprime      = GradientOfCostFunction,
229                 args        = (),
230                 bounds      = Bounds,
231                 maxfun      = self._parameters["MaximumNumberOfSteps"],
232                 pgtol       = self._parameters["ProjectedGradientTolerance"],
233                 ftol        = self._parameters["CostDecrementTolerance"],
234                 messages    = message,
235                 )
236         elif self._parameters["Minimizer"] == "CG":
237             Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
238                 f           = CostFunction,
239                 x0          = Xini,
240                 fprime      = GradientOfCostFunction,
241                 args        = (),
242                 maxiter     = self._parameters["MaximumNumberOfSteps"],
243                 gtol        = self._parameters["GradientNormTolerance"],
244                 disp        = disp,
245                 full_output = True,
246                 )
247         elif self._parameters["Minimizer"] == "NCG":
248             Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
249                 f           = CostFunction,
250                 x0          = Xini,
251                 fprime      = GradientOfCostFunction,
252                 args        = (),
253                 maxiter     = self._parameters["MaximumNumberOfSteps"],
254                 avextol     = self._parameters["CostDecrementTolerance"],
255                 disp        = disp,
256                 full_output = True,
257                 )
258         elif self._parameters["Minimizer"] == "BFGS":
259             Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
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"] == "LM":
270             Minimum, cov_x, infodict, mesg, rc = scipy.optimize.leastsq(
271                 func        = CostFunctionLM,
272                 x0          = Xini,
273                 Dfun        = GradientOfCostFunctionLM,
274                 args        = (),
275                 ftol        = self._parameters["CostDecrementTolerance"],
276                 maxfev      = self._parameters["MaximumNumberOfSteps"],
277                 gtol        = self._parameters["GradientNormTolerance"],
278                 full_output = True,
279                 )
280             nfeval = infodict['nfev']
281         else:
282             raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
283         #
284         IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
285         MinJ    = self.StoredVariables["CostFunctionJ"][IndexMin]
286         #
287         # Correction pour pallier a un bug de TNC sur le retour du Minimum
288         # ----------------------------------------------------------------
289         if self._parameters["StoreInternalVariables"]:
290             Minimum = self.StoredVariables["CurrentState"][IndexMin]
291         #
292         # Obtention de l'analyse
293         # ----------------------
294         Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
295         #
296         self.StoredVariables["Analysis"].store( Xa.A1 )
297         #
298         # Calculs et/ou stockages supplémentaires
299         # ---------------------------------------
300         if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
301             self.StoredVariables["Innovation"].store( numpy.ravel(d) )
302         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
303             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
304         if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
305             self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(Hm(Xa)) )
306         if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
307             self.StoredVariables["OMB"].store( numpy.ravel(d) )
308         #
309         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
310         logging.debug("%s Terminé"%self._name)
311         #
312         return 0
313
314 # ==============================================================================
315 if __name__ == "__main__":
316     print '\n AUTODIAGNOSTIC \n'