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