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