1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2018 EDF R&D
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License.
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # Lesser General Public License for more details.
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
24 Informations sur le code et la plateforme, et mise à jour des chemins
26 La classe "PlatformInfo" permet de récupérer les informations générales sur
27 le code et la plateforme sous forme de strings, ou d'afficher directement
28 les informations disponibles par les méthodes. L'impression directe d'un
29 objet de cette classe affiche les informations minimales. Par exemple :
31 print PlatformInfo().getVersion()
32 created = PlatformInfo().getDate()
34 La classe "PathManagement" permet de mettre à jour les chemins système pour
35 ajouter les outils numériques, matrices... On l'utilise en instanciant
36 simplement cette classe, sans meme récupérer d'objet :
39 La classe "SystemUsage" permet de sous Unix les différentes tailles
40 mémoires du process courant. Ces tailles peuvent être assez variables et
41 dépendent de la fiabilité des informations du système dans le suivi des
44 __author__ = "Jean-Philippe ARGAUD"
50 # ==============================================================================
51 class PlatformInfo(object):
53 Rassemblement des informations sur le code et la plateforme
60 "Retourne le nom de l'application"
61 import daCore.version as dav
65 "Retourne le numéro de la version"
66 import daCore.version as dav
70 "Retourne la date de création de la version"
71 import daCore.version as dav
75 "Retourne l'année de création de la version"
76 import daCore.version as dav
79 def getPythonVersion(self):
80 "Retourne la version de python disponible"
81 return ".".join([str(x) for x in sys.version_info[0:3]]) # map(str,sys.version_info[0:3]))
83 def getNumpyVersion(self):
84 "Retourne la version de numpy disponible"
86 return numpy.version.version
88 def getScipyVersion(self):
89 "Retourne la version de scipy disponible"
91 __version = scipy.version.version
96 def getMatplotlibVersion(self):
97 "Retourne la version de matplotlib disponible"
99 __version = matplotlib.__version__
104 def getGnuplotVersion(self):
105 "Retourne la version de gnuplotpy disponible"
107 __version = Gnuplot.__version__
112 def getSphinxVersion(self):
113 "Retourne la version de sphinx disponible"
115 __version = sphinx.__version__
120 def getNloptVersion(self):
121 "Retourne la version de nlopt disponible"
123 __version = "%s.%s.%s"%(
124 nlopt.version_major(),
125 nlopt.version_minor(),
126 nlopt.version_bugfix(),
132 def getCurrentMemorySize(self):
133 "Retourne la taille mémoire courante utilisée"
136 def MaximumPrecision(self):
137 "Retourne la precision maximale flottante pour Numpy"
140 numpy.array([1.,], dtype='float128')
146 def MachinePrecision(self):
147 # Alternative sans module :
151 # eps = (1.0 + eps/2) - 1.0
152 return sys.float_info.epsilon
155 import daCore.version as dav
156 return "%s %s (%s)"%(dav.name,dav.version,dav.date)
158 # ==============================================================================
162 import scipy.optimize
169 has_matplotlib = True
171 has_matplotlib = False
191 has_salome = bool( "ROOT_SALOME" in os.environ )
192 has_yacs = bool( "YACS_ROOT_DIR" in os.environ )
193 has_adao = bool( "ADAO_ROOT_DIR" in os.environ )
194 has_eficas = bool( "EFICAS_ROOT_DIR" in os.environ )
196 # ==============================================================================
197 def uniq(__sequence):
199 Fonction pour rendre unique chaque élément d'une liste, en préservant l'ordre
202 return [x for x in __sequence if x not in __seen and not __seen.add(x)]
204 def date2int(__date, __lang="FR"):
206 Fonction de secours, conversion pure : dd/mm/yy hh:mm ---> int(yyyymmddhhmm)
208 __date = __date.strip()
209 if __date.count('/') == 2 and __date.count(':') == 0 and __date.count(' ') == 0:
210 d,m,y = __date.split("/")
211 __number = (10**4)*int(y)+(10**2)*int(m)+int(d)
212 elif __date.count('/') == 2 and __date.count(':') == 1 and __date.count(' ') > 0:
213 part1, part2 = __date.split()
214 d,m,y = part1.strip().split("/")
215 h,n = part2.strip().split(":")
216 __number = (10**8)*int(y)+(10**6)*int(m)+(10**4)*int(d)+(10**2)*int(h)+int(n)
218 raise ValueError("Cannot convert \"%s\" as a D/M/Y H:M date"%d)
221 # ==============================================================================
222 class PathManagement(object):
224 Mise à jour du path système pour les répertoires d'outils
227 "Déclaration des répertoires statiques"
228 parent = os.path.abspath(os.path.join(os.path.dirname(__file__),".."))
230 self.__paths["daNumerics"] = os.path.join(parent,"daNumerics")
232 for v in self.__paths.values():
233 sys.path.insert(0, v )
235 # Conserve en unique exemplaire chaque chemin
236 sys.path = uniq( sys.path )
241 Renvoie le dictionnaire des chemins ajoutés
245 # ==============================================================================
246 class SystemUsage(object):
248 Permet de récupérer les différentes tailles mémoires du process courant
251 # Le module resource renvoie 0 pour les tailles mémoire. On utilise donc
252 # plutôt : http://code.activestate.com/recipes/286222/ et Wikipedia
254 _proc_status = '/proc/%d/status' % os.getpid()
255 _memo_status = '/proc/meminfo'
257 'o' : 1.0, # Multiples SI de l'octet
261 'kio': 1024.0, # Multiples binaires de l'octet
262 'Mio': 1024.0*1024.0,
263 'Gio': 1024.0*1024.0*1024.0,
264 'B': 1.0, # Multiples binaires du byte=octet
266 'MB' : 1024.0*1024.0,
267 'GB' : 1024.0*1024.0*1024.0,
274 def _VmA(self, VmKey, unit):
275 "Lecture des paramètres mémoire de la machine"
277 t = open(self._memo_status)
281 return 0.0 # non-Linux?
282 i = v.index(VmKey) # get VmKey line e.g. 'VmRSS: 9999 kB\n ...'
283 v = v[i:].split(None, 3) # whitespace
285 return 0.0 # invalid format?
286 # convert Vm value to bytes
287 mem = float(v[1]) * self._scale[v[2]]
288 return mem / self._scale[unit]
290 def getAvailablePhysicalMemory(self, unit="o"):
291 "Renvoie la mémoire physique utilisable en octets"
292 return self._VmA('MemTotal:', unit)
294 def getAvailableSwapMemory(self, unit="o"):
295 "Renvoie la mémoire swap utilisable en octets"
296 return self._VmA('SwapTotal:', unit)
298 def getAvailableMemory(self, unit="o"):
299 "Renvoie la mémoire totale (physique+swap) utilisable en octets"
300 return self._VmA('MemTotal:', unit) + self._VmA('SwapTotal:', unit)
302 def getUsableMemory(self, unit="o"):
303 """Renvoie la mémoire utilisable en octets
304 Rq : il n'est pas sûr que ce décompte soit juste...
306 return self._VmA('MemFree:', unit) + self._VmA('SwapFree:', unit) + \
307 self._VmA('Cached:', unit) + self._VmA('SwapCached:', unit)
309 def _VmB(self, VmKey, unit):
310 "Lecture des paramètres mémoire du processus"
312 t = open(self._proc_status)
316 return 0.0 # non-Linux?
317 i = v.index(VmKey) # get VmKey line e.g. 'VmRSS: 9999 kB\n ...'
318 v = v[i:].split(None, 3) # whitespace
320 return 0.0 # invalid format?
321 # convert Vm value to bytes
322 mem = float(v[1]) * self._scale[v[2]]
323 return mem / self._scale[unit]
325 def getUsedMemory(self, unit="o"):
326 "Renvoie la mémoire résidente utilisée en octets"
327 return self._VmB('VmRSS:', unit)
329 def getVirtualMemory(self, unit="o"):
330 "Renvoie la mémoire totale utilisée en octets"
331 return self._VmB('VmSize:', unit)
333 def getUsedStacksize(self, unit="o"):
334 "Renvoie la taille du stack utilisé en octets"
335 return self._VmB('VmStk:', unit)
337 def getMaxUsedMemory(self, unit="o"):
338 "Renvoie la mémoire résidente maximale mesurée"
339 return self._VmB('VmHWM:', unit)
341 def getMaxVirtualMemory(self, unit="o"):
342 "Renvoie la mémoire totale maximale mesurée"
343 return self._VmB('VmPeak:', unit)
345 # ==============================================================================
346 if __name__ == "__main__":
347 print('\n AUTODIAGNOSTIC \n')