Skip to content

Commit

Permalink
Added count_nonzero to numpy
Browse files Browse the repository at this point in the history
--HG--
branch : numpypy_count_nonzero
  • Loading branch information
Anders Lehmann committed Jul 7, 2012
1 parent ed01475 commit 3a5e8ce
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 0 deletions.
1 change: 1 addition & 0 deletions pypy/module/micronumpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,4 +166,5 @@ class Module(MixedModule):
'eye': 'app_numpy.eye',
'max': 'app_numpy.max',
'arange': 'app_numpy.arange',
'count_nonzero': 'app_numpy.count_nonzero',
}
4 changes: 4 additions & 0 deletions pypy/module/micronumpy/app_numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

import _numpypy

def count_nonzero(a):
if not hasattr(a, 'count_nonzero'):
a = _numpypy.array(a)
return a.count_nonzero()

def average(a):
# This implements a weighted average, for now we don't implement the
Expand Down
5 changes: 5 additions & 0 deletions pypy/module/micronumpy/interp_numarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,10 @@ def _prepare_slice_args(self, space, w_idx):
i += 1
return Chunks(result)

def descr_count_nonzero(self, space):
res = self.count_all_true()
return space.wrap(res)

def count_all_true(self):
sig = self.find_sig()
frame = sig.create_frame(self)
Expand Down Expand Up @@ -1486,6 +1490,7 @@ def concatenate(space, w_args, axis=0):
take = interp2app(BaseArray.descr_take),
compress = interp2app(BaseArray.descr_compress),
repeat = interp2app(BaseArray.descr_repeat),
count_nonzero = interp2app(BaseArray.descr_count_nonzero),
)


Expand Down
6 changes: 6 additions & 0 deletions pypy/module/micronumpy/test/test_numarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -2042,6 +2042,12 @@ def test_item(self):
raises(ValueError, "array(5).item(1)")
assert array([1]).item() == 1

def test_count_nonzero(self):
from _numpypy import array
a = array([1,0,5,0,10])
assert a.count_nonzero() == 3


class AppTestSupport(BaseNumpyAppTest):
def setup_class(cls):
import struct
Expand Down
7 changes: 7 additions & 0 deletions pypy/module/micronumpy/test/test_ufuncs.py
Original file line number Diff line number Diff line change
Expand Up @@ -640,6 +640,13 @@ def test_count_reduce_items(self):
raises(ValueError, count_reduce_items, a, -4)
raises(ValueError, count_reduce_items, a, (0, 2, -4))

def test_count_nonzero(self):
from _numpypy import where, count_nonzero, arange
a = arange(10)
assert count_nonzero(a) == 9
a[9] = 0
assert count_nonzero(a) == 8

def test_true_divide(self):
from _numpypy import arange, array, true_divide
assert (true_divide(arange(3), array([2, 2, 2])) == array([0, 0.5, 1])).all()
Expand Down

0 comments on commit 3a5e8ce

Please sign in to comment.