Salome HOME
d488fb3f38d9fd1f95e0d57f5783c42674ebc48e
[modules/adao.git] / src / daComposant / daAlgorithms / NonLinearLeastSquares.py
1 #-*-coding:iso-8859-1-*-
2 #
3 # Copyright (C) 2008-2016 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
25 import numpy, scipy.optimize
26
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
29     def __init__(self):
30         BasicObjects.Algorithm.__init__(self, "NONLINEARLEASTSQUARES")
31         self.defineRequiredParameter(
32             name     = "Minimizer",
33             default  = "LBFGSB",
34             typecast = str,
35             message  = "Minimiseur utilisé",
36             listval  = ["LBFGSB","TNC", "CG", "NCG", "BFGS", "LM"],
37             )
38         self.defineRequiredParameter(
39             name     = "MaximumNumberOfSteps",
40             default  = 15000,
41             typecast = int,
42             message  = "Nombre maximal de pas d'optimisation",
43             minval   = -1,
44             )
45         self.defineRequiredParameter(
46             name     = "CostDecrementTolerance",
47             default  = 1.e-7,
48             typecast = float,
49             message  = "Diminution relative minimale du cout lors de l'arrêt",
50             )
51         self.defineRequiredParameter(
52             name     = "ProjectedGradientTolerance",
53             default  = -1,
54             typecast = float,
55             message  = "Maximum des composantes du gradient projeté lors de l'arrêt",
56             minval   = -1,
57             )
58         self.defineRequiredParameter(
59             name     = "GradientNormTolerance",
60             default  = 1.e-05,
61             typecast = float,
62             message  = "Maximum des composantes du gradient lors de l'arrêt",
63             )
64         self.defineRequiredParameter(
65             name     = "StoreInternalVariables",
66             default  = False,
67             typecast = bool,
68             message  = "Stockage des variables internes ou intermédiaires du calcul",
69             )
70         self.defineRequiredParameter(
71             name     = "StoreSupplementaryCalculations",
72             default  = [],
73             typecast = tuple,
74             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
75             listval  = ["BMA", "OMA", "OMB", "CurrentState", "CostFunctionJ", "CostFunctionJb", "CostFunctionJo", "Innovation", "SimulatedObservationAtCurrentState", "SimulatedObservationAtOptimum"]
76             )
77         self.defineRequiredParameter( # Pas de type
78             name     = "Bounds",
79             message  = "Liste des valeurs de bornes",
80             )
81
82     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
83         self._pre_run()
84         if logging.getLogger().level < logging.WARNING:
85             self.__iprint, self.__disp = 1, 1
86             self.__message = scipy.optimize.tnc.MSG_ALL
87         else:
88             self.__iprint, self.__disp = -1, 0
89             self.__message = scipy.optimize.tnc.MSG_NONE
90         #
91         # Paramètres de pilotage
92         # ----------------------
93         self.setParameters(Parameters)
94         #
95         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):
96             Bounds = self._parameters["Bounds"]
97             logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
98         else:
99             Bounds = None
100         #
101         # Correction pour pallier a un bug de TNC sur le retour du Minimum
102         if self._parameters.has_key("Minimizer") == "TNC":
103             self.setParameterValue("StoreInternalVariables",True)
104         #
105         # Opérateurs
106         # ----------
107         Hm = HO["Direct"].appliedTo
108         Ha = HO["Adjoint"].appliedInXTo
109         #
110         # Utilisation éventuelle d'un vecteur H(Xb) précalculé
111         # ----------------------------------------------------
112         if HO["AppliedToX"] is not None and HO["AppliedToX"].has_key("HXb"):
113             HXb = Hm( Xb, HO["AppliedToX"]["HXb"])
114         else:
115             HXb = Hm( Xb )
116         HXb = numpy.asmatrix(numpy.ravel( HXb )).T
117         #
118         # Calcul de l'innovation
119         # ----------------------
120         if Y.size != HXb.size:
121             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))
122         if max(Y.shape) != max(HXb.shape):
123             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))
124         d  = Y - HXb
125         #
126         # Précalcul des inversions de B et R
127         # ----------------------------------
128         RI = R.getI()
129         if self._parameters["Minimizer"] == "LM":
130             RdemiI = R.choleskyI()
131         #
132         # Définition de la fonction-coût
133         # ------------------------------
134         def CostFunction(x):
135             _X  = numpy.asmatrix(numpy.ravel( x )).T
136             if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
137                 self.StoredVariables["CurrentState"].store( _X )
138             _HX = Hm( _X )
139             _HX = numpy.asmatrix(numpy.ravel( _HX )).T
140             if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
141                 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
142             Jb  = 0.
143             Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
144             J   = float( Jb ) + float( Jo )
145             self.StoredVariables["CostFunctionJb"].store( Jb )
146             self.StoredVariables["CostFunctionJo"].store( Jo )
147             self.StoredVariables["CostFunctionJ" ].store( J )
148             return J
149         #
150         def GradientOfCostFunction(x):
151             _X      = numpy.asmatrix(numpy.ravel( x )).T
152             _HX     = Hm( _X )
153             _HX     = numpy.asmatrix(numpy.ravel( _HX )).T
154             GradJb  = 0.
155             GradJo  = - Ha( (_X, RI * (Y - _HX)) )
156             GradJ   = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
157             return GradJ.A1
158         #
159         def CostFunctionLM(x):
160             _X  = numpy.asmatrix(numpy.ravel( x )).T
161             _HX = Hm( _X )
162             _HX = numpy.asmatrix(numpy.ravel( _HX )).T
163             Jb  = 0.
164             Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
165             J   = float( Jb ) + float( Jo )
166             if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
167                 self.StoredVariables["CurrentState"].store( _X )
168             self.StoredVariables["CostFunctionJb"].store( Jb )
169             self.StoredVariables["CostFunctionJo"].store( Jo )
170             self.StoredVariables["CostFunctionJ" ].store( J )
171             #
172             return numpy.ravel( RdemiI*(Y - _HX) )
173         #
174         def GradientOfCostFunctionLM(x):
175             _X      = numpy.asmatrix(numpy.ravel( x )).T
176             _HX     = Hm( _X )
177             _HX     = numpy.asmatrix(numpy.ravel( _HX )).T
178             GradJb  = 0.
179             GradJo  = - Ha( (_X, RI * (Y - _HX)) )
180             GradJ   = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
181             return - RdemiI*HO["Tangent"].asMatrix( _X )
182         #
183         # Point de démarrage de l'optimisation : Xini = Xb
184         # ------------------------------------
185         if type(Xb) is type(numpy.matrix([])):
186             Xini = Xb.A1.tolist()
187         else:
188             Xini = list(Xb)
189         #
190         # Minimisation de la fonctionnelle
191         # --------------------------------
192         nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
193         #
194         if self._parameters["Minimizer"] == "LBFGSB":
195             Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
196                 func        = CostFunction,
197                 x0          = Xini,
198                 fprime      = GradientOfCostFunction,
199                 args        = (),
200                 bounds      = Bounds,
201                 maxfun      = self._parameters["MaximumNumberOfSteps"]-1,
202                 factr       = self._parameters["CostDecrementTolerance"]*1.e14,
203                 pgtol       = self._parameters["ProjectedGradientTolerance"],
204                 iprint      = self.__iprint,
205                 )
206             nfeval = Informations['funcalls']
207             rc     = Informations['warnflag']
208         elif self._parameters["Minimizer"] == "TNC":
209             Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
210                 func        = CostFunction,
211                 x0          = Xini,
212                 fprime      = GradientOfCostFunction,
213                 args        = (),
214                 bounds      = Bounds,
215                 maxfun      = self._parameters["MaximumNumberOfSteps"],
216                 pgtol       = self._parameters["ProjectedGradientTolerance"],
217                 ftol        = self._parameters["CostDecrementTolerance"],
218                 messages    = self.__message,
219                 )
220         elif self._parameters["Minimizer"] == "CG":
221             Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
222                 f           = CostFunction,
223                 x0          = Xini,
224                 fprime      = GradientOfCostFunction,
225                 args        = (),
226                 maxiter     = self._parameters["MaximumNumberOfSteps"],
227                 gtol        = self._parameters["GradientNormTolerance"],
228                 disp        = self.__disp,
229                 full_output = True,
230                 )
231         elif self._parameters["Minimizer"] == "NCG":
232             Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
233                 f           = CostFunction,
234                 x0          = Xini,
235                 fprime      = GradientOfCostFunction,
236                 args        = (),
237                 maxiter     = self._parameters["MaximumNumberOfSteps"],
238                 avextol     = self._parameters["CostDecrementTolerance"],
239                 disp        = self.__disp,
240                 full_output = True,
241                 )
242         elif self._parameters["Minimizer"] == "BFGS":
243             Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
244                 f           = CostFunction,
245                 x0          = Xini,
246                 fprime      = GradientOfCostFunction,
247                 args        = (),
248                 maxiter     = self._parameters["MaximumNumberOfSteps"],
249                 gtol        = self._parameters["GradientNormTolerance"],
250                 disp        = self.__disp,
251                 full_output = True,
252                 )
253         elif self._parameters["Minimizer"] == "LM":
254             Minimum, cov_x, infodict, mesg, rc = scipy.optimize.leastsq(
255                 func        = CostFunctionLM,
256                 x0          = Xini,
257                 Dfun        = GradientOfCostFunctionLM,
258                 args        = (),
259                 ftol        = self._parameters["CostDecrementTolerance"],
260                 maxfev      = self._parameters["MaximumNumberOfSteps"],
261                 gtol        = self._parameters["GradientNormTolerance"],
262                 full_output = True,
263                 )
264             nfeval = infodict['nfev']
265         else:
266             raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
267         #
268         IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
269         MinJ     = self.StoredVariables["CostFunctionJ"][IndexMin]
270         #
271         # Correction pour pallier a un bug de TNC sur le retour du Minimum
272         # ----------------------------------------------------------------
273         if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
274             Minimum = self.StoredVariables["CurrentState"][IndexMin]
275         #
276         # Obtention de l'analyse
277         # ----------------------
278         Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
279         #
280         self.StoredVariables["Analysis"].store( Xa.A1 )
281         #
282         if "OMA"                           in self._parameters["StoreSupplementaryCalculations"] or \
283            "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
284             HXa = Hm(Xa)
285         #
286         #
287         # Calculs et/ou stockages supplémentaires
288         # ---------------------------------------
289         if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
290             self.StoredVariables["Innovation"].store( numpy.ravel(d) )
291         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
292             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
293         if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
294             self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
295         if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
296             self.StoredVariables["OMB"].store( numpy.ravel(d) )
297         if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
298             self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
299         #
300         self._post_run(HO)
301         return 0
302
303 # ==============================================================================
304 if __name__ == "__main__":
305     print '\n AUTODIAGNOSTIC \n'