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"],
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"]
89 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
91 if logging.getLogger().level < logging.WARNING:
96 # Paramètres de pilotage
97 # ----------------------
98 self.setParameters(Parameters)
102 Hm = HO["Direct"].appliedTo
104 # Précalcul des inversions de B et R
105 # ----------------------------------
109 # Définition de la fonction-coût
110 # ------------------------------
111 def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
112 _X = numpy.asmatrix(numpy.ravel( x )).T
113 self.StoredVariables["CurrentState"].store( _X )
115 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
116 _Innovation = Y - _HX
117 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"] or \
118 "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
119 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
120 if "InnovationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
121 self.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
123 if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","DA"]:
124 if BI is None or RI is None:
125 raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
126 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
127 Jo = 0.5 * (_Innovation).T * RI * (_Innovation)
128 elif QualityMeasure in ["WeightedLeastSquares","WLS"]:
130 raise ValueError("Observation error covariance matrix has to be properly defined!")
132 Jo = 0.5 * (_Innovation).T * RI * (_Innovation)
133 elif QualityMeasure in ["LeastSquares","LS","L2"]:
135 Jo = 0.5 * (_Innovation).T * (_Innovation)
136 elif QualityMeasure in ["AbsoluteValue","L1"]:
138 Jo = numpy.sum( numpy.abs(_Innovation) )
139 elif QualityMeasure in ["MaximumError","ME"]:
141 Jo = numpy.max( numpy.abs(_Innovation) )
143 J = float( Jb ) + float( Jo )
145 self.StoredVariables["CostFunctionJb"].store( Jb )
146 self.StoredVariables["CostFunctionJo"].store( Jo )
147 self.StoredVariables["CostFunctionJ" ].store( J )
148 if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
149 "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
150 "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"] or \
151 "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
152 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
153 if "IndexOfOptimum" in self._parameters["StoreSupplementaryCalculations"]:
154 self.StoredVariables["IndexOfOptimum"].store( IndexMin )
155 if "CurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
156 self.StoredVariables["CurrentOptimum"].store( self.StoredVariables["CurrentState"][IndexMin] )
157 if "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
158 self.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] )
159 if "CostFunctionJAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
160 self.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJb"][IndexMin] )
161 self.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJo"][IndexMin] )
162 self.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( self.StoredVariables["CostFunctionJ" ][IndexMin] )
165 # Point de démarrage de l'optimisation : Xini = Xb
166 # ------------------------------------
167 Xini = numpy.ravel(Xb)
169 # Minimisation de la fonctionnelle
170 # --------------------------------
171 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
173 if self._parameters["Minimizer"] == "POWELL":
174 Minimum, J_optimal, direc, niter, nfeval, rc = scipy.optimize.fmin_powell(
177 args = (self._parameters["QualityCriterion"],),
178 maxiter = self._parameters["MaximumNumberOfSteps"]-1,
179 maxfun = self._parameters["MaximumNumberOfFunctionEvaluations"]-1,
180 xtol = self._parameters["StateVariationTolerance"],
181 ftol = self._parameters["CostDecrementTolerance"],
185 elif self._parameters["Minimizer"] == "SIMPLEX":
186 Minimum, J_optimal, niter, nfeval, rc = scipy.optimize.fmin(
189 args = (self._parameters["QualityCriterion"],),
190 maxiter = self._parameters["MaximumNumberOfSteps"]-1,
191 maxfun = self._parameters["MaximumNumberOfFunctionEvaluations"]-1,
192 xtol = self._parameters["StateVariationTolerance"],
193 ftol = self._parameters["CostDecrementTolerance"],
198 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
200 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
201 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
202 Minimum = self.StoredVariables["CurrentState"][IndexMin]
204 # Obtention de l'analyse
205 # ----------------------
206 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
208 self.StoredVariables["Analysis"].store( Xa.A1 )
210 if "OMA" in self._parameters["StoreSupplementaryCalculations"] or \
211 "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
212 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
213 HXa = self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
214 elif "SimulatedObservationAtCurrentOptimum" in self._parameters["StoreSupplementaryCalculations"]:
215 HXa = self.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
219 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
220 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
221 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
222 self.StoredVariables["OMB"].store( numpy.ravel(d) )
223 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
224 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
225 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
226 self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
227 if "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
228 self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(Hm(Xb)) )
229 if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
230 self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
235 # ==============================================================================
236 if __name__ == "__main__":
237 print '\n AUTODIAGNOSTIC \n'