1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008-2023 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"
54 # ==============================================================================
55 class PlatformInfo(object):
57 Rassemblement des informations sur le code et la plateforme
66 "Retourne le nom de l'application"
67 import daCore.version as dav
71 "Retourne le numéro de la version"
72 import daCore.version as dav
76 "Retourne la date de création de la version"
77 import daCore.version as dav
81 "Retourne l'année de création de la version"
82 import daCore.version as dav
85 def getSystemInformation(self, __prefix=""):
87 __msg += "\n%s%30s : %s" %(__prefix,"platform.system",platform.system())
88 __msg += "\n%s%30s : %s" %(__prefix,"sys.platform",sys.platform)
89 __msg += "\n%s%30s : %s" %(__prefix,"platform.version",platform.version())
90 __msg += "\n%s%30s : %s" %(__prefix,"platform.platform",platform.platform())
91 __msg += "\n%s%30s : %s" %(__prefix,"platform.machine",platform.machine())
92 if len(platform.processor())>0:
93 __msg += "\n%s%30s : %s" %(__prefix,"platform.processor",platform.processor())
95 if sys.platform.startswith('linux'):
96 if hasattr(platform, 'linux_distribution'):
97 __msg += "\n%s%30s : %s" %(__prefix,
98 "platform.linux_distribution",str(platform.linux_distribution()))
99 elif hasattr(platform, 'dist'):
100 __msg += "\n%s%30s : %s" %(__prefix,"platform.dist",str(platform.dist()))
101 elif sys.platform.startswith('darwin'):
102 if hasattr(platform, 'mac_ver'):
104 '0' : 'Cheetah', '1' : 'Puma', '2' : 'Jaguar',
105 '3' : 'Panther', '4' : 'Tiger', '5' : 'Leopard',
106 '6' : 'Snow Leopard', '7' : 'Lion', '8' : 'Mountain Lion',
107 '9' : 'Mavericks', '10': 'Yosemite', '11': 'El Capitan',
108 '12': 'Sierra', '13': 'High Sierra', '14': 'Mojave',
109 '15': 'Catalina', '16': 'Big Sur', '17': 'Monterey',
111 for key in __macosxv:
112 if (platform.mac_ver()[0].split('.')[1] == key):
113 __msg += "\n%s%30s : %s" %(__prefix,
114 "platform.mac_ver",str(platform.mac_ver()[0]+"(" + __macosxv[key]+")"))
115 elif hasattr(platform, 'dist'):
116 __msg += "\n%s%30s : %s" %(__prefix,"platform.dist",str(platform.dist()))
117 elif os.name == 'nt':
118 __msg += "\n%s%30s : %s" %(__prefix,"platform.win32_ver",platform.win32_ver()[1])
121 __msg += "\n%s%30s : %s" %(__prefix,"platform.python_implementation",platform.python_implementation())
122 __msg += "\n%s%30s : %s" %(__prefix,"sys.executable",sys.executable)
123 __msg += "\n%s%30s : %s" %(__prefix,"sys.version",sys.version.replace('\n',''))
124 __msg += "\n%s%30s : %s" %(__prefix,"sys.getfilesystemencoding",str(sys.getfilesystemencoding()))
125 __msg += "\n%s%30s : %s" %(__prefix,"locale.getdefaultlocale",str(locale.getdefaultlocale()))
127 __msg += "\n%s%30s : %s" %(__prefix,"os.cpu_count",os.cpu_count())
128 if hasattr(os, 'sched_getaffinity'):
129 __msg += "\n%s%30s : %s" %(__prefix,"len(os.sched_getaffinity(0))",len(os.sched_getaffinity(0)))
131 __msg += "\n%s%30s : %s" %(__prefix,"len(os.sched_getaffinity(0))","Unsupported on this platform")
133 __msg += "\n%s%30s : %s" %(__prefix,"platform.node",platform.node())
134 __msg += "\n%s%30s : %s" %(__prefix,"os.path.expanduser",os.path.expanduser('~'))
137 def getPythonVersion(self):
138 "Retourne la version de python disponible"
139 return ".".join([str(x) for x in sys.version_info[0:3]]) # map(str,sys.version_info[0:3]))
141 def getNumpyVersion(self):
142 "Retourne la version de numpy disponible"
144 return numpy.version.version
146 def getScipyVersion(self):
147 "Retourne la version de scipy disponible"
149 __version = scipy.version.version
154 def getMatplotlibVersion(self):
155 "Retourne la version de matplotlib disponible"
157 __version = matplotlib.__version__
162 def getGnuplotVersion(self):
163 "Retourne la version de gnuplotpy disponible"
165 __version = Gnuplot.__version__
170 def getSphinxVersion(self):
171 "Retourne la version de sphinx disponible"
173 __version = sphinx.__version__
178 def getNloptVersion(self):
179 "Retourne la version de nlopt disponible"
181 __version = "%s.%s.%s"%(
182 nlopt.version_major(),
183 nlopt.version_minor(),
184 nlopt.version_bugfix(),
190 def getSdfVersion(self):
191 "Retourne la version de sdf disponible"
193 __version = sdf.__version__
198 def getCurrentMemorySize(self):
199 "Retourne la taille mémoire courante utilisée"
202 def MaximumPrecision(self):
203 "Retourne la precision maximale flottante pour Numpy"
206 numpy.array([1.,], dtype='float128')
212 def MachinePrecision(self):
213 # Alternative sans module :
217 # eps = (1.0 + eps/2) - 1.0
218 return sys.float_info.epsilon
221 import daCore.version as dav
222 return "%s %s (%s)"%(dav.name,dav.version,dav.date)
224 # ==============================================================================
229 raise ImportError("Numpy is not available, despites the fact it is mandatory.")
234 import scipy.optimize
241 has_matplotlib = True
243 has_matplotlib = False
269 has_salome = bool( "SALOME_ROOT_DIR" in os.environ )
270 has_yacs = bool( "YACS_ROOT_DIR" in os.environ )
271 has_adao = bool( "ADAO_ROOT_DIR" in os.environ )
272 has_eficas = bool( "EFICAS_ROOT_DIR" in os.environ )
274 # ==============================================================================
275 def uniq( __sequence ):
277 Fonction pour rendre unique chaque élément d'une liste, en préservant l'ordre
280 return [x for x in __sequence if x not in __seen and not __seen.add(x)]
282 def isIterable( __sequence, __check = False, __header = "" ):
284 Vérification que l'argument est un itérable interne.
285 Remarque : pour permettre le test correct en MultiFonctions,
286 - Ne pas accepter comme itérable un "numpy.ndarray"
287 - Ne pas accepter comme itérable avec hasattr(__sequence, "__iter__")
289 if isinstance( __sequence, (list, tuple, map, dict) ):
291 elif type(__sequence).__name__ in ('generator','range'):
293 elif "_iterator" in type(__sequence).__name__:
295 elif "itertools" in str(type(__sequence)):
299 if __check and not __isOk:
300 raise TypeError("Not iterable or unkown input type%s: %s"%(__header, type(__sequence),))
303 def date2int( __date, __lang="FR" ):
305 Fonction de secours, conversion pure : dd/mm/yy hh:mm ---> int(yyyymmddhhmm)
307 __date = __date.strip()
308 if __date.count('/') == 2 and __date.count(':') == 0 and __date.count(' ') == 0:
309 d,m,y = __date.split("/")
310 __number = (10**4)*int(y)+(10**2)*int(m)+int(d)
311 elif __date.count('/') == 2 and __date.count(':') == 1 and __date.count(' ') > 0:
312 part1, part2 = __date.split()
313 d,m,y = part1.strip().split("/")
314 h,n = part2.strip().split(":")
315 __number = (10**8)*int(y)+(10**6)*int(m)+(10**4)*int(d)+(10**2)*int(h)+int(n)
317 raise ValueError("Cannot convert \"%s\" as a D/M/Y H:M date"%d)
320 def strvect2liststr( __strvect ):
322 Fonction de secours, conversion d'une chaîne de caractères de
323 représentation de vecteur en une liste de chaînes de caractères de
324 représentation de flottants
326 for s in ("array", "matrix", "list", "tuple", "[", "]", "(", ")"):
327 __strvect = __strvect.replace(s,"") # Rien
329 __strvect = __strvect.replace(s," ") # Blanc
330 return __strvect.split()
332 def strmatrix2liststr( __strvect ):
334 Fonction de secours, conversion d'une chaîne de caractères de
335 représentation de matrice en une liste de chaînes de caractères de
336 représentation de flottants
338 for s in ("array", "matrix", "list", "tuple", "[", "(", "'", '"'):
339 __strvect = __strvect.replace(s,"") # Rien
340 __strvect = __strvect.replace(","," ") # Blanc
342 __strvect = __strvect.replace(s,";") # "]" et ")" par ";"
343 __strvect = re.sub(r';\s*;',r';',__strvect)
344 __strvect = __strvect.rstrip(";") # Après ^ et avant v
345 __strmat = [__l.split() for __l in __strvect.split(";")]
348 def checkFileNameConformity( __filename, __warnInsteadOfPrint=True ):
349 if sys.platform.startswith("win") and len(__filename) > 256:
351 __msg = (" For some shared or older file systems on Windows, a file "+\
352 "name longer than 256 characters can lead to access problems."+\
353 "\n The name of the file in question is the following:"+\
354 "\n %s")%(__filename,)
355 if __warnInsteadOfPrint: logging.warning(__msg)
362 def checkFileNameImportability( __filename, __warnInsteadOfPrint=True ):
363 if str(__filename).count(".") > 1:
365 __msg = (" The file name contains %i point(s) before the extension "+\
366 "separator, which can potentially lead to problems when "+\
367 "importing this file into Python, as it can then be recognized "+\
368 "as a sub-module (generating a \"ModuleNotFoundError\"). If it "+\
369 "is intentional, make sure that there is no module with the "+\
370 "same name as the part before the first point, and that there is "+\
371 "no \"__init__.py\" file in the same directory."+\
372 "\n The name of the file in question is the following:"+\
373 "\n %s")%(int(str(__filename).count(".")-1), __filename)
374 if __warnInsteadOfPrint is None: pass
375 elif __warnInsteadOfPrint: logging.warning(__msg)
382 # ==============================================================================
383 class PathManagement(object):
385 Mise à jour du path système pour les répertoires d'outils
387 __slots__ = ("__paths")
390 "Déclaration des répertoires statiques"
391 parent = os.path.abspath(os.path.join(os.path.dirname(__file__),".."))
393 self.__paths["daNumerics"] = os.path.join(parent,"daNumerics")
395 for v in self.__paths.values():
396 if os.path.isdir(v): sys.path.insert(0, v )
398 # Conserve en unique exemplaire chaque chemin
399 sys.path = uniq( sys.path )
404 Renvoie le dictionnaire des chemins ajoutés
408 # ==============================================================================
409 class SystemUsage(object):
411 Permet de récupérer les différentes tailles mémoires du process courant
415 # Le module resource renvoie 0 pour les tailles mémoire. On utilise donc
416 # plutôt : http://code.activestate.com/recipes/286222/ et Wikipedia
418 _proc_status = '/proc/%d/status' % os.getpid()
419 _memo_status = '/proc/meminfo'
421 'o' : 1.0, # Multiples SI de l'octet
425 'kio': 1024.0, # Multiples binaires de l'octet
426 'Mio': 1024.0*1024.0,
427 'Gio': 1024.0*1024.0*1024.0,
428 'B': 1.0, # Multiples binaires du byte=octet
430 'MB' : 1024.0*1024.0,
431 'GB' : 1024.0*1024.0*1024.0,
438 def _VmA(self, VmKey, unit):
439 "Lecture des paramètres mémoire de la machine"
441 t = open(self._memo_status)
445 return 0.0 # non-Linux?
446 i = v.index(VmKey) # get VmKey line e.g. 'VmRSS: 9999 kB\n ...'
447 v = v[i:].split(None, 3) # whitespace
449 return 0.0 # invalid format?
450 # convert Vm value to bytes
451 mem = float(v[1]) * self._scale[v[2]]
452 return mem / self._scale[unit]
454 def getAvailablePhysicalMemory(self, unit="o"):
455 "Renvoie la mémoire physique utilisable en octets"
456 return self._VmA('MemTotal:', unit)
458 def getAvailableSwapMemory(self, unit="o"):
459 "Renvoie la mémoire swap utilisable en octets"
460 return self._VmA('SwapTotal:', unit)
462 def getAvailableMemory(self, unit="o"):
463 "Renvoie la mémoire totale (physique+swap) utilisable en octets"
464 return self._VmA('MemTotal:', unit) + self._VmA('SwapTotal:', unit)
466 def getUsableMemory(self, unit="o"):
467 """Renvoie la mémoire utilisable en octets
468 Rq : il n'est pas sûr que ce décompte soit juste...
470 return self._VmA('MemFree:', unit) + self._VmA('SwapFree:', unit) + \
471 self._VmA('Cached:', unit) + self._VmA('SwapCached:', unit)
473 def _VmB(self, VmKey, unit):
474 "Lecture des paramètres mémoire du processus"
476 t = open(self._proc_status)
480 return 0.0 # non-Linux?
481 i = v.index(VmKey) # get VmKey line e.g. 'VmRSS: 9999 kB\n ...'
482 v = v[i:].split(None, 3) # whitespace
484 return 0.0 # invalid format?
485 # convert Vm value to bytes
486 mem = float(v[1]) * self._scale[v[2]]
487 return mem / self._scale[unit]
489 def getUsedMemory(self, unit="o"):
490 "Renvoie la mémoire résidente utilisée en octets"
491 return self._VmB('VmRSS:', unit)
493 def getVirtualMemory(self, unit="o"):
494 "Renvoie la mémoire totale utilisée en octets"
495 return self._VmB('VmSize:', unit)
497 def getUsedStacksize(self, unit="o"):
498 "Renvoie la taille du stack utilisé en octets"
499 return self._VmB('VmStk:', unit)
501 def getMaxUsedMemory(self, unit="o"):
502 "Renvoie la mémoire résidente maximale mesurée"
503 return self._VmB('VmHWM:', unit)
505 def getMaxVirtualMemory(self, unit="o"):
506 "Renvoie la mémoire totale maximale mesurée"
507 return self._VmB('VmPeak:', unit)
509 # ==============================================================================
510 if __name__ == "__main__":
511 print('\n AUTODIAGNOSTIC\n')