1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2017 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",
86 listval = ["CurrentState", "CostFunctionJ", "CostFunctionJb", "CostFunctionJo", "CostFunctionJAtCurrentOptimum", "CurrentOptimum", "IndexOfOptimum", "InnovationAtCurrentState", "BMA", "OMA", "OMB", "SimulatedObservationAtBackground", "SimulatedObservationAtCurrentOptimum", "SimulatedObservationAtCurrentState", "SimulatedObservationAtOptimum"]
88 self.defineRequiredParameter( # Pas de type
90 message = "Liste des valeurs de bornes",
92 self.requireInputArguments(
93 mandatory= ("Xb", "Y", "HO", "R", "B" ),
96 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
97 self._pre_run(Parameters, Xb, Y, R, B, Q)
99 if not PlatformInfo.has_nlopt and not self._parameters["Minimizer"] in ["COBYLA", "POWELL", "SIMPLEX"]:
100 logging.debug("%s Absence de NLopt, utilisation forcee du minimiseur SIMPLEX"%(self._name,))
101 self._parameters["Minimizer"] = "SIMPLEX"
105 Hm = HO["Direct"].appliedTo
107 # Précalcul des inversions de B et R
108 # ----------------------------------
112 # Définition de la fonction-coût
113 # ------------------------------
114 def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
115 _X = numpy.asmatrix(numpy.ravel( x )).T
116 self.StoredVariables["CurrentState"].store( _X )
118 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
119 _Innovation = Y - _HX
120 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"] or \
121 "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
122 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
123 if "InnovationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
124 self.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
126 if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","DA"]:
127 if BI is None or RI is None:
128 raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
129 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
130 Jo = 0.5 * (_Innovation).T * RI * (_Innovation)
131 elif QualityMeasure in ["WeightedLeastSquares","WLS"]:
133 raise ValueError("Observation error covariance matrix has to be properly defined!")
135 Jo = 0.5 * (_Innovation).T * RI * (_Innovation)
136 elif QualityMeasure in ["LeastSquares","LS","L2"]:
138 Jo = 0.5 * (_Innovation).T * (_Innovation)
139 elif QualityMeasure in ["AbsoluteValue","L1"]:
141 Jo = numpy.sum( numpy.abs(_Innovation) )
142 elif QualityMeasure in ["MaximumError","ME"]:
144 Jo = numpy.max( numpy.abs(_Innovation) )
146 J = float( Jb ) + float( Jo )
148 self.StoredVariables["CostFunctionJb"].store( Jb )
149 self.StoredVariables["CostFunctionJo"].store( Jo )
150 self.StoredVariables["CostFunctionJ" ].store( J )
151 if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
152 "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
153 "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
154 "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
155 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
156 if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"]:
157 self.StoredVariables["IndexOfOptimum"].store( IndexMin )
158 if "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
159 self.StoredVariables["CurrentOptimum"].store( self.StoredVariables["CurrentState"][IndexMin] )
160 if "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
161 self.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] )
162 if "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
163 self.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJb"][IndexMin] )
164 self.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJo"][IndexMin] )
165 self.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( self.StoredVariables["CostFunctionJ" ][IndexMin] )
168 # Point de démarrage de l'optimisation : Xini = Xb
169 # ------------------------------------
170 Xini = numpy.ravel(Xb)
171 if len(Xini) < 2 and self._parameters["Minimizer"] == "NEWUOA":
172 raise ValueError("The minimizer %s can not be used when the optimisation state dimension is 1. Please choose another minimizer."%self._parameters["Minimizer"])
174 # Minimisation de la fonctionnelle
175 # --------------------------------
176 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
178 if self._parameters["Minimizer"] == "POWELL":
179 Minimum, J_optimal, direc, niter, nfeval, rc = scipy.optimize.fmin_powell(
182 args = (self._parameters["QualityCriterion"],),
183 maxiter = self._parameters["MaximumNumberOfSteps"]-1,
184 maxfun = self._parameters["MaximumNumberOfFunctionEvaluations"],
185 xtol = self._parameters["StateVariationTolerance"],
186 ftol = self._parameters["CostDecrementTolerance"],
188 disp = self._parameters["optdisp"],
190 elif self._parameters["Minimizer"] == "COBYLA" and not PlatformInfo.has_nlopt:
191 def make_constraints(bounds):
193 for (i,(a,b)) in enumerate(bounds):
194 lower = lambda x: x[i] - a
195 upper = lambda x: b - x[i]
196 constraints = constraints + [lower] + [upper]
198 if self._parameters["Bounds"] is None:
199 raise ValueError("Bounds have to be given for all axes as a list of lower/upper pairs!")
200 Minimum = scipy.optimize.fmin_cobyla(
203 cons = make_constraints( self._parameters["Bounds"] ),
204 args = (self._parameters["QualityCriterion"],),
205 consargs = (), # To avoid extra-args
206 maxfun = self._parameters["MaximumNumberOfFunctionEvaluations"],
208 rhoend = self._parameters["StateVariationTolerance"],
209 catol = 2.*self._parameters["StateVariationTolerance"],
210 disp = self._parameters["optdisp"],
212 elif self._parameters["Minimizer"] == "COBYLA" and PlatformInfo.has_nlopt:
214 opt = nlopt.opt(nlopt.LN_COBYLA, Xini.size)
216 # DFO, so no gradient
217 return CostFunction(_Xx, self._parameters["QualityCriterion"])
218 opt.set_min_objective(_f)
219 if self._parameters["Bounds"] is not None:
220 lub = numpy.array(self._parameters["Bounds"],dtype=float).reshape((Xini.size,2))
221 lb = lub[:,0] ; lb[numpy.isnan(lb)] = -float('inf')
222 ub = lub[:,1] ; ub[numpy.isnan(ub)] = +float('inf')
223 if self._parameters["optdisp"]:
224 print("%s: upper bounds %s"%(opt.get_algorithm_name(),ub))
225 print("%s: lower bounds %s"%(opt.get_algorithm_name(),lb))
226 opt.set_upper_bounds(ub)
227 opt.set_lower_bounds(lb)
228 opt.set_ftol_rel(self._parameters["CostDecrementTolerance"])
229 opt.set_xtol_rel(2.*self._parameters["StateVariationTolerance"])
230 opt.set_maxeval(self._parameters["MaximumNumberOfFunctionEvaluations"])
231 Minimum = opt.optimize( Xini )
232 if self._parameters["optdisp"]:
233 print("%s: optimal state: %s"%(opt.get_algorithm_name(),Minimum))
234 print("%s: minimum of J: %s"%(opt.get_algorithm_name(),opt.last_optimum_value()))
235 print("%s: return code: %i"%(opt.get_algorithm_name(),opt.last_optimize_result()))
236 elif self._parameters["Minimizer"] == "SIMPLEX" and not PlatformInfo.has_nlopt:
237 Minimum, J_optimal, niter, nfeval, rc = scipy.optimize.fmin(
240 args = (self._parameters["QualityCriterion"],),
241 maxiter = self._parameters["MaximumNumberOfSteps"]-1,
242 maxfun = self._parameters["MaximumNumberOfFunctionEvaluations"],
243 xtol = self._parameters["StateVariationTolerance"],
244 ftol = self._parameters["CostDecrementTolerance"],
246 disp = self._parameters["optdisp"],
248 elif self._parameters["Minimizer"] == "SIMPLEX" and PlatformInfo.has_nlopt:
250 opt = nlopt.opt(nlopt.LN_NELDERMEAD, Xini.size)
252 # DFO, so no gradient
253 return CostFunction(_Xx, self._parameters["QualityCriterion"])
254 opt.set_min_objective(_f)
255 if self._parameters["Bounds"] is not None:
256 lub = numpy.array(self._parameters["Bounds"],dtype=float).reshape((Xini.size,2))
257 lb = lub[:,0] ; lb[numpy.isnan(lb)] = -float('inf')
258 ub = lub[:,1] ; ub[numpy.isnan(ub)] = +float('inf')
259 if self._parameters["optdisp"]:
260 print("%s: upper bounds %s"%(opt.get_algorithm_name(),ub))
261 print("%s: lower bounds %s"%(opt.get_algorithm_name(),lb))
262 opt.set_upper_bounds(ub)
263 opt.set_lower_bounds(lb)
264 opt.set_ftol_rel(self._parameters["CostDecrementTolerance"])
265 opt.set_xtol_rel(2.*self._parameters["StateVariationTolerance"])
266 opt.set_maxeval(self._parameters["MaximumNumberOfFunctionEvaluations"])
267 Minimum = opt.optimize( Xini )
268 if self._parameters["optdisp"]:
269 print("%s: optimal state: %s"%(opt.get_algorithm_name(),Minimum))
270 print("%s: minimum of J: %s"%(opt.get_algorithm_name(),opt.last_optimum_value()))
271 print("%s: return code: %i"%(opt.get_algorithm_name(),opt.last_optimize_result()))
272 elif self._parameters["Minimizer"] == "BOBYQA" and PlatformInfo.has_nlopt:
274 opt = nlopt.opt(nlopt.LN_BOBYQA, 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"] == "NEWUOA" and PlatformInfo.has_nlopt:
298 opt = nlopt.opt(nlopt.LN_NEWUOA, 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"] == "SUBPLEX" and PlatformInfo.has_nlopt:
322 opt = nlopt.opt(nlopt.LN_SBPLX, 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()))
345 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
347 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
348 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
349 Minimum = self.StoredVariables["CurrentState"][IndexMin]
351 # Obtention de l'analyse
352 # ----------------------
353 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
355 self.StoredVariables["Analysis"].store( Xa.A1 )
357 if "OMA" in self._parameters["StoreSupplementaryCalculations"] or \
358 "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
359 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
360 HXa = self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
361 elif "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
362 HXa = self.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
366 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
367 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
368 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
369 self.StoredVariables["OMB"].store( numpy.ravel(d) )
370 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
371 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
372 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
373 self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
374 if "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
375 self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(Hm(Xb)) )
376 if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
377 self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
382 # ==============================================================================
383 if __name__ == "__main__":
384 print('\n AUTODIAGNOSTIC \n')