numpy_memoryview.pyx 18.2 KB
Newer Older
1 2 3 4 5 6 7
# tag: numpy
# mode: run

"""
Test slicing for memoryviews and memoryviewslices
"""

Stefan Behnel's avatar
Stefan Behnel committed
8 9
import sys

10
cimport numpy as np
11
import numpy as np
12
cimport cython
13
from cython cimport view
14

15
include "cythonarrayutil.pxi"
16
include "../buffers/mockbuffers.pxi"
17

18
ctypedef np.int32_t dtype_t
19 20 21 22

def get_array():
    # We need to type our array to get a __pyx_get_buffer() that typechecks
    # for np.ndarray and calls __getbuffer__ in numpy.pxd
23 24
    cdef np.ndarray[dtype_t, ndim=3] a
    a = np.arange(8 * 14 * 11, dtype=np.int32).reshape(8, 14, 11)
25 26 27 28 29 30 31 32 33 34
    return a

a = get_array()

def ae(*args):
    "assert equals"
    for x in args:
        if x != args[0]:
            raise AssertionError(args)

35 36 37 38 39 40 41 42 43 44 45 46
__test__ = {}

def testcase(f):
    __test__[f.__name__] = f.__doc__
    return f

def testcase_numpy_1_5(f):
    major, minor, *rest = np.__version__.split('.')
    if (int(major), int(minor)) >= (1, 5):
        __test__[f.__name__] = f.__doc__
    return f

47 48 49 50 51 52 53 54

def gc_collect_if_required():
    major, minor, *rest = np.__version__.split('.')
    if (int(major), int(minor)) >= (1, 14):
        import gc
        gc.collect()


55 56 57 58
#
### Test slicing memoryview slices
#

59
@testcase
60 61 62 63
def test_partial_slicing(array):
    """
    >>> test_partial_slicing(a)
    """
64
    cdef dtype_t[:, :, :] a = array
65 66
    obj = array[4]

67 68
    cdef dtype_t[:, :] b = a[4, :]
    cdef dtype_t[:, :] c = a[4]
69 70 71 72 73 74

    ae(b.shape[0], c.shape[0], obj.shape[0])
    ae(b.shape[1], c.shape[1], obj.shape[1])
    ae(b.strides[0], c.strides[0], obj.strides[0])
    ae(b.strides[1], c.strides[1], obj.strides[1])

75
@testcase
76 77 78 79
def test_ellipsis(array):
    """
    >>> test_ellipsis(a)
    """
80
    cdef dtype_t[:, :, :] a = array
81

82
    cdef dtype_t[:, :] b = a[..., 4]
83 84
    b_obj = array[..., 4]

85
    cdef dtype_t[:, :] c = a[4, ...]
86 87
    c_obj = array[4, ...]

88
    cdef dtype_t[:, :] d = a[2:8, ..., 2]
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
    d_obj = array[2:8, ..., 2]

    ae(tuple([b.shape[i] for i in range(2)]), b_obj.shape)
    ae(tuple([b.strides[i] for i in range(2)]), b_obj.strides)
    for i in range(b.shape[0]):
        for j in range(b.shape[1]):
            ae(b[i, j], b_obj[i, j])

    ae(tuple([c.shape[i] for i in range(2)]), c_obj.shape)
    ae(tuple([c.strides[i] for i in range(2)]), c_obj.strides)
    for i in range(c.shape[0]):
        for j in range(c.shape[1]):
            ae(c[i, j], c_obj[i, j])

    ae(tuple([d.shape[i] for i in range(2)]), d_obj.shape)
    ae(tuple([d.strides[i] for i in range(2)]), d_obj.strides)
    for i in range(d.shape[0]):
        for j in range(d.shape[1]):
            ae(d[i, j], d_obj[i, j])

109
    cdef dtype_t[:] e = a[..., 5, 6]
110 111 112 113 114 115 116
    e_obj = array[..., 5, 6]
    ae(e.shape[0], e_obj.shape[0])
    ae(e.strides[0], e_obj.strides[0])

#
### Test slicing memoryview objects
#
117
@testcase
118 119 120 121
def test_partial_slicing_memoryview(array):
    """
    >>> test_partial_slicing_memoryview(a)
    """
