1 #-*-coding:iso-8859-1-*-
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",
93 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
95 if logging.getLogger().level < logging.WARNING:
100 # Paramètres de pilotage
101 # ----------------------
102 self.setParameters(Parameters)
104 if not PlatformInfo.has_nlopt and not self._parameters["Minimizer"] in ["COBYLA", "POWELL", "SIMPLEX"]:
105 self._parameters["Minimizer"] = "SIMPLEX"
106 if self._parameters.has_key("Bounds") and (type(self._parameters["Bounds"]) is type([]) or type(self._parameters["Bounds"]) is type(())) and (len(self._parameters["Bounds"]) > 0):
107 Bounds = self._parameters["Bounds"]
108 logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
114 Hm = HO["Direct"].appliedTo
116 # Précalcul des inversions de B et R
117 # ----------------------------------
121 # Définition de la fonction-coût
122 # ------------------------------
123 def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
124 _X = numpy.asmatrix(numpy.ravel( x )).T
125 self.StoredVariables["CurrentState"].store( _X )
127 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
128 _Innovation = Y - _HX
129 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"] or \
130 "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
131 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
132 if "InnovationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
133 self.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
135 if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","DA"]:
136 if BI is None or RI is None:
137 raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
138 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
139 Jo = 0.5 * (_Innovation).T * RI * (_Innovation)
140 elif QualityMeasure in ["WeightedLeastSquares","WLS"]:
142 raise ValueError("Observation error covariance matrix has to be properly defined!")
144 Jo = 0.5 * (_Innovation).T * RI * (_Innovation)
145 elif QualityMeasure in ["LeastSquares","LS","L2"]:
147 Jo = 0.5 * (_Innovation).T * (_Innovation)
148 elif QualityMeasure in ["AbsoluteValue","L1"]:
150 Jo = numpy.sum( numpy.abs(_Innovation) )
151 elif QualityMeasure in ["MaximumError","ME"]:
153 Jo = numpy.max( numpy.abs(_Innovation) )
155 J = float( Jb ) + float( Jo )
157 self.StoredVariables["CostFunctionJb"].store( Jb )
158 self.StoredVariables["CostFunctionJo"].store( Jo )
159 self.StoredVariables["CostFunctionJ" ].store( J )
160 if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
161 "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
162 "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
163 "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
164 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
165 if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"]:
166 self.StoredVariables["IndexOfOptimum"].store( IndexMin )
167 if "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
168 self.StoredVariables["CurrentOptimum"].store( self.StoredVariables["CurrentState"][IndexMin] )
169 if "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
170 self.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] )
171 if "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
172 self.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJb"][IndexMin] )
173 self.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJo"][IndexMin] )
174 self.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( self.StoredVariables["CostFunctionJ" ][IndexMin] )
177 # Point de démarrage de l'optimisation : Xini = Xb
178 # ------------------------------------
179 Xini = numpy.ravel(Xb)
180 if len(Xini) < 2 and self._parameters["Minimizer"] == "NEWUOA":
181 raise ValueError("The minimizer %s can not be used when the optimisation state dimension is 1. Please choose another minimizer."%self._parameters["Minimizer"])
183 # Minimisation de la fonctionnelle
184 # --------------------------------
185 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
187 if self._parameters["Minimizer"] == "POWELL":
188 Minimum, J_optimal, direc, niter, nfeval, rc = scipy.optimize.fmin_powell(
191 args = (self._parameters["QualityCriterion"],),
192 maxiter = self._parameters["MaximumNumberOfSteps"]-1,
193 maxfun = self._parameters["MaximumNumberOfFunctionEvaluations"],
194 xtol = self._parameters["StateVariationTolerance"],
195 ftol = self._parameters["CostDecrementTolerance"],
199 elif self._parameters["Minimizer"] == "COBYLA" and not PlatformInfo.has_nlopt:
200 def make_constraints(bounds):
202 for (i,(a,b)) in enumerate(bounds):
203 lower = lambda x: x[i] - a
204 upper = lambda x: b - x[i]
205 constraints = constraints + [lower] + [upper]
208 raise ValueError("Bounds have to be given for all axes as a list of lower/upper pairs!")
209 Minimum = scipy.optimize.fmin_cobyla(
212 cons = make_constraints( Bounds ),
213 args = (self._parameters["QualityCriterion"],),
214 consargs = (), # To avoid extra-args
215 maxfun = self._parameters["MaximumNumberOfFunctionEvaluations"],
217 rhoend = self._parameters["StateVariationTolerance"],
218 catol = 2.*self._parameters["StateVariationTolerance"],
221 elif self._parameters["Minimizer"] == "COBYLA" and PlatformInfo.has_nlopt:
223 opt = nlopt.opt(nlopt.LN_COBYLA, Xini.size)
225 # DFO, so no gradient
226 return CostFunction(_Xx, self._parameters["QualityCriterion"])
227 opt.set_min_objective(_f)
228 if Bounds is not None:
229 lub = numpy.array(Bounds).reshape((Xini.size,2))
233 print "%s: upper bounds %s"%(opt.get_algorithm_name(),ub)
234 print "%s: lower bounds %s"%(opt.get_algorithm_name(),lb)
235 opt.set_upper_bounds(ub)
236 opt.set_lower_bounds(lb)
237 opt.set_ftol_rel(self._parameters["CostDecrementTolerance"])
238 opt.set_xtol_rel(2.*self._parameters["StateVariationTolerance"])
239 opt.set_maxeval(self._parameters["MaximumNumberOfFunctionEvaluations"])
240 Minimum = opt.optimize( Xini )
242 print "%s: optimal state: %s"%(opt.get_algorithm_name(),Minimum)
243 print "%s: minimum of J: %s"%(opt.get_algorithm_name(),opt.last_optimum_value())
244 print "%s: return code: %i"%(opt.get_algorithm_name(),opt.last_optimize_result())
245 elif self._parameters["Minimizer"] == "SIMPLEX" and not PlatformInfo.has_nlopt:
246 Minimum, J_optimal, niter, nfeval, rc = scipy.optimize.fmin(
249 args = (self._parameters["QualityCriterion"],),
250 maxiter = self._parameters["MaximumNumberOfSteps"]-1,
251 maxfun = self._parameters["MaximumNumberOfFunctionEvaluations"],
252 xtol = self._parameters["StateVariationTolerance"],
253 ftol = self._parameters["CostDecrementTolerance"],
257 elif self._parameters["Minimizer"] == "SIMPLEX" and PlatformInfo.has_nlopt:
259 opt = nlopt.opt(nlopt.LN_NELDERMEAD, Xini.size)
261 # DFO, so no gradient
262 return CostFunction(_Xx, self._parameters["QualityCriterion"])
263 opt.set_min_objective(_f)
264 if Bounds is not None:
265 lub = numpy.array(Bounds).reshape((Xini.size,2))
269 print "%s: upper bounds %s"%(opt.get_algorithm_name(),ub)
270 print "%s: lower bounds %s"%(opt.get_algorithm_name(),lb)
271 opt.set_upper_bounds(ub)
272 opt.set_lower_bounds(lb)
273 opt.set_ftol_rel(self._parameters["CostDecrementTolerance"])
274 opt.set_xtol_rel(2.*self._parameters["StateVariationTolerance"])
275 opt.set_maxeval(self._parameters["MaximumNumberOfFunctionEvaluations"])
276 Minimum = opt.optimize( Xini )
278 print "%s: optimal state: %s"%(opt.get_algorithm_name(),Minimum)
279 print "%s: minimum of J: %s"%(opt.get_algorithm_name(),opt.last_optimum_value())
280 print "%s: return code: %i"%(opt.get_algorithm_name(),opt.last_optimize_result())
281 elif self._parameters["Minimizer"] == "BOBYQA" and PlatformInfo.has_nlopt:
283 opt = nlopt.opt(nlopt.LN_BOBYQA, Xini.size)
285 # DFO, so no gradient
286 return CostFunction(_Xx, self._parameters["QualityCriterion"])
287 opt.set_min_objective(_f)
288 if Bounds is not None:
289 lub = numpy.array(Bounds).reshape((Xini.size,2))
293 print "%s: upper bounds %s"%(opt.get_algorithm_name(),ub)
294 print "%s: lower bounds %s"%(opt.get_algorithm_name(),lb)
295 opt.set_upper_bounds(ub)
296 opt.set_lower_bounds(lb)
297 opt.set_ftol_rel(self._parameters["CostDecrementTolerance"])
298 opt.set_xtol_rel(2.*self._parameters["StateVariationTolerance"])
299 opt.set_maxeval(self._parameters["MaximumNumberOfFunctionEvaluations"])
300 Minimum = opt.optimize( Xini )
302 print "%s: optimal state: %s"%(opt.get_algorithm_name(),Minimum)
303 print "%s: minimum of J: %s"%(opt.get_algorithm_name(),opt.last_optimum_value())
304 print "%s: return code: %i"%(opt.get_algorithm_name(),opt.last_optimize_result())
305 elif self._parameters["Minimizer"] == "NEWUOA" and PlatformInfo.has_nlopt:
307 opt = nlopt.opt(nlopt.LN_NEWUOA, Xini.size)
309 # DFO, so no gradient
310 return CostFunction(_Xx, self._parameters["QualityCriterion"])
311 opt.set_min_objective(_f)
312 if Bounds is not None:
313 lub = numpy.array(Bounds).reshape((Xini.size,2))
317 print "%s: upper bounds %s"%(opt.get_algorithm_name(),ub)
318 print "%s: lower bounds %s"%(opt.get_algorithm_name(),lb)
319 opt.set_upper_bounds(ub)
320 opt.set_lower_bounds(lb)
321 opt.set_ftol_rel(self._parameters["CostDecrementTolerance"])
322 opt.set_xtol_rel(2.*self._parameters["StateVariationTolerance"])
323 opt.set_maxeval(self._parameters["MaximumNumberOfFunctionEvaluations"])
324 Minimum = opt.optimize( Xini )
326 print "%s: optimal state: %s"%(opt.get_algorithm_name(),Minimum)
327 print "%s: minimum of J: %s"%(opt.get_algorithm_name(),opt.last_optimum_value())
328 print "%s: return code: %i"%(opt.get_algorithm_name(),opt.last_optimize_result())
329 elif self._parameters["Minimizer"] == "SUBPLEX" and PlatformInfo.has_nlopt:
331 opt = nlopt.opt(nlopt.LN_SBPLX, Xini.size)
333 # DFO, so no gradient
334 return CostFunction(_Xx, self._parameters["QualityCriterion"])
335 opt.set_min_objective(_f)
336 if Bounds is not None:
337 lub = numpy.array(Bounds).reshape((Xini.size,2))
341 print "%s: upper bounds %s"%(opt.get_algorithm_name(),ub)
342 print "%s: lower bounds %s"%(opt.get_algorithm_name(),lb)
343 opt.set_upper_bounds(ub)
344 opt.set_lower_bounds(lb)
345 opt.set_ftol_rel(self._parameters["CostDecrementTolerance"])
346 opt.set_xtol_rel(2.*self._parameters["StateVariationTolerance"])
347 opt.set_maxeval(self._parameters["MaximumNumberOfFunctionEvaluations"])
348 Minimum = opt.optimize( Xini )
350 print "%s: optimal state: %s"%(opt.get_algorithm_name(),Minimum)
351 print "%s: minimum of J: %s"%(opt.get_algorithm_name(),opt.last_optimum_value())
352 print "%s: return code: %i"%(opt.get_algorithm_name(),opt.last_optimize_result())
354 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
356 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
357 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
358 Minimum = self.StoredVariables["CurrentState"][IndexMin]
360 # Obtention de l'analyse
361 # ----------------------
362 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
364 self.StoredVariables["Analysis"].store( Xa.A1 )
366 if "OMA" in self._parameters["StoreSupplementaryCalculations"] or \
367 "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
368 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
369 HXa = self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
370 elif "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
371 HXa = self.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
375 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
376 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
377 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
378 self.StoredVariables["OMB"].store( numpy.ravel(d) )
379 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
380 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
381 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
382 self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
383 if "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
384 self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(Hm(Xb)) )
385 if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
386 self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
391 # ==============================================================================
392 if __name__ == "__main__":
393 print '\n AUTODIAGNOSTIC \n'