[Numpy-discussion] "aligned" matrix / ctypes
Zachary Pincus
zachary.pincus at yale.edu
Fri Apr 25 12:09:55 EDT 2008
Hello all,
Attached is code (plus tests) for allocating aligned arrays -- I think
this addresses all the requests in this thread, with regard to
allowing for different kinds of alignment. Thanks Robert and Anne for
your help and suggestions. Hopefully this will be useful.
The core is a function for allocating arrays with totally arbitrary
alignment along each dimension (e.g. you could allocate an 10x20 array
of uint16's where each uint16 is aligned to 4-byte boundaries and each
row of 20 uint16's is aligned to 32-byte boundaries, and the entire
buffer is aligned to a 128-byte boundary.) I've also included helper
functions for two common cases: when you want everything aligned to a
particular multiple (every element, row, etc. as well as the whole
buffer), and when you want an array where the rows (second-fastest
moving index) are so aligned (this was my original use case, for fast
image-blitting).
Zach
def aligned_empty(shape, dtype, dim_alignments, array_alignment):
'''Allocate an empty array with the given shape and dtype, where
the array
buffer starts at a memory address evenly-divisible by
array_alignment, and
where items along each dimension are offset from the first item on
that
dimension by a byte offset that is an integer multiple of the
corresponding
value in the dim_alignments tuple.
Example: To allocate a 20x30 array of floats32s, where individual
data
elements are aligned to 16-bute boundaries, each row is aligned to
a 64-byte
boundary, and the array's buffer starts on a 128-byte boundary, call:
aligned_empty((20,30), numpy.float32, (64, 16), 128)
'''
def aligned_rows_empty(shape, dtype, alignment, order='C'):
'''Return an array where the rows (second-fastest-moving index) are
aligned
to byte boundaries evenly-divisible by 'alignment'. If 'order' is
'C', then
the indexing is such that the fastest-moving index is the last one;
if the
order is 'F', then the fastest-moving index is the first.'''
def aligned_elements_empty(shape, dtype, alignment, order='C'):
'''Return an array where each element is aligned to byte boundaries
evenly-
divisible by 'alignment'.'''
-------------- next part --------------
A non-text attachment was scrubbed...
Name: aligned_allocator.py
Type: text/x-python-script
Size: 4449 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20080425/6cbef197/attachment.bin>
-------------- next part --------------
More information about the NumPy-Discussion
mailing list