Salome HOME
dernieres modifs
[tools/eficas.git] / generator / DefautASTER.py
1 # Copyright (C) 2007-2013   EDF R&D
2 #
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License.
7 #
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 # Lesser General Public License for more details.
12 #
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 #
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 #
19 """
20 Ce module contient les variables
21 par defaut pour Aster
22 """
23
24 from OpenturnsSTD import STDGenerateur
25 from OpenturnsXML import XMLGenerateur
26
27 #====================================================
28 # Preparation du fichier STD
29 #====================================================
30 # C.1. Parties du texte en dur dans le fichier STD
31 #-------------------------------------------------
32
33 DecalSTD     = "  "
34 DecalSTDsaut = "\n  "
35
36 TexteSTDFIN ="\n\nexcept : \n"
37 TexteSTDFIN += DecalSTD + "error_message = sys.exc_type\n"
38 TexteSTDFIN += "\nif error_message is not None :\n"
39 TexteSTDFIN += DecalSTD + "texte  = \"\\n=================================================\""
40 TexteSTDFIN += DecalSTD + "texte += \"\\nMessage d'erreur : \" + str(error_message)"
41 TexteSTDFIN += DecalSTD + "texte += \"\\n=================================================\\n\""
42 TexteSTDFIN += DecalSTD + "print texte"
43 TexteSTDFIN += DecalSTD + "\nsys.exit(error_message)\n"
44
45 # C.2. Definition de composants dans le fichier STD
46 #--------------------------------------------------
47
48 NomFunction              = "myFunction"
49 NomPhysicalStartingPoint = "myPhysicalStartingPoint"
50 NomCollection            = "myCollection"
51 NomCopule                = "myCopula"
52 NomDistribution          = "myDistribution"
53 NomRandomVector_in       = "myRandomVector_in"
54 NomRandomVector_out      = "myRandomVector_out"
55 NomEvent                 = "myEvent"
56 NomMethod                = "myMethod"
57 NomAlgo                  = "myAlgo"
58 NomRoot                  = "myRoot"
59 NomSampling              = "mySampling"
60 NomSolverSD              = "mySolver"
61 NomResu                  = "myResu"
62
63 class Defaut :
64 # Cette classe ajoute les parametres par defaut propres au Solver Aster
65 # Elle va d abord enrichir le dictionnaire DictMCVal avec des valeurs par defaut
66 # C est la methode enrichitMCVal
67 # Elle va ensuite enrichir les variables
68 # C est la methode enrichitListeVariables
69   
70   def __init__(self, parent) :
71        self.parent=parent
72        self.enrichitMCVal()
73        self.enrichitListeVariables()
74
75
76   def enrichitMCVal(self) :
77   #=====================
78       # InformationSolver : nom du wrapper, type de fichiers d'echange, etc
79       #----------------------------------------------------------------------
80       # Ajoute les informations sur le wrapper 
81       #        nom du wrapper, type de fichiers d'echange, etc.
82        dico = { "WrapperPath" : "Code_Aster.so",
83                  "FunctionName" : "Code_Aster",
84                  "WrapCouplingMode" : "fork",
85                  "State" : "shared",
86                  "InDataTransfer" : "files",
87                  "OutDataTransfer" : "files",
88               }
89
90        self.parent.ajouteDictMCVal(dico)
91
92       #InformationSolverFile : parametres par defaut pour les fichiers d'echange
93       #--------------------------------------------------------------------------
94
95        liste = []
96        dicoIn = { "Id" : "file_in", "Type" : "in", "Name" : "StdIn", "Path" : "commandes_aster" }
97        liste.append(dicoIn)
98        dicoOut = { "Id" : "file_out", "Type" : "out", "Name" : "StdOut", "Path" : "resultats_aster", }
99        liste.append(dicoOut)
100        dicoFile={"exchange_file" : liste} 
101        self.parent.ajouteDictMCVal(dicoFile)
102
103 # D.2. InformationSolverCommande : arguments, etc
104 #-------------------------------------------------------------------------
105 # InformationSolverCommande est un dictionnaire indexe par le nom du solveur externe appele.
106 # InformationSolverCommande[solveur] est lui-meme un dictionnaire qui contient les parametres
107 # supplementaires pour la commande.
108 # Des parametres sont donnes sous forme de tuple : (ok/nok, "mot-cle") ou (ok/nok, "mot-cle", valeur)
109 # . On ajoute seulement si ok
110 # . Avec (ok/nok, "mot-cle"), on ajoute en arguments les couples ("mot-cle", nom_du_parametre)
111 # . Avec (ok/nok, "mot-cle", valeur), on ajoute en arguments les couples ("mot-cle", valeur)
112
113
114 #       dico = { "file_out"    : (1, "-fic_de_aster_vers_ot"),
115 #                "variable_in" : (1, "-variable") }
116 #       self.parent.InformationSolverCommande["Code_Aster"] = dico          
117
118
119   def enrichitListeVariables(self) :
120        # parametres par defaut pour chaque variable
121        #--------------------------------------------
122
123        dico_in = { "Regexp" : '"^" , "Name", "(.*)= *[0-9eE.+-]+([)]?;?)$"',
124                    "Format" : '"Name", "\\1=%20.13G\\2"'
125                  }
126        dico_out = { "Regexp" : '"(.*)"' }
127        self.parent.ajouteInfoVariables(dico_in,dico_out)          
128
129 class MonSTDGenerateur(STDGenerateur) :
130
131   def CreeResu (self) :
132   #------------------
133     '''
134     Le resultat :
135     . Donnees :
136       . l'algorithme choisi.
137     . Resultats :
138       . Ecriture des odres d'impression.
139     '''
140     if self.DictMCVal.has_key("Analysis"):
141        self.Analysis = str(self.DictMCVal["Analysis"])
142     else :
143        self.Analysis = None
144     self.fic_resu_OpenTURNS = "fic_resu_OpenTURNS_glop"
145     Algorithm = str (self.DictMCVal["Algorithm"])
146     texte  = "\n\n# Le resultat\n"
147     texte += DecalSTDsaut + NomResu + " = " + NomAlgo +  ".getResult()"
148     texte += DecalSTDsaut + "###" + "print " + NomResu
149     texte += DecalSTDsaut + "text_resu  = \"Resultats\\n=======\\n\""
150
151 #   Particularites des algorithmes de fiabilite
152
153     if self.Analysis in ( "Reliability", ) :
154       texte += DecalSTDsaut + "aux = " + NomResu + ".getIsStandardPointOriginInFailureSpace()"
155       texte += DecalSTDsaut + "if aux :"
156       texte += DecalSTDsaut + DecalSTD + "texte_bis = \"est\""
157       texte += DecalSTDsaut + "else :"
158       texte += DecalSTDsaut + DecalSTD + "texte_bis = \"n\'est pas\""
159       texte += DecalSTDsaut + "text_resu += \"\\nLe point initial \" + texte_bis + \" dans l\'espace de defaillance.\""
160       l_aux = [ ("Probabilite de defaillance", "EventProbability") ]
161       l_aux.append ( ("Indice de confiance generalise", "GeneralisedReliabilityIndex") )
162       l_aux.append ( ("Indice de confiance de Hasofer", "HasoferReliabilityIndex") )
163       for t_aux in l_aux :
164         texte += DecalSTDsaut + "text_resu += \"\\n" + t_aux[0] + " = \" + str(" \
165                               + NomResu + ".get" + t_aux[1] + "())"
166       l_aux = []
167       l_aux.append("StandardSpaceDesignPoint")
168       l_aux.append("PhysicalSpaceDesignPoint")
169       l_aux.append("ImportanceFactors")
170       texte += DecalSTDsaut + "l_aux_var = []"
171       for DictVariable in self.ListeVariables :
172         if ( DictVariable["Type"] == "in" ) :
173           texte += DecalSTDsaut + "l_aux_var.append(\"" + DictVariable["Name"] + "\")"
174       texte += DecalSTDsaut + "l_aux = []"
175       for type_resu in l_aux :
176         texte += DecalSTDsaut + "l_aux.append(" + NomResu + ".get" + type_resu + "())"
177       texte += DecalSTDsaut + "for resu in l_aux :"       
178       texte += DecalSTDsaut + DecalSTD + "if not resu.isEmpty() :"       
179       texte += DecalSTDsaut + DecalSTD + DecalSTD + "text_resu += \"\\n\" + resu.getName() + \" :\""       
180       texte += DecalSTDsaut + DecalSTD + DecalSTD + "size = resu.getDimension()"       
181       texte += DecalSTDsaut + DecalSTD + DecalSTD + "l_aux_1 = resu.getCollection()"       
182       texte += DecalSTDsaut + DecalSTD + DecalSTD + "for iaux in range(size) :"       
183       texte += DecalSTDsaut + DecalSTD + DecalSTD + DecalSTD + "text_resu += \"\\n. \" + l_aux_var[iaux] + \" : \" + str(l_aux_1[iaux])"       
184
185 #   Particularites des algorithmes de simulation
186
187     if self.Analysis in ( "Simulation", ) :
188       l_aux = [ ("Probabilite de defaillance", "ProbabilityEstimate") ]
189       l_aux.append ( ("Variance", "VarianceEstimate") )
190       l_aux.append ( ("Nombre d\'iterations", "OuterSampling") )
191       for t_aux in l_aux :
192         texte += DecalSTDsaut + "text_resu += \"\\n" + t_aux[0] + " = \" + str(" \
193                               + NomResu + ".get" + t_aux[1] + "())"
194       texte += DecalSTDsaut + "text_resu += \"\\nNombre d'evaluations de l'etat limite = \" + str(" \
195                                + NomResu + ".getOuterSampling()*" + NomResu + ".getBlockSize())"
196       if self.DictMCVal.has_key("ConfidenceIntervalProbability") :
197         aux = self.DictMCVal["ConfidenceIntervalProbability"]
198         texte += DecalSTDsaut + "proba = " + NomResu + ".getProbabilityEstimate()"
199         texte += DecalSTDsaut + "t_aux = "
200         if ( type(aux) is type(0.) ) :
201           texte += "(" + str(aux) + ")"
202           t_aux = [ str(aux) ]
203         else :
204           texte += str(aux)
205         texte += DecalSTDsaut + "for val in t_aux :"
206         texte += DecalSTDsaut + DecalSTD + "length = " + NomResu + ".getConfidenceLength(val)"
207         texte += DecalSTDsaut + DecalSTD + "vinf = str( proba - 0.5*length )"
208         texte += DecalSTDsaut + DecalSTD + "vsup = str( proba + 0.5*length )"
209         texte += DecalSTDsaut + DecalSTD + "text_resu += \"\\nIntervalle de confiance a \" + str(val) + \" = [ \" "
210         texte += "+ vinf + \" , \" + vsup + \" ]\""
211
212 #   Generalites
213
214     texte += DecalSTDsaut + "d_aux = {}"
215     texte += DecalSTDsaut + "d_aux[\"E\"] = ( \"de la fonction\", " + NomFunction + ".getEvaluationCallsNumber() )"
216     texte += DecalSTDsaut + "d_aux[\"G\"] = ( \"du gradient\", " + NomFunction + ".getGradientCallsNumber() )"
217     texte += DecalSTDsaut + "d_aux[\"H\"] = ( \"du hessien\", " + NomFunction + ".getHessianCallsNumber() )"
218     texte += DecalSTDsaut + "for cle in d_aux.keys() :"
219     texte += DecalSTDsaut + DecalSTD + "if d_aux[cle][1] > 0 :"
220     texte += DecalSTDsaut + DecalSTD + DecalSTD + "text_resu += \"\\nNombre d\'appels au solveur pour le calcul \"" \
221                                 + " + d_aux[cle][0] + \" = \" + str(d_aux[cle][1])"
222
223 #   Impression
224
225     texte += DecalSTDsaut + "print \"\\n\", text_resu, \"\\n\""
226     texte += DecalSTDsaut + "file_resu = open(\"" + self.fic_resu_OpenTURNS + "\", \"w\")"
227     texte += DecalSTDsaut + "file_resu.write(text_resu)"
228     texte += DecalSTDsaut + "file_resu.close()"
229     texte += DecalSTDsaut + "probability = " + NomResu + ".getEventProbability()"
230
231     return texte
232