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