]> SALOME platform Git repositories - tools/eficas.git/blob - Aster/Cata/cataSTA10/Macro/reca_utilitaires.py
Salome HOME
Modif V6_4_°
[tools/eficas.git] / Aster / Cata / cataSTA10 / Macro / reca_utilitaires.py
1 #@ MODIF reca_utilitaires Macro  DATE 11/05/2010   AUTEUR COURTOIS M.COURTOIS 
2 # -*- coding: iso-8859-1 -*-
3 # RESPONSABLE ASSIRE A.ASSIRE
4 #            CONFIGURATION MANAGEMENT OF EDF VERSION
5 # ======================================================================
6 # COPYRIGHT (C) 1991 - 2006  EDF R&D                  WWW.CODE-ASTER.ORG
7 # THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY  
8 # IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY  
9 # THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR     
10 # (AT YOUR OPTION) ANY LATER VERSION.                                                  
11 #                                                                       
12 # THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT   
13 # WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF            
14 # MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU      
15 # GENERAL PUBLIC LICENSE FOR MORE DETAILS.                              
16 #                                                                       
17 # YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE     
18 # ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER,         
19 #    1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.        
20 # ======================================================================
21
22 import copy
23 import os
24 import string
25 import types
26 import sys
27 import glob
28
29 import numpy as NP
30
31 try:    import Gnuplot
32 except: pass
33
34 try:
35    import aster
36    CPU_Exception = aster.ArretCPUError
37    from Cata.cata import INFO_EXEC_ASTER, DEFI_FICHIER, IMPR_FONCTION, DETRUIRE
38    from Accas import _F
39    from Utilitai.Utmess import UTMESS, MessageLog
40 except:
41    CPU_Exception = StandardError
42
43
44 # ------------------------------------------------------------------------------
45 # ------------------------------------------------------------------------------
46
47 #_____________________________________________
48 #
49 # DIVERS UTILITAIRES POUR LA MACRO
50 #_____________________________________________
51
52
53 def transforme_list_Num(parametres,res_exp):
54    """
55       Transforme les données entrées par l'utilisateur en tableau numpy
56    """
57
58    dim_para = len(parametres)  #donne le nb de parametres
59    val_para = NP.zeros(dim_para)
60    borne_inf = NP.zeros(dim_para)
61    borne_sup = NP.zeros(dim_para)
62    para = []
63    for i in range(dim_para):
64       para.append(parametres[i][0])
65       val_para[i] = parametres[i][1]
66       borne_inf[i] = parametres[i][2]
67       borne_sup[i] = parametres[i][3]
68    return para,val_para,borne_inf,borne_sup
69
70
71 # ------------------------------------------------------------------------------
72
73 def mes_concepts(list_concepts=[],base=None):
74    """
75       Fonction qui liste les concepts créés
76    """
77    for e in base.etapes:
78       if e.nom in ('INCLUDE','MACR_RECAL',) :
79         list_concepts=list(mes_concepts(list_concepts=list_concepts,base=e))
80       elif (e.sd != None) and (e.parent.nom=='INCLUDE') :
81         nom_concept=e.sd.get_name()
82         if not(nom_concept in list_concepts):
83           list_concepts.append( nom_concept )
84    return tuple(list_concepts)
85
86
87 # ------------------------------------------------------------------------------
88
89 def detr_concepts(self):
90    """
91       Fonction qui detruit les concepts créés
92    """
93    liste_concepts=mes_concepts(base=self.parent)
94    for e in liste_concepts:
95       nom = string.strip(e)
96       DETRUIRE( OBJET =self.g_context['_F'](CHAINE = nom), INFO=1, ALARME='NON')
97       if self.jdc.g_context.has_key(nom) : del self.jdc.g_context[nom]
98    del(liste_concepts)
99
100
101 # ------------------------------------------------------------------------------
102 def Random_Tmp_Name(prefix=None):
103    crit = False
104    while crit == False:
105       nombre = int(random.random()*10000000)
106       if prefix: fic = prefix + str(nombre)
107       else:
108          if os.environ.has_key('TEMP'): fic = os.path.join( os.environ['TEMP'], 'file%s' % str(nombre) )
109          else:                          fic = '/tmp/file' + str(nombre)
110       if not os.path.isfile(fic): crit = True
111    return fic
112
113
114
115
116 #_____________________________________________
117 #
118 # CALCUL DU TEMPS CPU RESTANT
119 #_____________________________________________
120
121
122 def temps_CPU(restant_old,temps_iter_old):
123    """
124       Fonction controlant le temps CPU restant
125    """
126    CPU=INFO_EXEC_ASTER(LISTE_INFO = ("CPU_RESTANT",))
127    TEMPS=CPU['CPU_RESTANT',1]
128    DETRUIRE(CONCEPT=_F(NOM=CPU),INFO=1)
129    err=0
130    # Indique une execution interactive
131    if (TEMPS>1.E+9):
132      return 0.,0.,0
133    # Indique une execution en batch
134    else:
135       restant=TEMPS
136       # Initialisation
137       if (restant_old==0.):
138          temps_iter=-1.
139       else:
140          # Première mesure
141          if (temps_iter_old==-1.):
142             temps_iter=(restant_old-restant)
143          # Mesure courante
144          else:
145             temps_iter=(temps_iter_old + (restant_old-restant))/2.
146          if ((temps_iter>0.96*restant)or(restant<0.)):
147             err=1
148             msg = MessageLog.GetText('F', 'RECAL0_53')
149             raise CPU_Exception, msg
150
151    return restant,temps_iter,err
152
153
154
155
156 #_____________________________________________
157 #
158 # IMPRESSIONS GRAPHIQUES
159 #_____________________________________________
160
161
162 def graphique(FORMAT, L_F, res_exp, reponses, iter, UL_out, pilote, fichier=None, INFO=0):
163
164   if iter: txt_iter = 'Iteration : ' + str(iter)
165   else:    txt_iter = ''
166
167   # Le try/except est la pour eviter de planter betement dans un trace de courbes (DISPLAY non defini, etc...)
168   try:
169      if FORMAT=='XMGRACE':
170          for i in range(len(L_F)):
171              _tmp = []
172              courbe1 = res_exp[i]
173              _tmp.append( { 'ABSCISSE': courbe1[:,0].tolist(), 'ORDONNEE': courbe1[:,1].tolist(), 'COULEUR': 1, 'LEGENDE' : 'Expérience'} )
174              courbe2 = L_F[i]
175              _tmp.append( { 'ABSCISSE': courbe2[:,0].tolist(), 'ORDONNEE': courbe2[:,1].tolist(), 'COULEUR': 2, 'LEGENDE' : 'Calcul'} )
176
177              motscle2= {'COURBE': _tmp }
178              motscle2['PILOTE']= pilote
179
180              IMPR_FONCTION(FORMAT='XMGRACE',
181                            UNITE=int(UL_out),
182                            TITRE='Courbe : ' + reponses[i][0],
183                            SOUS_TITRE=txt_iter,
184                            LEGENDE_X=reponses[i][1],
185                            LEGENDE_Y=reponses[i][2],
186                            **motscle2
187                            );
188              dic = {''           : '',
189                     'POSTSCRIPT' : '.ps',
190                     'EPS'        : '.eps',
191                     'MIF'        : '.mif',
192                     'SVG'        : '.svg',
193                     'PNM'        : '.pnm',
194                     'PNG'        : '.png',
195                     'JPEG'       : '.jpg',
196                     'PDF'        : '.pdf', 
197                     'INTERACTIF' : '.agr'
198                     }
199              ext = dic[pilote]
200              if ext!='':
201                os.system('mv ./fort.%s ./REPE_OUT/courbes_%s_iter_%s%s' % (str(UL_out), reponses[i][0], str(iter), ext ) )
202
203      elif FORMAT=='GNUPLOT':
204
205          if fichier:
206             if INFO>=2: UTMESS('I','RECAL0_41',valk=fichier )
207             # On efface les anciens graphes
208             liste = glob.glob(fichier + '*.ps')
209             for fic in liste:
210                try:    os.remove(fic)
211                except: pass
212
213          graphe=[]
214          impr=Gnuplot.Gnuplot()
215          Gnuplot.GnuplotOpts.prefer_inline_data=1
216          impr('set data style linespoints')
217          impr('set grid')
218          impr('set pointsize 1.')
219          impr('set terminal postscript color')
220          impr('set output "fort.'+str(UL_out)+'"')
221
222          for i in range(len(L_F)):
223                graphe.append(Gnuplot.Gnuplot(persist=0))
224                graphe[i]('set data style linespoints')
225                graphe[i]('set grid')
226                graphe[i]('set pointsize 1.')
227                graphe[i].xlabel(reponses[i][1])
228                graphe[i].ylabel(reponses[i][2])
229                graphe[i].title(reponses[i][0]+'  ' + txt_iter)
230                graphe[i].plot(Gnuplot.Data(L_F[i],title='Calcul'),Gnuplot.Data(res_exp[i],title='Experimental'))
231                if pilote=='INTERACTIF':
232                   graphe[i]('pause 5')
233                else:
234                   if fichier:
235                      if INFO>=2: UTMESS('I','RECAL0_41',valk=fichier + '_' + str(i) + '.ps' )
236                      graphe[i].hardcopy(fichier + '_' + str(i) + '.ps', enhanced=1, color=1)
237
238                impr.xlabel(reponses[i][1])
239                impr.ylabel(reponses[i][2])
240                impr.title(reponses[i][0]+'  Iteration '+str(iter))
241                impr.plot(Gnuplot.Data(L_F[i],title='Calcul'),Gnuplot.Data(res_exp[i],title='Experimental'))
242
243   except Exception, err:
244      UTMESS('A','RECAL0_42',valk=str(err) )
245