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, copy
24 from daCore import BasicObjects
26 # ==============================================================================
27 class ElementaryAlgorithm(BasicObjects.Algorithm):
29 BasicObjects.Algorithm.__init__(self, "PARTICLESWARMOPTIMIZATION")
30 self.defineRequiredParameter(
31 name = "MaximumNumberOfIterations",
34 message = "Nombre maximal de pas d'optimisation",
36 oldname = "MaximumNumberOfSteps",
38 self.defineRequiredParameter(
39 name = "MaximumNumberOfFunctionEvaluations",
42 message = "Nombre maximal d'évaluations de la fonction",
45 self.defineRequiredParameter(
47 typecast = numpy.random.seed,
48 message = "Graine fixée pour le générateur aléatoire",
50 self.defineRequiredParameter(
51 name = "NumberOfInsects",
54 message = "Nombre d'insectes dans l'essaim",
57 self.defineRequiredParameter(
58 name = "SwarmVelocity",
61 message = "Vitesse de groupe imposée par l'essaim",
64 self.defineRequiredParameter(
65 name = "GroupRecallRate",
68 message = "Taux de rappel au meilleur insecte du groupe (entre 0 et 1)",
72 self.defineRequiredParameter(
73 name = "QualityCriterion",
74 default = "AugmentedWeightedLeastSquares",
76 message = "Critère de qualité utilisé",
78 "AugmentedWeightedLeastSquares", "AWLS", "DA",
79 "WeightedLeastSquares", "WLS",
80 "LeastSquares", "LS", "L2",
81 "AbsoluteValue", "L1",
85 self.defineRequiredParameter(
86 name = "StoreInternalVariables",
89 message = "Stockage des variables internes ou intermédiaires du calcul",
91 self.defineRequiredParameter(
92 name = "StoreSupplementaryCalculations",
95 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
102 "CurrentIterationNumber",
107 "SimulatedObservationAtBackground",
108 "SimulatedObservationAtCurrentState",
109 "SimulatedObservationAtOptimum",
112 self.defineRequiredParameter( # Pas de type
114 message = "Liste des valeurs de bornes d'incréments de paramètres",
116 self.requireInputArguments(
117 mandatory= ("Xb", "Y", "HO", "R", "B"),
119 self.setAttributes(tags=(
126 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
127 self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
129 if ("BoxBounds" in self._parameters) and isinstance(self._parameters["BoxBounds"], (list, tuple)) and (len(self._parameters["BoxBounds"]) > 0):
130 BoxBounds = self._parameters["BoxBounds"]
131 logging.debug("%s Prise en compte des bornes d'incréments de paramètres effectuée"%(self._name,))
133 raise ValueError("Particle Swarm Optimization requires bounds on all variables increments to be truly given (BoxBounds).")
134 BoxBounds = numpy.array(BoxBounds)
135 if numpy.isnan(BoxBounds).any():
136 raise ValueError("Particle Swarm Optimization requires bounds on all variables increments to be truly given (BoxBounds), \"None\" is not allowed. The actual increments bounds are:\n%s"%BoxBounds)
138 Phig = float( self._parameters["GroupRecallRate"] )
140 logging.debug("%s Taux de rappel au meilleur insecte du groupe (entre 0 et 1) = %s et à la meilleure position précédente (son complémentaire à 1) = %s"%(self._name, str(Phig), str(Phip)))
142 Hm = HO["Direct"].appliedTo
147 def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
148 _X = numpy.ravel( x ).reshape((-1,1))
149 _HX = numpy.ravel( Hm( _X ) ).reshape((-1,1))
150 _Innovation = Y - _HX
152 if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","DA"]:
153 if BI is None or RI is None:
154 raise ValueError("Background and Observation error covariance matrices has to be properly defined!")
155 Jb = 0.5 * (_X - Xb).T @ (BI @ (_X - Xb))
156 Jo = 0.5 * _Innovation.T @ (RI @ _Innovation)
157 elif QualityMeasure in ["WeightedLeastSquares","WLS"]:
159 raise ValueError("Observation error covariance matrix has to be properly defined!")
161 Jo = 0.5 * _Innovation.T @ (RI @ _Innovation)
162 elif QualityMeasure in ["LeastSquares","LS","L2"]:
164 Jo = 0.5 * _Innovation.T @ _Innovation
165 elif QualityMeasure in ["AbsoluteValue","L1"]:
167 Jo = numpy.sum( numpy.abs(_Innovation) )
168 elif QualityMeasure in ["MaximumError","ME"]:
170 Jo = numpy.max( numpy.abs(_Innovation) )
172 J = float( Jb ) + float( Jo )
177 Xini = numpy.ravel(Xb)
179 Xini = numpy.zeros(len(BoxBounds[:,0]))
181 SpaceUp = BoxBounds[:,1] + Xini
182 SpaceLow = BoxBounds[:,0] + Xini
183 nbparam = len(SpaceUp)
185 # Initialisation de l'essaim
186 # --------------------------
187 NumberOfFunctionEvaluations = 0
188 LimitVelocity = numpy.abs(SpaceUp-SpaceLow)
192 for i in range(nbparam) :
193 PosInsect.append(numpy.random.uniform(low=SpaceLow[i], high=SpaceUp[i], size=self._parameters["NumberOfInsects"]))
194 VelocityInsect.append(numpy.random.uniform(low=-LimitVelocity[i], high=LimitVelocity[i], size=self._parameters["NumberOfInsects"]))
195 VelocityInsect = numpy.array(VelocityInsect)
196 PosInsect = numpy.array(PosInsect)
198 BestPosInsect = numpy.array(PosInsect)
200 _Best = copy.copy(SpaceLow)
201 _qualityBest = CostFunction(_Best,self._parameters["QualityCriterion"])
202 NumberOfFunctionEvaluations += 1
204 for i in range(self._parameters["NumberOfInsects"]):
205 insect = numpy.ravel(PosInsect[:,i])
206 quality = CostFunction(insect,self._parameters["QualityCriterion"])
207 NumberOfFunctionEvaluations += 1
208 qBestPosInsect.append(quality)
209 if quality < _qualityBest:
210 _Best = copy.copy( insect )
211 _qualityBest = copy.copy( quality )
212 logging.debug("%s Initialisation, Insecte = %s, Qualité = %s"%(self._name, str(_Best), str(_qualityBest)))
214 self.StoredVariables["CurrentIterationNumber"].store( len(self.StoredVariables["CostFunctionJ"]) )
215 if self._parameters["StoreInternalVariables"] or self._toStore("CurrentState"):
216 self.StoredVariables["CurrentState"].store( _Best )
217 self.StoredVariables["CostFunctionJb"].store( 0. )
218 self.StoredVariables["CostFunctionJo"].store( 0. )
219 self.StoredVariables["CostFunctionJ" ].store( _qualityBest )
221 # Minimisation de la fonctionnelle
222 # --------------------------------
223 for n in range(self._parameters["MaximumNumberOfIterations"]):
224 for i in range(self._parameters["NumberOfInsects"]) :
225 insect = numpy.ravel(PosInsect[:,i])
226 rp = numpy.random.uniform(size=nbparam)
227 rg = numpy.random.uniform(size=nbparam)
228 for j in range(nbparam) :
229 VelocityInsect[j,i] = self._parameters["SwarmVelocity"]*VelocityInsect[j,i] + Phip*rp[j]*(BestPosInsect[j,i]-PosInsect[j,i]) + Phig*rg[j]*(_Best[j]-PosInsect[j,i])
230 PosInsect[j,i] = PosInsect[j,i]+VelocityInsect[j,i]
231 quality = CostFunction(insect,self._parameters["QualityCriterion"])
232 NumberOfFunctionEvaluations += 1
233 if quality < qBestPosInsect[i]:
234 BestPosInsect[:,i] = copy.copy( insect )
235 qBestPosInsect[i] = copy.copy( quality )
236 if quality < _qualityBest :
237 _Best = copy.copy( insect )
238 _qualityBest = copy.copy( quality )
239 logging.debug("%s Etape %i, Insecte = %s, Qualité = %s"%(self._name, n, str(_Best), str(_qualityBest)))
241 self.StoredVariables["CurrentIterationNumber"].store( len(self.StoredVariables["CostFunctionJ"]) )
242 if self._parameters["StoreInternalVariables"] or self._toStore("CurrentState"):
243 self.StoredVariables["CurrentState"].store( _Best )
244 if self._toStore("SimulatedObservationAtCurrentState"):
246 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HmX )
247 self.StoredVariables["CostFunctionJb"].store( 0. )
248 self.StoredVariables["CostFunctionJo"].store( 0. )
249 self.StoredVariables["CostFunctionJ" ].store( _qualityBest )
250 if NumberOfFunctionEvaluations > self._parameters["MaximumNumberOfFunctionEvaluations"]:
251 logging.debug("%s Stopping search because the number %i of function evaluations is exceeding the maximum %i."%(self._name, NumberOfFunctionEvaluations, self._parameters["MaximumNumberOfFunctionEvaluations"]))
254 # Obtention de l'analyse
255 # ----------------------
258 self.StoredVariables["Analysis"].store( Xa )
260 # Calculs et/ou stockages supplémentaires
261 # ---------------------------------------
262 if self._toStore("OMA") or \
263 self._toStore("SimulatedObservationAtOptimum"):
265 if self._toStore("Innovation") or \
266 self._toStore("OMB") or \
267 self._toStore("SimulatedObservationAtBackground"):
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( numpy.ravel(Y) - numpy.ravel(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')