Salome HOME
7f698e05adaa2e369aa19dfd03cc474e611ff310
[modules/adao.git] / src / daComposant / daCore / PlatformInfo.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2018 EDF R&D
4 #
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.
9 #
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.
14 #
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
18 #
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #
21 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
22
23 """
24     Informations sur le code et la plateforme, et mise à jour des chemins
25
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 :
30         print PlatformInfo()
31         print PlatformInfo().getVersion()
32         created = PlatformInfo().getDate()
33
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 :
37         PathManagement()
38
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
42     process.
43 """
44 __author__ = "Jean-Philippe ARGAUD"
45 __all__ = []
46
47 import os
48 import sys
49
50 # ==============================================================================
51 class PlatformInfo(object):
52     """
53     Rassemblement des informations sur le code et la plateforme
54     """
55     def __init__(self):
56         "Sans effet"
57         pass
58
59     def getName(self):
60         "Retourne le nom de l'application"
61         import daCore.version as dav
62         return dav.name
63
64     def getVersion(self):
65         "Retourne le numéro de la version"
66         import daCore.version as dav
67         return dav.version
68
69     def getDate(self):
70         "Retourne la date de création de la version"
71         import daCore.version as dav
72         return dav.date
73
74     def getPythonVersion(self):
75         "Retourne la version de python disponible"
76         return ".".join([str(x) for x in sys.version_info[0:3]]) # map(str,sys.version_info[0:3]))
77
78     def getNumpyVersion(self):
79         "Retourne la version de numpy disponible"
80         import numpy.version
81         return numpy.version.version
82
83     def getScipyVersion(self):
84         "Retourne la version de scipy disponible"
85         if has_scipy:
86             __version = scipy.version.version
87         else:
88             __version = "0.0.0"
89         return __version
90
91     def getMatplotlibVersion(self):
92         "Retourne la version de matplotlib disponible"
93         if has_matplotlib:
94             __version = matplotlib.__version__
95         else:
96             __version = "0.0.0"
97         return __version
98
99     def getGnuplotVersion(self):
100         "Retourne la version de gnuplotpy disponible"
101         if has_gnuplot:
102             __version = Gnuplot.__version__
103         else:
104             __version = "0.0"
105         return __version
106
107     def getSphinxVersion(self):
108         "Retourne la version de sphinx disponible"
109         if has_sphinx:
110             __version = sphinx.__version__
111         else:
112             __version = "0.0.0"
113         return __version
114
115     def getNloptVersion(self):
116         "Retourne la version de nlopt disponible"
117         if has_nlopt:
118             __version = "%s.%s.%s"%(
119                 nlopt.version_major(),
120                 nlopt.version_minor(),
121                 nlopt.version_bugfix(),
122                 )
123         else:
124             __version = "0.0.0"
125         return __version
126
127     def getCurrentMemorySize(self):
128         "Retourne la taille mémoire courante utilisée"
129         return 1
130
131     def MaximumPrecision(self):
132         "Retourne la precision maximale flottante pour Numpy"
133         import numpy
134         try:
135             numpy.array([1.,], dtype='float128')
136             mfp = 'float128'
137         except Exception:
138             mfp = 'float64'
139         return mfp
140
141     def MachinePrecision(self):
142         # Alternative sans module :
143         # eps = 2.38
144         # while eps > 0:
145         #     old_eps = eps
146         #     eps = (1.0 + eps/2) - 1.0
147         return sys.float_info.epsilon
148
149     def __str__(self):
150         import daCore.version as dav
151         return "%s %s (%s)"%(dav.name,dav.version,dav.date)
152
153 # ==============================================================================
154 try:
155     import scipy
156     import scipy.version
157     import scipy.optimize
158     has_scipy = True
159 except ImportError:
160     has_scipy = False
161
162 try:
163     import matplotlib
164     has_matplotlib = True
165 except ImportError:
166     has_matplotlib = False
167
168 try:
169     import Gnuplot
170     has_gnuplot = True
171 except ImportError:
172     has_gnuplot = False
173
174 try:
175     import sphinx
176     has_sphinx = True
177 except ImportError:
178     has_sphinx = False
179
180 try:
181     import nlopt
182     has_nlopt = True
183 except ImportError:
184     has_nlopt = False
185
186 has_salome = bool( "ROOT_SALOME"   in os.environ )
187 has_yacs   = bool( "YACS_ROOT_DIR" in os.environ )
188 has_adao   = bool( "ADAO_ROOT_DIR" in os.environ )
189
190 # ==============================================================================
191 def uniq(sequence):
192     """
193     Fonction pour rendre unique chaque élément d'une liste, en préservant l'ordre
194     """
195     __seen = set()
196     return [x for x in sequence if x not in __seen and not __seen.add(x)]
197
198 # ==============================================================================
199 class PathManagement(object):
200     """
201     Mise à jour du path système pour les répertoires d'outils
202     """
203     def __init__(self):
204         "Déclaration des répertoires statiques"
205         parent = os.path.abspath(os.path.join(os.path.dirname(__file__),".."))
206         self.__paths = {}
207         self.__paths["daExternals"] = os.path.join(parent,"daExternals")
208         self.__paths["daMatrices"]  = os.path.join(parent,"daMatrices")
209         self.__paths["daNumerics"]  = os.path.join(parent,"daNumerics")
210         #
211         for v in self.__paths.values():
212             sys.path.insert(0, v )
213         #
214         # Conserve en unique exemplaire chaque chemin
215         sys.path = uniq( sys.path )
216         del parent
217
218     def getpaths(self):
219         """
220         Renvoie le dictionnaire des chemins ajoutés
221         """
222         return self.__paths
223
224 # ==============================================================================
225 class SystemUsage(object):
226     """
227     Permet de récupérer les différentes tailles mémoires du process courant
228     """
229     #
230     # Le module resource renvoie 0 pour les tailles mémoire. On utilise donc
231     # plutôt : http://code.activestate.com/recipes/286222/ et Wikipedia
232     #
233     _proc_status = '/proc/%d/status' % os.getpid()
234     _memo_status = '/proc/meminfo'
235     _scale = {
236         'o'  : 1.0,     # Multiples SI de l'octet
237         'ko' : 1.e3,
238         'Mo' : 1.e6,
239         'Go' : 1.e9,
240         'kio': 1024.0,  # Multiples binaires de l'octet
241         'Mio': 1024.0*1024.0,
242         'Gio': 1024.0*1024.0*1024.0,
243         'B':     1.0,   # Multiples binaires du byte=octet
244         'kB' : 1024.0,
245         'MB' : 1024.0*1024.0,
246         'GB' : 1024.0*1024.0*1024.0,
247         }
248     #
249     def __init__(self):
250         "Sans effet"
251         pass
252     #
253     def _VmA(self, VmKey, unit):
254         "Lecture des paramètres mémoire de la machine"
255         try:
256             t = open(self._memo_status)
257             v = t.read()
258             t.close()
259         except IOError:
260             return 0.0           # non-Linux?
261         i = v.index(VmKey)       # get VmKey line e.g. 'VmRSS:  9999  kB\n ...'
262         v = v[i:].split(None, 3) # whitespace
263         if len(v) < 3:
264             return 0.0           # invalid format?
265         # convert Vm value to bytes
266         mem = float(v[1]) * self._scale[v[2]]
267         return mem / self._scale[unit]
268     #
269     def getAvailablePhysicalMemory(self, unit="o"):
270         "Renvoie la mémoire physique utilisable en octets"
271         return self._VmA('MemTotal:', unit)
272     #
273     def getAvailableSwapMemory(self, unit="o"):
274         "Renvoie la mémoire swap utilisable en octets"
275         return self._VmA('SwapTotal:', unit)
276     #
277     def getAvailableMemory(self, unit="o"):
278         "Renvoie la mémoire totale (physique+swap) utilisable en octets"
279         return self._VmA('MemTotal:', unit) + self._VmA('SwapTotal:', unit)
280     #
281     def getUsableMemory(self, unit="o"):
282         """Renvoie la mémoire utilisable en octets
283         Rq : il n'est pas sûr que ce décompte soit juste...
284         """
285         return self._VmA('MemFree:', unit) + self._VmA('SwapFree:', unit) + \
286                self._VmA('Cached:', unit) + self._VmA('SwapCached:', unit)
287     #
288     def _VmB(self, VmKey, unit):
289         "Lecture des paramètres mémoire du processus"
290         try:
291             t = open(self._proc_status)
292             v = t.read()
293             t.close()
294         except IOError:
295             return 0.0           # non-Linux?
296         i = v.index(VmKey)       # get VmKey line e.g. 'VmRSS:  9999  kB\n ...'
297         v = v[i:].split(None, 3) # whitespace
298         if len(v) < 3:
299             return 0.0           # invalid format?
300         # convert Vm value to bytes
301         mem = float(v[1]) * self._scale[v[2]]
302         return mem / self._scale[unit]
303     #
304     def getUsedMemory(self, unit="o"):
305         "Renvoie la mémoire résidente utilisée en octets"
306         return self._VmB('VmRSS:', unit)
307     #
308     def getVirtualMemory(self, unit="o"):
309         "Renvoie la mémoire totale utilisée en octets"
310         return self._VmB('VmSize:', unit)
311     #
312     def getUsedStacksize(self, unit="o"):
313         "Renvoie la taille du stack utilisé en octets"
314         return self._VmB('VmStk:', unit)
315     #
316     def getMaxUsedMemory(self, unit="o"):
317         "Renvoie la mémoire résidente maximale mesurée"
318         return self._VmB('VmHWM:', unit)
319     #
320     def getMaxVirtualMemory(self, unit="o"):
321         "Renvoie la mémoire totale maximale mesurée"
322         return self._VmB('VmPeak:', unit)
323
324 # ==============================================================================
325 if __name__ == "__main__":
326     print('\n AUTODIAGNOSTIC \n')