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