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