Salome HOME
Correcting A-shape verification
[modules/adao.git] / src / daComposant / daAlgorithms / ParticleSwarmOptimization.py
1 #-*-coding:iso-8859-1-*-
2 #
3 #  Copyright (C) 2008-2012 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, H=None, M=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 = H["Direct"].appliedTo
117         #
118         # Précalcul des inversions de B et R
119         # ----------------------------------
120         if B is not None:
121             BI = B.I
122         elif self._parameters["B_scalar"] is not None:
123             BI = 1.0 / self._parameters["B_scalar"]
124         else:
125             BI = None
126         #
127         if R is not None:
128             RI = R.I
129         elif self._parameters["R_scalar"] is not None:
130             RI = 1.0 / self._parameters["R_scalar"]
131         else:
132             RI = None
133         #
134         # Définition de la fonction-coût
135         # ------------------------------
136         def CostFunction(x, QualityMeasure="AugmentedPonderatedLeastSquares"):
137             _X  = numpy.asmatrix(numpy.ravel( x )).T
138             _HX = Hm( _X )
139             _HX = numpy.asmatrix(numpy.ravel( _HX )).T
140             #
141             if QualityMeasure in ["AugmentedPonderatedLeastSquares","APLS","DA"]:
142                 if BI is None or RI is None:
143                     raise ValueError("Background and Observation error covariance matrix has to be properly defined!")
144                 Jb  = 0.5 * (_X - Xb).T * BI * (_X - Xb)
145                 Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
146                 J   = float( Jb ) + float( Jo )
147             elif QualityMeasure in ["PonderatedLeastSquares","PLS"]:
148                 if RI is None:
149                     raise ValueError("Observation error covariance matrix has to be properly defined!")
150                 Jb  = 0.
151                 Jo  = 0.5 * (Y - _HX).T * RI * (Y - _HX)
152                 J   = float( Jb ) + float( Jo )
153             elif QualityMeasure in ["LeastSquares","LS","L2"]:
154                 Jb  = 0.
155                 Jo  = 0.5 * (Y - _HX).T * (Y - _HX)
156                 J   = float( Jb ) + float( Jo )
157             elif QualityMeasure in ["AbsoluteValue","L1"]:
158                 Jb  = 0.
159                 Jo  = numpy.sum( numpy.abs(Y - _HX) )
160                 J   = float( Jb ) + float( Jo )
161             elif QualityMeasure in ["MaximumError","ME"]:
162                 Jb  = 0.
163                 Jo  = numpy.max( numpy.abs(Y - _HX) )
164                 J   = float( Jb ) + float( Jo )
165             #
166             return J
167         #
168         # Point de démarrage de l'optimisation : Xini = Xb
169         # ------------------------------------
170         if type(Xb) is type(numpy.matrix([])):
171             Xini = Xb.A1.tolist()
172         elif Xb is not None:
173             Xini = list(Xb)
174         else:
175             Xini = numpy.zeros(len(BoxBounds[:,0]))
176         #
177         # Initialisation des bornes
178         # -------------------------
179         SpaceUp  = BoxBounds[:,1] + Xini
180         Spacelow = BoxBounds[:,0] + Xini
181         nbparam  = len(SpaceUp)
182         #
183         # Initialisation de l'essaim
184         # --------------------------
185         LimitVelocity = numpy.abs(SpaceUp-Spacelow)
186         #
187         PosInsect = []
188         VelocityInsect = []
189         for i in range(nbparam) :
190             PosInsect.append(numpy.random.uniform(low=Spacelow[i], high=SpaceUp[i], size=self._parameters["NumberOfInsects"]))
191             VelocityInsect.append(numpy.random.uniform(low=-LimitVelocity[i], high=LimitVelocity[i], size=self._parameters["NumberOfInsects"]))
192         VelocityInsect = numpy.matrix(VelocityInsect)
193         PosInsect = numpy.matrix(PosInsect)
194         #
195         BestPosInsect = numpy.array(PosInsect)
196         qBestPosInsect = []
197         Best = copy.copy(Spacelow)
198         qBest = CostFunction(Best,self._parameters["QualityCriterion"])
199         #
200         for i in range(self._parameters["NumberOfInsects"]):
201             insect  = numpy.array(PosInsect[:,i].A1)
202             quality = CostFunction(insect,self._parameters["QualityCriterion"])
203             qBestPosInsect.append(quality)
204             if quality < qBest:
205                 Best  = insect
206                 qBest = quality
207         #
208         # Minimisation de la fonctionnelle
209         # --------------------------------
210         for n in range(self._parameters["MaximumNumberOfSteps"]):
211             for i in range(self._parameters["NumberOfInsects"]) :
212                 insect  = PosInsect[:,i]
213                 rp = numpy.random.uniform(size=nbparam)
214                 rg = numpy.random.uniform(size=nbparam)
215                 for j in range(nbparam) :
216                     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])
217                     PosInsect[j,i] = PosInsect[j,i]+VelocityInsect[j,i]
218                 quality = CostFunction(insect,self._parameters["QualityCriterion"])
219                 if quality < qBestPosInsect[i]:
220                     BestPosInsect[:,i] = numpy.ravel( insect )
221                     if quality < qBest :
222                         Best  = numpy.ravel( insect )
223                         qBest = quality
224             #
225             if self._parameters["StoreInternalVariables"]:
226                 self.StoredVariables["CurrentState"].store( Best )
227             self.StoredVariables["CostFunctionJb"].store( 0. )
228             self.StoredVariables["CostFunctionJo"].store( 0. )
229             self.StoredVariables["CostFunctionJ" ].store( qBest )
230         #
231         # Obtention de l'analyse
232         # ----------------------
233         Xa = numpy.asmatrix(numpy.ravel( Best )).T
234         #
235         self.StoredVariables["Analysis"].store( Xa.A1 )
236         #
237         # Calculs et/ou stockages supplémentaires
238         # ---------------------------------------
239         if "Innovation" in self._parameters["StoreSupplementaryCalculations"] or "OMB" in self._parameters["StoreSupplementaryCalculations"]:
240             d = Y - Hm(Xb)
241         if "Innovation" in self._parameters["StoreSupplementaryCalculations"]:
242             self.StoredVariables["Innovation"].store( numpy.ravel(d) )
243         if "BMA" in self._parameters["StoreSupplementaryCalculations"]:
244             self.StoredVariables["BMA"].store( numpy.ravel(Xb - Xa) )
245         if "OMA" in self._parameters["StoreSupplementaryCalculations"]:
246             self.StoredVariables["OMA"].store( numpy.ravel(Y - Hm(Xa)) )
247         if "OMB" in self._parameters["StoreSupplementaryCalculations"]:
248             self.StoredVariables["OMB"].store( numpy.ravel(d) )
249         #
250         logging.debug("%s Taille mémoire utilisée de %.1f Mo"%(self._name, m.getUsedMemory("M")))
251         logging.debug("%s Terminé"%self._name)
252         #
253         return 0
254
255 # ==============================================================================
256 if __name__ == "__main__":
257     print '\n AUTODIAGNOSTIC \n'