]> SALOME platform Git repositories - modules/adao.git/blob - src/daComposant/daAlgorithms/DerivativeFreeOptimization.py
Salome HOME
Internal tests improvements and version update
[modules/adao.git] / src / daComposant / daAlgorithms / DerivativeFreeOptimization.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, PlatformInfo
25 import numpy, scipy.optimize
26
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
29     def __init__(self):
30         BasicObjects.Algorithm.__init__(self, "DERIVATIVEFREEOPTIMIZATION")
31         self.defineRequiredParameter(
32             name     = "Minimizer",
33             default  = "BOBYQA",
34             typecast = str,
35             message  = "Minimiseur utilisé",
36             listval  = ["BOBYQA", "COBYLA", "NEWUOA", "POWELL", "SIMPLEX", "SUBPLEX"],
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     = "MaximumNumberOfFunctionEvaluations",
47             default  = 15000,
48             typecast = int,
49             message  = "Nombre maximal d'évaluations de la fonction",
50             minval   = -1,
51             )
52         self.defineRequiredParameter(
53             name     = "StateVariationTolerance",
54             default  = 1.e-4,
55             typecast = float,
56             message  = "Variation relative maximale de l'état lors de l'arrêt",
57             )
58         self.defineRequiredParameter(
59             name     = "CostDecrementTolerance",
60             default  = 1.e-7,
61             typecast = float,
62             message  = "Diminution relative minimale du cout lors de l'arrêt",
63             )
64         self.defineRequiredParameter(
65             name     = "QualityCriterion",
66             default  = "AugmentedWeightedLeastSquares",
67             typecast = str,
68             message  = "Critère de qualité utilisé",
69             listval  = ["AugmentedWeightedLeastSquares","AWLS","DA",
70                         "WeightedLeastSquares","WLS",
71                         "LeastSquares","LS","L2",
72                         "AbsoluteValue","L1",
73                         "MaximumError","ME"],
74             )
75         self.defineRequiredParameter(
76             name     = "StoreInternalVariables",
77             default  = False,
78             typecast = bool,
79             message  = "Stockage des variables internes ou intermédiaires du calcul",
80             )
81         self.defineRequiredParameter(
82             name     = "StoreSupplementaryCalculations",
83             default  = [],
84             typecast = tuple,
85             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
86             listval  = ["CurrentState", "CostFunctionJ", "CostFunctionJb", "CostFunctionJo", "CostFunctionJAtCurrentOptimum", "CurrentOptimum", "IndexOfOptimum", "InnovationAtCurrentState", "BMA", "OMA", "OMB", "SimulatedObservationAtBackground", "SimulatedObservationAtCurrentOptimum", "SimulatedObservationAtCurrentState", "SimulatedObservationAtOptimum"]
87             )
88         self.defineRequiredParameter( # Pas de type
89             name     = "Bounds",
90             message  = "Liste des valeurs de bornes",
91             )
92         self.requireInputArguments(
93             mandatory= ("Xb", "Y", "HO", "R", "B" ),
94             )
95
96     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
97         self._pre_run(Parameters, Xb, Y, R, B, Q)
98         #
99         if not PlatformInfo.has_nlopt and not self._parameters["Minimizer"] in ["COBYLA", "POWELL", "SIMPLEX"]:
100             logging.debug("%s Absence de NLopt, utilisation forcee du minimiseur SIMPLEX"%(self._name,))
101             self._parameters["Minimizer"] = "SIMPLEX"
102         #
103         # Opérateurs
104         # ----------
105         Hm = HO["Direct"].appliedTo
106         #
107         # Précalcul des inversions de B et R
108         # ----------------------------------
109         BI = B.getI()
110         RI = R.getI()
111         #
112         # Définition de la fonction-coût
113         # ------------------------------
114         def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
115             _X  = numpy.asmatrix(numpy.ravel( x )).T
116             self.StoredVariables["CurrentState"].store( _X )
117             _HX = Hm( _X )
118             _HX = numpy.asmatrix(numpy.ravel( _HX )).T
119             _Innovation = Y - _HX
120             if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"] or \
121                "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
122                 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
123             if "InnovationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
124                 self.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
125             #
126             if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","DA"]:
127                 if BI is None or RI is None:
128                     raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
129                 Jb  = 0.5 * (_X - Xb).T * BI * (_X - Xb)
130                 Jo  = 0.5 * (_Innovation).T * RI * (_Innovation)
131             elif QualityMeasure in ["WeightedLeastSquares","WLS"]:
132                 if RI is None:
133                     raise ValueError("Observation error covariance matrix has to be properly defined!")
134                 Jb  = 0.
135                 Jo  = 0.5 * (_Innovation).T * RI * (_Innovation)
136             elif QualityMeasure in ["LeastSquares","LS","L2"]:
137                 Jb  = 0.
138                 Jo  = 0.5 * (_Innovation).T * (_Innovation)
139             elif QualityMeasure in ["AbsoluteValue","L1"]:
140                 Jb  = 0.
141                 Jo  = numpy.sum( numpy.abs(_Innovation) )
142             elif QualityMeasure in ["MaximumError","ME"]:
143                 Jb  = 0.
144                 Jo  = numpy.max( numpy.abs(_Innovation) )
145             #
146             J   = float( Jb ) + float( Jo )
147             #
148             self.StoredVariables["CostFunctionJb"].store( Jb )
149             self.StoredVariables["CostFunctionJo"].store( Jo )
150             self.StoredVariables["CostFunctionJ" ].store( J )
151             if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
152                "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
153                "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
154                "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
155                 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
156             if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"]:
157                 self.StoredVariables["IndexOfOptimum"].store( IndexMin )
158             if "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
159                 self.StoredVariables["CurrentOptimum"].store( self.StoredVariables["CurrentState"][IndexMin] )
160             if "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
161                 self.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] )
162             if "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
163                 self.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJb"][IndexMin] )
164                 self.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJo"][IndexMin] )
165                 self.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( self.StoredVariables["CostFunctionJ" ][IndexMin] )
166             return J
167         #
168         # Point de démarrage de l'optimisation : Xini = Xb
169         # ------------------------------------
170         Xini = numpy.ravel(Xb)
171         if len(Xini) < 2 and self._parameters["Minimizer"] == "NEWUOA":
172             raise ValueError("The minimizer %s can not be used when the optimisation state dimension is 1. Please choose another minimizer."%self._parameters["Minimizer"])
173         #
174         # Minimisation de la fonctionnelle
175         # --------------------------------
176         nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
177         #
178         if self._parameters["Minimizer"] == "POWELL":
179             Minimum, J_optimal, direc, niter, nfeval, rc = scipy.optimize.fmin_powell(
180                 func        = CostFunction,
181                 x0          = Xini,
182                 args        = (self._parameters["QualityCriterion"],),
183                 maxiter     = self._parameters["MaximumNumberOfSteps"]-1,
184                 maxfun      = self._parameters["MaximumNumberOfFunctionEvaluations"],
185                 xtol        = self._parameters["StateVariationTolerance"],
186                 ftol        = self._parameters["CostDecrementTolerance"],
187                 full_output = True,
188                 disp        = self._parameters["optdisp"],
189                 )
190         elif self._parameters["Minimizer"] == "COBYLA" and not PlatformInfo.has_nlopt:
191             def make_constraints(bounds):
192                 constraints = []
193                 for (i,(a,b)) in enumerate(bounds):
194                     lower = lambda x: x[i] - a
195                     upper = lambda x: b - x[i]
196                     constraints = constraints + [lower] + [upper]
197                 return constraints
198             if self._parameters["Bounds"] is None:
199                 raise ValueError("Bounds have to be given for all axes as a list of lower/upper pairs!")
200             Minimum = scipy.optimize.fmin_cobyla(
201                 func        = CostFunction,
202                 x0          = Xini,
203                 cons        = make_constraints( self._parameters["Bounds"] ),
204                 args        = (self._parameters["QualityCriterion"],),
205                 consargs    = (), # To avoid extra-args
206                 maxfun      = self._parameters["MaximumNumberOfFunctionEvaluations"],
207                 rhobeg      = 1.0,
208                 rhoend      = self._parameters["StateVariationTolerance"],
209                 catol       = 2.*self._parameters["StateVariationTolerance"],
210                 disp        = self._parameters["optdisp"],
211                 )
212         elif self._parameters["Minimizer"] == "COBYLA" and PlatformInfo.has_nlopt:
213             import nlopt
214             opt = nlopt.opt(nlopt.LN_COBYLA, Xini.size)
215             def _f(_Xx, Grad):
216                 # DFO, so no gradient
217                 return CostFunction(_Xx, self._parameters["QualityCriterion"])
218             opt.set_min_objective(_f)
219             if self._parameters["Bounds"] is not None:
220                 lub = numpy.array(self._parameters["Bounds"],dtype=float).reshape((Xini.size,2))
221                 lb = lub[:,0] ; lb[numpy.isnan(lb)] = -float('inf')
222                 ub = lub[:,1] ; ub[numpy.isnan(ub)] = +float('inf')
223                 if self._parameters["optdisp"]:
224                     print("%s: upper bounds %s"%(opt.get_algorithm_name(),ub))
225                     print("%s: lower bounds %s"%(opt.get_algorithm_name(),lb))
226                 opt.set_upper_bounds(ub)
227                 opt.set_lower_bounds(lb)
228             opt.set_ftol_rel(self._parameters["CostDecrementTolerance"])
229             opt.set_xtol_rel(2.*self._parameters["StateVariationTolerance"])
230             opt.set_maxeval(self._parameters["MaximumNumberOfFunctionEvaluations"])
231             Minimum = opt.optimize( Xini )
232             if self._parameters["optdisp"]:
233                 print("%s: optimal state: %s"%(opt.get_algorithm_name(),Minimum))
234                 print("%s: minimum of J: %s"%(opt.get_algorithm_name(),opt.last_optimum_value()))
235                 print("%s: return code: %i"%(opt.get_algorithm_name(),opt.last_optimize_result()))
236         elif self._parameters["Minimizer"] == "SIMPLEX" and not PlatformInfo.has_nlopt:
237             Minimum, J_optimal, niter, nfeval, rc = scipy.optimize.fmin(
238                 func        = CostFunction,
239                 x0          = Xini,
240                 args        = (self._parameters["QualityCriterion"],),
241                 maxiter     = self._parameters["MaximumNumberOfSteps"]-1,
242                 maxfun      = self._parameters["MaximumNumberOfFunctionEvaluations"],
243                 xtol        = self._parameters["StateVariationTolerance"],
244                 ftol        = self._parameters["CostDecrementTolerance"],
245                 full_output = True,
246                 disp        = self._parameters["optdisp"],
247                 )
248         elif self._parameters["Minimizer"] == "SIMPLEX" and PlatformInfo.has_nlopt:
249             import nlopt
250             opt = nlopt.opt(nlopt.LN_NELDERMEAD, Xini.size)
251             def _f(_Xx, Grad):
252                 # DFO, so no gradient
253                 return CostFunction(_Xx, self._parameters["QualityCriterion"])
254             opt.set_min_objective(_f)
255             if self._parameters["Bounds"] is not None:
256                 lub = numpy.array(self._parameters["Bounds"],dtype=float).reshape((Xini.size,2))
257                 lb = lub[:,0] ; lb[numpy.isnan(lb)] = -float('inf')
258                 ub = lub[:,1] ; ub[numpy.isnan(ub)] = +float('inf')
259                 if self._parameters["optdisp"]:
260                     print("%s: upper bounds %s"%(opt.get_algorithm_name(),ub))
261                     print("%s: lower bounds %s"%(opt.get_algorithm_name(),lb))
262                 opt.set_upper_bounds(ub)
263                 opt.set_lower_bounds(lb)
264             opt.set_ftol_rel(self._parameters["CostDecrementTolerance"])
265             opt.set_xtol_rel(2.*self._parameters["StateVariationTolerance"])
266             opt.set_maxeval(self._parameters["MaximumNumberOfFunctionEvaluations"])
267             Minimum = opt.optimize( Xini )
268             if self._parameters["optdisp"]:
269                 print("%s: optimal state: %s"%(opt.get_algorithm_name(),Minimum))
270                 print("%s: minimum of J: %s"%(opt.get_algorithm_name(),opt.last_optimum_value()))
271                 print("%s: return code: %i"%(opt.get_algorithm_name(),opt.last_optimize_result()))
272         elif self._parameters["Minimizer"] == "BOBYQA" and PlatformInfo.has_nlopt:
273             import nlopt
274             opt = nlopt.opt(nlopt.LN_BOBYQA, Xini.size)
275             def _f(_Xx, Grad):
276                 # DFO, so no gradient
277                 return CostFunction(_Xx, self._parameters["QualityCriterion"])
278             opt.set_min_objective(_f)
279             if self._parameters["Bounds"] is not None:
280                 lub = numpy.array(self._parameters["Bounds"],dtype=float).reshape((Xini.size,2))
281                 lb = lub[:,0] ; lb[numpy.isnan(lb)] = -float('inf')
282                 ub = lub[:,1] ; ub[numpy.isnan(ub)] = +float('inf')
283                 if self._parameters["optdisp"]:
284                     print("%s: upper bounds %s"%(opt.get_algorithm_name(),ub))
285                     print("%s: lower bounds %s"%(opt.get_algorithm_name(),lb))
286                 opt.set_upper_bounds(ub)
287                 opt.set_lower_bounds(lb)
288             opt.set_ftol_rel(self._parameters["CostDecrementTolerance"])
289             opt.set_xtol_rel(2.*self._parameters["StateVariationTolerance"])
290             opt.set_maxeval(self._parameters["MaximumNumberOfFunctionEvaluations"])
291             Minimum = opt.optimize( Xini )
292             if self._parameters["optdisp"]:
293                 print("%s: optimal state: %s"%(opt.get_algorithm_name(),Minimum))
294                 print("%s: minimum of J: %s"%(opt.get_algorithm_name(),opt.last_optimum_value()))
295                 print("%s: return code: %i"%(opt.get_algorithm_name(),opt.last_optimize_result()))
296         elif self._parameters["Minimizer"] == "NEWUOA" and PlatformInfo.has_nlopt:
297             import nlopt
298             opt = nlopt.opt(nlopt.LN_NEWUOA, Xini.size)
299             def _f(_Xx, Grad):
300                 # DFO, so no gradient
301                 return CostFunction(_Xx, self._parameters["QualityCriterion"])
302             opt.set_min_objective(_f)
303             if self._parameters["Bounds"] is not None:
304                 lub = numpy.array(self._parameters["Bounds"],dtype=float).reshape((Xini.size,2))
305                 lb = lub[:,0] ; lb[numpy.isnan(lb)] = -float('inf')
306                 ub = lub[:,1] ; ub[numpy.isnan(ub)] = +float('inf')
307                 if self._parameters["optdisp"]:
308                     print("%s: upper bounds %s"%(opt.get_algorithm_name(),ub))
309                     print("%s: lower bounds %s"%(opt.get_algorithm_name(),lb))
310                 opt.set_upper_bounds(ub)
311                 opt.set_lower_bounds(lb)
312             opt.set_ftol_rel(self._parameters["CostDecrementTolerance"])
313             opt.set_xtol_rel(2.*self._parameters["StateVariationTolerance"])
314             opt.set_maxeval(self._parameters["MaximumNumberOfFunctionEvaluations"])
315             Minimum = opt.optimize( Xini )
316             if self._parameters["optdisp"]:
317                 print("%s: optimal state: %s"%(opt.get_algorithm_name(),Minimum))
318                 print("%s: minimum of J: %s"%(opt.get_algorithm_name(),opt.last_optimum_value()))
319                 print("%s: return code: %i"%(opt.get_algorithm_name(),opt.last_optimize_result()))
320         elif self._parameters["Minimizer"] == "SUBPLEX" and PlatformInfo.has_nlopt:
321             import nlopt
322             opt = nlopt.opt(nlopt.LN_SBPLX, Xini.size)
323             def _f(_Xx, Grad):
324                 # DFO, so no gradient
325                 return CostFunction(_Xx, self._parameters["QualityCriterion"])
326             opt.set_min_objective(_f)
327             if self._parameters["Bounds"] is not None:
328                 lub = numpy.array(self._parameters["Bounds"],dtype=float).reshape((Xini.size,2))
329                 lb = lub[:,0] ; lb[numpy.isnan(lb)] = -float('inf')
330                 ub = lub[:,1] ; ub[numpy.isnan(ub)] = +float('inf')
331                 if self._parameters["optdisp"]:
332                     print("%s: upper bounds %s"%(opt.get_algorithm_name(),ub))
333                     print("%s: lower bounds %s"%(opt.get_algorithm_name(),lb))
334                 opt.set_upper_bounds(ub)
335                 opt.set_lower_bounds(lb)
336             opt.set_ftol_rel(self._parameters["CostDecrementTolerance"])
337             opt.set_xtol_rel(2.*self._parameters["StateVariationTolerance"])
338             opt.set_maxeval(self._parameters["MaximumNumberOfFunctionEvaluations"])
339             Minimum = opt.optimize( Xini )
340             if self._parameters["optdisp"]:
341                 print("%s: optimal state: %s"%(opt.get_algorithm_name(),Minimum))
342                 print("%s: minimum of J: %s"%(opt.get_algorithm_name(),opt.last_optimum_value()))
343                 print("%s: return code: %i"%(opt.get_algorithm_name(),opt.last_optimize_result()))
344         else:
345             raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
346         #
347         IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
348         MinJ     = self.StoredVariables["CostFunctionJ"][IndexMin]
349         Minimum  = self.StoredVariables["CurrentState"][IndexMin]
350         #
351         # Obtention de l'analyse
352         # ----------------------
353         Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
354         #
355         self.StoredVariables["Analysis"].store( Xa.A1 )
356         #
357         if "OMA"                           in self._parameters["StoreSupplementaryCalculations"] or \
358            "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
359             if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
360                 HXa = self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
361             elif "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
362                 HXa = self.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
363             else:
364                 HXa = Hm(Xa)
365         #
366         if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
367             self.StoredVariables["Innovation"].store( numpy.ravel(d) )
368         if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
369             self.StoredVariables["OMB"].store( numpy.ravel(d) )
370         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
371             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
372         if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
373             self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
374         if "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
375             self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(Hm(Xb)) )
376         if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
377             self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
378         #
379         self._post_run()
380         return 0
381
382 # ==============================================================================
383 if __name__ == "__main__":
384     print('\n AUTODIAGNOSTIC \n')