MCPcopy Create free account
hub / github.com/numpy/numpy / test_iter_reduction

Function test_iter_reduction

numpy/core/tests/test_nditer.py:2569–2626  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

2567 op_axes=[[0, 1], [-1, -1]])
2568
2569def test_iter_reduction():
2570 # Test doing reductions with the iterator
2571
2572 a = np.arange(6)
2573 i = nditer([a, None], ['reduce_ok'],
2574 [['readonly'], ['readwrite', 'allocate']],
2575 op_axes=[[0], [-1]])
2576 # Need to initialize the output operand to the addition unit
2577 with i:
2578 i.operands[1][...] = 0
2579 # Do the reduction
2580 for x, y in i:
2581 y[...] += x
2582 # Since no axes were specified, should have allocated a scalar
2583 assert_equal(i.operands[1].ndim, 0)
2584 assert_equal(i.operands[1], np.sum(a))
2585
2586 a = np.arange(6).reshape(2, 3)
2587 i = nditer([a, None], ['reduce_ok', 'external_loop'],
2588 [['readonly'], ['readwrite', 'allocate']],
2589 op_axes=[[0, 1], [-1, -1]])
2590 # Need to initialize the output operand to the addition unit
2591 with i:
2592 i.operands[1][...] = 0
2593 # Reduction shape/strides for the output
2594 assert_equal(i[1].shape, (6,))
2595 assert_equal(i[1].strides, (0,))
2596 # Do the reduction
2597 for x, y in i:
2598 # Use a for loop instead of ``y[...] += x``
2599 # (equivalent to ``y[...] = y[...].copy() + x``),
2600 # because y has zero strides we use for the reduction
2601 for j in range(len(y)):
2602 y[j] += x[j]
2603 # Since no axes were specified, should have allocated a scalar
2604 assert_equal(i.operands[1].ndim, 0)
2605 assert_equal(i.operands[1], np.sum(a))
2606
2607 # This is a tricky reduction case for the buffering double loop
2608 # to handle
2609 a = np.ones((2, 3, 5))
2610 it1 = nditer([a, None], ['reduce_ok', 'external_loop'],
2611 [['readonly'], ['readwrite', 'allocate']],
2612 op_axes=[None, [0, -1, 1]])
2613 it2 = nditer([a, None], ['reduce_ok', 'external_loop',
2614 'buffered', 'delay_bufalloc'],
2615 [['readonly'], ['readwrite', 'allocate']],
2616 op_axes=[None, [0, -1, 1]], buffersize=10)
2617 with it1, it2:
2618 it1.operands[1].fill(0)
2619 it2.operands[1].fill(0)
2620 it2.reset()
2621 for x in it1:
2622 x[1][...] += x[0]
2623 for x in it2:
2624 x[1][...] += x[0]
2625 assert_equal(it1.operands[1], it2.operands[1])
2626 assert_equal(it2.operands[1].sum(), a.size)

Callers

nothing calls this directly

Calls 3

assert_equalFunction · 0.90
reshapeMethod · 0.80
sumMethod · 0.45

Tested by

no test coverage detected