1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2015 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(
40 typecast = numpy.random.seed,
41 message = "Graine fixée pour le générateur aléatoire",
43 self.defineRequiredParameter(
44 name = "NumberOfInsects",
47 message = "Nombre d'insectes dans l'essaim",
50 self.defineRequiredParameter(
51 name = "SwarmVelocity",
54 message = "Vitesse de groupe imposée par l'essaim",
57 self.defineRequiredParameter(
58 name = "GroupRecallRate",
61 message = "Taux de rappel au meilleur insecte du groupe (entre 0 et 1)",
65 self.defineRequiredParameter(
66 name = "QualityCriterion",
67 default = "AugmentedWeightedLeastSquares",
69 message = "Critère de qualité utilisé",
70 listval = ["AugmentedWeightedLeastSquares","AWLS","AugmentedPonderatedLeastSquares","APLS","DA",
71 "WeightedLeastSquares","WLS","PonderatedLeastSquares","PLS",
72 "LeastSquares","LS","L2",
76 self.defineRequiredParameter(
77 name = "StoreInternalVariables",
80 message = "Stockage des variables internes ou intermédiaires du calcul",
82 self.defineRequiredParameter(
83 name = "StoreSupplementaryCalculations",
86 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
87 listval = ["BMA", "OMA", "OMB", "Innovation"]
90 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
93 # Paramètres de pilotage
94 # ----------------------
95 self.setParameters(Parameters)
97 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):
98 BoxBounds = self._parameters["BoxBounds"]
99 logging.debug("%s Prise en compte des bornes d'incréments de paramètres effectuee"%(self._name,))
101 raise ValueError("Particle Swarm Optimization requires bounds on all variables to be given.")
102 BoxBounds = numpy.array(BoxBounds)
103 if numpy.isnan(BoxBounds).any():
104 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)
106 Phig = float( self._parameters["GroupRecallRate"] )
108 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)))
110 # Opérateur d'observation
111 # -----------------------
112 Hm = HO["Direct"].appliedTo
114 # Précalcul des inversions de B et R
115 # ----------------------------------
119 # Définition de la fonction-coût
120 # ------------------------------
121 def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
122 _X = numpy.asmatrix(numpy.ravel( x )).T
124 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
126 if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","AugmentedPonderatedLeastSquares","APLS","DA"]:
127 if BI is None or RI is None:
128 raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
129 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
130 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
131 elif QualityMeasure in ["WeightedLeastSquares","WLS","PonderatedLeastSquares","PLS"]:
133 raise ValueError("Observation error covariance matrix has to be properly defined!")
135 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
136 elif QualityMeasure in ["LeastSquares","LS","L2"]:
138 Jo = 0.5 * (Y - _HX).T * (Y - _HX)
139 elif QualityMeasure in ["AbsoluteValue","L1"]:
141 Jo = numpy.sum( numpy.abs(Y - _HX) )
142 elif QualityMeasure in ["MaximumError","ME"]:
144 Jo = numpy.max( numpy.abs(Y - _HX) )
146 J = float( Jb ) + float( Jo )
148 if self._parameters["StoreInternalVariables"]:
149 self.StoredVariables["CurrentState"].store( _X )
150 self.StoredVariables["CostFunctionJb"].store( Jb )
151 self.StoredVariables["CostFunctionJo"].store( Jo )
152 self.StoredVariables["CostFunctionJ" ].store( J )
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.ravel(PosInsect[:,i])
189 quality = CostFunction(insect,self._parameters["QualityCriterion"])
190 qBestPosInsect.append(quality)
192 Best = copy.copy( insect )
193 qBest = copy.copy( quality )
194 logging.debug("%s Initialisation, Insecte = %s, Qualité = %s"%(self._name, str(Best), str(qBest)))
196 if self._parameters["StoreInternalVariables"]:
197 self.StoredVariables["CurrentState"].store( Best )
198 self.StoredVariables["CostFunctionJb"].store( 0. )
199 self.StoredVariables["CostFunctionJo"].store( 0. )
200 self.StoredVariables["CostFunctionJ" ].store( qBest )
202 # Minimisation de la fonctionnelle
203 # --------------------------------
204 for n in range(self._parameters["MaximumNumberOfSteps"]):
205 for i in range(self._parameters["NumberOfInsects"]) :
206 insect = numpy.ravel(PosInsect[:,i])
207 rp = numpy.random.uniform(size=nbparam)
208 rg = numpy.random.uniform(size=nbparam)
209 for j in range(nbparam) :
210 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])
211 PosInsect[j,i] = PosInsect[j,i]+VelocityInsect[j,i]
212 quality = CostFunction(insect,self._parameters["QualityCriterion"])
213 if quality < qBestPosInsect[i]:
214 BestPosInsect[:,i] = copy.copy( insect )
215 qBestPosInsect[i] = copy.copy( quality )
217 Best = copy.copy( insect )
218 qBest = copy.copy( quality )
219 logging.debug("%s Etape %i, Insecte = %s, Qualité = %s"%(self._name, n, str(Best), str(qBest)))
221 if self._parameters["StoreInternalVariables"]:
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 # Obtention de l'analyse
228 # ----------------------
229 Xa = numpy.asmatrix(numpy.ravel( Best )).T
231 self.StoredVariables["Analysis"].store( Xa.A1 )
233 # Calculs et/ou stockages supplémentaires
234 # ---------------------------------------
235 if "Innovation" in self._parameters["StoreSupplementaryCalculations"] or "OMB" in self._parameters["StoreSupplementaryCalculations"]:
237 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
238 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
239 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
240 self.StoredVariables["BMA"].store( numpy.ravel(Xb - Xa) )
241 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
242 self.StoredVariables["OMA"].store( numpy.ravel(Y - Hm(Xa)) )
243 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
244 self.StoredVariables["OMB"].store( numpy.ravel(d) )
249 # ==============================================================================
250 if __name__ == "__main__":
251 print '\n AUTODIAGNOSTIC \n'