122
    cdef dtype_t[:, :, :] _a = array
123 124 125 126 127 128 129 130 131 132 133
    a = _a
    obj = array[4]

    b = a[4, :]
    c = a[4]

    ae(b.shape[0], c.shape[0], obj.shape[0])
    ae(b.shape[1], c.shape[1], obj.shape[1])
    ae(b.strides[0], c.strides[0], obj.strides[0])
    ae(b.strides[1], c.strides[1], obj.strides[1])

134
@testcase
135 136 137 138
def test_ellipsis_memoryview(array):
    """
    >>> test_ellipsis_memoryview(a)
    """
139
    cdef dtype_t[:, :, :] _a = array
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
    a = _a

    b = a[..., 4]
    b_obj = array[..., 4]

    c = a[4, ...]
    c_obj = array[4, ...]

    d = a[2:8, ..., 2]
    d_obj = array[2:8, ..., 2]

    ae(tuple([b.shape[i] for i in range(2)]), b_obj.shape)
    ae(tuple([b.strides[i] for i in range(2)]), b_obj.strides)
    for i in range(b.shape[0]):
        for j in range(b.shape[1]):
            ae(b[i, j], b_obj[i, j])

    ae(tuple([c.shape[i] for i in range(2)]), c_obj.shape)
    ae(tuple([c.strides[i] for i in range(2)]), c_obj.strides)
    for i in range(c.shape[0]):
        for j in range(c.shape[1]):
            ae(c[i, j], c_obj[i, j])

    ae(tuple([d.shape[i] for i in range(2)]), d_obj.shape)
    ae(tuple([d.strides[i] for i in range(2)]), d_obj.strides)
    for i in range(d.shape[0]):
        for j in range(d.shape[1]):
            ae(d[i, j], d_obj[i, j])

    e = a[..., 5, 6]
    e_obj = array[..., 5, 6]
    ae(e.shape[0], e_obj.shape[0])
172
    ae(e.strides[0], e_obj.strides[0])
173

174

175
@testcase
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
def test_transpose():
    """
    >>> test_transpose()
    3 4
    (3, 4)
    (3, 4)
    11 11 11 11 11 11
    """
    cdef dtype_t[:, :] a

    numpy_obj = np.arange(4 * 3, dtype=np.int32).reshape(4, 3)

    a = numpy_obj
    a_obj = a

    cdef dtype_t[:, :] b = a.T
    print a.T.shape[0], a.T.shape[1]
    print a_obj.T.shape
194
    print tuple(map(int, numpy_obj.T.shape)) # might use longs in Py2
195

Mark Florisson's avatar
Mark Florisson committed
196 197 198 199 200 201 202
    cdef dtype_t[:, :] c
    with nogil:
        c = a.T.T

    assert (<object> a).shape == (<object> c).shape
    assert (<object> a).strides == (<object> c).strides

203 204
    print a[3, 2], a.T[2, 3], a_obj[3, 2], a_obj.T[2, 3], numpy_obj[3, 2], numpy_obj.T[2, 3]

205 206 207 208 209 210 211 212 213 214 215 216 217 218

@testcase
def test_transpose_type(a):
    """
    >>> a = np.zeros((5, 10), dtype=np.float64)
    >>> a[4, 6] = 9
    >>> test_transpose_type(a)
    9.0
    """
    cdef double[:, ::1] m = a
    cdef double[::1, :] m_transpose = a.T
    print m_transpose[6, 4]


219
@testcase_numpy_1_5
220 221
def test_numpy_like_attributes(cyarray):
    """
222 223 224
    For some reason this fails in numpy 1.4, with shape () and strides (40, 8)
    instead of 20, 4 on my machine. Investigate this.

225
    >>> cyarray = create_array(shape=(8, 5), mode="c")
226 227 228 229 230
    >>> test_numpy_like_attributes(cyarray)
    >>> test_numpy_like_attributes(cyarray.memview)
    """
    numarray = np.asarray(cyarray)

231 232 233 234 235
    assert cyarray.shape == numarray.shape, (cyarray.shape, numarray.shape)
    assert cyarray.strides == numarray.strides, (cyarray.strides, numarray.strides)
    assert cyarray.ndim == numarray.ndim, (cyarray.ndim, numarray.ndim)
    assert cyarray.size == numarray.size, (cyarray.size, numarray.size)
    assert cyarray.nbytes == numarray.nbytes, (cyarray.nbytes, numarray.nbytes)
