1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2017 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",
94 listval = ["BMA", "OMA", "OMB", "CurrentState", "CostFunctionJ", "CostFunctionJb", "CostFunctionJo", "Innovation", "SimulatedObservationAtBackground", "SimulatedObservationAtCurrentState", "SimulatedObservationAtOptimum"]
96 self.defineRequiredParameter( # Pas de type
98 message = "Liste des valeurs de bornes d'incréments de paramètres",
100 self.requireInputArguments(
101 mandatory= ("Xb", "Y", "HO", "R", "B"),
104 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
105 self._pre_run(Parameters, Xb, Y, R, B, Q)
107 if ("BoxBounds" in self._parameters) and isinstance(self._parameters["BoxBounds"], (list, tuple)) and (len(self._parameters["BoxBounds"]) > 0):
108 BoxBounds = self._parameters["BoxBounds"]
109 logging.debug("%s Prise en compte des bornes d'incréments de paramètres effectuee"%(self._name,))
111 raise ValueError("Particle Swarm Optimization requires bounds on all variables to be given.")
112 BoxBounds = numpy.array(BoxBounds)
113 if numpy.isnan(BoxBounds).any():
114 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)
116 Phig = float( self._parameters["GroupRecallRate"] )
118 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)))
120 # Opérateur d'observation
121 # -----------------------
122 Hm = HO["Direct"].appliedTo
124 # Précalcul des inversions de B et R
125 # ----------------------------------
129 # Définition de la fonction-coût
130 # ------------------------------
131 def CostFunction(x, QualityMeasure="AugmentedWeightedLeastSquares"):
132 _X = numpy.asmatrix(numpy.ravel( x )).T
134 _HX = numpy.asmatrix(numpy.ravel( _HX )).T
136 if QualityMeasure in ["AugmentedWeightedLeastSquares","AWLS","AugmentedPonderatedLeastSquares","APLS","DA"]:
137 if BI is None or RI is None:
138 raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
139 Jb = 0.5 * (_X - Xb).T * BI * (_X - Xb)
140 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
141 elif QualityMeasure in ["WeightedLeastSquares","WLS","PonderatedLeastSquares","PLS"]:
143 raise ValueError("Observation error covariance matrix has to be properly defined!")
145 Jo = 0.5 * (Y - _HX).T * RI * (Y - _HX)
146 elif QualityMeasure in ["LeastSquares","LS","L2"]:
148 Jo = 0.5 * (Y - _HX).T * (Y - _HX)
149 elif QualityMeasure in ["AbsoluteValue","L1"]:
151 Jo = numpy.sum( numpy.abs(Y - _HX) )
152 elif QualityMeasure in ["MaximumError","ME"]:
154 Jo = numpy.max( numpy.abs(Y - _HX) )
156 J = float( Jb ) + float( Jo )
160 # Point de démarrage de l'optimisation : Xini = Xb
161 # ------------------------------------
162 if isinstance(Xb, type(numpy.matrix([]))):
163 Xini = Xb.A1.tolist()
167 Xini = numpy.zeros(len(BoxBounds[:,0]))
169 # Initialisation des bornes
170 # -------------------------
171 SpaceUp = BoxBounds[:,1] + Xini
172 SpaceLow = BoxBounds[:,0] + Xini
173 nbparam = len(SpaceUp)
175 # Initialisation de l'essaim
176 # --------------------------
177 NumberOfFunctionEvaluations = 0
178 LimitVelocity = numpy.abs(SpaceUp-SpaceLow)
182 for i in range(nbparam) :
183 PosInsect.append(numpy.random.uniform(low=SpaceLow[i], high=SpaceUp[i], size=self._parameters["NumberOfInsects"]))
184 VelocityInsect.append(numpy.random.uniform(low=-LimitVelocity[i], high=LimitVelocity[i], size=self._parameters["NumberOfInsects"]))
185 VelocityInsect = numpy.matrix(VelocityInsect)
186 PosInsect = numpy.matrix(PosInsect)
188 BestPosInsect = numpy.array(PosInsect)
190 Best = copy.copy(SpaceLow)
191 qBest = CostFunction(Best,self._parameters["QualityCriterion"])
192 NumberOfFunctionEvaluations += 1
194 for i in range(self._parameters["NumberOfInsects"]):
195 insect = numpy.ravel(PosInsect[:,i])
196 quality = CostFunction(insect,self._parameters["QualityCriterion"])
197 NumberOfFunctionEvaluations += 1
198 qBestPosInsect.append(quality)
200 Best = copy.copy( insect )
201 qBest = copy.copy( quality )
202 logging.debug("%s Initialisation, Insecte = %s, Qualité = %s"%(self._name, str(Best), str(qBest)))
204 if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
205 self.StoredVariables["CurrentState"].store( Best )
206 self.StoredVariables["CostFunctionJb"].store( 0. )
207 self.StoredVariables["CostFunctionJo"].store( 0. )
208 self.StoredVariables["CostFunctionJ" ].store( qBest )
210 # Minimisation de la fonctionnelle
211 # --------------------------------
212 for n in range(self._parameters["MaximumNumberOfSteps"]):
213 for i in range(self._parameters["NumberOfInsects"]) :
214 insect = numpy.ravel(PosInsect[:,i])
215 rp = numpy.random.uniform(size=nbparam)
216 rg = numpy.random.uniform(size=nbparam)
217 for j in range(nbparam) :
218 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])
219 PosInsect[j,i] = PosInsect[j,i]+VelocityInsect[j,i]
220 quality = CostFunction(insect,self._parameters["QualityCriterion"])
221 NumberOfFunctionEvaluations += 1
222 if quality < qBestPosInsect[i]:
223 BestPosInsect[:,i] = copy.copy( insect )
224 qBestPosInsect[i] = copy.copy( quality )
226 Best = copy.copy( insect )
227 qBest = copy.copy( quality )
228 logging.debug("%s Etape %i, Insecte = %s, Qualité = %s"%(self._name, n, str(Best), str(qBest)))
230 if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
231 self.StoredVariables["CurrentState"].store( Best )
232 if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
233 _HmX = Hm( numpy.asmatrix(numpy.ravel( Best )).T )
234 _HmX = numpy.asmatrix(numpy.ravel( _HmX )).T
235 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HmX )
236 self.StoredVariables["CostFunctionJb"].store( 0. )
237 self.StoredVariables["CostFunctionJo"].store( 0. )
238 self.StoredVariables["CostFunctionJ" ].store( qBest )
239 if NumberOfFunctionEvaluations > self._parameters["MaximumNumberOfFunctionEvaluations"]:
240 logging.debug("%s Stopping search because the number %i of function evaluations is exceeding the maximum %i."%(self._name, NumberOfFunctionEvaluations, self._parameters["MaximumNumberOfFunctionEvaluations"]))
243 # Obtention de l'analyse
244 # ----------------------
245 Xa = numpy.asmatrix(numpy.ravel( Best )).T
247 self.StoredVariables["Analysis"].store( Xa.A1 )
249 if "Innovation" in self._parameters["StoreSupplementaryCalculations"] or \
250 "OMB" in self._parameters["StoreSupplementaryCalculations"] or \
251 "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
254 if "OMA" in self._parameters["StoreSupplementaryCalculations"] or \
255 "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
258 # Calculs et/ou stockages supplémentaires
259 # ---------------------------------------
260 if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
261 self.StoredVariables["Innovation"].store( numpy.ravel(d) )
262 if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
263 self.StoredVariables["BMA"].store( numpy.ravel(Xb) - numpy.ravel(Xa) )
264 if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
265 self.StoredVariables["OMA"].store( numpy.ravel(Y) - numpy.ravel(HXa) )
266 if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
267 self.StoredVariables["OMB"].store( numpy.ravel(d) )
268 if "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
269 self.StoredVariables["SimulatedObservationAtBackground"].store( numpy.ravel(HXb) )
270 if "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
271 self.StoredVariables["SimulatedObservationAtOptimum"].store( numpy.ravel(HXa) )
276 # ==============================================================================
277 if __name__ == "__main__":
278 print('\n AUTODIAGNOSTIC \n')