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é",
79 "AugmentedWeightedLeastSquares", "AWLS",
80 "WeightedLeastSquares", "WLS",
81 "LeastSquares", "LS", "L2",
82 "AbsoluteValue", "L1",
86 "AugmentedPonderatedLeastSquares","APLS",
87 "PonderatedLeastSquares","PLS",
90 self.defineRequiredParameter(
91 name = "StoreInternalVariables",
94 message = "Stockage des variables internes ou intermédiaires du calcul",
96 self.defineRequiredParameter(
97 name = "StoreSupplementaryCalculations",
100 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
107 "CurrentIterationNumber",
112 "SimulatedObservationAtBackground",
113 "SimulatedObservationAtCurrentState",
114 "SimulatedObservationAtOptimum",
117 self.defineRequiredParameter( # Pas de type
119 message = "Liste des valeurs de bornes d'incréments de paramètres",
121 self.requireInputArguments(
122 mandatory= ("Xb", "Y", "HO", "R", "B"),
124 self.setAttributes(tags=(
130 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
131 self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
133 if ("BoxBounds" in self._parameters) and isinstance(self._parameters["BoxBounds"], (list, tuple)) and (len(self._parameters["BoxBounds"]) > 0):
134 BoxBounds = self._parameters["BoxBounds"]
135 logging.debug("%s Prise en compte des bornes d'incréments de paramètres effectuée"%(self._name,))
137 raise ValueError("Particle Swarm Optimization requires bounds on all variables increments to be truly given (BoxBounds).")
138 BoxBounds = numpy.array(BoxBounds)
139 if numpy.isnan(BoxBounds).any():
140 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)
142 Phig = float( self._parameters["GroupRecallRate"] )
144 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)))
146 Hm = HO["Direct"].appliedTo
151 # Définition de la fonction-coût
152 # ------------------------------
153 def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
154 _X = numpy.asmatrix(numpy.ravel( x )).T
156 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
158 if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","AugmentedPonderatedLeastSquares","APLS","DA"]:
159 if BI is None or RI is None:
160 raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
161 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
162 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
163 elif QualityMeasure in ["WeightedLeastSquares","WLS","PonderatedLeastSquares","PLS"]:
165 raise ValueError("Observation error covariance matrix has to be properly defined!")
167 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
168 elif QualityMeasure in ["LeastSquares","LS","L2"]:
170 Jo = 0.5 * (Y - _HX).T * (Y - _HX)
171 elif QualityMeasure in ["AbsoluteValue","L1"]:
173 Jo = numpy.sum( numpy.abs(Y - _HX) )
174 elif QualityMeasure in ["MaximumError","ME"]:
176 Jo = numpy.max( numpy.abs(Y - _HX) )
178 J = float( Jb ) + float( Jo )
183 Xini = numpy.ravel(Xb)
185 Xini = numpy.zeros(len(BoxBounds[:,0]))
187 SpaceUp = BoxBounds[:,1] + Xini
188 SpaceLow = BoxBounds[:,0] + Xini
189 nbparam = len(SpaceUp)
191 # Initialisation de l'essaim
192 # --------------------------
193 NumberOfFunctionEvaluations = 0
194 LimitVelocity = numpy.abs(SpaceUp-SpaceLow)
198 for i in range(nbparam) :
199 PosInsect.append(numpy.random.uniform(low=SpaceLow[i], high=SpaceUp[i], size=self._parameters["NumberOfInsects"]))
200 VelocityInsect.append(numpy.random.uniform(low=-LimitVelocity[i], high=LimitVelocity[i], size=self._parameters["NumberOfInsects"]))
201 VelocityInsect = numpy.matrix(VelocityInsect)
202 PosInsect = numpy.matrix(PosInsect)
204 BestPosInsect = numpy.array(PosInsect)
206 Best = copy.copy(SpaceLow)
207 qBest = CostFunction(Best,self._parameters["QualityCriterion"])
208 NumberOfFunctionEvaluations += 1
210 for i in range(self._parameters["NumberOfInsects"]):
211 insect = numpy.ravel(PosInsect[:,i])
212 quality = CostFunction(insect,self._parameters["QualityCriterion"])
213 NumberOfFunctionEvaluations += 1
214 qBestPosInsect.append(quality)
216 Best = copy.copy( insect )
217 qBest = copy.copy( quality )
218 logging.debug("%s Initialisation, Insecte = %s, Qualité = %s"%(self._name, str(Best), str(qBest)))
220 self.StoredVariables["CurrentIterationNumber"].store( len(self.StoredVariables["CostFunctionJ"]) )
221 if self._parameters["StoreInternalVariables"] or self._toStore("CurrentState"):
222 self.StoredVariables["CurrentState"].store( Best )
223 self.StoredVariables["CostFunctionJb"].store( 0. )
224 self.StoredVariables["CostFunctionJo"].store( 0. )
225 self.StoredVariables["CostFunctionJ" ].store( qBest )
227 # Minimisation de la fonctionnelle
228 # --------------------------------
229 for n in range(self._parameters["MaximumNumberOfSteps"]):
230 for i in range(self._parameters["NumberOfInsects"]) :
231 insect = numpy.ravel(PosInsect[:,i])
232 rp = numpy.random.uniform(size=nbparam)
233 rg = numpy.random.uniform(size=nbparam)
234 for j in range(nbparam) :
235 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])
236 PosInsect[j,i] = PosInsect[j,i]+VelocityInsect[j,i]
237 quality = CostFunction(insect,self._parameters["QualityCriterion"])
238 NumberOfFunctionEvaluations += 1
239 if quality < qBestPosInsect[i]:
240 BestPosInsect[:,i] = copy.copy( insect )
241 qBestPosInsect[i] = copy.copy( quality )
243 Best = copy.copy( insect )
244 qBest = copy.copy( quality )
245 logging.debug("%s Etape %i, Insecte = %s, Qualité = %s"%(self._name, n, str(Best), str(qBest)))
247 self.StoredVariables["CurrentIterationNumber"].store( len(self.StoredVariables["CostFunctionJ"]) )
248 if self._parameters["StoreInternalVariables"] or self._toStore("CurrentState"):
249 self.StoredVariables["CurrentState"].store( Best )
250 if self._toStore("SimulatedObservationAtCurrentState"):
251 _HmX = Hm( numpy.asmatrix(numpy.ravel( Best )).T )
252 _HmX = numpy.asmatrix(numpy.ravel( _HmX )).T
253 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HmX )
254 self.StoredVariables["CostFunctionJb"].store( 0. )
255 self.StoredVariables["CostFunctionJo"].store( 0. )
256 self.StoredVariables["CostFunctionJ" ].store( qBest )
257 if NumberOfFunctionEvaluations > self._parameters["MaximumNumberOfFunctionEvaluations"]:
258 logging.debug("%s Stopping search because the number %i of function evaluations is exceeding the maximum %i."%(self._name, NumberOfFunctionEvaluations, self._parameters["MaximumNumberOfFunctionEvaluations"]))
261 # Obtention de l'analyse
262 # ----------------------
263 Xa = numpy.asmatrix(numpy.ravel( Best )).T
265 self.StoredVariables["Analysis"].store( Xa.A1 )
267 if self._toStore("Innovation") or \
268 self._toStore("OMB") or \
269 self._toStore("SimulatedObservationAtBackground"):
272 if self._toStore("OMA") or \
273 self._toStore("SimulatedObservationAtOptimum"):
276 # Calculs et/ou stockages supplémentaires
277 # ---------------------------------------
278 if self._toStore("Innovation"):
279 self.StoredVariables["Innovation"].store( d )
280 if self._toStore("BMA"):
281 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
282 if self._toStore("OMA"):
283 self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
284 if self._toStore("OMB"):
285 self.StoredVariables["OMB"].store( d )
286 if self._toStore("SimulatedObservationAtBackground"):
287 self.StoredVariables["SimulatedObservationAtBackground"].store( HXb )
288 if self._toStore("SimulatedObservationAtOptimum"):
289 self.StoredVariables["SimulatedObservationAtOptimum"].store( HXa )
294 # ==============================================================================
295 if __name__ == "__main__":
296 print('\n AUTODIAGNOSTIC\n')