236 237 238

    cdef int[:, :] mslice = numarray
    assert (<object> mslice).base is numarray
239

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
@testcase_numpy_1_5
def test_copy_and_contig_attributes(a):
    """
    >>> a = np.arange(20, dtype=np.int32).reshape(5, 4)
    >>> test_copy_and_contig_attributes(a)
    """
    cdef np.int32_t[:, :] mslice = a
    m = mslice

    # Test object copy attributes
    assert np.all(a == np.array(m.copy()))
    assert a.strides == m.strides == m.copy().strides

    assert np.all(a == np.array(m.copy_fortran()))
    assert m.copy_fortran().strides == (4, 20)

    # Test object is_*_contig attributes
    assert m.is_c_contig() and m.copy().is_c_contig()
    assert m.copy_fortran().is_f_contig() and not m.is_f_contig()
259 260 261 262 263 264 265 266

ctypedef int td_cy_int
cdef extern from "bufaccess.h":
    ctypedef td_cy_int td_h_short # Defined as short, but Cython doesn't know this!
    ctypedef float td_h_double # Defined as double
    ctypedef unsigned int td_h_ushort # Defined as unsigned short
ctypedef td_h_short td_h_cy_short

267
cdef void dealloc_callback(void *data):
268 269
    print "deallocating..."

270
def build_numarray(array array):
271
    array.callback_free_data = dealloc_callback
272 273 274 275
    return np.asarray(array)

def index(array array):
    print build_numarray(array)[3, 2]
276 277 278 279 280 281 282 283

@testcase_numpy_1_5
def test_coerce_to_numpy():
    """
    Test coercion to NumPy arrays, especially with automatically
    generated format strings.

    >>> test_coerce_to_numpy()
284
    [97, 98, 600, 700, 800]
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
    deallocating...
    (600, 700)
    deallocating...
    ((100, 200), (300, 400), 500)
    deallocating...
    (97, 900)
    deallocating...
    99
    deallocating...
    111
    deallocating...
    222
    deallocating...
    333
    deallocating...
    11.1
    deallocating...
    12.2
    deallocating...
304
    13.25
305 306 307
    deallocating...
    (14.4+15.5j)
    deallocating...
308
    (16.5+17.7j)
309
    deallocating...
310
    (18.8125+19.9375j)
311 312 313 314 315 316 317 318 319 320 321
    deallocating...
    22
    deallocating...
    33.33
    deallocating...
    44
    deallocating...
    """
    #
    ### First set up some C arrays that will be used to hold data
    #
Robert Bradshaw's avatar
Robert Bradshaw committed
322 323 324 325
    cdef MyStruct[20] mystructs
    cdef SmallStruct[20] smallstructs
    cdef NestedStruct[20] nestedstructs
    cdef PackedStruct[20] packedstructs
326

Robert Bradshaw's avatar
Robert Bradshaw committed
327 328 329 330 331
    cdef signed char[20] chars
    cdef short[20] shorts
    cdef int[20] ints
    cdef long long[20] longlongs
    cdef td_h_short[20] externs
332

Robert Bradshaw's avatar
Robert Bradshaw committed
333 334 335
    cdef float[20] floats
    cdef double[20] doubles
    cdef long double[20] longdoubles
336

Robert Bradshaw's avatar
Robert Bradshaw committed
337 338 339
    cdef float complex[20] floatcomplex
    cdef double complex[20] doublecomplex
    cdef long double complex[20] longdoublecomplex
340

Robert Bradshaw's avatar
Robert Bradshaw committed
341 342 343
    cdef td_h_short[20] h_shorts
    cdef td_h_double[20] h_doubles
    cdef td_h_ushort[20] h_ushorts
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

    cdef Py_ssize_t idx = 17

    #
    ### Initialize one element in each array
    #
    mystructs[idx] = {
        'a': 'a',
        'b': 'b',
        'c': 600,
        'd': 700,
        'e': 800,
    }

    smallstructs[idx] = { 'a': 600, 'b': 700 }

    nestedstructs[idx] = {
        'x': { 'a': 100, 'b': 200 },
        'y': { 'a': 300, 'b': 400 },
        'z': 500,
    }

    packedstructs[idx] = { 'a': 'a', 'b': 900 }

    chars[idx] = 99
    shorts[idx] = 111
    ints[idx] = 222
    longlongs[idx] = 333
    externs[idx] = 444
