-
Notifications
You must be signed in to change notification settings - Fork 0
/
general.py
424 lines (322 loc) · 10.6 KB
/
general.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Author: Eleftherios Garyfallidis
Description: General Usage Python functions e.g. for exception handling, system information etc.
'''
import sys
import traceback
import platform
import time
import array
import os
def timing(f, n, a):
'''
Time a function f with argument a n times
'''
print f.__name__,
r = range(n)
t1 = time.clock()
for i in r:
f(a); f(a); f(a); f(a); f(a); f(a); f(a); f(a); f(a); f(a)
t2 = time.clock()
print round(t2-t1, 3)
def exceptinfo(maxTBlevel=5):
cla, exc, trbk = sys.exc_info()
excName = cla.__name__
try:
excArgs = exc.__dict__["args"]
except KeyError:
excArgs = "<no args>"
excTb = traceback.format_tb(trbk, maxTBlevel)
return (excName, excArgs, excTb)
def systeminfo():
arch=platform.architecture()
release=platform.release()
uname=platform.uname()
plat=sys.platform
pyversion=sys.version.split(' ')[0]
#print(sys.getwindowsversion())
info='This is a '+arch[0]+' '+uname[0]+' os.'
if uname[0]=='Linux':
info2='Exact os version is ' + uname[2]+ '.'
else:
info2='Exact os version is ' + uname[2] +' '+ uname[3]+'.'
info3='The name of this computer is ' + uname[1]+'.'
info4='The version of Python is '+pyversion+'.\n'
print(info)
print(info2)
print(info3)
print(info4)
if uname[0]=='Windows':
try:
from ctypes.wintypes import windll
class MEMORYSTATUS(Structure):
_fields_ = [
('dwLength', DWORD),
('dwMemoryLoad', DWORD),
('dwTotalPhys', DWORD),
('dwAvailPhys', DWORD),
('dwTotalPageFile', DWORD),
('dwAvailPageFile', DWORD),
('dwTotalVirtual', DWORD),
('dwAvailVirtual', DWORD),
]
x = MEMORYSTATUS()
windll.kernel32.GlobalMemoryStatus(byref(x))
print('%d MB physical RAM left.' % (x.dwAvailPhys/1024**2))
print('%d MB physical RAM in total.' % (x.dwTotalPhys/1024**2))
print('%d MB total virtual memory.' % (x.dwTotalVirtual/1024**2))
except:
print('Ctypes.wintypes module is not installed.')
if uname[0]=='Linux':
import re
re_meminfo_parser = re.compile(r'^(?P<key>\S*):\s*(?P<value>\d*)\s*kB')
result = dict()
for line in open('/proc/meminfo'):
match = re_meminfo_parser.match(line)
if not match:
continue # skip lines that don't parse
key, value = match.groups(['key', 'value'])
result[key] = int(value)
print('The system has %d MB total memory.' %(result['MemTotal']/1024))
'''
for cpu usage see /proc/stat
for loadvg see /proc/loadavg
'''
def number_of_processors():
''' number of virtual processors on the computer '''
# Windows
if os.name == 'nt':
return int(os.getenv('NUMBER_OF_PROCESSORS'))
# Linux
elif sys.platform == 'linux2':
retv = 0
with open('/proc/cpuinfo','rt') as cpuinfo:
for line in cpuinfo:
if line[:9] == 'processor': retv += 1
return retv
# Please add similar hacks for MacOSX, Solaris, Irix,
# FreeBSD, HPUX, etc.
else:
raise RuntimeError, 'unknown platform'
def listint2str(list):
'''
The fastest way to convert a list of integers into a string, presuming that the integers are ASCII values.
http://www.python.org/doc/essays/list2str.html
'''
return array.array('B',list).tostring()
def str2listint(string):
'''
The fastest way to create a list of integer ASCII values from a string
http://www.python.org/doc/essays/list2str.html
'''
return array.array('b',string).tolist()
def usingswig():
'''
nano example.c
nano example.i
swig -python example.i
gcc -c example.c example_wrap.c -I/usr/include/python2.6 -fPIC
ld -shared example.o example_wrap.o -o _example.so
/* File : example.c from www.swig.org/tutorial.html*/
#include <time.h>
double My_variable = 3.0;
int fact(int n) {
if (n <= 1) return 1;
else return n*fact(n-1);
}
int my_mod(int x, int y) {
return (x%y);
}
char *get_time()
{
time_t ltime;
time(<ime);
return ctime(<ime);
}
'''
def loadsharedobjectexample():
'''
Example of how to compile with g++ and load a shared library in python
Lets assume that we have the following fibonacci.c file
Then compile it using g++ -o fib.so -shared fibonacci.c -fPIC
This example is similar to http://www.scipy.org/Cookbook/Ctypes with some
changes to play with scipy rather than numpy.
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
typedef struct Weather_t {
int timestamp;
char desc[12];
} Weather;
typedef void*(*allocator_t)(int, int*);
/* Function prototypes */
int fib(int a);
void fibseries(int *a, int elements, int *series);
void fibmatrix(int *a, int rows, int columns, int *matrix);
void fibmatrix2(float** data, int len);
void fibmatrix3(float** data, int rows, int columns);
void foo(allocator_t allocator);
void print_weather(Weather* w, int nelems);
int fib(int a)
{
if (a <= 0) /* Error -- wrong input will return -1. */
return -1;
else if (a==1)
return 0;
else if ((a==2)||(a==3))
return 1;
else
return fib(a - 2) + fib(a - 1);
}
void fibseries(int *a, int elements, int *series)
{
int i;
for (i=0; i < elements; i++)
{
series[i] = fib(a[i]);
}
}
void fibmatrix(int *a, int rows, int columns, int *matrix)
{
int i, j;
for (i=0; i<rows; i++)
for (j=0; j<columns; j++)
{
matrix[i * columns + j] = fib(a[i * columns + j]);
}
}
void fibmatrix2(float** data, int len) {
float** x = data;
for (int i = 0; i < len; i++, x++) {
/* do something with *x */
}
}
void fibmatrix3(float** data, int rows, int columns) {
float** x = data;
//for (int i = 0; i < len; i++, x++) {
/* do something with *x */
for (int i=0; i<rows; i++)
for (int j=0; j<columns; j++)
{
x[i][j]=0;
}
}
void foo(allocator_t allocator) {
int dim = 2;
int shape[] = {2, 3};
float* data = NULL;
int i, j;
printf("foo calling allocator\n");
data = (float*) allocator(dim, shape);
printf("allocator returned in foo\n");
printf("data = 0x%p\n", data);
for (i = 0; i < shape[0]; i++) {
for (j = 0; j < shape[1]; j++) {
*data++ = (i + 1) * (j + 1);
}
}
}
void print_weather(Weather* w, int nelems)
{
int i;
for (i=0;i<nelems;++i) {
printf("timestamp: %d\ndescription: %s\n\n", w[i].timestamp, w[i].desc);
}
}
#ifdef __cplusplus
}
#endif
'''
import ctypes as ct
import scipy as sp
#name and directory of the shared lib
lib = sp.ctypeslib.load_library('fib', '/home/eg01/Devel/BirchLGB/birch_py')
#dealing with fib
lib.fib.argtypes=[ct.c_int]
lib.fib.restype=ct.c_int
a=20
print 'The '+str(a) +' fibonacci number is :'
print lib.fib(int(a))
#dealing with fibseries
lib.fibseries.argtypes = [sp.ctypeslib.ndpointer(dtype = sp.intc), ct.c_int, sp.ctypeslib.ndpointer(dtype = sp.intc)]
lib.fibseries.restype = ct.c_void_p
b=[1,2,3,4,5,6,7,8,9]
b = sp.asarray(b, dtype=sp.intc)
result = sp.empty(len(b), dtype=sp.intc)
lib.fibseries(b, len(b), result)
print 'Series ',result
#dealing with fibmatrix
lib.fibmatrix.argtypes = [sp.ctypeslib.ndpointer(dtype = sp.intc),ct.c_int,ct.c_int,sp.ctypeslib.ndpointer(dtype = sp.intc)]
lib.fibmatrix.restype= ct.c_void_p
A=sp.array([[1,2,3],[4,5,6],[7,8,9]])
rows=A.shape[0]
cols=A.shape[1]
A=sp.asarray(A,dtype=sp.intc)
Mat=sp.empty_like(A)
lib.fibmatrix(A,int(rows),int(cols),Mat)
print 'Matrix'
print Mat.reshape(rows,cols)
#dealing with double pointers
'''
x = sp.array([[1,2,3], [4,5,6], [7,8,9]], 'i4')
i4ptr = ct.POINTER(ct.c_int)
D = (i4ptr*len(x))(*[row.ctypes.data_as(i4ptr) for row in x])
print D
'''
#dealing with structures
dat = [[1126877361,'sunny'], [1126877371,'rain'], [1126877385,'damn nasty'], [1126877387,'sunny']]
dat_dtype = sp.dtype([('timestamp','i4'),('desc','|S12')])
arr = sp.rec.fromrecords(dat,dtype=dat_dtype)
lib.print_weather.restype = None
lib.print_weather.argtypes = [sp.ctypeslib.ndpointer(dat_dtype, flags='aligned, contiguous'), ct.c_int]
lib.print_weather(arr, arr.size)
print arr
'''
void foo(float** data, int len) {
float** x = data;
for (int i = 0; i < len; i++, x++) {
/* do something with *x */
}
}
You can create the necessary structure from an existing 2-D NumPy array using the following code:
Toggle line numbers
x = N.array([[10,20,30], [40,50,60], [80,90,100]], 'f4')
f4ptr = POINTER(c_float)
data = (f4ptr*len(x))(*[row.ctypes.data_as(f4ptr) for row in x])
'''
#dealing with function pointers
'''
allocated_arrays = []
def allocate(dim, shape):
print 'allocate called'
x = N.zeros(shape[:dim], 'f4')
allocated_arrays.append(x)
ptr = x.ctypes.data_as(ct.c_void_p).value
print hex(ptr)
print 'allocate returning'
return ptr
ALLOCATOR = ct.CFUNCTYPE(ct.c_long, ct.c_int, ct.POINTER(ct.c_int))
lib.foo.argtypes = [ALLOCATOR]
lib.foo.restype = ct.c_void_p
print 'calling foo'
lib.foo(ALLOCATOR(allocate))
print 'foo returned'
print allocated_arrays[0]
'''
return
if __name__ == "__main__":
try:
x = x + 1
except:
print exceptinfo()
'''
try:
x=x+1
except:
print sys.exc_type #non thread_safe
print sys.exc_value #non thread_safe
print sys.exc_info() #thread_safe
'''