1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2014 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()
28 # ==============================================================================
29 class ElementaryAlgorithm(BasicObjects.Algorithm):
31 BasicObjects.Algorithm.__init__(self, "PARTICLESWARMOPTIMIZATION")
32 self.defineRequiredParameter(
33 name = "MaximumNumberOfSteps",
36 message = "Nombre maximal de pas d'optimisation",
39 self.defineRequiredParameter(
41 typecast = numpy.random.seed,
42 message = "Graine fixée pour le générateur aléatoire",
44 self.defineRequiredParameter(
45 name = "NumberOfInsects",
48 message = "Nombre d'insectes dans l'essaim",
51 self.defineRequiredParameter(
52 name = "SwarmVelocity",
55 message = "Vitesse de groupe imposée par l'essaim",
58 self.defineRequiredParameter(
59 name = "GroupRecallRate",
62 message = "Taux de rappel au meilleur insecte du groupe (entre 0 et 1)",
66 self.defineRequiredParameter(
67 name = "QualityCriterion",
68 default = "AugmentedPonderatedLeastSquares",
70 message = "Critère de qualité utilisé",
71 listval = ["AugmentedPonderatedLeastSquares","APLS","DA",
72 "PonderatedLeastSquares","PLS",
73 "LeastSquares","LS","L2",
77 self.defineRequiredParameter(
78 name = "StoreInternalVariables",
81 message = "Stockage des variables internes ou intermédiaires du calcul",
83 self.defineRequiredParameter(
84 name = "StoreSupplementaryCalculations",
87 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
88 listval = ["BMA", "OMA", "OMB", "Innovation"]
91 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
92 logging.debug("%s Lancement"%self._name)
93 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
95 # Paramètres de pilotage
96 # ----------------------
97 self.setParameters(Parameters)
99 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):
100 BoxBounds = self._parameters["BoxBounds"]
101 logging.debug("%s Prise en compte des bornes d'incréments de paramètres effectuee"%(self._name,))
103 raise ValueError("Particle Swarm Optimization requires bounds on all variables to be given.")
104 BoxBounds = numpy.array(BoxBounds)
105 if numpy.isnan(BoxBounds).any():
106 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)
108 Phig = float( self._parameters["GroupRecallRate"] )
110 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)))
112 # Opérateur d'observation
113 # -----------------------
114 Hm = HO["Direct"].appliedTo
116 # Précalcul des inversions de B et R
117 # ----------------------------------
121 # Définition de la fonction-coût
122 # ------------------------------
123 def CostFunction(x, QualityMeasure="AugmentedPonderatedLeastSquares"):
124 _X = numpy.asmatrix(numpy.ravel( x )).T
126 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
128 if QualityMeasure in ["AugmentedPonderatedLeastSquares","APLS","DA"]:
129 if BI is None or RI is None:
130 raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
131 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
132 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
133 J = float( Jb ) + float( Jo )
134 elif QualityMeasure in ["PonderatedLeastSquares","PLS"]:
136 raise ValueError("Observation error covariance matrix has to be properly defined!")
138 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
139 J = float( Jb ) + float( Jo )
140 elif QualityMeasure in ["LeastSquares","LS","L2"]:
142 Jo = 0.5 * (Y - _HX).T * (Y - _HX)
143 J = float( Jb ) + float( Jo )
144 elif QualityMeasure in ["AbsoluteValue","L1"]:
146 Jo = numpy.sum( numpy.abs(Y - _HX) )
147 J = float( Jb ) + float( Jo )
148 elif QualityMeasure in ["MaximumError","ME"]:
150 Jo = numpy.max( numpy.abs(Y - _HX) )
151 J = float( Jb ) + float( Jo )
155 # Point de démarrage de l'optimisation : Xini = Xb
156 # ------------------------------------
157 if type(Xb) is type(numpy.matrix([])):
158 Xini = Xb.A1.tolist()
162 Xini = numpy.zeros(len(BoxBounds[:,0]))
164 # Initialisation des bornes
165 # -------------------------
166 SpaceUp = BoxBounds[:,1] + Xini
167 Spacelow = BoxBounds[:,0] + Xini
168 nbparam = len(SpaceUp)
170 # Initialisation de l'essaim
171 # --------------------------
172 LimitVelocity = numpy.abs(SpaceUp-Spacelow)
176 for i in range(nbparam) :
177 PosInsect.append(numpy.random.uniform(low=Spacelow[i], high=SpaceUp[i], size=self._parameters["NumberOfInsects"]))
178 VelocityInsect.append(numpy.random.uniform(low=-LimitVelocity[i], high=LimitVelocity[i], size=self._parameters["NumberOfInsects"]))
179 VelocityInsect = numpy.matrix(VelocityInsect)
180 PosInsect = numpy.matrix(PosInsect)
182 BestPosInsect = numpy.array(PosInsect)
184 Best = copy.copy(Spacelow)
185 qBest = CostFunction(Best,self._parameters["QualityCriterion"])
187 for i in range(self._parameters["NumberOfInsects"]):
188 insect = numpy.array(PosInsect[:,i].A1)
189 quality = CostFunction(insect,self._parameters["QualityCriterion"])
190 qBestPosInsect.append(quality)
195 # Minimisation de la fonctionnelle
196 # --------------------------------
197 for n in range(self._parameters["MaximumNumberOfSteps"]):
198 for i in range(self._parameters["NumberOfInsects"]) :
199 insect = PosInsect[:,i]
200 rp = numpy.random.uniform(size=nbparam)
201 rg = numpy.random.uniform(size=nbparam)
202 for j in range(nbparam) :
203 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])
204 PosInsect[j,i] = PosInsect[j,i]+VelocityInsect[j,i]
205 quality = CostFunction(insect,self._parameters["QualityCriterion"])
206 if quality < qBestPosInsect[i]:
207 BestPosInsect[:,i] = numpy.ravel( insect )
209 Best = numpy.ravel( insect )
212 if self._parameters["StoreInternalVariables"]:
213 self.StoredVariables["CurrentState"].store( Best )
214 self.StoredVariables["CostFunctionJb"].store( 0. )
215 self.StoredVariables["CostFunctionJo"].store( 0. )
216 self.StoredVariables["CostFunctionJ" ].store( qBest )
218 # Obtention de l'analyse
219 # ----------------------
220 Xa = numpy.asmatrix(numpy.ravel( Best )).T
222 self.StoredVariables["Analysis"].store( Xa.A1 )
224 # Calculs et/ou stockages supplémentaires
225 # ---------------------------------------
226 if "Innovation" in self._parameters["StoreSupplementaryCalculations"] or "OMB" in self._parameters["StoreSupplementaryCalculations"]:
228 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
229 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
230 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
231 self.StoredVariables["BMA"].store( numpy.ravel(Xb - Xa) )
232 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
233 self.StoredVariables["OMA"].store( numpy.ravel(Y - Hm(Xa)) )
234 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
235 self.StoredVariables["OMB"].store( numpy.ravel(d) )
237 logging.debug("%s Nombre d'évaluation(s) de l'opérateur d'observation direct/tangent/adjoint.: %i/%i/%i"%(self._name, HO["Direct"].nbcalls(0),HO["Tangent"].nbcalls(0),HO["Adjoint"].nbcalls(0)))
238 logging.debug("%s Nombre d'appels au cache d'opérateur d'observation direct/tangent/adjoint..: %i/%i/%i"%(self._name, HO["Direct"].nbcalls(3),HO["Tangent"].nbcalls(3),HO["Adjoint"].nbcalls(3)))
239 logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
240 logging.debug("%s Terminé"%self._name)
244 # ==============================================================================
245 if __name__ == "__main__":
246 print '\n AUTODIAGNOSTIC \n'