373
    assert externs[idx] == 444  # avoid "set but not used" C compiler warning
374 375 376

    floats[idx] = 11.1
    doubles[idx] = 12.2
377
    longdoubles[idx] = 13.25
378 379

    floatcomplex[idx] = 14.4 + 15.5j
380
    doublecomplex[idx] = 16.5 + 17.7j
381
    longdoublecomplex[idx] = 18.8125 + 19.9375j  # x/64 to avoid float format rounding issues
382 383 384 385 386 387 388 389

    h_shorts[idx] = 22
    h_doubles[idx] = 33.33
    h_ushorts[idx] = 44

    #
    ### Create a NumPy array and see if our element can be correctly retrieved
    #
390 391 392
    mystruct_array = build_numarray(<MyStruct[:4, :5]> <MyStruct *> mystructs)
    print [int(x) for x in mystruct_array[3, 2]]
    del mystruct_array
393 394 395 396
    index(<SmallStruct[:4, :5]> <SmallStruct *> smallstructs)
    index(<NestedStruct[:4, :5]> <NestedStruct *> nestedstructs)
    index(<PackedStruct[:4, :5]> <PackedStruct *> packedstructs)

397
    index(<signed char[:4, :5]> <signed char *> chars)
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
    index(<short[:4, :5]> <short *> shorts)
    index(<int[:4, :5]> <int *> ints)
    index(<long long[:4, :5]> <long long *> longlongs)

    index(<float[:4, :5]> <float *> floats)
    index(<double[:4, :5]> <double *> doubles)
    index(<long double[:4, :5]> <long double *> longdoubles)

    index(<float complex[:4, :5]> <float complex *> floatcomplex)
    index(<double complex[:4, :5]> <double complex *> doublecomplex)
    index(<long double complex[:4, :5]> <long double complex *> longdoublecomplex)

    index(<td_h_short[:4, :5]> <td_h_short *> h_shorts)
    index(<td_h_double[:4, :5]> <td_h_double *> h_doubles)
    index(<td_h_ushort[:4, :5]> <td_h_ushort *> h_ushorts)


@testcase_numpy_1_5
def test_memslice_getbuffer():
    """
418
    >>> test_memslice_getbuffer(); gc_collect_if_required()
419 420 421 422 423
    [[ 0  2  4]
     [10 12 14]]
    callback called
    """
    cdef int[:, :] array = create_array((4, 5), mode="c", use_callback=True)
424
    print(np.asarray(array)[::2, ::2])
425 426 427 428 429 430 431 432

cdef class DeallocateMe(object):
    def __dealloc__(self):
        print "deallocated!"

# Disabled! References cycles don't seem to be supported by NumPy
# @testcase
def acquire_release_cycle(obj):
433
    DISABLED_DOCSTRING = """
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
    >>> a = np.arange(20, dtype=np.object)
    >>> a[10] = DeallocateMe()
    >>> acquire_release_cycle(a)
    deallocated!
    """
    import gc

    cdef object[:] buf = obj
    buf[1] = buf

    gc.collect()

    del buf

    gc.collect()
449 450 451

cdef packed struct StructArray:
    int a[4]
452
    signed char b[5]
453 454 455 456

