Salome HOME
Documentation corrections for outputs
[modules/adao.git] / src / daComposant / daAlgorithms / NonLinearLeastSquares.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2015 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", "Innovation", "SimulatedObservationAtCurrentState", "SimulatedObservationAtOptimum"]
76             )
77
78     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
79         self._pre_run()
80         if logging.getLogger().level < logging.WARNING:
81             self.__iprint, self.__disp = 1, 1
82             self.__message = scipy.optimize.tnc.MSG_ALL
83         else:
84             self.__iprint, self.__disp = -1, 0
85             self.__message = scipy.optimize.tnc.MSG_NONE
86         #
87         # Paramètres de pilotage
88         # ----------------------
89         self.setParameters(Parameters)
90         #
91         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):
92             Bounds = self._parameters["Bounds"]
93             logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
94         else:
95             Bounds = None
96         #
97         # Correction pour pallier a un bug de TNC sur le retour du Minimum
98         if self._parameters.has_key("Minimizer") == "TNC":
99             self.setParameterValue("StoreInternalVariables",True)
100         #
101         # Opérateurs
102         # ----------
103         Hm = HO["Direct"].appliedTo
104         Ha = HO["Adjoint"].appliedInXTo
105         #
106         # Utilisation éventuelle d'un vecteur H(Xb) précalculé
107         # ----------------------------------------------------
108         if HO["AppliedToX"] is not None and HO["AppliedToX"].has_key("HXb"):
109             HXb = HO["AppliedToX"]["HXb"]
110         else:
111             HXb = Hm( Xb )
112         HXb = numpy.asmatrix(numpy.ravel( HXb )).T
113         #
114         # Calcul de l'innovation
115         # ----------------------
116         if Y.size != HXb.size:
117             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))
118         if max(Y.shape) != max(HXb.shape):
119             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))
120         d  = Y - HXb
121         #
122         # Précalcul des inversions de B et R
123         # ----------------------------------
124         RI = R.getI()
125         if self._parameters["Minimizer"] == "LM":
126             RdemiI = R.choleskyI()
127         #
128         # Définition de la fonction-coût
129         # ------------------------------
130         def CostFunction(x):
131             _X  = numpy.asmatrix(numpy.ravel( x )).T
132             _HX = Hm( _X )
133             _HX = numpy.asmatrix(numpy.ravel( _HX )).T
134             Jb  = 0.
135             Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
136             J   = float( Jb ) + float( Jo )
137             if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
138                 self.StoredVariables["CurrentState"].store( _X )
139             if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
140                 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
141             self.StoredVariables["CostFunctionJb"].store( Jb )
142             self.StoredVariables["CostFunctionJo"].store( Jo )
143             self.StoredVariables["CostFunctionJ" ].store( J )
144             return J
145         #
146         def GradientOfCostFunction(x):
147             _X      = numpy.asmatrix(numpy.ravel( x )).T
148             _HX     = Hm( _X )
149             _HX     = numpy.asmatrix(numpy.ravel( _HX )).T
150             GradJb  = 0.
151             GradJo  = - Ha( (_X, RI * (Y - _HX)) )
152             GradJ   = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
153             return GradJ.A1
154         #
155         def CostFunctionLM(x):
156             _X  = numpy.asmatrix(numpy.ravel( x )).T
157             _HX = Hm( _X )
158             _HX = numpy.asmatrix(numpy.ravel( _HX )).T
159             Jb  = 0.
160             Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
161             J   = float( Jb ) + float( Jo )
162             if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
163                 self.StoredVariables["CurrentState"].store( _X )
164             self.StoredVariables["CostFunctionJb"].store( Jb )
165             self.StoredVariables["CostFunctionJo"].store( Jo )
166             self.StoredVariables["CostFunctionJ" ].store( J )
167             #
168             return numpy.ravel( RdemiI*(Y - _HX) )
169         #
170         def GradientOfCostFunctionLM(x):
171             _X      = numpy.asmatrix(numpy.ravel( x )).T
172             _HX     = Hm( _X )
173             _HX     = numpy.asmatrix(numpy.ravel( _HX )).T
174             GradJb  = 0.
175             GradJo  = - Ha( (_X, RI * (Y - _HX)) )
176             GradJ   = numpy.asmatrix( numpy.ravel( GradJb ) + numpy.ravel( GradJo ) ).T
177             return - RdemiI*HO["Tangent"].asMatrix( _X )
178         #
179         # Point de démarrage de l'optimisation : Xini = Xb
180         # ------------------------------------
181         if type(Xb) is type(numpy.matrix([])):
182             Xini = Xb.A1.tolist()
183         else:
184             Xini = list(Xb)
185         #
186         # Minimisation de la fonctionnelle
187         # --------------------------------
188         nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
189         #
190         if self._parameters["Minimizer"] == "LBFGSB":
191             Minimum, J_optimal, Informations = scipy.optimize.fmin_l_bfgs_b(
192                 func        = CostFunction,
193                 x0          = Xini,
194                 fprime      = GradientOfCostFunction,
195                 args        = (),
196                 bounds      = Bounds,
197                 maxfun      = self._parameters["MaximumNumberOfSteps"]-1,
198                 factr       = self._parameters["CostDecrementTolerance"]*1.e14,
199                 pgtol       = self._parameters["ProjectedGradientTolerance"],
200                 iprint      = self.__iprint,
201                 )
202             nfeval = Informations['funcalls']
203             rc     = Informations['warnflag']
204         elif self._parameters["Minimizer"] == "TNC":
205             Minimum, nfeval, rc = scipy.optimize.fmin_tnc(
206                 func        = CostFunction,
207                 x0          = Xini,
208                 fprime      = GradientOfCostFunction,
209                 args        = (),
210                 bounds      = Bounds,
211                 maxfun      = self._parameters["MaximumNumberOfSteps"],
212                 pgtol       = self._parameters["ProjectedGradientTolerance"],
213                 ftol        = self._parameters["CostDecrementTolerance"],
214                 messages    = self.__message,
215                 )
216         elif self._parameters["Minimizer"] == "CG":
217             Minimum, fopt, nfeval, grad_calls, rc = scipy.optimize.fmin_cg(
218                 f           = CostFunction,
219                 x0          = Xini,
220                 fprime      = GradientOfCostFunction,
221                 args        = (),
222                 maxiter     = self._parameters["MaximumNumberOfSteps"],
223                 gtol        = self._parameters["GradientNormTolerance"],
224                 disp        = self.__disp,
225                 full_output = True,
226                 )
227         elif self._parameters["Minimizer"] == "NCG":
228             Minimum, fopt, nfeval, grad_calls, hcalls, rc = scipy.optimize.fmin_ncg(
229                 f           = CostFunction,
230                 x0          = Xini,
231                 fprime      = GradientOfCostFunction,
232                 args        = (),
233                 maxiter     = self._parameters["MaximumNumberOfSteps"],
234                 avextol     = self._parameters["CostDecrementTolerance"],
235                 disp        = self.__disp,
236                 full_output = True,
237                 )
238         elif self._parameters["Minimizer"] == "BFGS":
239             Minimum, fopt, gopt, Hopt, nfeval, grad_calls, rc = scipy.optimize.fmin_bfgs(
240                 f           = CostFunction,
241                 x0          = Xini,
242                 fprime      = GradientOfCostFunction,
243                 args        = (),
244                 maxiter     = self._parameters["MaximumNumberOfSteps"],
245                 gtol        = self._parameters["GradientNormTolerance"],
246                 disp        = self.__disp,
247                 full_output = True,
248                 )
249         elif self._parameters["Minimizer"] == "LM":
250             Minimum, cov_x, infodict, mesg, rc = scipy.optimize.leastsq(
251                 func        = CostFunctionLM,
252                 x0          = Xini,
253                 Dfun        = GradientOfCostFunctionLM,
254                 args        = (),
255                 ftol        = self._parameters["CostDecrementTolerance"],
256                 maxfev      = self._parameters["MaximumNumberOfSteps"],
257                 gtol        = self._parameters["GradientNormTolerance"],
258                 full_output = True,
259                 )
260             nfeval = infodict['nfev']
261         else:
262             raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
263         #
264         IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
265         MinJ     = self.StoredVariables["CostFunctionJ"][IndexMin]
266         #
267         # Correction pour pallier a un bug de TNC sur le retour du Minimum
268         # ----------------------------------------------------------------
269         if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
270             Minimum = self.StoredVariables["CurrentState"][IndexMin]
271         #
272         # Obtention de l'analyse
273         # ----------------------
274         Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
275         #
276         self.StoredVariables["Analysis"].store( Xa.A1 )
277         #
278         if "OMA"                           in self._parameters["StoreSupplementaryCalculations"] or \
279            "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
280             HXa = Hm(Xa)
281         #
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(HXa) )
291         if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
292             self.StoredVariables["OMB"].store( numpy.ravel(d) )
293         if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
294             self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
295         #
296         self._post_run(HO)
297         return 0
298
299 # ==============================================================================
300 if __name__ == "__main__":
301     print '\n AUTODIAGNOSTIC \n'