1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2016 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
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 = ["POWELL", "SIMPLEX", "COBYLA"],
38 self.defineRequiredParameter(
39 name = "MaximumNumberOfSteps",
42 message = "Nombre maximal de pas d'optimisation",
45 self.defineRequiredParameter(
46 name = "MaximumNumberOfFunctionEvaluations",
49 message = "Nombre maximal de 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 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):
105 Bounds = self._parameters["Bounds"]
106 logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
112 Hm = HO["Direct"].appliedTo
114 # Précalcul des inversions de B et R
115 # ----------------------------------
119 # Définition de la fonction-coût
120 # ------------------------------
121 def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
122 _X = numpy.asmatrix(numpy.ravel( x )).T
123 self.StoredVariables["CurrentState"].store( _X )
125 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
126 _Innovation = Y - _HX
127 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"] or \
128 "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
129 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
130 if "InnovationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
131 self.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
133 if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","DA"]:
134 if BI is None or RI is None:
135 raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
136 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
137 Jo = 0.5 * (_Innovation).T * RI * (_Innovation)
138 elif QualityMeasure in ["WeightedLeastSquares","WLS"]:
140 raise ValueError("Observation error covariance matrix has to be properly defined!")
142 Jo = 0.5 * (_Innovation).T * RI * (_Innovation)
143 elif QualityMeasure in ["LeastSquares","LS","L2"]:
145 Jo = 0.5 * (_Innovation).T * (_Innovation)
146 elif QualityMeasure in ["AbsoluteValue","L1"]:
148 Jo = numpy.sum( numpy.abs(_Innovation) )
149 elif QualityMeasure in ["MaximumError","ME"]:
151 Jo = numpy.max( numpy.abs(_Innovation) )
153 J = float( Jb ) + float( Jo )
155 self.StoredVariables["CostFunctionJb"].store( Jb )
156 self.StoredVariables["CostFunctionJo"].store( Jo )
157 self.StoredVariables["CostFunctionJ" ].store( J )
158 if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
159 "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
160 "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
161 "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
162 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
163 if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"]:
164 self.StoredVariables["IndexOfOptimum"].store( IndexMin )
165 if "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
166 self.StoredVariables["CurrentOptimum"].store( self.StoredVariables["CurrentState"][IndexMin] )
167 if "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
168 self.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] )
169 if "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
170 self.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJb"][IndexMin] )
171 self.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJo"][IndexMin] )
172 self.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( self.StoredVariables["CostFunctionJ" ][IndexMin] )
175 # Point de démarrage de l'optimisation : Xini = Xb
176 # ------------------------------------
177 Xini = numpy.ravel(Xb)
179 # Minimisation de la fonctionnelle
180 # --------------------------------
181 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
183 if self._parameters["Minimizer"] == "POWELL":
184 Minimum, J_optimal, direc, niter, nfeval, rc = scipy.optimize.fmin_powell(
187 args = (self._parameters["QualityCriterion"],),
188 maxiter = self._parameters["MaximumNumberOfSteps"]-1,
189 maxfun = self._parameters["MaximumNumberOfFunctionEvaluations"],
190 xtol = self._parameters["StateVariationTolerance"],
191 ftol = self._parameters["CostDecrementTolerance"],
195 elif self._parameters["Minimizer"] == "SIMPLEX":
196 Minimum, J_optimal, niter, nfeval, rc = scipy.optimize.fmin(
199 args = (self._parameters["QualityCriterion"],),
200 maxiter = self._parameters["MaximumNumberOfSteps"]-1,
201 maxfun = self._parameters["MaximumNumberOfFunctionEvaluations"],
202 xtol = self._parameters["StateVariationTolerance"],
203 ftol = self._parameters["CostDecrementTolerance"],
207 elif self._parameters["Minimizer"] == "COBYLA":
208 def make_constraints(bounds):
210 for (i,(a,b)) in enumerate(bounds):
211 lower = lambda x: x[i] - a
212 upper = lambda x: b - x[i]
213 constraints = constraints + [lower] + [upper]
216 raise ValueError("Bounds have to be given for all axes as a list of lower/upper pairs!")
217 Minimum = scipy.optimize.fmin_cobyla(
220 cons = make_constraints( Bounds ),
221 args = (self._parameters["QualityCriterion"],),
222 consargs = (), # To avoid extra-args
223 maxfun = self._parameters["MaximumNumberOfFunctionEvaluations"],
225 rhoend = self._parameters["StateVariationTolerance"],
226 catol = 2.*self._parameters["StateVariationTolerance"],
230 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
232 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
233 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
234 Minimum = self.StoredVariables["CurrentState"][IndexMin]
236 # Obtention de l'analyse
237 # ----------------------
238 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
240 self.StoredVariables["Analysis"].store( Xa.A1 )
242 if "OMA" in self._parameters["StoreSupplementaryCalculations"] or \
243 "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
244 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
245 HXa = self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
246 elif "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
247 HXa = self.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
251 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
252 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
253 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
254 self.StoredVariables["OMB"].store( numpy.ravel(d) )
255 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
256 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
257 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
258 self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
259 if "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
260 self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(Hm(Xb)) )
261 if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
262 self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
267 # ==============================================================================
268 if __name__ == "__main__":
269 print '\n AUTODIAGNOSTIC \n'