Here are the examples of the python api numpy.testing.assert_ taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
159 Examples
3
Example 1
Project: hyperopt Source File: test_rdists.py
def check_d_samples(dfn, n, rtol=1e-2, atol=1e-2):
counts = defaultdict(lambda: 0)
#print 'sample', dfn.rvs(size=n)
inc = 1.0 / n
for s in dfn.rvs(size=n):
counts[s] += inc
for ii, p in sorted(counts.items()):
t = np.allclose(dfn.pmf(ii), p, rtol=rtol, atol=atol)
if not t:
print 'Error in sampling frequencies', ii
print 'value\tpmf\tfreq'
for jj in sorted(counts):
print ('%.2f\t%.3f\t%.4f' % (
jj, dfn.pmf(jj), counts[jj]))
npt.assert_(t,
"n = %i; pmf = %f; p = %f" % (
n, dfn.pmf(ii), p))
3
Example 2
Project: pylearn2 Source File: test_four_regions.py
def test_four_regions():
dataset = FourRegions(5000)
X = dataset.get_design_matrix()
np.testing.assert_(((X < 1.) & (X > -1.)).all())
y = dataset.get_targets()
np.testing.assert_equal(np.unique(y), [0, 1, 2, 3])
3
Example 3
Project: SHARPpy Source File: test_utils.py
def test_mag_user_missing_single():
missing = 50
input_u = missing
input_v = 10
correct_answer = ma.masked
returned_answer = utils.mag(input_u, input_v, missing)
npt.assert_(type(returned_answer), type(correct_answer))
3
Example 4
Project: chaco Source File: datarange_2d_test_case.py
def assert_close_(desired,actual):
diff_allowed = 1e-5
diff = abs(ravel(actual) - ravel(desired))
for d in diff:
if not isinf(d):
assert_(alltrue(d <= diff_allowed))
return
3
Example 5
Project: statsmodels Source File: test_regression.py
def test_fvalue_implicit_constant():
nobs = 100
np.random.seed(2)
x = np.random.randn(nobs, 1)
x = ((x > 0) == [True, False]).astype(int)
y = x.sum(1) + np.random.randn(nobs)
w = 1 + 0.25 * np.random.rand(nobs)
from statsmodels.regression.linear_model import OLS, WLS
res = OLS(y, x).fit(cov_type='HC1')
assert_(np.isnan(res.fvalue))
assert_(np.isnan(res.f_pvalue))
res.summary()
res = WLS(y, x).fit(cov_type='HC1')
assert_(np.isnan(res.fvalue))
assert_(np.isnan(res.f_pvalue))
res.summary()
3
Example 6
Project: SHARPpy Source File: test_utils.py
def test_vec2comp_user_missing_val_single():
missing = 50
input_wdir = missing
input_wspd = 30
returned_u, returned_v = utils.vec2comp(input_wdir, input_wspd, missing)
npt.assert_(type(returned_u), type(ma.masked))
npt.assert_(type(returned_v), type(ma.masked))
3
Example 7
Project: pylearn2 Source File: test_yaml_parse.py
def test_preproc_pkl():
fd, fname = tempfile.mkstemp()
with os.fdopen(fd, 'wb') as f:
d = ('a', 1)
cPickle.dump(d, f)
environ['TEST_VAR'] = fname
loaded = load('a: !pkl: "${TEST_VAR}"')
assert_(loaded['a'] == d)
del environ['TEST_VAR']
3
Example 8
Project: scikit-image Source File: test_denoise.py
def test_denoise_tv_bregman_3d():
img = checkerboard.copy()
# add some random noise
img += 0.5 * img.std() * np.random.rand(*img.shape)
img = np.clip(img, 0, 1)
out1 = restoration.denoise_tv_bregman(img, weight=10)
out2 = restoration.denoise_tv_bregman(img, weight=5)
# make sure noise is reduced in the checkerboard cells
assert_(img[30:45, 5:15].std() > out1[30:45, 5:15].std())
assert_(out1[30:45, 5:15].std() > out2[30:45, 5:15].std())
3
Example 9
Project: sima Source File: test_hmm.py
def test_hmm_missing_frame(self):
global tmp_dir
frames = Sequence.create('TIFF', example_tiff())
masked_seq = frames.mask([(5, None, None)])
with warnings.catch_warnings():
warnings.simplefilter('ignore')
corrected = self.hm2d.correct(
[masked_seq], os.path.join(
tmp_dir, 'test_hmm_missing_frame.sima'))
assert_(all(np.all(np.isfinite(seq.displacements))
for seq in corrected))
assert_(np.prod(corrected.frame_shape) > 0)
3
Example 10
Project: scikit-image Source File: test_unwrap.py
def test_unwrap_3d_middle_wrap_around():
# Segmentation fault in 3D unwrap phase with middle dimension connected
# GitHub issue #1171
image = np.zeros((20, 30, 40), dtype=np.float32)
unwrap = unwrap_phase(image, wrap_around=[False, True, False])
assert_(np.all(unwrap == 0))
3
Example 11
Project: CommPy Source File: test_gfields.py
def test_closure(self):
for m in arange(1, 9):
x = GF(arange(2**m), m)
for a in x.elements:
for b in x.elements:
assert_((GF(array([a]), m) + GF(array([b]), m)).elements[0] in x.elements)
assert_((GF(array([a]), m) * GF(array([b]), m)).elements[0] in x.elements)
3
Example 12
Project: statsmodels Source File: test_ar.py
def test_ar_named_series():
dates = sm.tsa.datetools.dates_from_range("2011m1", length=72)
y = Series(np.random.randn(72), name="foobar", index=dates)
results = sm.tsa.AR(y).fit(2)
assert_(results.params.index.equals(Index(["const", "L1.foobar",
"L2.foobar"])))
3
Example 13
Project: scikit-image Source File: test_clear_border.py
def test_clear_border_non_binary():
image = np.array([[1, 2, 3, 1, 2],
[3, 3, 5, 4, 2],
[3, 4, 5, 4, 2],
[3, 3, 2, 1, 2]])
result = clear_border(image)
expected = np.array([[0, 0, 0, 0, 0],
[0, 0, 5, 4, 0],
[0, 4, 5, 4, 0],
[0, 0, 0, 0, 0]])
assert_array_equal(result, expected)
assert_(not np.all(image == result))
3
Example 14
Project: hyperopt Source File: test_rdists.py
def test_distribution_rvs(self):
alpha = 0.01
loc = 0
scale = 1
arg = (loc, scale)
distfn = loguniform_gen(0, 1)
D,pval = stats.kstest(distfn.rvs, distfn.cdf, args=arg, N=1000)
if (pval < alpha):
npt.assert_(pval > alpha,
"D = %f; pval = %f; alpha = %f; args=%s" % (
D, pval, alpha, arg))
3
Example 15
Project: scikit-image Source File: test_denoise.py
def test_denoise_tv_bregman_2d():
img = checkerboard_gray.copy()
# add some random noise
img += 0.5 * img.std() * np.random.rand(*img.shape)
img = np.clip(img, 0, 1)
out1 = restoration.denoise_tv_bregman(img, weight=10)
out2 = restoration.denoise_tv_bregman(img, weight=5)
# make sure noise is reduced in the checkerboard cells
assert_(img[30:45, 5:15].std() > out1[30:45, 5:15].std())
assert_(out1[30:45, 5:15].std() > out2[30:45, 5:15].std())
3
Example 16
def test_floats():
loaded = load("a: { a: -1.23, b: 1.23e-1 }")
assert_(isinstance(loaded['a']['a'], float))
assert_(isinstance(loaded['a']['b'], float))
assert_((loaded['a']['a'] + 1.23) < 1e-3)
assert_((loaded['a']['b'] - 1.23e-1) < 1e-3)
3
Example 17
Project: SHARPpy Source File: test_utils.py
def test_comp2vec_user_missing_val_single():
missing = 50
input_u = missing
input_v = 30
returned_wdir, returned_wspd = utils.vec2comp(input_u, input_v, missing)
npt.assert_(type(returned_wdir), type(ma.masked))
npt.assert_(type(returned_wspd), type(ma.masked))
3
Example 18
def test_unpickle():
fd, fname = tempfile.mkstemp()
with os.fdopen(fd, 'wb') as f:
d = {'a': 1, 'b': 2}
cPickle.dump(d, f)
loaded = load("{'a': !pkl: '%s'}" % fname)
assert_(loaded['a'] == d)
os.remove(fname)
3
Example 19
Project: scikit-image Source File: test_denoise.py
def test_denoise_tv_chambolle_3d():
"""Apply the TV denoising algorithm on a 3D image representing a sphere."""
x, y, z = np.ogrid[0:40, 0:40, 0:40]
mask = (x - 22)**2 + (y - 20)**2 + (z - 17)**2 < 8**2
mask = 100 * mask.astype(np.float)
mask += 60
mask += 20 * np.random.rand(*mask.shape)
mask[mask < 0] = 0
mask[mask > 255] = 255
res = restoration.denoise_tv_chambolle(mask.astype(np.uint8), weight=0.1)
assert_(res.dtype == np.float)
assert_(res.std() * 255 < mask.std())
3
Example 20
Project: sima Source File: test_hmm.py
def test_hmm_tmp(self): # TODO: remove when displacements.pkl is updated
global tmp_dir
frames = Sequence.create('TIFF', example_tiff())
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning)
corrected = self.hm2d.correct(
[frames], os.path.join(tmp_dir, 'test_hmm_2.sima'))
with open(misc.example_data() + '/displacements.pkl', 'rb') as fh:
displacements = [d.reshape((20, 1, 128, 2))
for d in pickle.load(fh)]
displacements_ = [seq.displacements for seq in corrected]
diffs = displacements_[0] - displacements[0]
assert_(
((diffs - diffs.mean(axis=2).mean(axis=1).mean(axis=0)) > 1).mean()
<= 0.001)
3
Example 21
Project: statsmodels Source File: test_data.py
def test_hasconst(self):
for x, result in zip(self.exogs, self.results):
mod = self.mod(self.y, x)
assert_equal(mod.k_constant, result[0]) #['k_constant'])
assert_equal(mod.data.k_constant, result[0])
if result[1] is None:
assert_(mod.data.const_idx is None)
else:
assert_equal(mod.data.const_idx, result[1])
# extra check after fit, some models raise on singular
fit_kwds = getattr(self, 'fit_kwds', {})
try:
res = mod.fit(**fit_kwds)
assert_equal(res.model.k_constant, result[0])
assert_equal(res.model.data.k_constant, result[0])
except:
pass
3
Example 22
def test_remove_data_pickle(results, xf):
res, l = check_pickle(results)
#Note: 10000 is just a guess for the limit on the length of the pickle
np.testing.assert_(l < 10000, msg='pickle length not %d < %d' % (l, 10000))
pred1 = results.predict(xf, exposure=1, offset=0)
pred2 = res.predict(xf, exposure=1, offset=0)
np.testing.assert_equal(pred2, pred1)
3
Example 23
Project: scikit-image Source File: test_denoise.py
def test_denoise_tv_chambolle_1d():
"""Apply the TV denoising algorithm on a 1D sinusoid."""
x = 125 + 100*np.sin(np.linspace(0, 8*np.pi, 1000))
x += 20 * np.random.rand(x.size)
x = np.clip(x, 0, 255)
res = restoration.denoise_tv_chambolle(x.astype(np.uint8), weight=0.1)
assert_(res.dtype == np.float)
assert_(res.std() * 255 < x.std())
3
Example 24
def test_pickle(self):
from statsmodels.compat.python import BytesIO
fh = BytesIO()
#test wrapped results load save pickle
self.res1.save(fh)
fh.seek(0,0)
res_unpickled = self.res1.__class__.load(fh)
assert_(type(res_unpickled) is type(self.res1))
3
Example 25
Project: scikit-image Source File: test_unwrap.py
def test_unwrap_2d_compressed_mask():
# ValueError when image is masked array with a compressed mask (no masked
# elments). GitHub issue #1346
image = np.ma.zeros((10, 10))
unwrap = unwrap_phase(image)
assert_(np.all(unwrap == 0))
3
Example 26
def test_norm():
"""Test for norm"""
tensor = np.array([[[1, 2],
[0.5, 0.5]],
[[-3, -0.5],
[0.5, -1]]])
true_res_order2 = 4
true_res_order1 = 9
res_order2 = norm(tensor, order=2)
res_order1 = norm(tensor, order=1)
assert_(true_res_order1 == res_order1)
assert_(true_res_order2 == res_order2)
assert_(norm(tensor, 0.5) == sc_norm(tensor_to_vec(tensor), 0.5))
3
Example 27
def test_MSE():
"""Test for MSE"""
y_true = np.array([1, 0, 1.5, 0.5])
y_pred = np.array([1, 1, 1, 1])
true_mse = 1.5
assert_(MSE(y_true, y_pred), true_mse)
3
Example 28
Project: scikit-image Source File: test_unwrap.py
def test_unwrap_3d_all_masked():
# all elements masked
image = np.ma.zeros((10, 10, 10))
image[:] = np.ma.masked
unwrap = unwrap_phase(image)
assert_(np.ma.isMaskedArray(unwrap))
assert_(np.all(unwrap.mask))
# 1 unmasked element, still zero edges
image = np.ma.zeros((10, 10, 10))
image[:] = np.ma.masked
image[0, 0, 0] = 0
unwrap = unwrap_phase(image)
assert_(np.ma.isMaskedArray(unwrap))
assert_(np.sum(unwrap.mask) == 999) # all but one masked
assert_(unwrap[0, 0, 0] == 0)
3
Example 29
def check_text(file_contents, keyword, text_string=None):
# If text_string is None, this code just checks the keyword.
chunk_type, chunk_data, file_contents = next_chunk(file_contents)
assert_equal(chunk_type, b"tEXt")
assert_(b'\x00' in chunk_data)
key, text = chunk_data.split(b'\x00', 1)
assert_equal(key, keyword)
if text_string is not None:
assert_equal(text, text_string)
return file_contents
3
Example 30
Project: scikit-image Source File: test_denoise.py
def test_denoise_tv_chambolle_weighting():
# make sure a specified weight gives consistent results regardless of
# the number of input image dimensions
rstate = np.random.RandomState(1234)
img2d = astro_gray.copy()
img2d += 0.15 * rstate.standard_normal(img2d.shape)
img2d = np.clip(img2d, 0, 1)
# generate 4D image by tiling
img4d = np.tile(img2d[..., None, None], (1, 1, 2, 2))
w = 0.2
denoised_2d = restoration.denoise_tv_chambolle(img2d, weight=w)
denoised_4d = restoration.denoise_tv_chambolle(img4d, weight=w)
assert_(measure.compare_ssim(denoised_2d,
denoised_4d[:, :, 0, 0]) > 0.99)
3
Example 31
Project: codetools Source File: test_namespace_tools.py
def test_namespace_in_exec():
# Verify that namespace decorator does *NOT* work in exec'd code.
dic = {'a':2, 'namespace':namespace}
exec code_to_exec in dic
assert_equal(set(dic.keys()), set(['a', '__builtins__', 'namespace',
'f', 'ns']))
ns = dic['ns']
assert_('x' in dir(ns))
assert_('y' not in dir(ns))
assert_equal(ns.x, 1)
3
Example 32
Project: SHARPpy Source File: test_utils.py
def test_vec2comp_default_missing_val_single():
input_wdir = MISSING
input_wspd = 30
returned_u, returned_v = utils.vec2comp(input_wdir, input_wspd)
npt.assert_(type(returned_u), type(ma.masked))
npt.assert_(type(returned_v), type(ma.masked))
3
Example 33
def test_distribution_rvs(self):
return
alpha = 0.01
loc = 0
scale = 1
arg = (loc, scale)
distfn = lognorm_gen(0, 1)
D,pval = stats.kstest(distfn.rvs, distfn.cdf, args=arg, N=1000)
if (pval < alpha):
npt.assert_(pval > alpha,
"D = %f; pval = %f; alpha = %f; args=%s" % (
D, pval, alpha, arg))
3
Example 34
Project: scikit-image Source File: test_denoise.py
def test_denoise_tv_chambolle_float_result_range():
# astronaut image
img = astro_gray
int_astro = np.multiply(img, 255).astype(np.uint8)
assert_(np.max(int_astro) > 1)
denoised_int_astro = restoration.denoise_tv_chambolle(int_astro,
weight=0.1)
# test if the value range of output float data is within [0.0:1.0]
assert_(denoised_int_astro.dtype == np.float)
assert_(np.max(denoised_int_astro) <= 1.0)
assert_(np.min(denoised_int_astro) >= 0.0)
3
Example 35
Project: pylearn2 Source File: test_yaml_parse.py
def test_load_path():
fd, fname = tempfile.mkstemp()
with os.fdopen(fd, 'wb') as f:
f.write(six.b("a: 23"))
loaded = load_path(fname)
assert_(loaded['a'] == 23)
os.remove(fname)
3
Example 36
Project: SHARPpy Source File: test_utils.py
def test_comp2vec_default_missing_val_single():
input_u = MISSING
input_v = 30
returned_wdir, returned_wspd = utils.comp2vec(input_u, input_v)
npt.assert_(type(returned_wdir), type(ma.masked))
npt.assert_(type(returned_wspd), type(ma.masked))
3
Example 37
Project: pylearn2 Source File: test_yaml_parse.py
def test_preproc_rhs():
environ['TEST_VAR'] = '10'
loaded = load('a: "${TEST_VAR}"')
print("loaded['a'] is %s" % loaded['a'])
assert_(loaded['a'] == "10")
del environ['TEST_VAR']
3
Example 38
Project: scikit-image Source File: test_denoise.py
def test_denoise_tv_bregman_float_result_range():
# astronaut image
img = astro_gray.copy()
int_astro = np.multiply(img, 255).astype(np.uint8)
assert_(np.max(int_astro) > 1)
denoised_int_astro = restoration.denoise_tv_bregman(int_astro, weight=60.0)
# test if the value range of output float data is within [0.0:1.0]
assert_(denoised_int_astro.dtype == np.float)
assert_(np.max(denoised_int_astro) <= 1.0)
assert_(np.min(denoised_int_astro) >= 0.0)
3
Example 39
Project: pylearn2 Source File: test_yaml_parse.py
def test_late_preproc_pkl():
fd, fname = tempfile.mkstemp()
with os.fdopen(fd, 'wb') as f:
array = np.arange(10)
np.save(f, array)
environ['TEST_VAR'] = fname
loaded = load('a: !obj:pylearn2.datasets.npy_npz.NpyDataset '
'{ file: "${TEST_VAR}"}\n')
# Assert the unsubstituted TEST_VAR is in yaml_src
assert_(loaded['a'].yaml_src.find("${TEST_VAR}") != -1)
del environ['TEST_VAR']
3
Example 40
Project: SHARPpy Source File: test_utils.py
def test_mag_default_missing_single():
input_u = MISSING
input_v = 10
correct_answer = ma.masked
returned_answer = utils.mag(input_u, input_v)
npt.assert_(type(returned_answer), type(correct_answer))
3
Example 41
Project: pylearn2 Source File: test_yaml_parse.py
def test_unpickle_key():
fd, fname = tempfile.mkstemp()
with os.fdopen(fd, 'wb') as f:
d = ('a', 1)
cPickle.dump(d, f)
loaded = load("{!pkl: '%s': 50}" % fname)
assert_(first_key(loaded) == d)
assert_(first_value(loaded) == 50)
os.remove(fname)
3
Example 42
Project: scikit-image Source File: test_binary.py
def test_out_argument():
for func in (binary.binary_erosion, binary.binary_dilation):
strel = np.ones((3, 3), dtype=np.uint8)
img = np.ones((10, 10))
out = np.zeros_like(img)
out_saved = out.copy()
func(img, strel, out=out)
testing.assert_(np.any(out != out_saved))
testing.assert_array_equal(out, func(img, strel))
3
Example 43
Project: sima Source File: test_hmm.py
def test_lookup_tables():
min_displacements = np.array([0, -1, -1])
max_displacements = np.array([0, 1, 1])
log_markov_matrix = np.ones((1, 2, 2))
position_tbl, transition_tbl, log_markov_tbl = hmm._lookup_tables(
[min_displacements, max_displacements + 1], log_markov_matrix)
pos_tbl = [[0, int(old_div(i, 3)) - 1, i % 3 - 1] for i in range(9)]
assert_array_equal(position_tbl, pos_tbl)
assert_(all(transition_tbl[list(range(9)), list(range(8, -1, -1))] == 4))
assert_(all(log_markov_tbl == 1))
3
Example 44
def test_labels(self):
2, 10, 14
labels = pandas.Index([0, 1, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24])
data = sm_data.handle_data(self.y, self.X, 'drop')
np.testing.assert_(data.row_labels.equals(labels))
3
Example 45
Project: scikit-image Source File: test_denoise.py
def test_denoise_bilateral_2d():
img = checkerboard_gray.copy()[:50,:50]
# add some random noise
img += 0.5 * img.std() * np.random.rand(*img.shape)
img = np.clip(img, 0, 1)
out1 = restoration.denoise_bilateral(img, sigma_color=0.1,
sigma_spatial=10, multichannel=False)
out2 = restoration.denoise_bilateral(img, sigma_color=0.2,
sigma_spatial=20, multichannel=False)
# make sure noise is reduced in the checkerboard cells
assert_(img[30:45, 5:15].std() > out1[30:45, 5:15].std())
assert_(out1[30:45, 5:15].std() > out2[30:45, 5:15].std())
3
Example 46
def test_range():
"""Output of edge detection should be in [0, 1]"""
image = np.random.random((100, 100))
for detector in (filters.sobel, filters.scharr,
filters.prewitt, filters.roberts):
out = detector(image)
assert_(out.min() >= 0,
"Minimum of `{0}` is smaller than zero".format(
detector.__name__)
)
assert_(out.max() <= 1,
"Maximum of `{0}` is larger than 1".format(
detector.__name__)
)
3
Example 47
Project: scikit-image Source File: test_denoise.py
def test_denoise_tv_chambolle_2d():
# astronaut image
img = astro_gray.copy()
# add noise to astronaut
img += 0.5 * img.std() * np.random.rand(*img.shape)
# clip noise so that it does not exceed allowed range for float images.
img = np.clip(img, 0, 1)
# denoise
denoised_astro = restoration.denoise_tv_chambolle(img, weight=0.1)
# which dtype?
assert_(denoised_astro.dtype in [np.float, np.float32, np.float64])
from scipy import ndimage as ndi
grad = ndi.morphological_gradient(img, size=((3, 3)))
grad_denoised = ndi.morphological_gradient(denoised_astro, size=((3, 3)))
# test if the total variation has decreased
assert_(grad_denoised.dtype == np.float)
assert_(np.sqrt((grad_denoised**2).sum()) < np.sqrt((grad**2).sum()))
3
Example 48
Project: scikit-image Source File: test_denoise.py
def test_denoise_tv_chambolle_4d():
""" TV denoising for a 4D input."""
im = 255 * np.random.rand(8, 8, 8, 8)
res = restoration.denoise_tv_chambolle(im.astype(np.uint8), weight=0.1)
assert_(res.dtype == np.float)
assert_(res.std() * 255 < im.std())
3
Example 49
Project: scikit-image Source File: test_unwrap.py
def test_unwrap_2d_all_masked():
# Segmentation fault when image is masked array with a all elements masked
# GitHub issue #1347
# all elements masked
image = np.ma.zeros((10, 10))
image[:] = np.ma.masked
unwrap = unwrap_phase(image)
assert_(np.ma.isMaskedArray(unwrap))
assert_(np.all(unwrap.mask))
# 1 unmasked element, still zero edges
image = np.ma.zeros((10, 10))
image[:] = np.ma.masked
image[0, 0] = 0
unwrap = unwrap_phase(image)
assert_(np.ma.isMaskedArray(unwrap))
assert_(np.sum(unwrap.mask) == 99) # all but one masked
assert_(unwrap[0, 0] == 0)
3
Example 50
def test_RMSE():
"""Test for RMSE"""
y_true = np.array([1, 2, 0.5, 1.5, 0.5, -1, -1])
y_pred = np.array([1, 2, 1, 1, 1, -0.5, 0])
true_mse = 2
assert_(MSE(y_true, y_pred), true_mse)