1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2013 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, PlatformInfo
25 m = PlatformInfo.SystemUsage()
30 # ==============================================================================
31 class ElementaryAlgorithm(BasicObjects.Algorithm):
33 BasicObjects.Algorithm.__init__(self, "PARTICLESWARMOPTIMIZATION")
34 self.defineRequiredParameter(
35 name = "MaximumNumberOfSteps",
38 message = "Nombre maximal de pas d'optimisation",
41 self.defineRequiredParameter(
43 typecast = numpy.random.seed,
44 message = "Graine fixée pour le générateur aléatoire",
46 self.defineRequiredParameter(
47 name = "NumberOfInsects",
50 message = "Nombre d'insectes dans l'essaim",
53 self.defineRequiredParameter(
54 name = "SwarmVelocity",
57 message = "Vitesse de groupe imposée par l'essaim",
60 self.defineRequiredParameter(
61 name = "GroupRecallRate",
64 message = "Taux de rappel au meilleur insecte du groupe (entre 0 et 1)",
68 self.defineRequiredParameter(
69 name = "QualityCriterion",
70 default = "AugmentedPonderatedLeastSquares",
72 message = "Critère de qualité utilisé",
73 listval = ["AugmentedPonderatedLeastSquares","APLS","DA",
74 "PonderatedLeastSquares","PLS",
75 "LeastSquares","LS","L2",
79 self.defineRequiredParameter(
80 name = "StoreInternalVariables",
83 message = "Stockage des variables internes ou intermédiaires du calcul",
85 self.defineRequiredParameter(
86 name = "StoreSupplementaryCalculations",
89 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
90 listval = ["BMA", "OMA", "OMB", "Innovation"]
93 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
94 logging.debug("%s Lancement"%self._name)
95 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
97 # Paramètres de pilotage
98 # ----------------------
99 self.setParameters(Parameters)
101 if self._parameters.has_key("BoxBounds") and (type(self._parameters["BoxBounds"]) is type([]) or type(self._parameters["BoxBounds"]) is type(())) and (len(self._parameters["BoxBounds"]) > 0):
102 BoxBounds = self._parameters["BoxBounds"]
103 logging.debug("%s Prise en compte des bornes d'incréments de paramètres effectuee"%(self._name,))
105 raise ValueError("Particle Swarm Optimization requires bounds on all variables to be given.")
106 BoxBounds = numpy.array(BoxBounds)
107 if numpy.isnan(BoxBounds).any():
108 raise ValueError("Particle Swarm Optimization requires bounds on all variables increments to be truly given, \"None\" is not allowed. The actual increments bounds are:\n%s"%BoxBounds)
110 Phig = float( self._parameters["GroupRecallRate"] )
112 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)))
114 # Opérateur d'observation
115 # -----------------------
116 Hm = HO["Direct"].appliedTo
118 # Précalcul des inversions de B et R
119 # ----------------------------------
122 elif self._parameters["B_scalar"] is not None:
123 BI = 1.0 / self._parameters["B_scalar"]
129 elif self._parameters["R_scalar"] is not None:
130 RI = 1.0 / self._parameters["R_scalar"]
134 # Définition de la fonction-coût
135 # ------------------------------
136 def CostFunction(x, QualityMeasure="AugmentedPonderatedLeastSquares"):
137 _X = numpy.asmatrix(numpy.ravel( x )).T
139 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
141 if QualityMeasure in ["AugmentedPonderatedLeastSquares","APLS","DA"]:
142 if BI is None or RI is None:
143 raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
144 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
145 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
146 J = float( Jb ) + float( Jo )
147 elif QualityMeasure in ["PonderatedLeastSquares","PLS"]:
149 raise ValueError("Observation error covariance matrix has to be properly defined!")
151 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
152 J = float( Jb ) + float( Jo )
153 elif QualityMeasure in ["LeastSquares","LS","L2"]:
155 Jo = 0.5 * (Y - _HX).T * (Y - _HX)
156 J = float( Jb ) + float( Jo )
157 elif QualityMeasure in ["AbsoluteValue","L1"]:
159 Jo = numpy.sum( numpy.abs(Y - _HX) )
160 J = float( Jb ) + float( Jo )
161 elif QualityMeasure in ["MaximumError","ME"]:
163 Jo = numpy.max( numpy.abs(Y - _HX) )
164 J = float( Jb ) + float( Jo )
168 # Point de démarrage de l'optimisation : Xini = Xb
169 # ------------------------------------
170 if type(Xb) is type(numpy.matrix([])):
171 Xini = Xb.A1.tolist()
175 Xini = numpy.zeros(len(BoxBounds[:,0]))
177 # Initialisation des bornes
178 # -------------------------
179 SpaceUp = BoxBounds[:,1] + Xini
180 Spacelow = BoxBounds[:,0] + Xini
181 nbparam = len(SpaceUp)
183 # Initialisation de l'essaim
184 # --------------------------
185 LimitVelocity = numpy.abs(SpaceUp-Spacelow)
189 for i in range(nbparam) :
190 PosInsect.append(numpy.random.uniform(low=Spacelow[i], high=SpaceUp[i], size=self._parameters["NumberOfInsects"]))
191 VelocityInsect.append(numpy.random.uniform(low=-LimitVelocity[i], high=LimitVelocity[i], size=self._parameters["NumberOfInsects"]))
192 VelocityInsect = numpy.matrix(VelocityInsect)
193 PosInsect = numpy.matrix(PosInsect)
195 BestPosInsect = numpy.array(PosInsect)
197 Best = copy.copy(Spacelow)
198 qBest = CostFunction(Best,self._parameters["QualityCriterion"])
200 for i in range(self._parameters["NumberOfInsects"]):
201 insect = numpy.array(PosInsect[:,i].A1)
202 quality = CostFunction(insect,self._parameters["QualityCriterion"])
203 qBestPosInsect.append(quality)
208 # Minimisation de la fonctionnelle
209 # --------------------------------
210 for n in range(self._parameters["MaximumNumberOfSteps"]):
211 for i in range(self._parameters["NumberOfInsects"]) :
212 insect = PosInsect[:,i]
213 rp = numpy.random.uniform(size=nbparam)
214 rg = numpy.random.uniform(size=nbparam)
215 for j in range(nbparam) :
216 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])
217 PosInsect[j,i] = PosInsect[j,i]+VelocityInsect[j,i]
218 quality = CostFunction(insect,self._parameters["QualityCriterion"])
219 if quality < qBestPosInsect[i]:
220 BestPosInsect[:,i] = numpy.ravel( insect )
222 Best = numpy.ravel( insect )
225 if self._parameters["StoreInternalVariables"]:
226 self.StoredVariables["CurrentState"].store( Best )
227 self.StoredVariables["CostFunctionJb"].store( 0. )
228 self.StoredVariables["CostFunctionJo"].store( 0. )
229 self.StoredVariables["CostFunctionJ" ].store( qBest )
231 # Obtention de l'analyse
232 # ----------------------
233 Xa = numpy.asmatrix(numpy.ravel( Best )).T
235 self.StoredVariables["Analysis"].store( Xa.A1 )
237 # Calculs et/ou stockages supplémentaires
238 # ---------------------------------------
239 if "Innovation" in self._parameters["StoreSupplementaryCalculations"] or "OMB" in self._parameters["StoreSupplementaryCalculations"]:
241 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
242 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
243 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
244 self.StoredVariables["BMA"].store( numpy.ravel(Xb - Xa) )
245 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
246 self.StoredVariables["OMA"].store( numpy.ravel(Y - Hm(Xa)) )
247 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
248 self.StoredVariables["OMB"].store( numpy.ravel(d) )
250 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
251 logging.debug("%s Terminé"%self._name)
255 # ==============================================================================
256 if __name__ == "__main__":
257 print '\n AUTODIAGNOSTIC \n'