]> SALOME platform Git repositories - modules/adao.git/blob - src/daComposant/daAlgorithms/ParticleSwarmOptimization.py
Salome HOME
Improving performance when using diagonal sparse matrices
[modules/adao.git] / src / daComposant / daAlgorithms / ParticleSwarmOptimization.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2013 EDF R&D
4 #
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.
9 #
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.
14 #
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
18 #
19 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #
21 #  Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
22
23 import logging
24 from daCore import BasicObjects, PlatformInfo
25 m = PlatformInfo.SystemUsage()
26
27 import numpy
28 import copy
29
30 # ==============================================================================
31 class ElementaryAlgorithm(BasicObjects.Algorithm):
32     def __init__(self):
33         BasicObjects.Algorithm.__init__(self, "PARTICLESWARMOPTIMIZATION")
34         self.defineRequiredParameter(
35             name     = "MaximumNumberOfSteps",
36             default  = 50,
37             typecast = int,
38             message  = "Nombre maximal de pas d'optimisation",
39             minval   = 1,
40             )
41         self.defineRequiredParameter(
42             name     = "SetSeed",
43             typecast = numpy.random.seed,
44             message  = "Graine fixée pour le générateur aléatoire",
45             )
46         self.defineRequiredParameter(
47             name     = "NumberOfInsects",
48             default  = 100,
49             typecast = int,
50             message  = "Nombre d'insectes dans l'essaim",
51             minval   = -1,
52             )
53         self.defineRequiredParameter(
54             name     = "SwarmVelocity",
55             default  = 1.,
56             typecast = float,
57             message  = "Vitesse de groupe imposée par l'essaim",
58             minval   = 0.,
59             )
60         self.defineRequiredParameter(
61             name     = "GroupRecallRate",
62             default  = 0.5,
63             typecast = float,
64             message  = "Taux de rappel au meilleur insecte du groupe (entre 0 et 1)",
65             minval   = 0.,
66             maxval   = 1.,
67             )
68         self.defineRequiredParameter(
69             name     = "QualityCriterion",
70             default  = "AugmentedPonderatedLeastSquares",
71             typecast = str,
72             message  = "Critère de qualité utilisé",
73             listval  = ["AugmentedPonderatedLeastSquares","APLS","DA",
74                         "PonderatedLeastSquares","PLS",
75                         "LeastSquares","LS","L2",
76                         "AbsoluteValue","L1",
77                         "MaximumError","ME"],
78             )
79         self.defineRequiredParameter(
80             name     = "StoreInternalVariables",
81             default  = False,
82             typecast = bool,
83             message  = "Stockage des variables internes ou intermédiaires du calcul",
84             )
85         self.defineRequiredParameter(
86             name     = "StoreSupplementaryCalculations",
87             default  = [],
88             typecast = tuple,
89             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
90             listval  = ["BMA", "OMA", "OMB", "Innovation"]
91             )
92
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")))
96         #
97         # Paramètres de pilotage
98         # ----------------------
99         self.setParameters(Parameters)
100         #
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,))
104         else:
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)
109         #
110         Phig = float( self._parameters["GroupRecallRate"] )
111         Phip = 1. - Phig
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)))
113         #
114         # Opérateur d'observation
115         # -----------------------
116         Hm = HO["Direct"].appliedTo
117         #
118         # Précalcul des inversions de B et R
119         # ----------------------------------
120         BI = B.getI()
121         RI = R.getI()
122         #
123         # Définition de la fonction-coût
124         # ------------------------------
125         def CostFunction(x, QualityMeasure="AugmentedPonderatedLeastSquares"):
126             _X  = numpy.asmatrix(numpy.ravel( x )).T
127             _HX = Hm( _X )
128             _HX = numpy.asmatrix(numpy.ravel( _HX )).T
129             #
130             if QualityMeasure in ["AugmentedPonderatedLeastSquares","APLS","DA"]:
131                 if BI is None or RI is None:
132                     raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
133                 Jb  = 0.5 * (_X - Xb).T * BI * (_X - Xb)
134                 Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
135                 J   = float( Jb ) + float( Jo )
136             elif QualityMeasure in ["PonderatedLeastSquares","PLS"]:
137                 if RI is None:
138                     raise ValueError("Observation error covariance matrix has to be properly defined!")
139                 Jb  = 0.
140                 Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
141                 J   = float( Jb ) + float( Jo )
142             elif QualityMeasure in ["LeastSquares","LS","L2"]:
143                 Jb  = 0.
144                 Jo  = 0.5 * (Y - _HX).T * (Y - _HX)
145                 J   = float( Jb ) + float( Jo )
146             elif QualityMeasure in ["AbsoluteValue","L1"]:
147                 Jb  = 0.
148                 Jo  = numpy.sum( numpy.abs(Y - _HX) )
149                 J   = float( Jb ) + float( Jo )
150             elif QualityMeasure in ["MaximumError","ME"]:
151                 Jb  = 0.
152                 Jo  = numpy.max( numpy.abs(Y - _HX) )
153                 J   = float( Jb ) + float( Jo )
154             #
155             return J
156         #
157         # Point de démarrage de l'optimisation : Xini = Xb
158         # ------------------------------------
159         if type(Xb) is type(numpy.matrix([])):
160             Xini = Xb.A1.tolist()
161         elif Xb is not None:
162             Xini = list(Xb)
163         else:
164             Xini = numpy.zeros(len(BoxBounds[:,0]))
165         #
166         # Initialisation des bornes
167         # -------------------------
168         SpaceUp  = BoxBounds[:,1] + Xini
169         Spacelow = BoxBounds[:,0] + Xini
170         nbparam  = len(SpaceUp)
171         #
172         # Initialisation de l'essaim
173         # --------------------------
174         LimitVelocity = numpy.abs(SpaceUp-Spacelow)
175         #
176         PosInsect = []
177         VelocityInsect = []
178         for i in range(nbparam) :
179             PosInsect.append(numpy.random.uniform(low=Spacelow[i], high=SpaceUp[i], size=self._parameters["NumberOfInsects"]))
180             VelocityInsect.append(numpy.random.uniform(low=-LimitVelocity[i], high=LimitVelocity[i], size=self._parameters["NumberOfInsects"]))
181         VelocityInsect = numpy.matrix(VelocityInsect)
182         PosInsect = numpy.matrix(PosInsect)
183         #
184         BestPosInsect = numpy.array(PosInsect)
185         qBestPosInsect = []
186         Best = copy.copy(Spacelow)
187         qBest = CostFunction(Best,self._parameters["QualityCriterion"])
188         #
189         for i in range(self._parameters["NumberOfInsects"]):
190             insect  = numpy.array(PosInsect[:,i].A1)
191             quality = CostFunction(insect,self._parameters["QualityCriterion"])
192             qBestPosInsect.append(quality)
193             if quality < qBest:
194                 Best  = insect
195                 qBest = quality
196         #
197         # Minimisation de la fonctionnelle
198         # --------------------------------
199         for n in range(self._parameters["MaximumNumberOfSteps"]):
200             for i in range(self._parameters["NumberOfInsects"]) :
201                 insect  = PosInsect[:,i]
202                 rp = numpy.random.uniform(size=nbparam)
203                 rg = numpy.random.uniform(size=nbparam)
204                 for j in range(nbparam) :
205                     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])
206                     PosInsect[j,i] = PosInsect[j,i]+VelocityInsect[j,i]
207                 quality = CostFunction(insect,self._parameters["QualityCriterion"])
208                 if quality < qBestPosInsect[i]:
209                     BestPosInsect[:,i] = numpy.ravel( insect )
210                     if quality < qBest :
211                         Best  = numpy.ravel( insect )
212                         qBest = quality
213             #
214             if self._parameters["StoreInternalVariables"]:
215                 self.StoredVariables["CurrentState"].store( Best )
216             self.StoredVariables["CostFunctionJb"].store( 0. )
217             self.StoredVariables["CostFunctionJo"].store( 0. )
218             self.StoredVariables["CostFunctionJ" ].store( qBest )
219         #
220         # Obtention de l'analyse
221         # ----------------------
222         Xa = numpy.asmatrix(numpy.ravel( Best )).T
223         #
224         self.StoredVariables["Analysis"].store( Xa.A1 )
225         #
226         # Calculs et/ou stockages supplémentaires
227         # ---------------------------------------
228         if "Innovation" in self._parameters["StoreSupplementaryCalculations"] or "OMB" in self._parameters["StoreSupplementaryCalculations"]:
229             d = Y - Hm(Xb)
230         if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
231             self.StoredVariables["Innovation"].store( numpy.ravel(d) )
232         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
233             self.StoredVariables["BMA"].store( numpy.ravel(Xb - Xa) )
234         if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
235             self.StoredVariables["OMA"].store( numpy.ravel(Y - Hm(Xa)) )
236         if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
237             self.StoredVariables["OMB"].store( numpy.ravel(d) )
238         #
239         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
240         logging.debug("%s Terminé"%self._name)
241         #
242         return 0
243
244 # ==============================================================================
245 if __name__ == "__main__":
246     print '\n AUTODIAGNOSTIC \n'