@testcase_numpy_1_5
def test_memslice_structarray(data, dtype):
    """
Stefan Behnel's avatar
Stefan Behnel committed
457
    >>> def b(s): return s.encode('ascii')
Stefan Behnel's avatar
Stefan Behnel committed
458 459 460 461
    >>> def to_byte_values(b):
    ...     if sys.version_info[0] >= 3: return list(b)
    ...     else: return map(ord, b)

Stefan Behnel's avatar
Stefan Behnel committed
462
    >>> data = [(range(4), b('spam\\0')), (range(4, 8), b('ham\\0\\0')), (range(8, 12), b('eggs\\0'))]
463
    >>> dtype = np.dtype([('a', '4i'), ('b', '5b')])
Stefan Behnel's avatar
Stefan Behnel committed
464
    >>> test_memslice_structarray([(L, to_byte_values(s)) for L, s in data], dtype)
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
    0
    1
    2
    3
    spam
    4
    5
    6
    7
    ham
    8
    9
    10
    11
    eggs

481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
    Test the same thing with the string format specifier

    >>> dtype = np.dtype([('a', '4i'), ('b', 'S5')])
    >>> test_memslice_structarray(data, dtype)
    0
    1
    2
    3
    spam
    4
    5
    6
    7
    ham
    8
    9
    10
    11
    eggs
500 501 502 503 504 505 506 507
    """
    a = np.empty((3,), dtype=dtype)
    a[:] = data
    cdef StructArray[:] myslice = a
    cdef int i, j
    for i in range(3):
        for j in range(4):
            print myslice[i].a[j]
Stefan Behnel's avatar
Stefan Behnel committed
508
        print myslice[i].b.decode('ASCII')
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526

@testcase_numpy_1_5
def test_structarray_errors(StructArray[:] a):
    """
    >>> dtype = np.dtype([('a', '4i'), ('b', '5b')])
    >>> test_structarray_errors(np.empty((5,), dtype=dtype))

    >>> dtype = np.dtype([('a', '6i'), ('b', '5b')])
    >>> test_structarray_errors(np.empty((5,), dtype=dtype))
    Traceback (most recent call last):
       ...
    ValueError: Expected a dimension of size 4, got 6

    >>> dtype = np.dtype([('a', '(4,4)i'), ('b', '5b')])
    >>> test_structarray_errors(np.empty((5,), dtype=dtype))
    Traceback (most recent call last):
       ...
    ValueError: Expected 1 dimension(s), got 2
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546

    Test the same thing with the string format specifier

    >>> dtype = np.dtype([('a', '4i'), ('b', 'S5')])
    >>> test_structarray_errors(np.empty((5,), dtype=dtype))

    >>> dtype = np.dtype([('a', '6i'), ('b', 'S5')])
    >>> test_structarray_errors(np.empty((5,), dtype=dtype))
    Traceback (most recent call last):
       ...
    ValueError: Expected a dimension of size 4, got 6

    >>> dtype = np.dtype([('a', '(4,4)i'), ('b', 'S5')])
    >>> test_structarray_errors(np.empty((5,), dtype=dtype))
    Traceback (most recent call last):
       ...
    ValueError: Expected 1 dimension(s), got 2
    """

cdef struct StringStruct:
547
    signed char c[4][4]
548

549
ctypedef signed char String[4][4]
550 551 552 553 554 555 556 557 558 559

def stringstructtest(StringStruct[:] view):
    pass

def stringtest(String[:] view):
    pass

@testcase_numpy_1_5
def test_string_invalid_dims():
    """
Stefan Behnel's avatar
Stefan Behnel committed
560
    >>> def b(s): return s.encode('ascii')
561
    >>> dtype = np.dtype([('a', 'S4')])
Stefan Behnel's avatar
Stefan Behnel committed
562
    >>> data = [b('spam'), b('eggs')]
563 564 565 566 567 568 569 570
    >>> stringstructtest(np.array(data, dtype=dtype))
    Traceback (most recent call last):
       ...
    ValueError: Expected 2 dimensions, got 1
    >>> stringtest(np.array(data, dtype='S4'))
    Traceback (most recent call last):
       ...
    ValueError: Expected 2 dimensions, got 1
571
    """
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595

ctypedef struct AttributesStruct:
    int attrib1
    float attrib2
    StringStruct attrib3

@testcase_numpy_1_5
def test_struct_attributes():
    """
    >>> test_struct_attributes()
    1
    2.0
    c
    """
    cdef AttributesStruct[10] a
    cdef AttributesStruct[:] myslice = a
    myslice[0].attrib1 = 1
    myslice[0].attrib2 = 2.0
    myslice[0].attrib3.c[0][0] = 'c'

    array = np.asarray(myslice)
    print array[0]['attrib1']
    print array[0]['attrib2']
    print chr(array[0]['attrib3']['c'][0][0])
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612

