]> SALOME platform Git repositories - tools/eficas.git/blob - Noyau/N_utils.py
Salome HOME
Modif V6_4_°
[tools/eficas.git] / Noyau / N_utils.py
1 #@ MODIF N_utils Noyau  DATE 28/06/2011   AUTEUR COURTOIS M.COURTOIS 
2 # -*- coding: iso-8859-1 -*-
3 # RESPONSABLE COURTOIS M.COURTOIS
4 #            CONFIGURATION MANAGEMENT OF EDF VERSION
5 # ======================================================================
6 # COPYRIGHT (C) 1991 - 2011  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
23 """
24    Ce module contient des fonctions utilitaires
25 """
26
27 # Modules Python
28 import sys
29
30 # Modules EFICAS
31 from N_Exception import AsException
32 from N_types     import is_int, is_float, is_complex, is_str, is_enum, is_assd
33
34 SEP='_'
35
36 try:
37    # Si la version de Python possede la fonction _getframe
38    # on l'utilise.
39    cur_frame=sys._getframe
40 except:
41    # Sinon on l'emule
42    def cur_frame(offset=0):
43      """ Retourne la frame d execution effective eventuellement en remontant
44          de offset niveaux dans la pile d execution
45          Si il y a moins de offset niveaux retourne None
46      """
47      try:1/0
48      except:
49        frame=sys.exc_info()[2].tb_frame.f_back
50      while offset > 0:
51        if frame == None:return None
52        frame=frame.f_back
53        offset=offset-1
54      return frame
55
56
57 def callee_where(niveau=4):
58    """
59       recupere la position de l appel
60    """
61    frame=cur_frame(niveau)
62    if frame == None: return 0,"inconnu",0,{}
63    try:
64      return frame.f_lineno,frame.f_code.co_filename,frame.f_code.co_firstlineno,frame.f_locals
65    except:
66      return 0,"inconnu",0,{}
67
68
69 def AsType(a):
70    """
71       Retourne le type d'un concept (a) à partir
72       des caracteristiques de l'objet Python
73    """
74    if is_enum(a):  return AsType(a[0])
75    if is_assd(a):  return type(a)
76    if is_float(a): return "R"
77    if is_int(a):   return "I"
78    if is_str(a):   return "TXM"
79    if a == None:   return None
80    print 'a=', a, type(a)
81    raise AsException("type inconnu")
82
83
84 def prbanner(s):
85    print "*"*(len(s)+10)
86    print "*"*5 + s + "*"*5
87    print "*"*(len(s)+10)
88
89
90 def repr_float(valeur):
91   """
92       Cette fonction represente le reel valeur comme une chaine de caracteres
93       sous forme mantisse exposant si necessaire cad si le nombre contient plus de
94       5 caractères
95       NB : valeur est un réel au format Python ou une chaine de caractères représentant un réel
96   """
97   if type(valeur) == str : valeur = eval(valeur)
98   if valeur == 0. : return '0.0'
99   if abs(valeur) > 1. :
100     if abs(valeur) < 10000. : return repr(valeur)
101   else :
102     if abs(valeur) > 0.01 : return repr(valeur)
103   t=repr(valeur)
104   if t.find('e') != -1 or t.find('E') != -1 :
105     # le réel est déjà sous forme mantisse exposant !
106     # --> on remplace e par E
107     t=t.replace('e','E')
108     # --> on doit encore vérifier que la mantisse contient bien un '.'
109     if t.find('.')!= -1:
110       return t
111     else:
112       # -->il faut rajouter le point avant le E
113       t=t.replace('E','.E')
114       return t
115   s=''
116   neg = 0
117   if t[0]=='-':
118     s=s+t[0]
119     t=t[1:]
120   cpt = 0
121   if t[0].atof() == 0.:
122     # réel plus petit que 1
123     neg = 1
124     t=t[2:]
125     cpt=1
126     while t[0].atof() == 0. :
127       cpt = cpt+1
128       t=t[1:]
129     s=s+t[0]+'.'
130     for c in t[1:]:
131       s=s+c
132   else:
133     # réel plus grand que 1
134     s=s+t[0]+'.'
135     if t[1:].atof() == 0.:
136       l=t[1:].split('.')
137       cpt = len(l[0])
138     else:
139       r=0
140       pt=0
141       for c in t[1:]:
142         r=r+1
143         if c != '.' :
144           if pt != 1 : cpt = cpt + 1
145           s=s+c
146         else:
147           pt = 1
148           if r+1 == len(t) or t[r+1:].atof() == 0.:break
149   s=s+'E'+neg*'-'+repr(cpt)
150   return s
151
152
153 def import_object(uri):
154     """Load and return a python object (class, function...).
155     Its `uri` looks like "mainpkg.subpkg.module.object", this means
156     that "mainpkg.subpkg.module" is imported and "object" is
157     the object to return.
158     """
159     path = uri.split('.')
160     modname = '.'.join(path[:-1])
161     if len(modname) == 0:
162         raise ImportError(u"invalid uri: %s" % uri)
163     mod = object = '?'
164     objname = path[-1]
165     try:
166         __import__(modname)
167         mod = sys.modules[modname]
168     except ImportError, err:
169         raise ImportError(u"can not import module : %s (%s)" % (modname, str(err)))
170     try:
171         object = getattr(mod, objname)
172     except AttributeError, err:
173         raise AttributeError(u"object (%s) not found in module '%s'. "
174             "Module content is: %s" % (objname, modname, tuple(dir(mod))))
175     return object
176
177
178 class Enum(object):
179     """
180     This class emulates a C-like enum for python. It is initialized with a list
181     of strings to be used as the enum symbolic keys. The enum values are automatically
182     generated as sequencing integer starting at 0.
183     """
184     def __init__(self, *keys):
185         """Constructor"""
186         self._dict_keys = {}
187         for inum, key in enumerate(keys):
188             setattr(self, key, 2**inum)
189             self._dict_keys[2**inum] = key
190
191     def exists(self, value):
192         """Tell if value is in the enumeration"""
193         return self.get_id(value) is not None
194
195     def get_id(self, value):
196         """Return the key associated to the given value"""
197         return self._dict_keys.get(value, None)