1 #-*-coding:iso-8859-1-*-
3 # Copyright (C) 2008-2016 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, "TABUSEARCH")
31 self.defineRequiredParameter(
32 name = "MaximumNumberOfSteps",
35 message = "Nombre maximal de pas d'optimisation",
38 self.defineRequiredParameter(
40 typecast = numpy.random.seed,
41 message = "Graine fixée pour le générateur aléatoire",
43 self.defineRequiredParameter(
44 name = "LengthOfTabuList",
47 message = "Longueur de la liste tabou",
50 self.defineRequiredParameter(
51 name = "NumberOfElementaryPerturbations",
54 message = "Nombre de perturbations élémentaires pour choisir une perturbation d'état",
57 self.defineRequiredParameter(
58 name = "NoiseDistribution",
61 message = "Distribution pour générer les perturbations d'état",
62 listval = ["Gaussian","Uniform"],
64 self.defineRequiredParameter(
65 name = "QualityCriterion",
66 default = "AugmentedWeightedLeastSquares",
68 message = "Critère de qualité utilisé",
69 listval = ["AugmentedWeightedLeastSquares","AWLS","DA",
70 "WeightedLeastSquares","WLS",
71 "LeastSquares","LS","L2",
75 self.defineRequiredParameter(
76 name = "NoiseHalfRange",
78 typecast = numpy.matrix,
79 message = "Demi-amplitude des perturbations uniformes centrées d'état pour chaque composante de l'état",
81 self.defineRequiredParameter(
82 name = "StandardDeviation",
84 typecast = numpy.matrix,
85 message = "Ecart-type des perturbations gaussiennes d'état pour chaque composante de l'état",
87 self.defineRequiredParameter(
88 name = "NoiseAddingProbability",
91 message = "Probabilité de perturbation d'une composante de l'état",
95 self.defineRequiredParameter(
96 name = "StoreInternalVariables",
99 message = "Stockage des variables internes ou intermédiaires du calcul",
101 self.defineRequiredParameter(
102 name = "StoreSupplementaryCalculations",
105 message = "Liste de calculs supplémentaires à stocker et/ou effectuer",
106 listval = ["BMA", "OMA", "OMB", "CurrentState", "CostFunctionJ", "CostFunctionJb", "CostFunctionJo", "Innovation", "SimulatedObservationAtBackground", "SimulatedObservationAtCurrentState", "SimulatedObservationAtOptimum"]
108 self.defineRequiredParameter( # Pas de type
110 message = "Liste des valeurs de bornes",
113 def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
116 # Paramètres de pilotage
117 # ----------------------
118 self.setParameters(Parameters)
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,))
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)
135 # Opérateur d'observation
136 # -----------------------
137 Hm = HO["Direct"].appliedTo
139 # Précalcul des inversions de B et R
140 # ----------------------------------
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
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
163 def StateInList( x, TL ):
164 _X = numpy.ravel( x )
167 if numpy.all(numpy.abs( _X - numpy.ravel(state) ) <= 1e-16*numpy.abs(_X)):
169 if _xInList: sys.exit()
172 # Minimisation de la fonctionnelle
173 # --------------------------------
176 # _qualityS = CostFunction( _S, self._parameters["QualityCriterion"] )
177 _qualityS = BasicObjects.CostFunction3D(
184 _SSC = self._parameters["StoreSupplementaryCalculations"],
185 _QM = self._parameters["QualityCriterion"],
186 _SSV = self.StoredVariables,
189 _Best, _qualityBest = _S, _qualityS
191 _TabuList.append( _S )
192 while _n < self._parameters["MaximumNumberOfSteps"]:
194 if len(_TabuList) > self._parameters["LengthOfTabuList"]:
196 _R = Tweak( _S, self._parameters["NoiseDistribution"], self._parameters["NoiseAddingProbability"] )
197 # _qualityR = CostFunction( _R, self._parameters["QualityCriterion"] )
198 _qualityR = BasicObjects.CostFunction3D(
205 _SSC = self._parameters["StoreSupplementaryCalculations"],
206 _QM = self._parameters["QualityCriterion"],
207 _SSV = self.StoredVariables,
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(
220 _SSC = self._parameters["StoreSupplementaryCalculations"],
221 _QM = self._parameters["QualityCriterion"],
222 _SSV = self.StoredVariables,
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
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 )
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'