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",
91 "CostFunctionJAtCurrentOptimum",
92 "CostFunctionJbAtCurrentOptimum",
93 "CostFunctionJoAtCurrentOptimum",
98 "InnovationAtCurrentState",
101 "SimulatedObservationAtBackground",
102 "SimulatedObservationAtCurrentOptimum",
103 "SimulatedObservationAtCurrentState",
104 "SimulatedObservationAtOptimum",
107 self.defineRequiredParameter( # Pas de type
109 message = "Liste des valeurs de bornes",
111 self.requireInputArguments(
112 mandatory= ("Xb", "Y", "HO", "R", "B" ),
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)
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"
124 Hm = HO["Direct"].appliedTo
126 # Précalcul des inversions de B et R
127 # ----------------------------------
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 )
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 )
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"]:
152 raise ValueError("Observation error covariance matrix has to be properly defined!")
154 Jo = 0.5 * (_Innovation).T * RI * (_Innovation)
155 elif QualityMeasure in ["LeastSquares","LS","L2"]:
157 Jo = 0.5 * (_Innovation).T * (_Innovation)
158 elif QualityMeasure in ["AbsoluteValue","L1"]:
160 Jo = numpy.sum( numpy.abs(_Innovation) )
161 elif QualityMeasure in ["MaximumError","ME"]:
163 Jo = numpy.max( numpy.abs(_Innovation) )
165 J = float( Jb ) + float( Jo )
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] )
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"])
197 # Minimisation de la fonctionnelle
198 # --------------------------------
199 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
201 if self._parameters["Minimizer"] == "POWELL":
202 Minimum, J_optimal, direc, niter, nfeval, rc = scipy.optimize.fmin_powell(
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"],
211 disp = self._parameters["optdisp"],
213 elif self._parameters["Minimizer"] == "COBYLA" and not PlatformInfo.has_nlopt:
214 def make_constraints(bounds):
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]
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(
226 cons = make_constraints( self._parameters["Bounds"] ),
227 args = (self._parameters["QualityCriterion"],),
228 consargs = (), # To avoid extra-args
229 maxfun = self._parameters["MaximumNumberOfFunctionEvaluations"],
231 rhoend = self._parameters["StateVariationTolerance"],
232 catol = 2.*self._parameters["StateVariationTolerance"],
233 disp = self._parameters["optdisp"],
235 elif self._parameters["Minimizer"] == "COBYLA" and PlatformInfo.has_nlopt:
237 opt = nlopt.opt(nlopt.LN_COBYLA, Xini.size)
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(
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"],
269 disp = self._parameters["optdisp"],
271 elif self._parameters["Minimizer"] == "SIMPLEX" and PlatformInfo.has_nlopt:
273 opt = nlopt.opt(nlopt.LN_NELDERMEAD, Xini.size)
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:
297 opt = nlopt.opt(nlopt.LN_BOBYQA, Xini.size)
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:
321 opt = nlopt.opt(nlopt.LN_NEWUOA, Xini.size)
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:
345 opt = nlopt.opt(nlopt.LN_SBPLX, Xini.size)
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()))
368 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
370 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
371 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
372 Minimum = self.StoredVariables["CurrentState"][IndexMin]
374 # Obtention de l'analyse
375 # ----------------------
376 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
378 self.StoredVariables["Analysis"].store( Xa.A1 )
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]
390 if self._toStore("Innovation") or \
391 self._toStore("OMB"):
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) )
409 # ==============================================================================
410 if __name__ == "__main__":
411 print('\n AUTODIAGNOSTIC \n')