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