]> SALOME platform Git repositories - modules/adao.git/blob - src/daComposant/daAlgorithms/DerivativeFreeOptimization.py
Salome HOME
Improvements for classification of algorithms extended to all
[modules/adao.git] / src / daComposant / daAlgorithms / DerivativeFreeOptimization.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2020 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  = [
87                 "Analysis",
88                 "BMA",
89                 "CostFunctionJ",
90                 "CostFunctionJb",
91                 "CostFunctionJo",
92                 "CostFunctionJAtCurrentOptimum",
93                 "CostFunctionJbAtCurrentOptimum",
94                 "CostFunctionJoAtCurrentOptimum",
95                 "CurrentOptimum",
96                 "CurrentState",
97                 "IndexOfOptimum",
98                 "Innovation",
99                 "InnovationAtCurrentState",
100                 "OMA",
101                 "OMB",
102                 "SimulatedObservationAtBackground",
103                 "SimulatedObservationAtCurrentOptimum",
104                 "SimulatedObservationAtCurrentState",
105                 "SimulatedObservationAtOptimum",
106                 ]
107             )
108         self.defineRequiredParameter( # Pas de type
109             name     = "Bounds",
110             message  = "Liste des valeurs de bornes",
111             )
112         self.requireInputArguments(
113             mandatory= ("Xb", "Y", "HO", "R", "B" ),
114             )
115         self.setAttributes(tags=(
116             "Optimization",
117             "NonLinear",
118             "MetaHeuristic",
119             ))
120
121     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
122         self._pre_run(Parameters, Xb, Y, R, B, Q)
123         #
124         if not PlatformInfo.has_nlopt and not self._parameters["Minimizer"] in ["COBYLA", "POWELL", "SIMPLEX"]:
125             logging.warning("%s Minimization by SIMPLEX is forced because %s is unavailable (COBYLA, POWELL are also available)"%(self._name,self._parameters["Minimizer"]))
126             self._parameters["Minimizer"] = "SIMPLEX"
127         #
128         # Opérateurs
129         # ----------
130         Hm = HO["Direct"].appliedTo
131         #
132         # Précalcul des inversions de B et R
133         # ----------------------------------
134         BI = B.getI()
135         RI = R.getI()
136         #
137         # Définition de la fonction-coût
138         # ------------------------------
139         def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
140             _X  = numpy.asmatrix(numpy.ravel( x )).T
141             self.StoredVariables["CurrentState"].store( _X )
142             _HX = Hm( _X )
143             _HX = numpy.asmatrix(numpy.ravel( _HX )).T
144             _Innovation = Y - _HX
145             if self._toStore("SimulatedObservationAtCurrentState") or \
146                 self._toStore("SimulatedObservationAtCurrentOptimum"):
147                 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
148             if self._toStore("InnovationAtCurrentState"):
149                 self.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
150             #
151             if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","DA"]:
152                 if BI is None or RI is None:
153                     raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
154                 Jb  = 0.5 * (_X - Xb).T * BI * (_X - Xb)
155                 Jo  = 0.5 * (_Innovation).T * RI * (_Innovation)
156             elif QualityMeasure in ["WeightedLeastSquares","WLS"]:
157                 if RI is None:
158                     raise ValueError("Observation error covariance matrix has to be properly defined!")
159                 Jb  = 0.
160                 Jo  = 0.5 * (_Innovation).T * RI * (_Innovation)
161             elif QualityMeasure in ["LeastSquares","LS","L2"]:
162                 Jb  = 0.
163                 Jo  = 0.5 * (_Innovation).T * (_Innovation)
164             elif QualityMeasure in ["AbsoluteValue","L1"]:
165                 Jb  = 0.
166                 Jo  = numpy.sum( numpy.abs(_Innovation) )
167             elif QualityMeasure in ["MaximumError","ME"]:
168                 Jb  = 0.
169                 Jo  = numpy.max( numpy.abs(_Innovation) )
170             #
171             J   = float( Jb ) + float( Jo )
172             #
173             self.StoredVariables["CostFunctionJb"].store( Jb )
174             self.StoredVariables["CostFunctionJo"].store( Jo )
175             self.StoredVariables["CostFunctionJ" ].store( J )
176             if self._toStore("IndexOfOptimum") or \
177                 self._toStore("CurrentOptimum") or \
178                 self._toStore("CostFunctionJAtCurrentOptimum") or \
179                 self._toStore("CostFunctionJbAtCurrentOptimum") or \
180                 self._toStore("CostFunctionJoAtCurrentOptimum") or \
181                 self._toStore("SimulatedObservationAtCurrentOptimum"):
182                 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
183             if self._toStore("IndexOfOptimum"):
184                 self.StoredVariables["IndexOfOptimum"].store( IndexMin )
185             if self._toStore("CurrentOptimum"):
186                 self.StoredVariables["CurrentOptimum"].store( self.StoredVariables["CurrentState"][IndexMin] )
187             if self._toStore("SimulatedObservationAtCurrentOptimum"):
188                 self.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] )
189             if self._toStore("CostFunctionJAtCurrentOptimum"):
190                 self.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( self.StoredVariables["CostFunctionJ" ][IndexMin] )
191             if self._toStore("CostFunctionJbAtCurrentOptimum"):
192                 self.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJb"][IndexMin] )
193             if self._toStore("CostFunctionJoAtCurrentOptimum"):
194                 self.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJo"][IndexMin] )
195             return J
196         #
197         # Point de démarrage de l'optimisation : Xini = Xb
198         # ------------------------------------
199         Xini = numpy.ravel(Xb)
200         if len(Xini) < 2 and self._parameters["Minimizer"] == "NEWUOA":
201             raise ValueError("The minimizer %s can not be used when the optimisation state dimension is 1. Please choose another minimizer."%self._parameters["Minimizer"])
202         #
203         # Minimisation de la fonctionnelle
204         # --------------------------------
205         nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
206         #
207         if self._parameters["Minimizer"] == "POWELL":
208             Minimum, J_optimal, direc, niter, nfeval, rc = scipy.optimize.fmin_powell(
209                 func        = CostFunction,
210                 x0          = Xini,
211                 args        = (self._parameters["QualityCriterion"],),
212                 maxiter     = self._parameters["MaximumNumberOfSteps"]-1,
213                 maxfun      = self._parameters["MaximumNumberOfFunctionEvaluations"],
214                 xtol        = self._parameters["StateVariationTolerance"],
215                 ftol        = self._parameters["CostDecrementTolerance"],
216                 full_output = True,
217                 disp        = self._parameters["optdisp"],
218                 )
219         elif self._parameters["Minimizer"] == "COBYLA" and not PlatformInfo.has_nlopt:
220             def make_constraints(bounds):
221                 constraints = []
222                 for (i,(a,b)) in enumerate(bounds):
223                     lower = lambda x: x[i] - a
224                     upper = lambda x: b - x[i]
225                     constraints = constraints + [lower] + [upper]
226                 return constraints
227             if self._parameters["Bounds"] is None:
228                 raise ValueError("Bounds have to be given for all axes as a list of lower/upper pairs!")
229             Minimum = scipy.optimize.fmin_cobyla(
230                 func        = CostFunction,
231                 x0          = Xini,
232                 cons        = make_constraints( self._parameters["Bounds"] ),
233                 args        = (self._parameters["QualityCriterion"],),
234                 consargs    = (), # To avoid extra-args
235                 maxfun      = self._parameters["MaximumNumberOfFunctionEvaluations"],
236                 rhobeg      = 1.0,
237                 rhoend      = self._parameters["StateVariationTolerance"],
238                 catol       = 2.*self._parameters["StateVariationTolerance"],
239                 disp        = self._parameters["optdisp"],
240                 )
241         elif self._parameters["Minimizer"] == "COBYLA" and PlatformInfo.has_nlopt:
242             import nlopt
243             opt = nlopt.opt(nlopt.LN_COBYLA, Xini.size)
244             def _f(_Xx, Grad):
245                 # DFO, so no gradient
246                 return CostFunction(_Xx, self._parameters["QualityCriterion"])
247             opt.set_min_objective(_f)
248             if self._parameters["Bounds"] is not None:
249                 lub = numpy.array(self._parameters["Bounds"],dtype=float).reshape((Xini.size,2))
250                 lb = lub[:,0] ; lb[numpy.isnan(lb)] = -float('inf')
251                 ub = lub[:,1] ; ub[numpy.isnan(ub)] = +float('inf')
252                 if self._parameters["optdisp"]:
253                     print("%s: upper bounds %s"%(opt.get_algorithm_name(),ub))
254                     print("%s: lower bounds %s"%(opt.get_algorithm_name(),lb))
255                 opt.set_upper_bounds(ub)
256                 opt.set_lower_bounds(lb)
257             opt.set_ftol_rel(self._parameters["CostDecrementTolerance"])
258             opt.set_xtol_rel(2.*self._parameters["StateVariationTolerance"])
259             opt.set_maxeval(self._parameters["MaximumNumberOfFunctionEvaluations"])
260             Minimum = opt.optimize( Xini )
261             if self._parameters["optdisp"]:
262                 print("%s: optimal state: %s"%(opt.get_algorithm_name(),Minimum))
263                 print("%s: minimum of J: %s"%(opt.get_algorithm_name(),opt.last_optimum_value()))
264                 print("%s: return code: %i"%(opt.get_algorithm_name(),opt.last_optimize_result()))
265         elif self._parameters["Minimizer"] == "SIMPLEX" and not PlatformInfo.has_nlopt:
266             Minimum, J_optimal, niter, nfeval, rc = scipy.optimize.fmin(
267                 func        = CostFunction,
268                 x0          = Xini,
269                 args        = (self._parameters["QualityCriterion"],),
270                 maxiter     = self._parameters["MaximumNumberOfSteps"]-1,
271                 maxfun      = self._parameters["MaximumNumberOfFunctionEvaluations"],
272                 xtol        = self._parameters["StateVariationTolerance"],
273                 ftol        = self._parameters["CostDecrementTolerance"],
274                 full_output = True,
275                 disp        = self._parameters["optdisp"],
276                 )
277         elif self._parameters["Minimizer"] == "SIMPLEX" and PlatformInfo.has_nlopt:
278             import nlopt
279             opt = nlopt.opt(nlopt.LN_NELDERMEAD, Xini.size)
280             def _f(_Xx, Grad):
281                 # DFO, so no gradient
282                 return CostFunction(_Xx, self._parameters["QualityCriterion"])
283             opt.set_min_objective(_f)
284             if self._parameters["Bounds"] is not None:
285                 lub = numpy.array(self._parameters["Bounds"],dtype=float).reshape((Xini.size,2))
286                 lb = lub[:,0] ; lb[numpy.isnan(lb)] = -float('inf')
287                 ub = lub[:,1] ; ub[numpy.isnan(ub)] = +float('inf')
288                 if self._parameters["optdisp"]:
289                     print("%s: upper bounds %s"%(opt.get_algorithm_name(),ub))
290                     print("%s: lower bounds %s"%(opt.get_algorithm_name(),lb))
291                 opt.set_upper_bounds(ub)
292                 opt.set_lower_bounds(lb)
293             opt.set_ftol_rel(self._parameters["CostDecrementTolerance"])
294             opt.set_xtol_rel(2.*self._parameters["StateVariationTolerance"])
295             opt.set_maxeval(self._parameters["MaximumNumberOfFunctionEvaluations"])
296             Minimum = opt.optimize( Xini )
297             if self._parameters["optdisp"]:
298                 print("%s: optimal state: %s"%(opt.get_algorithm_name(),Minimum))
299                 print("%s: minimum of J: %s"%(opt.get_algorithm_name(),opt.last_optimum_value()))
300                 print("%s: return code: %i"%(opt.get_algorithm_name(),opt.last_optimize_result()))
301         elif self._parameters["Minimizer"] == "BOBYQA" and PlatformInfo.has_nlopt:
302             import nlopt
303             opt = nlopt.opt(nlopt.LN_BOBYQA, Xini.size)
304             def _f(_Xx, Grad):
305                 # DFO, so no gradient
306                 return CostFunction(_Xx, self._parameters["QualityCriterion"])
307             opt.set_min_objective(_f)
308             if self._parameters["Bounds"] is not None:
309                 lub = numpy.array(self._parameters["Bounds"],dtype=float).reshape((Xini.size,2))
310                 lb = lub[:,0] ; lb[numpy.isnan(lb)] = -float('inf')
311                 ub = lub[:,1] ; ub[numpy.isnan(ub)] = +float('inf')
312                 if self._parameters["optdisp"]:
313                     print("%s: upper bounds %s"%(opt.get_algorithm_name(),ub))
314                     print("%s: lower bounds %s"%(opt.get_algorithm_name(),lb))
315                 opt.set_upper_bounds(ub)
316                 opt.set_lower_bounds(lb)
317             opt.set_ftol_rel(self._parameters["CostDecrementTolerance"])
318             opt.set_xtol_rel(2.*self._parameters["StateVariationTolerance"])
319             opt.set_maxeval(self._parameters["MaximumNumberOfFunctionEvaluations"])
320             Minimum = opt.optimize( Xini )
321             if self._parameters["optdisp"]:
322                 print("%s: optimal state: %s"%(opt.get_algorithm_name(),Minimum))
323                 print("%s: minimum of J: %s"%(opt.get_algorithm_name(),opt.last_optimum_value()))
324                 print("%s: return code: %i"%(opt.get_algorithm_name(),opt.last_optimize_result()))
325         elif self._parameters["Minimizer"] == "NEWUOA" and PlatformInfo.has_nlopt:
326             import nlopt
327             opt = nlopt.opt(nlopt.LN_NEWUOA, Xini.size)
328             def _f(_Xx, Grad):
329                 # DFO, so no gradient
330                 return CostFunction(_Xx, self._parameters["QualityCriterion"])
331             opt.set_min_objective(_f)
332             if self._parameters["Bounds"] is not None:
333                 lub = numpy.array(self._parameters["Bounds"],dtype=float).reshape((Xini.size,2))
334                 lb = lub[:,0] ; lb[numpy.isnan(lb)] = -float('inf')
335                 ub = lub[:,1] ; ub[numpy.isnan(ub)] = +float('inf')
336                 if self._parameters["optdisp"]:
337                     print("%s: upper bounds %s"%(opt.get_algorithm_name(),ub))
338                     print("%s: lower bounds %s"%(opt.get_algorithm_name(),lb))
339                 opt.set_upper_bounds(ub)
340                 opt.set_lower_bounds(lb)
341             opt.set_ftol_rel(self._parameters["CostDecrementTolerance"])
342             opt.set_xtol_rel(2.*self._parameters["StateVariationTolerance"])
343             opt.set_maxeval(self._parameters["MaximumNumberOfFunctionEvaluations"])
344             Minimum = opt.optimize( Xini )
345             if self._parameters["optdisp"]:
346                 print("%s: optimal state: %s"%(opt.get_algorithm_name(),Minimum))
347                 print("%s: minimum of J: %s"%(opt.get_algorithm_name(),opt.last_optimum_value()))
348                 print("%s: return code: %i"%(opt.get_algorithm_name(),opt.last_optimize_result()))
349         elif self._parameters["Minimizer"] == "SUBPLEX" and PlatformInfo.has_nlopt:
350             import nlopt
351             opt = nlopt.opt(nlopt.LN_SBPLX, Xini.size)
352             def _f(_Xx, Grad):
353                 # DFO, so no gradient
354                 return CostFunction(_Xx, self._parameters["QualityCriterion"])
355             opt.set_min_objective(_f)
356             if self._parameters["Bounds"] is not None:
357                 lub = numpy.array(self._parameters["Bounds"],dtype=float).reshape((Xini.size,2))
358                 lb = lub[:,0] ; lb[numpy.isnan(lb)] = -float('inf')
359                 ub = lub[:,1] ; ub[numpy.isnan(ub)] = +float('inf')
360                 if self._parameters["optdisp"]:
361                     print("%s: upper bounds %s"%(opt.get_algorithm_name(),ub))
362                     print("%s: lower bounds %s"%(opt.get_algorithm_name(),lb))
363                 opt.set_upper_bounds(ub)
364                 opt.set_lower_bounds(lb)
365             opt.set_ftol_rel(self._parameters["CostDecrementTolerance"])
366             opt.set_xtol_rel(2.*self._parameters["StateVariationTolerance"])
367             opt.set_maxeval(self._parameters["MaximumNumberOfFunctionEvaluations"])
368             Minimum = opt.optimize( Xini )
369             if self._parameters["optdisp"]:
370                 print("%s: optimal state: %s"%(opt.get_algorithm_name(),Minimum))
371                 print("%s: minimum of J: %s"%(opt.get_algorithm_name(),opt.last_optimum_value()))
372                 print("%s: return code: %i"%(opt.get_algorithm_name(),opt.last_optimize_result()))
373         else:
374             raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
375         #
376         IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
377         MinJ     = self.StoredVariables["CostFunctionJ"][IndexMin]
378         Minimum  = self.StoredVariables["CurrentState"][IndexMin]
379         #
380         # Obtention de l'analyse
381         # ----------------------
382         Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
383         #
384         self.StoredVariables["Analysis"].store( Xa.A1 )
385         #
386         # Calculs et/ou stockages supplémentaires
387         # ---------------------------------------
388         if self._toStore("OMA" ) or \
389             self._toStore("SimulatedObservationAtOptimum"):
390             if self._toStore("SimulatedObservationAtCurrentState"):
391                 HXa = self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
392             elif self._toStore("SimulatedObservationAtCurrentOptimum"):
393                 HXa = self.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
394             else:
395                 HXa = Hm(Xa)
396         if self._toStore("Innovation") or \
397             self._toStore("OMB"):
398             d  = Y - HXb
399         if self._toStore("Innovation"):
400             self.StoredVariables["Innovation"].store( numpy.ravel(d) )
401         if self._toStore("OMB"):
402             self.StoredVariables["OMB"].store( numpy.ravel(d) )
403         if self._toStore("BMA"):
404             self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
405         if self._toStore("OMA"):
406             self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
407         if self._toStore("SimulatedObservationAtBackground"):
408             self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(Hm(Xb)) )
409         if self._toStore("SimulatedObservationAtOptimum"):
410             self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
411         #
412         self._post_run()
413         return 0
414
415 # ==============================================================================
416 if __name__ == "__main__":
417     print('\n AUTODIAGNOSTIC\n')