Skip to content

Commit

Permalink
Merge pull request numpy#6690 from lzkelley/hist_check_range_finite
Browse files Browse the repository at this point in the history
BUG, MAINT: check that histogram range parameters are finite.
  • Loading branch information
jaimefrio committed Nov 17, 2015
2 parents cbc14f0 + 46d2e83 commit 4ee1ed5
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
13 changes: 10 additions & 3 deletions numpy/lib/function_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,8 +336,12 @@ def histogram(a, bins=10, range=None, normed=False, weights=None,
if (range is not None):
mn, mx = range
if (mn > mx):
raise AttributeError(
raise ValueError(
'max must be larger than min in range parameter.')
if not np.all(np.isfinite([mn, mx])):
raise ValueError(
'range parameter must be finite.')


if isinstance(bins, basestring):
bins = _hist_optim_numbins_estimator(a, bins)
Expand Down Expand Up @@ -422,7 +426,7 @@ def histogram(a, bins=10, range=None, normed=False, weights=None,
else:
bins = asarray(bins)
if (np.diff(bins) < 0).any():
raise AttributeError(
raise ValueError(
'bins must increase monotonically.')

# Initialize empty histogram
Expand Down Expand Up @@ -533,7 +537,7 @@ def histogramdd(sample, bins=10, range=None, normed=False, weights=None):
try:
M = len(bins)
if M != D:
raise AttributeError(
raise ValueError(
'The dimension of bins must be equal to the dimension of the '
' sample x.')
except TypeError:
Expand All @@ -551,6 +555,9 @@ def histogramdd(sample, bins=10, range=None, normed=False, weights=None):
smin = atleast_1d(array(sample.min(0), float))
smax = atleast_1d(array(sample.max(0), float))
else:
if not np.all(np.isfinite(range)):
raise ValueError(
'range parameter must be finite.')
smin = zeros(D)
smax = zeros(D)
for i in arange(D):
Expand Down
17 changes: 17 additions & 0 deletions numpy/lib/tests/test_function_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1267,6 +1267,13 @@ def test_empty(self):
assert_array_equal(a, np.array([0]))
assert_array_equal(b, np.array([0, 1]))

def test_finite_range(self):
# Normal ranges should be fine
vals = np.linspace(0.0, 1.0, num=100)
histogram(vals, range=[0.25,0.75])
assert_raises(ValueError, histogram, vals, range=[np.nan,0.75])
assert_raises(ValueError, histogram, vals, range=[0.25,np.inf])


class TestHistogramOptimBinNums(TestCase):
"""
Expand Down Expand Up @@ -1489,6 +1496,16 @@ def test_rightmost_binedge(self):
assert_(hist[0] == 0.0)
assert_(hist[1] == 0.0)

def test_finite_range(self):
vals = np.random.random((100,3))
histogramdd(vals, range=[[0.0,1.0],[0.25,0.75],[0.25,0.5]])
assert_raises(ValueError, histogramdd, vals,
range=[[0.0,1.0],[0.25,0.75],[0.25,np.inf]])
assert_raises(ValueError, histogramdd, vals,
range=[[0.0,1.0],[np.nan,0.75],[0.25,0.5]])




class TestUnique(TestCase):

Expand Down

0 comments on commit 4ee1ed5

Please sign in to comment.