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