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