1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2019 EDF R&D
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.
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.
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
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
24 from daCore import BasicObjects, PlatformInfo
25 import numpy, scipy.optimize
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
30 BasicObjects.Algorithm.__init__(self, "DERIVATIVEFREEOPTIMIZATION")
31 self.defineRequiredParameter(
35 message = "Minimiseur utilisé",
36 listval = ["BOBYQA", "COBYLA", "NEWUOA", "POWELL", "SIMPLEX", "SUBPLEX"],
38 self.defineRequiredParameter(
39 name = "MaximumNumberOfSteps",
42 message = "Nombre maximal de pas d'optimisation",
45 self.defineRequiredParameter(
46 name = "MaximumNumberOfFunctionEvaluations",
49 message = "Nombre maximal d'évaluations de la fonction",
52 self.defineRequiredParameter(
53 name = "StateVariationTolerance",
56 message = "Variation relative maximale de l'état lors de l'arrêt",
58 self.defineRequiredParameter(
59 name = "CostDecrementTolerance",
62 message = "Diminution relative minimale du cout lors de l'arrêt",
64 self.defineRequiredParameter(
65 name = "QualityCriterion",
66 default = "AugmentedWeightedLeastSquares",
68 message = "Critère de qualité utilisé",
69 listval = ["AugmentedWeightedLeastSquares","AWLS","DA",
70 "WeightedLeastSquares","WLS",
71 "LeastSquares","LS","L2",
75 self.defineRequiredParameter(
76 name = "StoreInternalVariables",
79 message = "Stockage des variables internes ou intermédiaires du calcul",
81 self.defineRequiredParameter(
82 name = "StoreSupplementaryCalculations",
85 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
92 "CostFunctionJAtCurrentOptimum",
93 "CostFunctionJbAtCurrentOptimum",
94 "CostFunctionJoAtCurrentOptimum",
99 "InnovationAtCurrentState",
102 "SimulatedObservationAtBackground",
103 "SimulatedObservationAtCurrentOptimum",
104 "SimulatedObservationAtCurrentState",
105 "SimulatedObservationAtOptimum",
108 self.defineRequiredParameter( # Pas de type
110 message = "Liste des valeurs de bornes",
112 self.requireInputArguments(
113 mandatory= ("Xb", "Y", "HO", "R", "B" ),
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)
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"
125 Hm = HO["Direct"].appliedTo
127 # Précalcul des inversions de B et R
128 # ----------------------------------
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 )
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 )
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"]:
153 raise ValueError("Observation error covariance matrix has to be properly defined!")
155 Jo = 0.5 * (_Innovation).T * RI * (_Innovation)
156 elif QualityMeasure in ["LeastSquares","LS","L2"]:
158 Jo = 0.5 * (_Innovation).T * (_Innovation)
159 elif QualityMeasure in ["AbsoluteValue","L1"]:
161 Jo = numpy.sum( numpy.abs(_Innovation) )
162 elif QualityMeasure in ["MaximumError","ME"]:
164 Jo = numpy.max( numpy.abs(_Innovation) )
166 J = float( Jb ) + float( Jo )
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] )
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"])
198 # Minimisation de la fonctionnelle
199 # --------------------------------
200 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
202 if self._parameters["Minimizer"] == "POWELL":
203 Minimum, J_optimal, direc, niter, nfeval, rc = scipy.optimize.fmin_powell(
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"],
212 disp = self._parameters["optdisp"],
214 elif self._parameters["Minimizer"] == "COBYLA" and not PlatformInfo.has_nlopt:
215 def make_constraints(bounds):
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]
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(
227 cons = make_constraints( self._parameters["Bounds"] ),
228 args = (self._parameters["QualityCriterion"],),
229 consargs = (), # To avoid extra-args
230 maxfun = self._parameters["MaximumNumberOfFunctionEvaluations"],
232 rhoend = self._parameters["StateVariationTolerance"],
233 catol = 2.*self._parameters["StateVariationTolerance"],
234 disp = self._parameters["optdisp"],
236 elif self._parameters["Minimizer"] == "COBYLA" and PlatformInfo.has_nlopt:
238 opt = nlopt.opt(nlopt.LN_COBYLA, Xini.size)
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(
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"],
270 disp = self._parameters["optdisp"],
272 elif self._parameters["Minimizer"] == "SIMPLEX" and PlatformInfo.has_nlopt:
274 opt = nlopt.opt(nlopt.LN_NELDERMEAD, Xini.size)
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:
298 opt = nlopt.opt(nlopt.LN_BOBYQA, Xini.size)
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:
322 opt = nlopt.opt(nlopt.LN_NEWUOA, Xini.size)
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:
346 opt = nlopt.opt(nlopt.LN_SBPLX, Xini.size)
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()))
369 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
371 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
372 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
373 Minimum = self.StoredVariables["CurrentState"][IndexMin]
375 # Obtention de l'analyse
376 # ----------------------
377 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
379 self.StoredVariables["Analysis"].store( Xa.A1 )
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]
391 if self._toStore("Innovation") or \
392 self._toStore("OMB"):
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) )
410 # ==============================================================================
411 if __name__ == "__main__":
412 print('\n AUTODIAGNOSTIC\n')