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é",
77 listval = ["AugmentedWeightedLeastSquares","AWLS","AugmentedPonderatedLeastSquares","APLS","DA",
78 "WeightedLeastSquares","WLS","PonderatedLeastSquares","PLS",
79 "LeastSquares","LS","L2",
83 self.defineRequiredParameter(
84 name = "StoreInternalVariables",
87 message = "Stockage des variables internes ou intermédiaires du calcul",
89 self.defineRequiredParameter(
90 name = "StoreSupplementaryCalculations",
93 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
100 "CurrentIterationNumber",
105 "SimulatedObservationAtBackground",
106 "SimulatedObservationAtCurrentState",
107 "SimulatedObservationAtOptimum",
110 self.defineRequiredParameter( # Pas de type
112 message = "Liste des valeurs de bornes d'incréments de paramètres",
114 self.requireInputArguments(
115 mandatory= ("Xb", "Y", "HO", "R", "B"),
117 self.setAttributes(tags=(
123 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
124 self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
126 if ("BoxBounds" in self._parameters) and isinstance(self._parameters["BoxBounds"], (list, tuple)) and (len(self._parameters["BoxBounds"]) > 0):
127 BoxBounds = self._parameters["BoxBounds"]
128 logging.debug("%s Prise en compte des bornes d'incréments de paramètres effectuée"%(self._name,))
130 raise ValueError("Particle Swarm Optimization requires bounds on all variables increments to be truly given (BoxBounds).")
131 BoxBounds = numpy.array(BoxBounds)
132 if numpy.isnan(BoxBounds).any():
133 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)
135 Phig = float( self._parameters["GroupRecallRate"] )
137 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)))
139 # Opérateur d'observation
140 # -----------------------
141 Hm = HO["Direct"].appliedTo
143 # Précalcul des inversions de B et R
144 # ----------------------------------
148 # Définition de la fonction-coût
149 # ------------------------------
150 def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
151 _X = numpy.asmatrix(numpy.ravel( x )).T
153 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
155 if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","AugmentedPonderatedLeastSquares","APLS","DA"]:
156 if BI is None or RI is None:
157 raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
158 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
159 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
160 elif QualityMeasure in ["WeightedLeastSquares","WLS","PonderatedLeastSquares","PLS"]:
162 raise ValueError("Observation error covariance matrix has to be properly defined!")
164 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
165 elif QualityMeasure in ["LeastSquares","LS","L2"]:
167 Jo = 0.5 * (Y - _HX).T * (Y - _HX)
168 elif QualityMeasure in ["AbsoluteValue","L1"]:
170 Jo = numpy.sum( numpy.abs(Y - _HX) )
171 elif QualityMeasure in ["MaximumError","ME"]:
173 Jo = numpy.max( numpy.abs(Y - _HX) )
175 J = float( Jb ) + float( Jo )
179 # Point de démarrage de l'optimisation : Xini = Xb
180 # ------------------------------------
181 if isinstance(Xb, type(numpy.matrix([]))):
182 Xini = Xb.A1.tolist()
186 Xini = numpy.zeros(len(BoxBounds[:,0]))
188 # Initialisation des bornes
189 # -------------------------
190 SpaceUp = BoxBounds[:,1] + Xini
191 SpaceLow = BoxBounds[:,0] + Xini
192 nbparam = len(SpaceUp)
194 # Initialisation de l'essaim
195 # --------------------------
196 NumberOfFunctionEvaluations = 0
197 LimitVelocity = numpy.abs(SpaceUp-SpaceLow)
201 for i in range(nbparam) :
202 PosInsect.append(numpy.random.uniform(low=SpaceLow[i], high=SpaceUp[i], size=self._parameters["NumberOfInsects"]))
203 VelocityInsect.append(numpy.random.uniform(low=-LimitVelocity[i], high=LimitVelocity[i], size=self._parameters["NumberOfInsects"]))
204 VelocityInsect = numpy.matrix(VelocityInsect)
205 PosInsect = numpy.matrix(PosInsect)
207 BestPosInsect = numpy.array(PosInsect)
209 Best = copy.copy(SpaceLow)
210 qBest = CostFunction(Best,self._parameters["QualityCriterion"])
211 NumberOfFunctionEvaluations += 1
213 for i in range(self._parameters["NumberOfInsects"]):
214 insect = numpy.ravel(PosInsect[:,i])
215 quality = CostFunction(insect,self._parameters["QualityCriterion"])
216 NumberOfFunctionEvaluations += 1
217 qBestPosInsect.append(quality)
219 Best = copy.copy( insect )
220 qBest = copy.copy( quality )
221 logging.debug("%s Initialisation, Insecte = %s, Qualité = %s"%(self._name, str(Best), str(qBest)))
223 self.StoredVariables["CurrentIterationNumber"].store( len(self.StoredVariables["CostFunctionJ"]) )
224 if self._parameters["StoreInternalVariables"] or self._toStore("CurrentState"):
225 self.StoredVariables["CurrentState"].store( Best )
226 self.StoredVariables["CostFunctionJb"].store( 0. )
227 self.StoredVariables["CostFunctionJo"].store( 0. )
228 self.StoredVariables["CostFunctionJ" ].store( qBest )
230 # Minimisation de la fonctionnelle
231 # --------------------------------
232 for n in range(self._parameters["MaximumNumberOfSteps"]):
233 for i in range(self._parameters["NumberOfInsects"]) :
234 insect = numpy.ravel(PosInsect[:,i])
235 rp = numpy.random.uniform(size=nbparam)
236 rg = numpy.random.uniform(size=nbparam)
237 for j in range(nbparam) :
238 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])
239 PosInsect[j,i] = PosInsect[j,i]+VelocityInsect[j,i]
240 quality = CostFunction(insect,self._parameters["QualityCriterion"])
241 NumberOfFunctionEvaluations += 1
242 if quality < qBestPosInsect[i]:
243 BestPosInsect[:,i] = copy.copy( insect )
244 qBestPosInsect[i] = copy.copy( quality )
246 Best = copy.copy( insect )
247 qBest = copy.copy( quality )
248 logging.debug("%s Etape %i, Insecte = %s, Qualité = %s"%(self._name, n, str(Best), str(qBest)))
250 self.StoredVariables["CurrentIterationNumber"].store( len(self.StoredVariables["CostFunctionJ"]) )
251 if self._parameters["StoreInternalVariables"] or self._toStore("CurrentState"):
252 self.StoredVariables["CurrentState"].store( Best )
253 if self._toStore("SimulatedObservationAtCurrentState"):
254 _HmX = Hm( numpy.asmatrix(numpy.ravel( Best )).T )
255 _HmX = numpy.asmatrix(numpy.ravel( _HmX )).T
256 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HmX )
257 self.StoredVariables["CostFunctionJb"].store( 0. )
258 self.StoredVariables["CostFunctionJo"].store( 0. )
259 self.StoredVariables["CostFunctionJ" ].store( qBest )
260 if NumberOfFunctionEvaluations > self._parameters["MaximumNumberOfFunctionEvaluations"]:
261 logging.debug("%s Stopping search because the number %i of function evaluations is exceeding the maximum %i."%(self._name, NumberOfFunctionEvaluations, self._parameters["MaximumNumberOfFunctionEvaluations"]))
264 # Obtention de l'analyse
265 # ----------------------
266 Xa = numpy.asmatrix(numpy.ravel( Best )).T
268 self.StoredVariables["Analysis"].store( Xa.A1 )
270 if self._toStore("Innovation") or \
271 self._toStore("OMB") or \
272 self._toStore("SimulatedObservationAtBackground"):
275 if self._toStore("OMA") or \
276 self._toStore("SimulatedObservationAtOptimum"):
279 # Calculs et/ou stockages supplémentaires
280 # ---------------------------------------
281 if self._toStore("Innovation"):
282 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
283 if self._toStore("BMA"):
284 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
285 if self._toStore("OMA"):
286 self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
287 if self._toStore("OMB"):
288 self.StoredVariables["OMB"].store( numpy.ravel(d) )
289 if self._toStore("SimulatedObservationAtBackground"):
290 self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
291 if self._toStore("SimulatedObservationAtOptimum"):
292 self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
297 # ==============================================================================
298 if __name__ == "__main__":
299 print('\n AUTODIAGNOSTIC\n')