]> SALOME platform Git repositories - tools/eficas.git/blob - generator/OpenturnsSTD.py
Salome HOME
CCAR: merge de la version 1.14 dans la branche principale
[tools/eficas.git] / generator / OpenturnsSTD.py
1 #@ AJOUT OpenturnsSolver Macro
2 # -*- coding: iso-8859-1 -*-
3 # RESPONSABLE
4
5 """
6 Ce module contient le generateur Etude pour Openturns
7 """
8
9 __revision__ = "V1.0"
10
11 import os
12
13
14
15 #=============================================
16 #  La classe de creation du fichier STD
17 #=============================================
18
19 class STDGenerateur :
20
21   '''
22   Generation du fichier pyhton
23   '''
24   def __init__ (self, DictMCVal, ListeVariables, DictLois ) :
25   #---------------------------------------------------------#
26
27     self.NomAlgo = "myAlgo"
28     self.DictMCVal = DictMCVal
29     self.ListeVariables = ListeVariables
30     self.DictLois = DictLois
31
32     self.ListeOrdreMCReliability = (
33       "MaximumIterationsNumber",
34       "MaximumAbsoluteError",
35       "RelativeAbsoluteError",
36       "MaximumConstraintError",
37       "MaximumResidualError",
38       )
39     self.ListeOrdreMCDirectionalSampling = (
40       "RootStrategy",
41       "SamplingStrategy",
42       )
43     self.ListeOrdreMCParametresAlgo = (
44       "BlockSize",
45       "MaximumCoefficientOfVariation",
46       ) 
47     self.ListeOrdreImportanceSampling = (
48       "ImportanceSampling_BlockSize",
49       "ImportanceSampling_MaximumCoefficientOfVariation",
50       "ImportanceSampling_MaximumOuterSampling",
51       ) 
52
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" ],
74       }
75
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" }, \
84       }
85
86                  
87
88   def CreeSTD (self) :
89   #------------------
90     '''
91     Pilotage de la creation du fichier python
92     '''
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()
103     return self.texte
104
105 #                       ______________________________________
106 #
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)
110 #
111   def CreeAnalyse (self) :
112   #----------------------
113   # Appelee  par CreeSTD
114     texte=""
115     if self.DictMCVal.has_key("Analysis"):
116        texte += apply( STDGenerateur.__dict__[self.DictMCVal["Analysis"]], (self,) )
117     return texte
118
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'
126        return texte
127
128     texte += "   myMethod = "+ self.DictMCVal["Method"] + "()\n"
129     texte += "   myMethod.setSpecificParameters( " + self.DictMCVal["Method"] + "SpecificParameters() )\n"
130
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 "
134
135     texte  += "\n# L'algorithme\n\n"
136     if not self.DictMCVal.has_key("Algorithm"):
137        print 'Attention Mot Clef "Algorithm" non renseigne'
138        return texte
139     texte += "   " + self.NomAlgo + " = " + str (self.DictMCVal["Algorithm"]) 
140     texte += "( NearestPointAlgorithm(myMethod), myEvent, myPhysicalStartingPoint )\n"
141     texte += "   " + self.NomAlgo + ".run()\n "
142    
143     if self.DictMCVal.has_key("ImportanceSampling") and self.DictMCVal["ImportanceSampling"]=="yes" :
144        texte += self.ImportanceSampling() 
145     return texte
146
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'
154        return texte
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() "
161     return texte
162
163
164   def DirectionalSampling (self) :
165   #-------------------------------
166   # Appelee eventuellement par Simulation
167     texte = ""
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,))
171     return texte
172
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"
181     return texte
182
183   def SamplingStrategy(self):
184   #--------------------------
185   # Appelee eventuellement par DirectionalSampling
186     texte += "   mySampling = " + self.DictMCVal["SamplingStrategy"] + "()\n"
187     texte += "   mySampling.setSamplingStrategy( SamplingStrategy( mySampling ) )\n"
188     return texte
189
190
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"
200     return texte
201
202   def CreeEvent (self) :
203   #------------------
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'
208        return texte
209     texte += "   seuil = " +str (self.DictMCVal["Threshold"]) + "\n"
210     texte += "   myEvent = Event(myRandomVector_out," 
211     texte += "ComparisonOperator(" + str (self.DictMCVal["ComparisonOperator"]) + "()), seuil) \n"
212     return texte
213
214   def ParametresAlgo( self ):
215   #---------------------------
216   # Appelee par Simulation
217
218     texte += "   nbMaxOutSampling = "
219
220     if self.DictMCVal["MaximumOuterSamplingType"] == "UserDefined" :
221        texte += str(self.DictMCVal["MaximumOuterSampling"])
222
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'
227
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 "
232
233 #                       _____________________________________
234
235   def CreeRandomGenerator (self) :
236   #-------------------------------
237   # Appelee par CreeSTD
238     texte = ""
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"]
242     return texte
243
244   def CreeFunction (self) :
245   #-------------------------
246   # Appelee par CreeSTD
247     '''
248     La fonction :
249     Remarque : le nom 'solver' est en dur ici. Il doit imperativement correspondre
250                  au nom du fichier xml : 'solver.xml'
251     '''
252     texte  = "\n# La fonction\n\n"
253     texte += '   myFunction = NumericalMathFunction(\"XXXXXX\")\n'
254     texte += '   dim = myFunction.getInputNumericalPointDimension()\n'
255     return texte
256
257
258   def CreeCopula (self) :
259   #------------------
260   # Appelee par CreeSTD
261     texte  = "\n# La copule\n\n"
262     texte += "   myCopula = IndependentCopula(dim)\n"
263     return texte
264
265
266   def CreeDistribution (self) :
267   #----------------------------
268   # Appelee par CreeSTD
269     texte  = "\n# La distribution\n\n"
270     texte +=  "   myDistribution = ComposedDistribution(myCollection, Copula(myCopula))\n"
271     return texte
272
273
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"
280     return texte
281
282
283 # _______________________________
284
285
286
287   def ImportanceSampling (self) :
288   #-----------------------------
289   # Appele eventuellement par Reliability
290
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"
296
297     texte += "   importanceSamplingAlgo = ImportanceSampling( myEvent, Distribution( myImportance ) )\n\n"
298
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"
303
304     texte += "\n   importanceSamplingAlgo.run()\n\n"
305     self.NomAlgo = "importanceSamplingAlgo"
306     return texte
307
308
309   def CreeResu (self) :
310   #------------------
311     '''
312     '''
313     texte  = "\n# Le resultat\n\n"
314     texte += " myResu  = " + self.NomAlgo +  ".getResult() \n"
315     texte += " probability = myResu.getEventProbability()"
316
317     return texte
318
319
320
321   def CreeLois (self) :
322   #------------------
323     '''
324     '''
325     code_erreur = 0
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"
330
331     numVar = 0
332     for DictVariable in self.ListeVariables :
333
334        boolLoiDef = True
335        if DictVariable.has_key("MarginalDistribution") and DictVariable.has_key("Name"):
336           ConceptLoi = DictVariable["MarginalDistribution"]
337           NomLoi = DictVariable["Name"]+"_Dist"
338        else :
339           boolLoiDef = False
340        
341        if boolLoiDef and self.DictLois.has_key(ConceptLoi):
342           loi = self.DictLois[ConceptLoi]
343        else :
344           boolLoiDef = False
345       
346        if boolLoiDef and loi.has_key("Kind") :
347           TypeLoi = loi["Kind"]
348        else :
349           boolLoiDef = False
350
351        if not boolLoiDef or TypeLoi not in self.listeParamLoi.keys() : 
352           texte += " Loi " + TypeLoi +" non programmee \n"
353           numVar += 1
354           continue
355
356        ListeParametres = []
357        TexteParametres = ""
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 + ","
363
364        texte += "   " + NomLoi + " = " + TypeLoi + "( " 
365
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"
370        else :
371           texte += TexteParametres[:-1] + " )\n"
372
373        texte += "   " + NomLoi + '.setName( "'+DictVariable["Name"] +'" )\n'
374        texte += "   myCollection["+str(numVar)+"] = Distribution( "+NomLoi+" )\n"
375
376        if self.DictMCVal["Analysis"] == "Reliability" :
377           texte += "   myPhysicalStartingPoint["+str(numVar)+"] = "
378           if DictVariable.has_key("PhysicalStartingPoint") :
379              texte += str(DictVariable["PhysicalStartingPoint"]) +"\n\n"
380           else :
381              texte += NomLoi+".computeQuantile( 0.5 )[0]\n\n"
382
383        numVar += 1
384     return texte
385
386
387 #                       _____________________________________________________
388
389   def CreeEntete (self) :
390   #------------------
391     '''
392     Entete :
393     '''
394
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"
405     texte += "try : \n"
406     return texte
407
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"
418     return texte
419