1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2022 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
23 import numpy, logging, scipy.optimize
24 from daCore import BasicObjects
26 # ==============================================================================
27 class ElementaryAlgorithm(BasicObjects.Algorithm):
29 BasicObjects.Algorithm.__init__(self, "DIFFERENTIALEVOLUTION")
30 self.defineRequiredParameter(
34 message = "Stratégie de minimisation utilisée",
52 self.defineRequiredParameter(
53 name = "MaximumNumberOfIterations",
56 message = "Nombre maximal de générations",
58 oldname = "MaximumNumberOfSteps",
60 self.defineRequiredParameter(
61 name = "MaximumNumberOfFunctionEvaluations",
64 message = "Nombre maximal d'évaluations de la fonction",
67 self.defineRequiredParameter(
69 typecast = numpy.random.seed,
70 message = "Graine fixée pour le générateur aléatoire",
72 self.defineRequiredParameter(
73 name = "PopulationSize",
76 message = "Taille approximative de la population à chaque génération",
79 self.defineRequiredParameter(
80 name = "MutationDifferentialWeight_F",
83 message = "Poids différentiel de mutation, constant ou aléatoire dans l'intervalle, noté F",
87 self.defineRequiredParameter(
88 name = "CrossOverProbability_CR",
91 message = "Probabilité de recombinaison ou de croisement, notée CR",
95 self.defineRequiredParameter(
96 name = "QualityCriterion",
97 default = "AugmentedWeightedLeastSquares",
99 message = "Critère de qualité utilisé",
101 "AugmentedWeightedLeastSquares", "AWLS", "DA",
102 "WeightedLeastSquares", "WLS",
103 "LeastSquares", "LS", "L2",
104 "AbsoluteValue", "L1",
105 "MaximumError", "ME",
108 self.defineRequiredParameter(
109 name = "StoreInternalVariables",
112 message = "Stockage des variables internes ou intermédiaires du calcul",
114 self.defineRequiredParameter(
115 name = "StoreSupplementaryCalculations",
118 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
125 "CostFunctionJAtCurrentOptimum",
126 "CostFunctionJbAtCurrentOptimum",
127 "CostFunctionJoAtCurrentOptimum",
128 "CurrentIterationNumber",
133 "InnovationAtCurrentState",
136 "SimulatedObservationAtBackground",
137 "SimulatedObservationAtCurrentOptimum",
138 "SimulatedObservationAtCurrentState",
139 "SimulatedObservationAtOptimum",
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["MaximumNumberOfIterations"],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))
164 Hm = HO["Direct"].appliedTo
169 def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
170 _X = numpy.ravel( x ).reshape((-1,1))
171 _HX = numpy.ravel( Hm( _X ) ).reshape((-1,1))
172 _Innovation = Y - _HX
173 self.StoredVariables["CurrentState"].store( _X )
174 if self._toStore("SimulatedObservationAtCurrentState") or \
175 self._toStore("SimulatedObservationAtCurrentOptimum"):
176 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HX )
177 if self._toStore("InnovationAtCurrentState"):
178 self.StoredVariables["InnovationAtCurrentState"].store( _Innovation )
180 if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","DA"]:
181 if BI is None or RI is None:
182 raise ValueError("Background and Observation error covariance matrices has to be properly defined!")
183 Jb = 0.5 * (_X - Xb).T @ (BI @ (_X - Xb))
184 Jo = 0.5 * _Innovation.T @ (RI @ _Innovation)
185 elif QualityMeasure in ["WeightedLeastSquares","WLS"]:
187 raise ValueError("Observation error covariance matrix has to be properly defined!")
189 Jo = 0.5 * _Innovation.T @ (RI @ _Innovation)
190 elif QualityMeasure in ["LeastSquares","LS","L2"]:
192 Jo = 0.5 * _Innovation.T @ _Innovation
193 elif QualityMeasure in ["AbsoluteValue","L1"]:
195 Jo = numpy.sum( numpy.abs(_Innovation) )
196 elif QualityMeasure in ["MaximumError","ME"]:
198 Jo = numpy.max( numpy.abs(_Innovation) )
200 J = float( Jb ) + float( Jo )
202 self.StoredVariables["CurrentIterationNumber"].store( len(self.StoredVariables["CostFunctionJ"]) )
203 self.StoredVariables["CostFunctionJb"].store( Jb )
204 self.StoredVariables["CostFunctionJo"].store( Jo )
205 self.StoredVariables["CostFunctionJ" ].store( J )
206 if self._toStore("IndexOfOptimum") or \
207 self._toStore("CurrentOptimum") or \
208 self._toStore("CostFunctionJAtCurrentOptimum") or \
209 self._toStore("CostFunctionJbAtCurrentOptimum") or \
210 self._toStore("CostFunctionJoAtCurrentOptimum") or \
211 self._toStore("SimulatedObservationAtCurrentOptimum"):
212 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
213 if self._toStore("IndexOfOptimum"):
214 self.StoredVariables["IndexOfOptimum"].store( IndexMin )
215 if self._toStore("CurrentOptimum"):
216 self.StoredVariables["CurrentOptimum"].store( self.StoredVariables["CurrentState"][IndexMin] )
217 if self._toStore("SimulatedObservationAtCurrentOptimum"):
218 self.StoredVariables["SimulatedObservationAtCurrentOptimum"].store( self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin] )
219 if self._toStore("CostFunctionJAtCurrentOptimum"):
220 self.StoredVariables["CostFunctionJAtCurrentOptimum" ].store( self.StoredVariables["CostFunctionJ" ][IndexMin] )
221 if self._toStore("CostFunctionJbAtCurrentOptimum"):
222 self.StoredVariables["CostFunctionJbAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJb"][IndexMin] )
223 if self._toStore("CostFunctionJoAtCurrentOptimum"):
224 self.StoredVariables["CostFunctionJoAtCurrentOptimum"].store( self.StoredVariables["CostFunctionJo"][IndexMin] )
227 Xini = numpy.ravel(Xb)
229 # Minimisation de la fonctionnelle
230 # --------------------------------
231 nbPreviousSteps = self.StoredVariables["CostFunctionJ"].stepnumber()
233 optResults = scipy.optimize.differential_evolution(
235 self._parameters["Bounds"],
236 strategy = str(self._parameters["Minimizer"]).lower(),
239 mutation = self._parameters["MutationDifferentialWeight_F"],
240 recombination = self._parameters["CrossOverProbability_CR"],
241 disp = self._parameters["optdisp"],
244 IndexMin = numpy.argmin( self.StoredVariables["CostFunctionJ"][nbPreviousSteps:] ) + nbPreviousSteps
245 MinJ = self.StoredVariables["CostFunctionJ"][IndexMin]
246 Minimum = self.StoredVariables["CurrentState"][IndexMin]
248 # Obtention de l'analyse
249 # ----------------------
252 self.StoredVariables["Analysis"].store( Xa )
254 # Calculs et/ou stockages supplémentaires
255 # ---------------------------------------
256 if self._toStore("OMA") or \
257 self._toStore("SimulatedObservationAtOptimum"):
258 if self._toStore("SimulatedObservationAtCurrentState"):
259 HXa = self.StoredVariables["SimulatedObservationAtCurrentState"][IndexMin]
260 elif self._toStore("SimulatedObservationAtCurrentOptimum"):
261 HXa = self.StoredVariables["SimulatedObservationAtCurrentOptimum"][-1]
264 HXa = HXa.reshape((-1,1))
265 if self._toStore("Innovation") or \
266 self._toStore("OMB") or \
267 self._toStore("SimulatedObservationAtBackground"):
268 HXb = Hm(Xb).reshape((-1,1))
270 if self._toStore("Innovation"):
271 self.StoredVariables["Innovation"].store( Innovation )
272 if self._toStore("OMB"):
273 self.StoredVariables["OMB"].store( Innovation )
274 if self._toStore("BMA"):
275 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
276 if self._toStore("OMA"):
277 self.StoredVariables["OMA"].store( Y - HXa )
278 if self._toStore("SimulatedObservationAtBackground"):
279 self.StoredVariables["SimulatedObservationAtBackground"].store( HXb )
280 if self._toStore("SimulatedObservationAtOptimum"):
281 self.StoredVariables["SimulatedObservationAtOptimum"].store( HXa )
286 # ==============================================================================
287 if __name__ == "__main__":
288 print('\n AUTODIAGNOSTIC\n')