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
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
30 BasicObjects.Algorithm.__init__(self, "PARTICLESWARMOPTIMIZATION")
31 self.defineRequiredParameter(
32 name = "MaximumNumberOfSteps",
35 message = "Nombre maximal de pas d'optimisation",
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",
84 "AugmentedPonderatedLeastSquares","APLS",
85 "PonderatedLeastSquares","PLS",
88 self.defineRequiredParameter(
89 name = "StoreInternalVariables",
92 message = "Stockage des variables internes ou intermédiaires du calcul",
94 self.defineRequiredParameter(
95 name = "StoreSupplementaryCalculations",
98 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
105 "CurrentIterationNumber",
110 "SimulatedObservationAtBackground",
111 "SimulatedObservationAtCurrentState",
112 "SimulatedObservationAtOptimum",
115 self.defineRequiredParameter( # Pas de type
117 message = "Liste des valeurs de bornes d'incréments de paramètres",
119 self.requireInputArguments(
120 mandatory= ("Xb", "Y", "HO", "R", "B"),
122 self.setAttributes(tags=(
128 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
129 self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
131 if ("BoxBounds" in self._parameters) and isinstance(self._parameters["BoxBounds"], (list, tuple)) and (len(self._parameters["BoxBounds"]) > 0):
132 BoxBounds = self._parameters["BoxBounds"]
133 logging.debug("%s Prise en compte des bornes d'incréments de paramètres effectuée"%(self._name,))
135 raise ValueError("Particle Swarm Optimization requires bounds on all variables increments to be truly given (BoxBounds).")
136 BoxBounds = numpy.array(BoxBounds)
137 if numpy.isnan(BoxBounds).any():
138 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)
140 Phig = float( self._parameters["GroupRecallRate"] )
142 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)))
144 # Opérateur d'observation
145 # -----------------------
146 Hm = HO["Direct"].appliedTo
148 # Précalcul des inversions de B et R
149 # ----------------------------------
153 # Définition de la fonction-coût
154 # ------------------------------
155 def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
156 _X = numpy.asmatrix(numpy.ravel( x )).T
158 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
160 if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","AugmentedPonderatedLeastSquares","APLS","DA"]:
161 if BI is None or RI is None:
162 raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
163 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
164 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
165 elif QualityMeasure in ["WeightedLeastSquares","WLS","PonderatedLeastSquares","PLS"]:
167 raise ValueError("Observation error covariance matrix has to be properly defined!")
169 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
170 elif QualityMeasure in ["LeastSquares","LS","L2"]:
172 Jo = 0.5 * (Y - _HX).T * (Y - _HX)
173 elif QualityMeasure in ["AbsoluteValue","L1"]:
175 Jo = numpy.sum( numpy.abs(Y - _HX) )
176 elif QualityMeasure in ["MaximumError","ME"]:
178 Jo = numpy.max( numpy.abs(Y - _HX) )
180 J = float( Jb ) + float( Jo )
184 # Point de démarrage de l'optimisation : Xini = Xb
185 # ------------------------------------
186 if isinstance(Xb, type(numpy.matrix([]))):
187 Xini = Xb.A1.tolist()
191 Xini = numpy.zeros(len(BoxBounds[:,0]))
193 # Initialisation des bornes
194 # -------------------------
195 SpaceUp = BoxBounds[:,1] + Xini
196 SpaceLow = BoxBounds[:,0] + Xini
197 nbparam = len(SpaceUp)
199 # Initialisation de l'essaim
200 # --------------------------
201 NumberOfFunctionEvaluations = 0
202 LimitVelocity = numpy.abs(SpaceUp-SpaceLow)
206 for i in range(nbparam) :
207 PosInsect.append(numpy.random.uniform(low=SpaceLow[i], high=SpaceUp[i], size=self._parameters["NumberOfInsects"]))
208 VelocityInsect.append(numpy.random.uniform(low=-LimitVelocity[i], high=LimitVelocity[i], size=self._parameters["NumberOfInsects"]))
209 VelocityInsect = numpy.matrix(VelocityInsect)
210 PosInsect = numpy.matrix(PosInsect)
212 BestPosInsect = numpy.array(PosInsect)
214 Best = copy.copy(SpaceLow)
215 qBest = CostFunction(Best,self._parameters["QualityCriterion"])
216 NumberOfFunctionEvaluations += 1
218 for i in range(self._parameters["NumberOfInsects"]):
219 insect = numpy.ravel(PosInsect[:,i])
220 quality = CostFunction(insect,self._parameters["QualityCriterion"])
221 NumberOfFunctionEvaluations += 1
222 qBestPosInsect.append(quality)
224 Best = copy.copy( insect )
225 qBest = copy.copy( quality )
226 logging.debug("%s Initialisation, Insecte = %s, Qualité = %s"%(self._name, str(Best), str(qBest)))
228 self.StoredVariables["CurrentIterationNumber"].store( len(self.StoredVariables["CostFunctionJ"]) )
229 if self._parameters["StoreInternalVariables"] or self._toStore("CurrentState"):
230 self.StoredVariables["CurrentState"].store( Best )
231 self.StoredVariables["CostFunctionJb"].store( 0. )
232 self.StoredVariables["CostFunctionJo"].store( 0. )
233 self.StoredVariables["CostFunctionJ" ].store( qBest )
235 # Minimisation de la fonctionnelle
236 # --------------------------------
237 for n in range(self._parameters["MaximumNumberOfSteps"]):
238 for i in range(self._parameters["NumberOfInsects"]) :
239 insect = numpy.ravel(PosInsect[:,i])
240 rp = numpy.random.uniform(size=nbparam)
241 rg = numpy.random.uniform(size=nbparam)
242 for j in range(nbparam) :
243 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])
244 PosInsect[j,i] = PosInsect[j,i]+VelocityInsect[j,i]
245 quality = CostFunction(insect,self._parameters["QualityCriterion"])
246 NumberOfFunctionEvaluations += 1
247 if quality < qBestPosInsect[i]:
248 BestPosInsect[:,i] = copy.copy( insect )
249 qBestPosInsect[i] = copy.copy( quality )
251 Best = copy.copy( insect )
252 qBest = copy.copy( quality )
253 logging.debug("%s Etape %i, Insecte = %s, Qualité = %s"%(self._name, n, str(Best), str(qBest)))
255 self.StoredVariables["CurrentIterationNumber"].store( len(self.StoredVariables["CostFunctionJ"]) )
256 if self._parameters["StoreInternalVariables"] or self._toStore("CurrentState"):
257 self.StoredVariables["CurrentState"].store( Best )
258 if self._toStore("SimulatedObservationAtCurrentState"):
259 _HmX = Hm( numpy.asmatrix(numpy.ravel( Best )).T )
260 _HmX = numpy.asmatrix(numpy.ravel( _HmX )).T
261 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HmX )
262 self.StoredVariables["CostFunctionJb"].store( 0. )
263 self.StoredVariables["CostFunctionJo"].store( 0. )
264 self.StoredVariables["CostFunctionJ" ].store( qBest )
265 if NumberOfFunctionEvaluations > self._parameters["MaximumNumberOfFunctionEvaluations"]:
266 logging.debug("%s Stopping search because the number %i of function evaluations is exceeding the maximum %i."%(self._name, NumberOfFunctionEvaluations, self._parameters["MaximumNumberOfFunctionEvaluations"]))
269 # Obtention de l'analyse
270 # ----------------------
271 Xa = numpy.asmatrix(numpy.ravel( Best )).T
273 self.StoredVariables["Analysis"].store( Xa.A1 )
275 if self._toStore("Innovation") or \
276 self._toStore("OMB") or \
277 self._toStore("SimulatedObservationAtBackground"):
280 if self._toStore("OMA") or \
281 self._toStore("SimulatedObservationAtOptimum"):
284 # Calculs et/ou stockages supplémentaires
285 # ---------------------------------------
286 if self._toStore("Innovation"):
287 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
288 if self._toStore("BMA"):
289 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
290 if self._toStore("OMA"):
291 self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
292 if self._toStore("OMB"):
293 self.StoredVariables["OMB"].store( numpy.ravel(d) )
294 if self._toStore("SimulatedObservationAtBackground"):
295 self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
296 if self._toStore("SimulatedObservationAtOptimum"):
297 self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
302 # ==============================================================================
303 if __name__ == "__main__":
304 print('\n AUTODIAGNOSTIC\n')