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
197 has_salome = bool( "ROOT_SALOME" in os.environ )
198 has_yacs = bool( "YACS_ROOT_DIR" in os.environ )
199 has_adao = bool( "ADAO_ROOT_DIR" in os.environ )
200 has_eficas = bool( "EFICAS_ROOT_DIR" in os.environ )
202 # ==============================================================================
203 def uniq(__sequence):
205 Fonction pour rendre unique chaque élément d'une liste, en préservant l'ordre
208 return [x for x in __sequence if x not in __seen and not __seen.add(x)]
210 def date2int(__date, __lang="FR"):
212 Fonction de secours, conversion pure : dd/mm/yy hh:mm ---> int(yyyymmddhhmm)
214 __date = __date.strip()
215 if __date.count('/') == 2 and __date.count(':') == 0 and __date.count(' ') == 0:
216 d,m,y = __date.split("/")
217 __number = (10**4)*int(y)+(10**2)*int(m)+int(d)
218 elif __date.count('/') == 2 and __date.count(':') == 1 and __date.count(' ') > 0:
219 part1, part2 = __date.split()
220 d,m,y = part1.strip().split("/")
221 h,n = part2.strip().split(":")
222 __number = (10**8)*int(y)+(10**6)*int(m)+(10**4)*int(d)+(10**2)*int(h)+int(n)
224 raise ValueError("Cannot convert \"%s\" as a D/M/Y H:M date"%d)
227 # ==============================================================================
228 class PathManagement(object):
230 Mise à jour du path système pour les répertoires d'outils
233 "Déclaration des répertoires statiques"
234 parent = os.path.abspath(os.path.join(os.path.dirname(__file__),".."))
236 self.__paths["daNumerics"] = os.path.join(parent,"daNumerics")
238 for v in self.__paths.values():
239 sys.path.insert(0, v )
241 # Conserve en unique exemplaire chaque chemin
242 sys.path = uniq( sys.path )
247 Renvoie le dictionnaire des chemins ajoutés
251 # ==============================================================================
252 class SystemUsage(object):
254 Permet de récupérer les différentes tailles mémoires du process courant
257 # Le module resource renvoie 0 pour les tailles mémoire. On utilise donc
258 # plutôt : http://code.activestate.com/recipes/286222/ et Wikipedia
260 _proc_status = '/proc/%d/status' % os.getpid()
261 _memo_status = '/proc/meminfo'
263 'o' : 1.0, # Multiples SI de l'octet
267 'kio': 1024.0, # Multiples binaires de l'octet
268 'Mio': 1024.0*1024.0,
269 'Gio': 1024.0*1024.0*1024.0,
270 'B': 1.0, # Multiples binaires du byte=octet
272 'MB' : 1024.0*1024.0,
273 'GB' : 1024.0*1024.0*1024.0,
280 def _VmA(self, VmKey, unit):
281 "Lecture des paramètres mémoire de la machine"
283 t = open(self._memo_status)
287 return 0.0 # non-Linux?
288 i = v.index(VmKey) # get VmKey line e.g. 'VmRSS: 9999 kB\n ...'
289 v = v[i:].split(None, 3) # whitespace
291 return 0.0 # invalid format?
292 # convert Vm value to bytes
293 mem = float(v[1]) * self._scale[v[2]]
294 return mem / self._scale[unit]
296 def getAvailablePhysicalMemory(self, unit="o"):
297 "Renvoie la mémoire physique utilisable en octets"
298 return self._VmA('MemTotal:', unit)
300 def getAvailableSwapMemory(self, unit="o"):
301 "Renvoie la mémoire swap utilisable en octets"
302 return self._VmA('SwapTotal:', unit)
304 def getAvailableMemory(self, unit="o"):
305 "Renvoie la mémoire totale (physique+swap) utilisable en octets"
306 return self._VmA('MemTotal:', unit) + self._VmA('SwapTotal:', unit)
308 def getUsableMemory(self, unit="o"):
309 """Renvoie la mémoire utilisable en octets
310 Rq : il n'est pas sûr que ce décompte soit juste...
312 return self._VmA('MemFree:', unit) + self._VmA('SwapFree:', unit) + \
313 self._VmA('Cached:', unit) + self._VmA('SwapCached:', unit)
315 def _VmB(self, VmKey, unit):
316 "Lecture des paramètres mémoire du processus"
318 t = open(self._proc_status)
322 return 0.0 # non-Linux?
323 i = v.index(VmKey) # get VmKey line e.g. 'VmRSS: 9999 kB\n ...'
324 v = v[i:].split(None, 3) # whitespace
326 return 0.0 # invalid format?
327 # convert Vm value to bytes
328 mem = float(v[1]) * self._scale[v[2]]
329 return mem / self._scale[unit]
331 def getUsedMemory(self, unit="o"):
332 "Renvoie la mémoire résidente utilisée en octets"
333 return self._VmB('VmRSS:', unit)
335 def getVirtualMemory(self, unit="o"):
336 "Renvoie la mémoire totale utilisée en octets"
337 return self._VmB('VmSize:', unit)
339 def getUsedStacksize(self, unit="o"):
340 "Renvoie la taille du stack utilisé en octets"
341 return self._VmB('VmStk:', unit)
343 def getMaxUsedMemory(self, unit="o"):
344 "Renvoie la mémoire résidente maximale mesurée"
345 return self._VmB('VmHWM:', unit)
347 def getMaxVirtualMemory(self, unit="o"):
348 "Renvoie la mémoire totale maximale mesurée"
349 return self._VmB('VmPeak:', unit)
351 # ==============================================================================
352 if __name__ == "__main__":
353 print('\n AUTODIAGNOSTIC \n')