1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2015 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 function",
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", "SimulatedObservationAtBackground", "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)
99 # self.setParameterValue("StoreInternalVariables",True)
100 # print self._parameters["StoreInternalVariables"]
104 Hm = HO["Direct"].appliedTo
106 # Précalcul des inversions de B et R
107 # ----------------------------------
111 # Définition de la fonction-coût
112 # ------------------------------
113 def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
114 _X = numpy.asmatrix(numpy.ravel( x )).T
115 self.StoredVariables["CurrentState"].store( _X )
117 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
118 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
119 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
121 if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","DA"]:
122 if BI is None or RI is None:
123 raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
124 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
125 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
126 elif QualityMeasure in ["WeightedLeastSquares","WLS"]:
128 raise ValueError("Observation error covariance matrix has to be properly defined!")
130 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
131 elif QualityMeasure in ["LeastSquares","LS","L2"]:
133 Jo = 0.5 * (Y - _HX).T * (Y - _HX)
134 elif QualityMeasure in ["AbsoluteValue","L1"]:
136 Jo = numpy.sum( numpy.abs(Y - _HX) )
137 elif QualityMeasure in ["MaximumError","ME"]:
139 Jo = numpy.max( numpy.abs(Y - _HX) )
141 J = float( Jb ) + float( Jo )
143 self.StoredVariables["CostFunctionJb"].store( Jb )
144 self.StoredVariables["CostFunctionJo"].store( Jo )
145 self.StoredVariables["CostFunctionJ" ].store( J )
148 # Point de démarrage de l'optimisation : Xini = Xb
149 # ------------------------------------
150 Xini = numpy.ravel(Xb)
152 # Minimisation de la fonctionnelle
153 # --------------------------------
154 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
156 if self._parameters["Minimizer"] == "POWELL":
157 Minimum, J_optimal, direc, niter, nfeval, rc = scipy.optimize.fmin_powell(
160 args = (self._parameters["QualityCriterion"],),
161 maxiter = self._parameters["MaximumNumberOfSteps"]-1,
162 maxfun = self._parameters["MaximumNumberOfFunctionEvaluations"]-1,
163 xtol = self._parameters["StateVariationTolerance"],
164 ftol = self._parameters["CostDecrementTolerance"],
168 elif self._parameters["Minimizer"] == "SIMPLEX":
169 Minimum, J_optimal, niter, nfeval, rc = scipy.optimize.fmin(
172 args = (self._parameters["QualityCriterion"],),
173 maxiter = self._parameters["MaximumNumberOfSteps"]-1,
174 maxfun = self._parameters["MaximumNumberOfFunctionEvaluations"]-1,
175 xtol = self._parameters["StateVariationTolerance"],
176 ftol = self._parameters["CostDecrementTolerance"],
181 raise ValueError("Error in Minimizer name: %s"%self._parameters["Minimizer"])
183 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
184 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
185 Minimum = self.StoredVariables["CurrentState"][IndexMin]
187 # Obtention de l'analyse
188 # ----------------------
189 Xa = numpy.asmatrix(numpy.ravel( Minimum )).T
191 self.StoredVariables["Analysis"].store( Xa.A1 )
193 if "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
194 self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(Hm(Xb)) )
195 if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
196 self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(Hm(Xa)) )
201 # ==============================================================================
202 if __name__ == "__main__":
203 print '\n AUTODIAGNOSTIC \n'