Salome HOME
Minor source corrections for compatibility
[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") == "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         RI = R.getI()
132         if self._parameters["Minimizer"] == "LM":
133             RdemiI = R.choleskyI()
134         #
135         # Définition de la fonction-coût
136         # ------------------------------
137         def CostFunction(x):
138             _X  = numpy.asmatrix(numpy.ravel( x )).T
139             _HX = Hm( _X )
140             _HX = numpy.asmatrix(numpy.ravel( _HX )).T
141             Jb  = 0.
142             Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
143             J   = float( Jb ) + float( Jo )
144             if self._parameters["StoreInternalVariables"]:
145                 self.StoredVariables["CurrentState"].store( _X.A1 )
146             self.StoredVariables["CostFunctionJb"].store( Jb )
147             self.StoredVariables["CostFunctionJo"].store( Jo )
148             self.StoredVariables["CostFunctionJ" ].store( J )
149             return J
150         #
151         def GradientOfCostFunction(x):
152             _X      = numpy.asmatrix(numpy.ravel( x )).T
153             _HX     = Hm( _X )
154             _HX     = numpy.asmatrix(numpy.ravel( _HX )).T
155             GradJb  = 0.
156             GradJo  = - Ha( (_X, RI * (Y - _HX)) )
157             GradJ   = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
158             return GradJ.A1
159         #
160         def CostFunctionLM(x):
161             _X  = numpy.asmatrix(numpy.ravel( x )).T
162             _HX = Hm( _X )
163             _HX = numpy.asmatrix(numpy.ravel( _HX )).T
164             Jb  = 0.
165             Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
166             J   = float( Jb ) + float( Jo )
167             if self._parameters["StoreInternalVariables"]:
168                 self.StoredVariables["CurrentState"].store( _X.A1 )
169             self.StoredVariables["CostFunctionJb"].store( Jb )
170             self.StoredVariables["CostFunctionJo"].store( Jo )
171             self.StoredVariables["CostFunctionJ" ].store( J )
172             #
173             return numpy.ravel( RdemiI*(Y - _HX) )
174         #
175         def GradientOfCostFunctionLM(x):
176             _X      = numpy.asmatrix(numpy.ravel( x )).T
177             _HX     = Hm( _X )
178             _HX     = numpy.asmatrix(numpy.ravel( _HX )).T
179             GradJb  = 0.
180             GradJo  = - Ha( (_X, RI * (Y - _HX)) )
181             GradJ   = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
182             return - RdemiI*HO["Tangent"].asMatrix( _X )
183         #
184         # Point de démarrage de l'optimisation : Xini = Xb
185         # ------------------------------------
186         if type(Xb) is type(numpy.matrix([])):
187             Xini = Xb.A1.tolist()
188         else:
189             Xini = list(Xb)
190         #
191         # Minimisation de la fonctionnelle
192         # --------------------------------
193         nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
194         #
195         if self._parameters["Minimizer"] == "LBFGSB":
196             Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
197                 func        = CostFunction,
198                 x0          = Xini,
199                 fprime      = GradientOfCostFunction,
200                 args        = (),
201                 bounds      = Bounds,
202                 maxfun      = self._parameters["MaximumNumberOfSteps"]-1,
203                 factr       = self._parameters["CostDecrementTolerance"]*1.e14,
204                 pgtol       = self._parameters["ProjectedGradientTolerance"],
205                 iprint      = iprint,
206                 )
207             nfeval = Informations['funcalls']
208             rc     = Informations['warnflag']
209         elif self._parameters["Minimizer"] == "TNC":
210             Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
211                 func        = CostFunction,
212                 x0          = Xini,
213                 fprime      = GradientOfCostFunction,
214                 args        = (),
215                 bounds      = Bounds,
216                 maxfun      = self._parameters["MaximumNumberOfSteps"],
217                 pgtol       = self._parameters["ProjectedGradientTolerance"],
218                 ftol        = self._parameters["CostDecrementTolerance"],
219                 messages    = message,
220                 )
221         elif self._parameters["Minimizer"] == "CG":
222             Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
223                 f           = CostFunction,
224                 x0          = Xini,
225                 fprime      = GradientOfCostFunction,
226                 args        = (),
227                 maxiter     = self._parameters["MaximumNumberOfSteps"],
228                 gtol        = self._parameters["GradientNormTolerance"],
229                 disp        = disp,
230                 full_output = True,
231                 )
232         elif self._parameters["Minimizer"] == "NCG":
233             Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
234                 f           = CostFunction,
235                 x0          = Xini,
236                 fprime      = GradientOfCostFunction,
237                 args        = (),
238                 maxiter     = self._parameters["MaximumNumberOfSteps"],
239                 avextol     = self._parameters["CostDecrementTolerance"],
240                 disp        = disp,
241                 full_output = True,
242                 )
243         elif self._parameters["Minimizer"] == "BFGS":
244             Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
245                 f           = CostFunction,
246                 x0          = Xini,
247                 fprime      = GradientOfCostFunction,
248                 args        = (),
249                 maxiter     = self._parameters["MaximumNumberOfSteps"],
250                 gtol        = self._parameters["GradientNormTolerance"],
251                 disp        = disp,
252                 full_output = True,
253                 )
254         elif self._parameters["Minimizer"] == "LM":
255             Minimum, cov_x, infodict, mesg, rc = scipy.optimize.leastsq(
256                 func        = CostFunctionLM,
257                 x0          = Xini,
258                 Dfun        = GradientOfCostFunctionLM,
259                 args        = (),
260                 ftol        = self._parameters["CostDecrementTolerance"],
261                 maxfev      = self._parameters["MaximumNumberOfSteps"],
262                 gtol        = self._parameters["GradientNormTolerance"],
263                 full_output = True,
264                 )
265             nfeval = infodict['nfev']
266         else:
267             raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
268         #
269         IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
270         MinJ     = self.StoredVariables["CostFunctionJ"][IndexMin]
271         #
272         # Correction pour pallier a un bug de TNC sur le retour du Minimum
273         # ----------------------------------------------------------------
274         if self._parameters["StoreInternalVariables"]:
275             Minimum = self.StoredVariables["CurrentState"][IndexMin]
276         #
277         # Obtention de l'analyse
278         # ----------------------
279         Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
280         #
281         self.StoredVariables["Analysis"].store( Xa.A1 )
282         #
283         # Calculs et/ou stockages supplémentaires
284         # ---------------------------------------
285         if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
286             self.StoredVariables["Innovation"].store( numpy.ravel(d) )
287         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
288             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
289         if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
290             self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(Hm(Xa)) )
291         if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
292             self.StoredVariables["OMB"].store( numpy.ravel(d) )
293         #
294         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
295         logging.debug("%s Terminé"%self._name)
296         #
297         return 0
298
299 # ==============================================================================
300 if __name__ == "__main__":
301     print '\n AUTODIAGNOSTIC \n'