1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2021 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, "DIFFERENTIALEVOLUTION")
31 self.defineRequiredParameter(
35 message = "Stratégie de minimisation utilisée",
53 self.defineRequiredParameter(
54 name = "MaximumNumberOfSteps",
57 message = "Nombre maximal de générations",
60 self.defineRequiredParameter(
61 name = "MaximumNumberOfFunctionEvaluations",
64 message = "Nombre maximal d'évaluations de la fonction",
67 self.defineRequiredParameter(
68 name = "PopulationSize",
71 message = "Taille approximative de la population à chaque génération",
74 self.defineRequiredParameter(
75 name = "MutationDifferentialWeight_F",
78 message = "Poids différentiel de mutation, constant ou aléatoire dans l'intervalle, noté F",
82 self.defineRequiredParameter(
83 name = "CrossOverProbability_CR",
86 message = "Probabilité de recombinaison ou de croisement, notée CR",
90 self.defineRequiredParameter(
91 name = "QualityCriterion",
92 default = "AugmentedWeightedLeastSquares",
94 message = "Critère de qualité utilisé",
96 "AugmentedWeightedLeastSquares","AWLS","DA",
97 "WeightedLeastSquares","WLS",
98 "LeastSquares","LS","L2",
103 self.defineRequiredParameter(
104 name = "StoreInternalVariables",
107 message = "Stockage des variables internes ou intermédiaires du calcul",
109 self.defineRequiredParameter(
110 name = "StoreSupplementaryCalculations",
113 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
120 "CostFunctionJAtCurrentOptimum",
121 "CostFunctionJbAtCurrentOptimum",
122 "CostFunctionJoAtCurrentOptimum",
123 "CurrentIterationNumber",
128 "InnovationAtCurrentState",
131 "SimulatedObservationAtBackground",
132 "SimulatedObservationAtCurrentOptimum",
133 "SimulatedObservationAtCurrentState",
134 "SimulatedObservationAtOptimum",
137 self.defineRequiredParameter(
139 typecast = numpy.random.seed,
140 message = "Graine fixée pour le générateur aléatoire",
142 self.defineRequiredParameter( # Pas de type
144 message = "Liste des valeurs de bornes",
146 self.requireInputArguments(
147 mandatory= ("Xb", "Y", "HO", "R", "B" ),
149 self.setAttributes(tags=(
156 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
157 self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
159 len_X = numpy.asarray(Xb).size
160 popsize = round(self._parameters["PopulationSize"]/len_X)
161 maxiter = min(self._parameters["MaximumNumberOfSteps"],round(self._parameters["MaximumNumberOfFunctionEvaluations"]/(popsize*len_X) - 1))
162 logging.debug("%s Nombre maximal de générations = %i, taille de la population à chaque génération = %i"%(self._name, maxiter, popsize*len_X))
166 Hm = HO["Direct"].appliedTo
168 # Précalcul des inversions de B et R
169 # ----------------------------------
173 # Définition de la fonction-coût
174 # ------------------------------
175 def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
176 _X = numpy.asmatrix(numpy.ravel( x )).T
177 self.StoredVariables["CurrentState"].store( _X )
179 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
180 _Innovation = Y - _HX
181 if self._toStore("SimulatedObservationAtCurrentState") or \
182 self._toStore("SimulatedObservationAtCurrentOptimum"):
183 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
184 if self._toStore("InnovationAtCurrentState"):
185 self.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
187 if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","DA"]:
188 if BI is None or RI is None:
189 raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
190 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
191 Jo = 0.5 * (_Innovation).T * RI * (_Innovation)
192 elif QualityMeasure in ["WeightedLeastSquares","WLS"]:
194 raise ValueError("Observation error covariance matrix has to be properly defined!")
196 Jo = 0.5 * (_Innovation).T * RI * (_Innovation)
197 elif QualityMeasure in ["LeastSquares","LS","L2"]:
199 Jo = 0.5 * (_Innovation).T * (_Innovation)
200 elif QualityMeasure in ["AbsoluteValue","L1"]:
202 Jo = numpy.sum( numpy.abs(_Innovation) )
203 elif QualityMeasure in ["MaximumError","ME"]:
205 Jo = numpy.max( numpy.abs(_Innovation) )
207 J = float( Jb ) + float( Jo )
209 self.StoredVariables["CurrentIterationNumber"].store( len(self.StoredVariables["CostFunctionJ"]) )
210 self.StoredVariables["CostFunctionJb"].store( Jb )
211 self.StoredVariables["CostFunctionJo"].store( Jo )
212 self.StoredVariables["CostFunctionJ" ].store( J )
213 if self._toStore("IndexOfOptimum") or \
214 self._toStore("CurrentOptimum") or \
215 self._toStore("CostFunctionJAtCurrentOptimum") or \
216 self._toStore("CostFunctionJbAtCurrentOptimum") or \
217 self._toStore("CostFunctionJoAtCurrentOptimum") or \
218 self._toStore("SimulatedObservationAtCurrentOptimum"):
219 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
220 if self._toStore("IndexOfOptimum"):
221 self.StoredVariables["IndexOfOptimum"].store( IndexMin )
222 if self._toStore("CurrentOptimum"):
223 self.StoredVariables["CurrentOptimum"].store( self.StoredVariables["CurrentState"][IndexMin] )
224 if self._toStore("SimulatedObservationAtCurrentOptimum"):
225 self.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] )
226 if self._toStore("CostFunctionJAtCurrentOptimum"):
227 self.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( self.StoredVariables["CostFunctionJ" ][IndexMin] )
228 if self._toStore("CostFunctionJbAtCurrentOptimum"):
229 self.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJb"][IndexMin] )
230 if self._toStore("CostFunctionJoAtCurrentOptimum"):
231 self.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJo"][IndexMin] )
234 # Point de démarrage de l'optimisation : Xini = Xb
235 # ------------------------------------
236 Xini = numpy.ravel(Xb)
238 # Minimisation de la fonctionnelle
239 # --------------------------------
240 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
242 optResults = scipy.optimize.differential_evolution(
244 self._parameters["Bounds"],
245 strategy = str(self._parameters["Minimizer"]).lower(),
248 mutation = self._parameters["MutationDifferentialWeight_F"],
249 recombination = self._parameters["CrossOverProbability_CR"],
250 disp = self._parameters["optdisp"],
253 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
254 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
255 Minimum = self.StoredVariables["CurrentState"][IndexMin]
257 # Obtention de l'analyse
258 # ----------------------
259 Xa = numpy.ravel( Minimum )
261 self.StoredVariables["Analysis"].store( Xa )
263 # Calculs et/ou stockages supplémentaires
264 # ---------------------------------------
265 if self._toStore("OMA") or self._toStore("SimulatedObservationAtOptimum"):
266 if self._toStore("SimulatedObservationAtCurrentState"):
267 HXa = self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
268 elif self._toStore("SimulatedObservationAtCurrentOptimum"):
269 HXa = self.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
272 if self._toStore("Innovation") or \
273 self._toStore("OMB"):
275 if self._toStore("Innovation"):
276 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
277 if self._toStore("OMB"):
278 self.StoredVariables["OMB"].store( numpy.ravel(d) )
279 if self._toStore("BMA"):
280 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
281 if self._toStore("OMA"):
282 self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
283 if self._toStore("SimulatedObservationAtBackground"):
284 self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(Hm(Xb)) )
285 if self._toStore("SimulatedObservationAtOptimum"):
286 self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
291 # ==============================================================================
292 if __name__ == "__main__":
293 print('\n AUTODIAGNOSTIC\n')