Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo

Close

[f02bc8]: PDSim / misc / datatypes.pyx Maximize Restore History

Download this file

datatypes.pyx    458 lines (393 with data), 15.3 kB

  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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
import cython
cimport cython
import numpy as np
cimport numpy as np
cimport cpython.array
from libc.stdlib cimport calloc, free, realloc
from libc.string cimport memcpy
from cpython cimport bool
cimport cython
@cython.final
cdef class arraym(object):
def __init__(self, data = None):
"""
data : list, array.array, numpy array, etc.
Notes
-----
If a numpy array is provided, the numpy buffer is used internally to access the data
Otherwise, as long as the iterable contains floating point values it should work
"""
cdef int i
cdef double el
cdef np.ndarray[np.float_t, ndim = 1] npdata
if data is not None:
self.N = len(data)
#Allocate the memory for the array that will be used internally
self.data = <double *> calloc(self.N, sizeof(double))
#If it is already an arraym instance, do a low-level copy of the data
if isinstance(data,arraym):
memcpy(self.data,(<arraym>data).data,self.N*sizeof(double))
#If a numpy array use the buffering interface
elif isinstance(data, np.ndarray):
npdata = data
for i in range(self.N):
self.data[i] = npdata[i]
else:
#Now it must either be an iterable or a failure
try:
for i,el in enumerate(data):
self.data[i] = el
except TypeError:
raise TypeError("Sorry but you provided a type to arraym that doesn't work. Good types are arraym, numpy arrays, or any iterable.")
else:
self.data = NULL
def __cinit__(self):
self.N = 0
self.data = NULL
cpdef set_size(self, int N):
"""
Set the size of the internal array, initialized to zeros
"""
#If a zero or negative length passed in, don't allocate memory, but set length flag
if N <= 0:
self.N = 0
return
if self.data == NULL:
#Allocate the memory for the array that will be used internally
self.data = <double *> calloc(N, sizeof(double))
self.N = N
cdef void set_data(self, double *data, int N):
if self.data == NULL:
#Allocate the memory for the array that will be used internally
self.data = <double *> calloc(N, sizeof(double))
self.N = N
elif not self.N == N:
raise ValueError('Memory already allocated for arraym, but sizes of arraym ('+str(self.N)+') and data ('+str(N)+') do not match')
memcpy(self.data,data,N*sizeof(double))
cpdef dealloc(self):
#Clean up the memory we allocated
if not self.data == NULL:
free(self.data)
self.data = NULL
self.N = 0
def __dealloc__(self):
#Clean up the memory we allocated
if not self.data == NULL:
free(self.data)
self.data = NULL
self.N = 0
def __add__(x, y):
cdef int i, N
cdef bint isarray_x, isarray_y
cdef double *zdata,*ydata
cdef double yd
cdef arraym z
isarray_x = isinstance(x, arraym)
isarray_y = isinstance(y, arraym)
if isarray_x & isarray_y:
check_dims(x, y)
N = (<arraym>x).N
z = (<arraym>x).copy()
zdata = z.data
ydata = (<arraym>y).data
# Add on the other array values
for i in range(N):
zdata[i] += ydata[i]
elif isarray_x != isarray_y:
if isarray_y:
x,y = y,x
N = (<arraym>x).N
z = (<arraym>x).copy()
zdata = (<arraym>z).data
try:
#Try to make an iterator out of y
iterator = iter(y)
except TypeError:
# not iterable - int, float, etc.
# Cast y to a double
yd = (<double>y)
# Add on the other array values
for i in range(N):
zdata[i] += yd
else:
# iterable - list, tuple, numpy array, etc.
for i in range(N):
zdata[i] += y[i]
return z
def __mul__(x, y):
cdef int i, N
cdef bint isarray_x, isarray_y
cdef double *zdata,*ydata
cdef double yd
cdef arraym z
isarray_x = isinstance(x, arraym)
isarray_y = isinstance(y, arraym)
if isarray_x & isarray_y:
check_dims(x, y)
N = (<arraym>x).N
z = (<arraym>x).copy()
zdata = (<arraym>z).data
ydata = (<arraym>y).data
for i in range(N):
zdata[i] *= ydata[i]
elif isarray_x != isarray_y:
if isarray_y:
x,y = y,x
N = (<arraym>x).N
z = (<arraym>x).copy()
zdata = (<arraym>z).data
try:
#Try to make an iterator out of y
iterator = iter(y)
except TypeError:
# not iterable - int, float, etc.
# Cast to a double
yd = (<double>y)
# Multiply by the other value
for i in range(N):
zdata[i] *= yd
else:
# iterable - list, tuple, numpy array, etc.
#No type introspection possible
for i in range(N):
zdata[i] *= y[i]
return z
def __truediv__(x, y):
cdef int i, N
cdef bint isarray_x, isarray_y
cdef double *zdata, *ydata
cdef double yd,xd
cdef arraym z
isarray_x = isinstance(x, arraym)
isarray_y = isinstance(y, arraym)
#Both x and y are arraym instances
if isarray_x & isarray_y:
check_dims(x, y)
N = (<arraym>x).N
z = (<arraym>x).copy()
zdata = (<arraym>z).data
ydata = (<arraym>y).data
# Add on the other array values
for i in range(N):
zdata[i] /= ydata[i]
#One of x and y is an arraym
elif isarray_x != isarray_y:
if isarray_y:
N = (<arraym>y).N
z = (<arraym>y).copy()
zdata = (<arraym>z).data
if isinstance(x,(int,float)):
# Cast lhs to a double and rhs to a double*
xd = (<double>x)
ydata = (<arraym>y).data
# Add on the other array values
for i in range(N):
zdata[i] = xd/ydata[i]
else:
#Hopefully it is an iterable
for i in range(len(x)):
z[i] = x[i]/y[i]
else:
N = (<arraym>x).N
z = (<arraym>x).copy()
zdata = (<arraym>z).data
if isinstance(y,(int,float)):
# Cast rhs to a double
yd = <double> y
# Add on the other array values
for i in range(N):
zdata[i] /= yd
else:
#Hopefully it is an iterable
for i in range(len(x)):
z[i] = x[i]/y[i]
return z
def __sub__(x, y):
cdef int i, N
cdef bint isarray_x, isarray_y
cdef double *zdata, *ydata
cdef double yd,xd
cdef arraym z
isarray_x = isinstance(x, arraym)
isarray_y = isinstance(y, arraym)
if isarray_x & isarray_y:
check_dims(x, y)
N = (<arraym>x).N
z = (<arraym>x).copy()
zdata = (<arraym>z).data
ydata = (<arraym>y).data
# Add on the other array values
for i in range(N):
zdata[i] -= ydata[i]
#One of x and y is an arraym
elif isarray_x != isarray_y:
if isarray_y:
N = (<arraym>y).N
z = (<arraym>y).copy()
zdata = (<arraym>z).data
if isinstance(x,(int,float)):
# Cast lhs to a double and rhs to a double*
xd = (<double>x)
ydata = (<arraym>y).data
# Add on the other array values
for i in range(N):
zdata[i] = xd - ydata[i]
else:
#Hopefully it is an iterable
for i in range(len(x)):
z[i] = x[i] - y[i]
else:
N = (<arraym>x).N
z = (<arraym>x).copy()
zdata = (<arraym>z).data
if isinstance(y,(int,float)):
# Cast rhs to a double
yd = <double> y
# Add on the other array values
for i in range(N):
zdata[i] -= yd
else:
#Hopefully it is an iterable
for i in range(len(x)):
z[i] = x[i] - y[i]
return z
cpdef arraym copy(self):
cdef arraym arr = arraym.__new__(arraym)
arr.set_data(self.data, self.N)
return arr
def __setitem__(self,int i, double y):
self.data[i]=y
@cython.returns(double)
def __getitem__(self, int i):
return self.data[i]
cdef arraym slice(self, int i, int j):
cdef int k
cdef arraym arr = arraym()
if j < i:
raise IndexError('Indices must be increasing')
if j == i:
raise IndexError('Length of slice must be greater than 1')
if j > self.N:
raise IndexError('End of slice out of bounds. Length of arraym is '+str(self.N)+' requested end is '+str(j))
arr.set_size(j-i)
memcpy(arr.data,self.data+i,(j-i)*sizeof(double))
return arr
cpdef extend(self, arraym array2):
cdef double* new_data
cdef int N = array2.N + self.N
#Only extend if there is something in the extension array
if N > self.N:
#Reallocate the array to extend its length
new_data = <double*>realloc(self.data, N*sizeof(double))
#Copy into the new array
memcpy(new_data+self.N, array2.data, array2.N*sizeof(double))
#Free the old array
free(self.data)
#Make self.data point to the newly allocated array
self.data = new_data
#Set the length
self.N = N
def __getslice__(self, Py_ssize_t i, Py_ssize_t j):
return self.slice(i,j)
def __iter__(self):
for i in range(self.N):
yield float(self.data[i])
def __repr__(self):
return str(list(self))
def __len__(self):
return self.N
cpdef arraym empty_arraym(int N):
"""
A convenience function to return an arraym with the given size initialized to zero
Parameters
----------
N: int
Size of the arraym to return initialized to zero
"""
cdef arraym arr = arraym()
arr.set_size(N)
return arr
###############################################################################
###############################################################################
## LISTM - Enhanced list with element-wise operators ##
###############################################################################
###############################################################################
cdef class listm(list):
"""
See http://docs.cython.org/src/userguide/special_methods.html
"""
def __add__(self,y):
cdef int i,N
cdef bool isarray_x,isarray_y
isarray_x = isinstance(self,listm)
isarray_y = isinstance(y,listm)
if isinstance(self,listm):
N=len(self)
if isinstance(y,int) or isinstance(y,float):
return listm([self[i]*y for i in range(N)])
else:
return listm([self[i]*y[i] for i in range(N)])
else:
### it is backwards, self is something else, y is a listm
N=len(y)
if isinstance(self,(int,float)) and not isinstance(y,(int,float)):
self,y = y,self
return listm([y[i]+self for i in range(N)])
else:
return listm([self[i]+y[i] for i in range(N)])
def __mul__(self,y):
cdef int i,N
if isinstance(self,listm):
N=len(self)
if isinstance(y,int) or isinstance(y,float):
return listm([self[i]*y for i in range(N)])
else:
return listm([self[i]*y[i] for i in range(N)])
else:
### it is backwards, self is something else, y is a listm
N=len(y)
if isinstance(self,int) or isinstance(self,float):
return listm([y[i]*self for i in range(N)])
else:
return listm([self[i]*y[i] for i in range(N)])
def __truediv__(self,y):
cdef int i,N
if isinstance(self,listm):
N=len(self)
if isinstance(y,int) or isinstance(y,float):
return listm([self[i]/y for i in range(N)])
else:
return listm([self[i]/y[i] for i in range(N)])
else:
### it is backwards, self is something else, y is a listm
N=len(y)
if isinstance(self,int) or isinstance(self,float):
return listm([self/y[i] for i in range(N)])
else:
return listm([self[i]/y[i] for i in range(N)])
def __sub__(self,y):
cdef int i,N
if isinstance(self,listm):
N=len(self)
if isinstance(y,int) or isinstance(y,float):
return listm([self[i]-y for i in range(N)])
else:
return listm([self[i]-y[i] for i in range(N)])
else:
### it is backwards, self is something else, y is a listm
N=len(y)
if isinstance(self,int) or isinstance(self,float):
return listm([self-y[i] for i in range(N)])
else:
return listm([self[i]-y[i] for i in range(N)])
def __reduce__(self):
d={}
d['data']=list(self)
return rebuildListm,(d,)
def copy(self):
"""
Return a copy of the listm instance
"""
return listm(self[:])
def rebuildListm(d):
return listm(d['data'])