internals.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. """
  2. ===============
  3. Array Internals
  4. ===============
  5. Internal organization of numpy arrays
  6. =====================================
  7. It helps to understand a bit about how numpy arrays are handled under the covers to help understand numpy better. This section will not go into great detail. Those wishing to understand the full details are referred to Travis Oliphant's book "Guide to NumPy".
  8. NumPy arrays consist of two major components, the raw array data (from now on,
  9. referred to as the data buffer), and the information about the raw array data.
  10. The data buffer is typically what people think of as arrays in C or Fortran,
  11. a contiguous (and fixed) block of memory containing fixed sized data items.
  12. NumPy also contains a significant set of data that describes how to interpret
  13. the data in the data buffer. This extra information contains (among other things):
  14. 1) The basic data element's size in bytes
  15. 2) The start of the data within the data buffer (an offset relative to the
  16. beginning of the data buffer).
  17. 3) The number of dimensions and the size of each dimension
  18. 4) The separation between elements for each dimension (the 'stride'). This
  19. does not have to be a multiple of the element size
  20. 5) The byte order of the data (which may not be the native byte order)
  21. 6) Whether the buffer is read-only
  22. 7) Information (via the dtype object) about the interpretation of the basic
  23. data element. The basic data element may be as simple as a int or a float,
  24. or it may be a compound object (e.g., struct-like), a fixed character field,
  25. or Python object pointers.
  26. 8) Whether the array is to interpreted as C-order or Fortran-order.
  27. This arrangement allow for very flexible use of arrays. One thing that it allows
  28. is simple changes of the metadata to change the interpretation of the array buffer.
  29. Changing the byteorder of the array is a simple change involving no rearrangement
  30. of the data. The shape of the array can be changed very easily without changing
  31. anything in the data buffer or any data copying at all
  32. Among other things that are made possible is one can create a new array metadata
  33. object that uses the same data buffer
  34. to create a new view of that data buffer that has a different interpretation
  35. of the buffer (e.g., different shape, offset, byte order, strides, etc) but
  36. shares the same data bytes. Many operations in numpy do just this such as
  37. slices. Other operations, such as transpose, don't move data elements
  38. around in the array, but rather change the information about the shape and strides so that the indexing of the array changes, but the data in the doesn't move.
  39. Typically these new versions of the array metadata but the same data buffer are
  40. new 'views' into the data buffer. There is a different ndarray object, but it
  41. uses the same data buffer. This is why it is necessary to force copies through
  42. use of the .copy() method if one really wants to make a new and independent
  43. copy of the data buffer.
  44. New views into arrays mean the object reference counts for the data buffer
  45. increase. Simply doing away with the original array object will not remove the
  46. data buffer if other views of it still exist.
  47. Multidimensional Array Indexing Order Issues
  48. ============================================
  49. What is the right way to index
  50. multi-dimensional arrays? Before you jump to conclusions about the one and
  51. true way to index multi-dimensional arrays, it pays to understand why this is
  52. a confusing issue. This section will try to explain in detail how numpy
  53. indexing works and why we adopt the convention we do for images, and when it
  54. may be appropriate to adopt other conventions.
  55. The first thing to understand is
  56. that there are two conflicting conventions for indexing 2-dimensional arrays.
  57. Matrix notation uses the first index to indicate which row is being selected and
  58. the second index to indicate which column is selected. This is opposite the
  59. geometrically oriented-convention for images where people generally think the
  60. first index represents x position (i.e., column) and the second represents y
  61. position (i.e., row). This alone is the source of much confusion;
  62. matrix-oriented users and image-oriented users expect two different things with
  63. regard to indexing.
  64. The second issue to understand is how indices correspond
  65. to the order the array is stored in memory. In Fortran the first index is the
  66. most rapidly varying index when moving through the elements of a two
  67. dimensional array as it is stored in memory. If you adopt the matrix
  68. convention for indexing, then this means the matrix is stored one column at a
  69. time (since the first index moves to the next row as it changes). Thus Fortran
  70. is considered a Column-major language. C has just the opposite convention. In
  71. C, the last index changes most rapidly as one moves through the array as
  72. stored in memory. Thus C is a Row-major language. The matrix is stored by
  73. rows. Note that in both cases it presumes that the matrix convention for
  74. indexing is being used, i.e., for both Fortran and C, the first index is the
  75. row. Note this convention implies that the indexing convention is invariant
  76. and that the data order changes to keep that so.
  77. But that's not the only way
  78. to look at it. Suppose one has large two-dimensional arrays (images or
  79. matrices) stored in data files. Suppose the data are stored by rows rather than
  80. by columns. If we are to preserve our index convention (whether matrix or
  81. image) that means that depending on the language we use, we may be forced to
  82. reorder the data if it is read into memory to preserve our indexing
  83. convention. For example if we read row-ordered data into memory without
  84. reordering, it will match the matrix indexing convention for C, but not for
  85. Fortran. Conversely, it will match the image indexing convention for Fortran,
  86. but not for C. For C, if one is using data stored in row order, and one wants
  87. to preserve the image index convention, the data must be reordered when
  88. reading into memory.
  89. In the end, which you do for Fortran or C depends on
  90. which is more important, not reordering data or preserving the indexing
  91. convention. For large images, reordering data is potentially expensive, and
  92. often the indexing convention is inverted to avoid that.
  93. The situation with
  94. numpy makes this issue yet more complicated. The internal machinery of numpy
  95. arrays is flexible enough to accept any ordering of indices. One can simply
  96. reorder indices by manipulating the internal stride information for arrays
  97. without reordering the data at all. NumPy will know how to map the new index
  98. order to the data without moving the data.
  99. So if this is true, why not choose
  100. the index order that matches what you most expect? In particular, why not define
  101. row-ordered images to use the image convention? (This is sometimes referred
  102. to as the Fortran convention vs the C convention, thus the 'C' and 'FORTRAN'
  103. order options for array ordering in numpy.) The drawback of doing this is
  104. potential performance penalties. It's common to access the data sequentially,
  105. either implicitly in array operations or explicitly by looping over rows of an
  106. image. When that is done, then the data will be accessed in non-optimal order.
  107. As the first index is incremented, what is actually happening is that elements
  108. spaced far apart in memory are being sequentially accessed, with usually poor
  109. memory access speeds. For example, for a two dimensional image 'im' defined so
  110. that im[0, 10] represents the value at x=0, y=10. To be consistent with usual
  111. Python behavior then im[0] would represent a column at x=0. Yet that data
  112. would be spread over the whole array since the data are stored in row order.
  113. Despite the flexibility of numpy's indexing, it can't really paper over the fact
  114. basic operations are rendered inefficient because of data order or that getting
  115. contiguous subarrays is still awkward (e.g., im[:,0] for the first row, vs
  116. im[0]), thus one can't use an idiom such as for row in im; for col in im does
  117. work, but doesn't yield contiguous column data.
  118. As it turns out, numpy is
  119. smart enough when dealing with ufuncs to determine which index is the most
  120. rapidly varying one in memory and uses that for the innermost loop. Thus for
  121. ufuncs there is no large intrinsic advantage to either approach in most cases.
  122. On the other hand, use of .flat with an FORTRAN ordered array will lead to
  123. non-optimal memory access as adjacent elements in the flattened array (iterator,
  124. actually) are not contiguous in memory.
  125. Indeed, the fact is that Python
  126. indexing on lists and other sequences naturally leads to an outside-to inside
  127. ordering (the first index gets the largest grouping, the next the next largest,
  128. and the last gets the smallest element). Since image data are normally stored
  129. by rows, this corresponds to position within rows being the last item indexed.
  130. If you do want to use Fortran ordering realize that
  131. there are two approaches to consider: 1) accept that the first index is just not
  132. the most rapidly changing in memory and have all your I/O routines reorder
  133. your data when going from memory to disk or visa versa, or use numpy's
  134. mechanism for mapping the first index to the most rapidly varying data. We
  135. recommend the former if possible. The disadvantage of the latter is that many
  136. of numpy's functions will yield arrays without Fortran ordering unless you are
  137. careful to use the 'order' keyword. Doing this would be highly inconvenient.
  138. Otherwise we recommend simply learning to reverse the usual order of indices
  139. when accessing elements of an array. Granted, it goes against the grain, but
  140. it is more in line with Python semantics and the natural order of the data.
  141. """
  142. from __future__ import division, absolute_import, print_function