#
### Test for NULL strides (C contiguous buffers)
#
cdef getbuffer(Buffer self, Py_buffer *info):
    info.buf = &self.m[0, 0]
    info.len = 10 * 20
    info.ndim = 2
    info.shape = self._shape
    info.strides = NULL
    info.suboffsets = NULL
    info.itemsize = 4
    info.readonly = 0
    self.format = b"f"
    info.format = self.format

cdef class Buffer(object):
Robert Bradshaw's avatar
Robert Bradshaw committed
613
    cdef Py_ssize_t[2] _shape
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
    cdef bytes format
    cdef float[:, :] m
    cdef object shape, strides

    def __init__(self):
        a = np.arange(200, dtype=np.float32).reshape(10, 20)
        self.m = a
        self.shape = a.shape
        self.strides = a.strides
        self._shape[0] = 10
        self._shape[1] = 20

    def __getbuffer__(self, Py_buffer *info, int flags):
        getbuffer(self, info)

cdef class SuboffsetsNoStridesBuffer(Buffer):
    def __getbuffer__(self, Py_buffer *info, int flags):
        getbuffer(self, info)
        info.suboffsets = self._shape

@testcase
def test_null_strides(Buffer buffer_obj):
    """
    >>> test_null_strides(Buffer())
    """
    cdef float[:, :] m1 = buffer_obj
    cdef float[:, ::1] m2 = buffer_obj
    cdef float[:, ::view.contiguous] m3 = buffer_obj

    assert (<object> m1).strides == buffer_obj.strides
    assert (<object> m2).strides == buffer_obj.strides, ((<object> m2).strides, buffer_obj.strides)
    assert (<object> m3).strides == buffer_obj.strides

    cdef int i, j
    for i in range(m1.shape[0]):
        for j in range(m1.shape[1]):
            assert m1[i, j] == buffer_obj.m[i, j]
            assert m2[i, j] == buffer_obj.m[i, j], (i, j, m2[i, j], buffer_obj.m[i, j])
            assert m3[i, j] == buffer_obj.m[i, j]

@testcase
def test_null_strides_error(buffer_obj):
    """
    >>> test_null_strides_error(Buffer())
    C-contiguous buffer is not indirect in dimension 1
    C-contiguous buffer is not indirect in dimension 0
    C-contiguous buffer is not contiguous in dimension 0
    C-contiguous buffer is not contiguous in dimension 0
    >>> test_null_strides_error(SuboffsetsNoStridesBuffer())
    Traceback (most recent call last):
        ...
    ValueError: Buffer exposes suboffsets but no strides
    """
    # valid
    cdef float[::view.generic, ::view.generic] full_buf = buffer_obj

    # invalid
    cdef float[:, ::view.indirect] indirect_buf1
    cdef float[::view.indirect, :] indirect_buf2
    cdef float[::1, :] fortran_buf1
    cdef float[::view.contiguous, :] fortran_buf2

    try:
        indirect_buf1 = buffer_obj
    except ValueError, e:
        print e

    try:
        indirect_buf2 = buffer_obj
    except ValueError, e:
        print e

    try:
        fortran_buf1 = buffer_obj
    except ValueError, e:
        print e

    try:
        fortran_buf2 = buffer_obj
    except ValueError, e:
Robert Bradshaw's avatar
Robert Bradshaw committed
694
        print e
695 696 697 698 699 700 701 702

def test_refcount_GH507():
    """
    >>> test_refcount_GH507()
    """
    a = np.arange(12).reshape([3, 4])
    cdef np.int_t[:,:] a_view = a
    cdef np.int_t[:,:] b = a_view[1:2,:].T
703 704 705 706 707 708 709 710


@cython.boundscheck(False)
@cython.wraparound(False)
def test_boundscheck_and_wraparound(double[:, :] x):
    """
    >>> import numpy as np
    >>> array = np.ones((2,2)) * 3.5
Stefan Behnel's avatar
Stefan Behnel committed
711
    >>> test_boundscheck_and_wraparound(array)
712 713 714 715 716 717 718 719 720
    """
    # Make sure we don't generate C compiler warnings for unused code here.
    cdef Py_ssize_t numrow = x.shape[0]
    cdef Py_ssize_t i
    for i in range(numrow):
        x[i, 0]
        x[i]
        x[i, ...]
        x[i, :]