Salome HOME
Coherence correction for documentation of algorithms
[modules/adao.git] / src / daComposant / daAlgorithms / TabuSearch.py
1 #-*-coding:iso-8859-1-*-
2 #
3 # Copyright (C) 2008-2016 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
25 import numpy
26
27 # ==============================================================================
28 class ElementaryAlgorithm(BasicObjects.Algorithm):
29     def __init__(self):
30         BasicObjects.Algorithm.__init__(self, "TABUSEARCH")
31         self.defineRequiredParameter(
32             name     = "MaximumNumberOfSteps",
33             default  = 50,
34             typecast = int,
35             message  = "Nombre maximal de pas d'optimisation",
36             minval   = 1,
37             )
38         self.defineRequiredParameter(
39             name     = "SetSeed",
40             typecast = numpy.random.seed,
41             message  = "Graine fixée pour le générateur aléatoire",
42             )
43         self.defineRequiredParameter(
44             name     = "LengthOfTabuList",
45             default  = 50,
46             typecast = int,
47             message  = "Longueur de la liste tabou",
48             minval   = 1,
49             )
50         self.defineRequiredParameter(
51             name     = "NumberOfElementaryPerturbations",
52             default  = 1,
53             typecast = int,
54             message  = "Nombre de perturbations élémentaires pour choisir une perturbation d'état",
55             minval   = 1,
56             )
57         self.defineRequiredParameter(
58             name     = "NoiseDistribution",
59             default  = "Uniform",
60             typecast = str,
61             message  = "Distribution pour générer les perturbations d'état",
62             listval  = ["Gaussian","Uniform"],
63             )
64         self.defineRequiredParameter(
65             name     = "QualityCriterion",
66             default  = "AugmentedWeightedLeastSquares",
67             typecast = str,
68             message  = "Critère de qualité utilisé",
69             listval  = ["AugmentedWeightedLeastSquares","AWLS","DA",
70                         "WeightedLeastSquares","WLS",
71                         "LeastSquares","LS","L2",
72                         "AbsoluteValue","L1",
73                         "MaximumError","ME"],
74             )
75         self.defineRequiredParameter(
76             name     = "NoiseHalfRange",
77             default  = [],
78             typecast = numpy.matrix,
79             message  = "Demi-amplitude des perturbations uniformes centrées d'état pour chaque composante de l'état",
80             )
81         self.defineRequiredParameter(
82             name     = "StandardDeviation",
83             default  = [],
84             typecast = numpy.matrix,
85             message  = "Ecart-type des perturbations gaussiennes d'état pour chaque composante de l'état",
86             )
87         self.defineRequiredParameter(
88             name     = "NoiseAddingProbability",
89             default  = 1.,
90             typecast = float,
91             message  = "Probabilité de perturbation d'une composante de l'état",
92             minval   = 0.,
93             maxval   = 1.,
94             )
95         self.defineRequiredParameter(
96             name     = "StoreInternalVariables",
97             default  = False,
98             typecast = bool,
99             message  = "Stockage des variables internes ou intermédiaires du calcul",
100             )
101         self.defineRequiredParameter(
102             name     = "StoreSupplementaryCalculations",
103             default  = [],
104             typecast = tuple,
105             message  = "Liste de calculs supplémentaires à stocker et/ou effectuer",
106             listval  = ["BMA", "OMA", "OMB", "CurrentState", "CostFunctionJ", "CostFunctionJb", "CostFunctionJo", "Innovation", "SimulatedObservationAtBackground", "SimulatedObservationAtCurrentState", "SimulatedObservationAtOptimum"]
107             )
108         self.defineRequiredParameter( # Pas de type
109             name     = "Bounds",
110             message  = "Liste des valeurs de bornes",
111             )
112
113     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
114         self._pre_run()
115         #
116         # Paramètres de pilotage
117         # ----------------------
118         self.setParameters(Parameters)
119         #
120         if self._parameters.has_key("Bounds") and (type(self._parameters["Bounds"]) is type([]) or type(self._parameters["Bounds"]) is type(())) and (len(self._parameters["Bounds"]) > 0):
121             Bounds = self._parameters["Bounds"]
122             logging.debug("%s Prise en compte des bornes effectuee"%(self._name,))
123         else:
124             Bounds = None
125         #
126         if self._parameters["NoiseDistribution"] == "Uniform":
127             nrange = numpy.ravel(self._parameters["NoiseHalfRange"]) # Vecteur
128             if nrange.size != Xb.size:
129                 raise ValueError("Noise generation by Uniform distribution requires range for all variable increments. The actual noise half range vector is:\n%s"%nrange)
130         elif self._parameters["NoiseDistribution"] == "Gaussian":
131             sigma = numpy.ravel(self._parameters["StandardDeviation"]) # Vecteur
132             if sigma.size != Xb.size:
133                 raise ValueError("Noise generation by Gaussian distribution requires standard deviation for all variable increments. The actual standard deviation vector is:\n%s"%sigma)
134         #
135         # Opérateur d'observation
136         # -----------------------
137         Hm = HO["Direct"].appliedTo
138         #
139         # Précalcul des inversions de B et R
140         # ----------------------------------
141         BI = B.getI()
142         RI = R.getI()
143         #
144         # Définition de la fonction de deplacement
145         # ----------------------------------------
146         def Tweak( x, NoiseDistribution, NoiseAddingProbability ):
147             _X  = numpy.asmatrix(numpy.ravel( x )).T
148             if NoiseDistribution == "Uniform":
149                 for i in xrange(_X.size):
150                     if NoiseAddingProbability >= numpy.random.uniform():
151                         _increment = numpy.random.uniform(low=-nrange[i], high=nrange[i])
152                         # On ne traite pas encore le dépassement des bornes ici
153                         _X[i] += _increment
154             elif NoiseDistribution == "Gaussian":
155                 for i in xrange(_X.size):
156                     if NoiseAddingProbability >= numpy.random.uniform():
157                         _increment = numpy.random.normal(loc=0., scale=sigma[i])
158                         # On ne traite pas encore le dépassement des bornes ici
159                         _X[i] += _increment
160             #
161             return _X
162         #
163         def StateInList( x, TL ):
164             _X  = numpy.ravel( x )
165             _xInList = False
166             for state in TL:
167                 if numpy.all(numpy.abs( _X - numpy.ravel(state) ) <= 1e-16*numpy.abs(_X)):
168                     _xInList = True
169             if _xInList: sys.exit()
170             return _xInList
171         #
172         # Minimisation de la fonctionnelle
173         # --------------------------------
174         _n = 0
175         _S = Xb
176         # _qualityS = CostFunction( _S, self._parameters["QualityCriterion"] )
177         _qualityS = BasicObjects.CostFunction3D(
178                    _S,
179             _Hm  = Hm,
180             _BI  = BI,
181             _RI  = RI,
182             _Xb  = Xb,
183             _Y   = Y,
184             _SSC = self._parameters["StoreSupplementaryCalculations"],
185             _QM  = self._parameters["QualityCriterion"],
186             _SSV = self.StoredVariables,
187             _sSc = False,
188             )
189         _Best, _qualityBest   =   _S, _qualityS
190         _TabuList = []
191         _TabuList.append( _S )
192         while _n < self._parameters["MaximumNumberOfSteps"]:
193             _n += 1
194             if len(_TabuList) > self._parameters["LengthOfTabuList"]:
195                 _TabuList.pop(0)
196             _R = Tweak( _S, self._parameters["NoiseDistribution"], self._parameters["NoiseAddingProbability"] )
197             # _qualityR = CostFunction( _R, self._parameters["QualityCriterion"] )
198             _qualityR = BasicObjects.CostFunction3D(
199                        _R,
200                 _Hm  = Hm,
201                 _BI  = BI,
202                 _RI  = RI,
203                 _Xb  = Xb,
204                 _Y   = Y,
205                 _SSC = self._parameters["StoreSupplementaryCalculations"],
206                 _QM  = self._parameters["QualityCriterion"],
207                 _SSV = self.StoredVariables,
208                 _sSc = False,
209                 )
210             for nbt in range(self._parameters["NumberOfElementaryPerturbations"]-1):
211                 _W = Tweak( _S, self._parameters["NoiseDistribution"], self._parameters["NoiseAddingProbability"] )
212                 # _qualityW = CostFunction( _W, self._parameters["QualityCriterion"] )
213                 _qualityW = BasicObjects.CostFunction3D(
214                            _W,
215                     _Hm  = Hm,
216                     _BI  = BI,
217                     _RI  = RI,
218                     _Xb  = Xb,
219                     _Y   = Y,
220                     _SSC = self._parameters["StoreSupplementaryCalculations"],
221                     _QM  = self._parameters["QualityCriterion"],
222                     _SSV = self.StoredVariables,
223                     _sSc = False,
224                     )
225                 if (not StateInList(_W, _TabuList)) and ( (_qualityW < _qualityR) or StateInList(_R,_TabuList) ):
226                     _R, _qualityR   =   _W, _qualityW
227             if (not StateInList( _R, _TabuList )) and (_qualityR < _qualityS):
228                 _S, _qualityS   =   _R, _qualityR
229                 _TabuList.append( _S )
230             if _qualityS < _qualityBest:
231                 _Best, _qualityBest   =   _S, _qualityS
232             #
233             if self._parameters["StoreInternalVariables"] or "CurrentState" in self._parameters["StoreSupplementaryCalculations"]:
234                 self.StoredVariables["CurrentState"].store( _Best )
235             if "SimulatedObservationAtCurrentState" in self._parameters["StoreSupplementaryCalculations"]:
236                 _HmX = Hm( numpy.asmatrix(numpy.ravel( _Best )).T )
237                 _HmX = numpy.asmatrix(numpy.ravel( _HmX )).T
238                 self.StoredVariables["SimulatedObservationAtCurrentState"].store( _HmX )
239             self.StoredVariables["CostFunctionJb"].store( 0. )
240             self.StoredVariables["CostFunctionJo"].store( 0. )
241             self.StoredVariables["CostFunctionJ" ].store( _qualityBest )
242         #
243         # Obtention de l'analyse
244         # ----------------------
245         Xa = numpy.asmatrix(numpy.ravel( _Best )).T
246         #
247         self.StoredVariables["Analysis"].store( Xa.A1 )
248         #
249         if "Innovation"                       in self._parameters["StoreSupplementaryCalculations"] or \
250            "OMB"                              in self._parameters["StoreSupplementaryCalculations"] or \
251            "SimulatedObservationAtBackground" in self._parameters["StoreSupplementaryCalculations"]:
252             HXb = Hm(Xb)
253             d = Y - HXb
254         if "OMA"                           in self._parameters["StoreSupplementaryCalculations"] or \
255            "SimulatedObservationAtOptimum" in self._parameters["StoreSupplementaryCalculations"]:
256             HXa = Hm(Xa)
257         #
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) )
272         #
273         self._post_run(HO)
274         return 0
275
276 # ==============================================================================
277 if __name__ == "__main__":
278     print '\n AUTODIAGNOSTIC \n'