File: numeric_demo.pyx

package info (click to toggle)
pyrex 0.9.3-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 1,140 kB
  • ctags: 2,220
  • sloc: python: 10,912; ansic: 3,111; makefile: 103; lisp: 12
file content (39 lines) | stat: -rw-r--r-- 962 bytes parent folder | download | duplicates (8)
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
#
#  This example demonstrates how to access the internals
#  of a Numeric array object.
#

cdef extern from "Numeric/arrayobject.h":

  struct PyArray_Descr:
    int type_num, elsize
    char type

  ctypedef class Numeric.ArrayType [object PyArrayObject]:
    cdef char *data
    cdef int nd
    cdef int *dimensions, *strides
    cdef object base
    cdef PyArray_Descr *descr
    cdef int flags

def print_2d_array(ArrayType a):
  print "Type:", chr(a.descr.type)
  if chr(a.descr.type) <> "f":
    raise TypeError("Float array required")
  if a.nd <> 2:
    raise ValueError("2 dimensional array required")
  cdef int nrows, ncols
  cdef float *elems, x
  nrows = a.dimensions[0]
  ncols = a.dimensions[1]
  elems = <float *>a.data
  hyphen = "-"
  divider = ("+" + 10 * hyphen) * ncols + "+"
  print divider
  for row in range(nrows):
    for col in range(ncols):
      x = elems[row * ncols + col]
      print "| %8f" % x,
    print "|"
    print divider