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