Skip to content

Instantly share code, notes, and snippets.

@rkern
Created May 24, 2016 10:18
Show Gist options
  • Save rkern/840b67903e0d033ede1ad47f54aa4200 to your computer and use it in GitHub Desktop.
Save rkern/840b67903e0d033ede1ad47f54aa4200 to your computer and use it in GitHub Desktop.
Fuzz test for histogram consistency.
import numpy as np
class BaseHistogramAccuracy(object):
# The number of fuzz tests to perform.
n_fuzz = 1000
# The PRNG seed to use.
seed = 8675309
def linspace(self, low, high, steps):
# Override with your best linspace function here.
raise NotImplementedError
def test_histogram_accuracy(self):
prng = np.random.RandomState(self.seed)
for i in range(self.n_fuzz):
low = float(prng.randint(-100, 101))
width = prng.randint(100, 2000)
high = low + width
nbins = width * prng.randint(1, 20)
yield self.check_accuracy, low, high, nbins
def check_accuracy(self, low, high, nbins):
steps = nbins + 1
edges = self.linspace(low, high, steps)
inner = edges[1:-1]
prev_inner = np.nextafter(inner, -np.inf)
next_inner = np.nextafter(inner, np.inf)
# The number just prior to each edge should be in the bin below said
# edge.
np.testing.assert_array_equal(
np.histogram(prev_inner, range=(low, high), bins=nbins)[0],
np.hstack([1] * len(inner) + [0]))
# The edge itself should fall in the bin above the edge.
np.testing.assert_array_equal(
np.histogram(inner, range=(low, high), bins=nbins)[0],
np.hstack([0] + [1] * len(inner)))
# And so should the number immediately after the edge.
np.testing.assert_array_equal(
np.histogram(next_inner, range=(low, high), bins=nbins)[0],
np.hstack([0] + [1] * len(inner)))
class TestLinspaceHistogramAccuracy(BaseHistogramAccuracy):
def linspace(self, low, high, steps):
x = np.linspace(low, high, steps)
return x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment