]> SALOME platform Git repositories - modules/adao.git/blob - src/daComposant/daAlgorithms/ParticleSwarmOptimization.py
Salome HOME
Improving calculation cache management
[modules/adao.git] / src / daComposant / daAlgorithms / ParticleSwarmOptimization.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2014 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 import numpy, copy
27
28 # ==============================================================================
29 class ElementaryAlgorithm(BasicObjects.Algorithm):
30     def __init__(self):
31         BasicObjects.Algorithm.__init__(self, "PARTICLESWARMOPTIMIZATION")
32         self.defineRequiredParameter(
33             name     = "MaximumNumberOfSteps",
34             default  = 50,
35             typecast = int,
36             message  = "Nombre maximal de pas d'optimisation",
37             minval   = 1,
38             )
39         self.defineRequiredParameter(
40             name     = "SetSeed",
41             typecast = numpy.random.seed,
42             message  = "Graine fixée pour le générateur aléatoire",
43             )
44         self.defineRequiredParameter(
45             name     = "NumberOfInsects",
46             default  = 100,
47             typecast = int,
48             message  = "Nombre d'insectes dans l'essaim",
49             minval   = -1,
50             )
51         self.defineRequiredParameter(
52             name     = "SwarmVelocity",
53             default  = 1.,
54             typecast = float,
55             message  = "Vitesse de groupe imposée par l'essaim",
56             minval   = 0.,
57             )
58         self.defineRequiredParameter(
59             name     = "GroupRecallRate",
60             default  = 0.5,
61             typecast = float,
62             message  = "Taux de rappel au meilleur insecte du groupe (entre 0 et 1)",
63             minval   = 0.,
64             maxval   = 1.,
65             )
66         self.defineRequiredParameter(
67             name     = "QualityCriterion",
68             default  = "AugmentedPonderatedLeastSquares",
69             typecast = str,
70             message  = "Critère de qualité utilisé",
71             listval  = ["AugmentedPonderatedLeastSquares","APLS","DA",
72                         "PonderatedLeastSquares","PLS",
73                         "LeastSquares","LS","L2",
74                         "AbsoluteValue","L1",
75                         "MaximumError","ME"],
76             )
77         self.defineRequiredParameter(
78             name     = "StoreInternalVariables",
79             default  = False,
80             typecast = bool,
81             message  = "Stockage des variables internes ou intermédiaires du calcul",
82             )
83         self.defineRequiredParameter(
84             name     = "StoreSupplementaryCalculations",
85             default  = [],
86             typecast = tuple,
87             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
88             listval  = ["BMA", "OMA", "OMB", "Innovation"]
89             )
90
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")))
94         #
95         # Paramètres de pilotage
96         # ----------------------
97         self.setParameters(Parameters)
98         #
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,))
102         else:
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)
107         #
108         Phig = float( self._parameters["GroupRecallRate"] )
109         Phip = 1. - Phig
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)))
111         #
112         # Opérateur d'observation
113         # -----------------------
114         Hm = HO["Direct"].appliedTo
115         #
116         # Précalcul des inversions de B et R
117         # ----------------------------------
118         BI = B.getI()
119         RI = R.getI()
120         #
121         # Définition de la fonction-coût
122         # ------------------------------
123         def CostFunction(x, QualityMeasure="AugmentedPonderatedLeastSquares"):
124             _X  = numpy.asmatrix(numpy.ravel( x )).T
125             _HX = Hm( _X )
126             _HX = numpy.asmatrix(numpy.ravel( _HX )).T
127             #
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"]:
135                 if RI is None:
136                     raise ValueError("Observation error covariance matrix has to be properly defined!")
137                 Jb  = 0.
138                 Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
139                 J   = float( Jb ) + float( Jo )
140             elif QualityMeasure in ["LeastSquares","LS","L2"]:
141                 Jb  = 0.
142                 Jo  = 0.5 * (Y - _HX).T * (Y - _HX)
143                 J   = float( Jb ) + float( Jo )
144             elif QualityMeasure in ["AbsoluteValue","L1"]:
145                 Jb  = 0.
146                 Jo  = numpy.sum( numpy.abs(Y - _HX) )
147                 J   = float( Jb ) + float( Jo )
148             elif QualityMeasure in ["MaximumError","ME"]:
149                 Jb  = 0.
150                 Jo  = numpy.max( numpy.abs(Y - _HX) )
151                 J   = float( Jb ) + float( Jo )
152             #
153             return J
154         #
155         # Point de démarrage de l'optimisation : Xini = Xb
156         # ------------------------------------
157         if type(Xb) is type(numpy.matrix([])):
158             Xini = Xb.A1.tolist()
159         elif Xb is not None:
160             Xini = list(Xb)
161         else:
162             Xini = numpy.zeros(len(BoxBounds[:,0]))
163         #
164         # Initialisation des bornes
165         # -------------------------
166         SpaceUp  = BoxBounds[:,1] + Xini
167         Spacelow = BoxBounds[:,0] + Xini
168         nbparam  = len(SpaceUp)
169         #
170         # Initialisation de l'essaim
171         # --------------------------
172         LimitVelocity = numpy.abs(SpaceUp-Spacelow)
173         #
174         PosInsect = []
175         VelocityInsect = []
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)
181         #
182         BestPosInsect = numpy.array(PosInsect)
183         qBestPosInsect = []
184         Best = copy.copy(Spacelow)
185         qBest = CostFunction(Best,self._parameters["QualityCriterion"])
186         #
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)
191             if quality < qBest:
192                 Best  = insect
193                 qBest = quality
194         #
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 )
208                     if quality < qBest :
209                         Best  = numpy.ravel( insect )
210                         qBest = quality
211             #
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 )
217         #
218         # Obtention de l'analyse
219         # ----------------------
220         Xa = numpy.asmatrix(numpy.ravel( Best )).T
221         #
222         self.StoredVariables["Analysis"].store( Xa.A1 )
223         #
224         # Calculs et/ou stockages supplémentaires
225         # ---------------------------------------
226         if "Innovation" in self._parameters["StoreSupplementaryCalculations"] or "OMB" in self._parameters["StoreSupplementaryCalculations"]:
227             d = Y - Hm(Xb)
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) )
236         #
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)
241         #
242         return 0
243
244 # ==============================================================================
245 if __name__ == "__main__":
246     print '\n AUTODIAGNOSTIC \n'