1 #@ AJOUT OpenturnsSolver Macro
2 # -*- coding: iso-8859-1 -*-
6 Ce module contient le generateur Etude pour Openturns
15 #=============================================
16 # La classe de creation du fichier STD
17 #=============================================
22 Generation du fichier pyhton
24 def __init__ (self, DictMCVal, ListeVariables, DictLois ) :
25 #---------------------------------------------------------#
27 self.NomAlgo = "myAlgo"
28 self.DictMCVal = DictMCVal
29 self.ListeVariables = ListeVariables
30 self.DictLois = DictLois
32 self.ListeOrdreMCReliability = (
33 "MaximumIterationsNumber",
34 "MaximumAbsoluteError",
35 "RelativeAbsoluteError",
36 "MaximumConstraintError",
37 "MaximumResidualError",
39 self.ListeOrdreMCDirectionalSampling = (
43 self.ListeOrdreMCParametresAlgo = (
45 "MaximumCoefficientOfVariation",
47 self.ListeOrdreImportanceSampling = (
48 "ImportanceSampling_BlockSize",
49 "ImportanceSampling_MaximumCoefficientOfVariation",
50 "ImportanceSampling_MaximumOuterSampling",
53 # Ce dictionnaire contient la liste de tous les parametres possibles pour chaque loi
54 # Les parametres qui n'apparaissent pas ne pourront pas etre substitues dans le fichier
55 # produit (etude python), et donc n'apparaitront pas.
56 self.listeParamLoi = {
57 "Beta" : ["Mu", "Sigma", "T", "R", "A", "B" ],
58 "Exponential" : ["Lambda", "Gamma" ],
59 "Gamma" : ["K", "Mu", "Sigma", "Lambda", "Gamma" ],
60 #"Geometric" : ["P", ],
61 "Gumbel" : ["Alpha","Beta","Mu","Sigma" ],
62 #"Histogram" : ["Sup", "Values" ],
63 "LogNormal" : ["MuLog", "SigmaLog", "Mu", "Sigma", "SigmaOverMu", "Gamma", ],
64 "Logistic" : [ "Alpha", "Beta" ],
65 #"MultiNomial" : [ "N", "Values" ],
66 "Normal" : ["Mu", "Sigma" ],
67 "Poisson" : [ "Lambda", ],
68 "Student" : [ "Mu", "Nu" ],
69 "Triangular" : [ "A", "M", "B" ],
70 "TruncatedNormal" : [ "MuN", "SigmaN", "A", "B" ],
71 "Uniform" : [ "A", "B" ],
72 #"UserDefined" : [ "Values", ],
73 "Weibull" : [ "Alpha", "Beta", "Mu", "Sigma", "Gamma" ],
76 # Ce dictionnaire contient, pour chaque loi qui possede plusieurs parametrages possibles,
77 # la correspondance entre le parametrage et son "numero" pour Open TURNS.
78 self.listeParamLoiSettings = {
79 "Beta" : { "RT" : "0", "MuSigma" : "1" }, \
80 "Gamma" : { "KLambda" : "0", "MuSigma" : "1" }, \
81 "Gumbel" : { "AlphaBeta" : "0", "MuSigma" : "1" }, \
82 "LogNormal" : { "MuSigmaLog" : "0", "MuSigma" : "1", "MuSigmaOverMu" : "2" }, \
83 "Weibull" : { "AlphaBeta" : "0", "MuSigma" : "1" }, \
91 Pilotage de la creation du fichier python
93 self.texte = self.CreeEntete()
94 self.texte += self.CreeRandomGenerator()
95 self.texte += self.CreeFunction()
96 self.texte += self.CreeLois()
97 self.texte += self.CreeCopula()
98 self.texte += self.CreeDistribution()
99 self.texte += self.CreeRandomVector()
100 self.texte += self.CreeAnalyse()
101 self.texte += self.CreeResu()
102 self.texte += self.CreeTexteFin()
105 # ______________________________________
107 # Methodes liees a la creation de la partie Analayse
108 # Si le mot clef Analyse existe la methode portant le meme nom va etre appele
109 # Exple : si self.DictMCVal["Analysis"]=="Reliability" on appelle la methode Reliability(self)
111 def CreeAnalyse (self) :
112 #----------------------
113 # Appelee par CreeSTD
115 if self.DictMCVal.has_key("Analysis"):
116 texte += apply( STDGenerateur.__dict__[self.DictMCVal["Analysis"]], (self,) )
119 def Reliability (self) :
120 #------------------------
121 # Appelee eventuellement par CreeAnalyse
122 texte = self.CreeEvent()
123 texte += "\n# La methode\n\n"
124 if not self.DictMCVal.has_key("Method"):
125 print 'Attention Mot Clef "Method" non renseigne'
128 texte += " myMethod = "+ self.DictMCVal["Method"] + "()\n"
129 texte += " myMethod.setSpecificParameters( " + self.DictMCVal["Method"] + "SpecificParameters() )\n"
131 for MC in self.ListeOrdreMCReliability :
132 if self.DictMCVal.has_key(MC) and self.DictMCVal[MC] != None :
133 texte += " myMethod.set"+ MC +"( " + str(self.DictMCVal[MC]) + " )\n\n "
135 texte += "\n# L'algorithme\n\n"
136 if not self.DictMCVal.has_key("Algorithm"):
137 print 'Attention Mot Clef "Algorithm" non renseigne'
139 texte += " " + self.NomAlgo + " = " + str (self.DictMCVal["Algorithm"])
140 texte += "( NearestPointAlgorithm(myMethod), myEvent, myPhysicalStartingPoint )\n"
141 texte += " " + self.NomAlgo + ".run()\n "
143 if self.DictMCVal.has_key("ImportanceSampling") and self.DictMCVal["ImportanceSampling"]=="yes" :
144 texte += self.ImportanceSampling()
147 def Simulation (self) :
148 #------------------------
149 # Appelee eventuellement par CreeAnalyse
150 texte = self.CreeEvent()
151 texte += "\n# L'algorithme\n\n"
152 if not self.DictMCVal.has_key("Algorithm"):
153 print 'Attention Mot Clef "Algorithm" non renseigne'
155 texte += " " + self.NomAlgo + " = " + str (self.DictMCVal["Algorithm"])
156 texte += "( myEvent )\n"
157 if self.DictMCVal["Algorithm"] == "DirectionalSampling" :
158 texte += self.DirectionalSampling()
159 texte += self.ParametresAlgo()
160 texte += " " + self.NomAlgo + ".run() "
164 def DirectionalSampling (self) :
165 #-------------------------------
166 # Appelee eventuellement par Simulation
168 for MC in self.ListeOrdreMCDirectionalSampling :
169 if self.DictMCVal.has_key(MC) and self.DictMCVal[MC] != None :
170 texte += apply(STDGenerateur.__dict__[self.DictMCVal[MC]], (self,))
173 def RootStrategy(self):
174 #----------------------
175 # Appelee eventuellement par DirectionalSampling
176 texte = " myRoot = " + self.DictMCVal["RootStrategy"] + "()\n"
177 if self.DictMCVal.has_key("Solver") and (self.DictMCVal["Solver"] != None) :
178 texte += " mySolver = " + self.DictMCVal["Solver"] + "() \n"
179 texte += " myRoot.setSolver( Solver( mySolver ) ) \n"
180 texte += " " + self.NomAlgo + ".setRootStrategy( RootStrategy( myRoot )) \n"
183 def SamplingStrategy(self):
184 #--------------------------
185 # Appelee eventuellement par DirectionalSampling
186 texte += " mySampling = " + self.DictMCVal["SamplingStrategy"] + "()\n"
187 texte += " mySampling.setSamplingStrategy( SamplingStrategy( mySampling ) )\n"
191 def QuadraticCumul (self) :
192 #--------------------------
193 # Appelee eventuellement par CreeAnalyse
194 texte = "\n# Cumul quadratique\n\n"
195 texte += " myQuadraticCumul = QuadraticCumul( myRandomVector_out)\n\n"
196 texte += " firstOrderMean = myQuadraticCumul.getMeanFirstOrder()\n"
197 texte += " secondOrderMean = myQuadraticCumul.getMeanSecondOrder()\n"
198 texte += " covariance = myQuadraticCumul.getCovariance()\n"
199 texte += " importanceFactors = myQuadraticCumul.getImportanceFactors()\n"
202 def CreeEvent (self) :
204 # Appelee eventuellement par Simulation et Reliability
205 texte = "\n# L'evenement\n\n"
206 if not self.DictMCVal.has_key("Threshold") or not self.DictMCVal.has_key("ComparisonOperator"):
207 print 'Attention Mot Clef "Threshold" ou "ComparisonOperator" non renseigne'
209 texte += " seuil = " +str (self.DictMCVal["Threshold"]) + "\n"
210 texte += " myEvent = Event(myRandomVector_out,"
211 texte += "ComparisonOperator(" + str (self.DictMCVal["ComparisonOperator"]) + "()), seuil) \n"
214 def ParametresAlgo( self ):
215 #---------------------------
216 # Appelee par Simulation
218 texte += " nbMaxOutSampling = "
220 if self.DictMCVal["MaximumOuterSamplingType"] == "UserDefined" :
221 texte += str(self.DictMCVal["MaximumOuterSampling"])
223 elif self.DictMCVal["MaximumOuterSamplingType"] == "Wilks" :
224 texte += "Wilks.ComputeSampleSize( " + str(self.DictMCVal["Wilks_Alpha"]) + ", " \
225 + str(self.DictMCVal["Wilks_Beta"]) + ", " + str(self.DictMCVal["Wilks_I"]) + " )"
226 texte += '\n print "MaximumOuterSampling = ", nbMaxOutSampling, "\n" \n'
228 texte += " " + NomAlgo + ".setMaximumOuterSampling(nbMaxOutSampling)"
229 for MC in self.ListeOrdreMCParametresAlgo :
230 if self.DictMCVal.has_key(MC) and self.DictMCVal[MC] != None :
231 texte += " myMethod.set"+ MC +"(" + str(self.DictMCVal[MC]) + ")\n\n "
233 # _____________________________________
235 def CreeRandomGenerator (self) :
236 #-------------------------------
237 # Appelee par CreeSTD
239 if self.DictMCVal.has_key("RandomGeneratorSeed") :
240 texte += "# We set the RandomGenerator seed in order to replay the study\n"
241 texte += " RandomGenerator().SetSeed(%d)\n" % self.DictMCVal["RandomGeneratorSeed"]
244 def CreeFunction (self) :
245 #-------------------------
246 # Appelee par CreeSTD
249 Remarque : le nom 'solver' est en dur ici. Il doit imperativement correspondre
250 au nom du fichier xml : 'solver.xml'
252 texte = "\n# La fonction\n\n"
253 texte += ' myFunction = NumericalMathFunction(\"XXXXXX\")\n'
254 texte += ' dim = myFunction.getInputNumericalPointDimension()\n'
258 def CreeCopula (self) :
260 # Appelee par CreeSTD
261 texte = "\n# La copule\n\n"
262 texte += " myCopula = IndependentCopula(dim)\n"
266 def CreeDistribution (self) :
267 #----------------------------
268 # Appelee par CreeSTD
269 texte = "\n# La distribution\n\n"
270 texte += " myDistribution = ComposedDistribution(myCollection, Copula(myCopula))\n"
274 def CreeRandomVector (self) :
275 #----------------------------
276 # Appelee par CreeSTD
277 texte = "\n# Le Random Vector\n\n"
278 texte += " myRandomVector_in = RandomVector(Distribution(myDistribution))\n"
279 texte += " myRandomVector_out = RandomVector(myFunction, myRandomVector_in)\n"
283 # _______________________________
287 def ImportanceSampling (self) :
288 #-----------------------------
289 # Appele eventuellement par Reliability
291 texte = " temporaryResult = " + self.NomAlgo + ".getResult()\n\n"
292 texte += " mean = temporaryResult.getPhysicalSpaceDesignPoint()\n"
293 texte += " sigma = NumericalPoint( mean.getDimension(), 1.0 )\n"
294 texte += " R = CorrelationMatrix( mean.getDimension() )\n"
295 texte += " myImportance = Normal( mean, sigma, R )\n\n\n"
297 texte += " importanceSamplingAlgo = ImportanceSampling( myEvent, Distribution( myImportance ) )\n\n"
299 for MC in self.ListeOrdreImportanceSampling :
300 if self.DictMCVal.has_key("MC") :
301 debut=" importanceSamplingAlgo.set"+MC.split("_")[-1]
302 texte += debut + "( " + str(self.DictMCVal[MC]) + " )\n"
304 texte += "\n importanceSamplingAlgo.run()\n\n"
305 self.NomAlgo = "importanceSamplingAlgo"
309 def CreeResu (self) :
313 texte = "\n# Le resultat\n\n"
314 texte += " myResu = " + self.NomAlgo + ".getResult() \n"
315 texte += " probability = myResu.getEventProbability()"
321 def CreeLois (self) :
326 texte = "\n# Les lois\n\n"
327 if self.DictMCVal.has_key("Analysis") and self.DictMCVal["Analysis"] == "Reliability" :
328 texte += " myPhysicalStartingPoint = NumericalPoint(dim, 0.0)\n"
329 texte += " myCollection = DistributionCollection(dim)\n\n"
332 for DictVariable in self.ListeVariables :
335 if DictVariable.has_key("MarginalDistribution") and DictVariable.has_key("Name"):
336 ConceptLoi = DictVariable["MarginalDistribution"]
337 NomLoi = DictVariable["Name"]+"_Dist"
341 if boolLoiDef and self.DictLois.has_key(ConceptLoi):
342 loi = self.DictLois[ConceptLoi]
346 if boolLoiDef and loi.has_key("Kind") :
347 TypeLoi = loi["Kind"]
351 if not boolLoiDef or TypeLoi not in self.listeParamLoi.keys() :
352 texte += " Loi " + TypeLoi +" non programmee \n"
358 for Param in self.listeParamLoi[TypeLoi]:
359 if loi.has_key(Param) :
360 texte += " " + NomLoi + "_" + Param + " = " + str(loi[Param]) + "\n"
361 ListeParametres.append(NomLoi + "_" + Param)
362 TexteParametres += NomLoi + "_" + Param + ","
364 texte += " " + NomLoi + " = " + TypeLoi + "( "
366 if loi.has_key("Settings" ) and self.listeParamLoiSettings.has_key(TypeLoi) \
367 and self.listeParamLoiSettings[TypeLoi].has_key(loi["Settings"]):
368 NumParam = self.listeParamLoiSettings[TypeLoi][loi["Settings"]]
369 texte += TexteParametres + NumParam +" )\n"
371 texte += TexteParametres[:-1] + " )\n"
373 texte += " " + NomLoi + '.setName( "'+DictVariable["Name"] +'" )\n'
374 texte += " myCollection["+str(numVar)+"] = Distribution( "+NomLoi+" )\n"
376 if self.DictMCVal["Analysis"] == "Reliability" :
377 texte += " myPhysicalStartingPoint["+str(numVar)+"] = "
378 if DictVariable.has_key("PhysicalStartingPoint") :
379 texte += str(DictVariable["PhysicalStartingPoint"]) +"\n\n"
381 texte += NomLoi+".computeQuantile( 0.5 )[0]\n\n"
387 # _____________________________________________________
389 def CreeEntete (self) :
395 texte = "#!/usr/bin/env python\n"
396 texte += "# -*- coding: iso-8859-1 -*-\n"
397 texte += "import sys\n"
398 texte += "import os\n"
399 if self.DictLois.has_key("dir_openturns_python") :
400 texte += "sys.path.append(\"" + self.DictLois["dir_openturns_python"] + "\")\n"
401 if self.DictLois.has_key("DTDDirectory") :
402 texte += "os.environ[\"OPENTURNS_WRAPPER_PATH\"] = \".:" + self.DictLois["DTDDirectory"] + "\"\n"
403 texte += "from openturns import *\n"
404 texte += "error_message = None\n"
408 def CreeTexteFin(self) :
409 #------------------------------------
410 texte ='\n\nexcept : \n'
411 texte += ' error_message = sys.exc_type\n'
412 texte += ' if error_message is not None :\n'
413 texte += ' texte = "================================================= \\n"\n'
414 texte += ' texte += " Message d\'erreur : \" + str(error_message) + "\\n"\n'
415 texte += ' texte += "=================================================\\n"\n'
416 texte += ' print texte"\n'
417 texte += "sys.exit(error_message)\n"