Here are the examples of the python api numpy.testing.dec.skipif taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
141 Examples
3
Example 1
Project: statsmodels Source File: test_mice.py
@dec.skipif(not have_matplotlib)
def test_plot_bivariate(self):
df = gendat()
imp_data = mice.MICEData(df)
imp_data.update_all()
plt.clf()
for plot_points in False, True:
fig = imp_data.plot_bivariate('x2', 'x4', plot_points=plot_points)
fig.get_axes()[0].set_title('plot_bivariate')
close_or_save(pdf, fig)
3
Example 2
Project: sima Source File: test_spikes.py
@dec.skipif(not _has_picos)
def test_estimate_parameters(self):
gamma_est, sigma_est = sima.spikes.estimate_parameters(
[self.fluors_long], mode="correct")
assert_(abs(gamma_est - self.gamma) < 0.01)
assert_(abs(sigma_est - self.sigma) < 0.01)
3
Example 3
Project: statsmodels Source File: test_gofplots.py
@dec.skipif(not have_matplotlib)
def test_qqplot_2samples_ProbPlotObjects(self):
# also tests all values for line
for line in ['r', 'q', '45', 's']:
# test with `ProbPlot` instances
fig = sm.qqplot_2samples(self.prbplt, self.other_prbplot,
line=line)
plt.close('all')
3
Example 4
Project: statsmodels Source File: test_tsaplots.py
@dec.skipif(not have_matplotlib)
def test_plot_pacf():
# Just test that it runs.
fig = plt.figure()
ax = fig.add_subplot(111)
ar = np.r_[1., -0.9]
ma = np.r_[1., 0.9]
armaprocess = tsp.ArmaProcess(ar, ma)
rs = np.random.RandomState(1234)
pacf = armaprocess.generate_sample(100, distrvs=rs.standard_normal)
plot_pacf(pacf, ax=ax)
plot_pacf(pacf, ax=ax, alpha=None)
plt.close(fig)
3
Example 5
Project: statsmodels Source File: test_regressionplots.py
@dec.skipif(not have_matplotlib)
def test_plot_fit(self):
res = self.res
fig = plot_fit(res, 0, y_true=None)
x0 = res.model.exog[:, 0]
yf = res.fittedvalues
y = res.model.endog
px1, px2 = fig.axes[0].get_lines()[0].get_data()
np.testing.assert_equal(x0, px1)
np.testing.assert_equal(y, px2)
px1, px2 = fig.axes[0].get_lines()[1].get_data()
np.testing.assert_equal(x0, px1)
np.testing.assert_equal(yf, px2)
close_or_save(pdf, fig)
3
Example 6
Project: statsmodels Source File: test_correlation.py
@dec.skipif(not have_matplotlib)
def test_plot_corr_grid():
hie_data = randhie.load_pandas()
corr_matrix = np.corrcoef(hie_data.data.values.T)
fig = plot_corr_grid([corr_matrix] * 2, xnames=hie_data.names)
plt.close(fig)
fig = plot_corr_grid([corr_matrix] * 5, xnames=[], ynames=hie_data.names)
plt.close(fig)
fig = plot_corr_grid([corr_matrix] * 3, normcolor=True, titles='', cmap='jet')
plt.close(fig)
3
Example 7
Project: vispy Source File: _testing.py
def requires_img_lib():
"""Decorator for tests that require an image library"""
from ..io import _check_img_lib
if sys.platform.startswith('win'):
has_img_lib = False # PIL breaks tests on windows (!)
else:
has_img_lib = not all(c is None for c in _check_img_lib())
return np.testing.dec.skipif(not has_img_lib, 'imageio or PIL required')
3
Example 8
@dec.skipif(_ctypes_missing or _ctypes_multivariate_fail,
msg="Compiled test functions not loaded")
def test_improvement(self):
def myfunc(x): # Euler's constant integrand
return -exp(-x)*log(x)
import time
start = time.time()
for i in xrange(20):
quad(self.lib._multivariate_indefinite, 0, 100)
fast = time.time() - start
start = time.time()
for i in xrange(20):
quad(myfunc, 0, 100)
slow = time.time() - start
# 2+ times faster speeds generated by nontrivial ctypes
# function (single variable)
assert_(fast < 0.5*slow, (fast, slow))
3
Example 9
@dec.skipif(not(sys.platform[:5] == 'linux'),
"Skipping fortran compiler mismatch on non Linux platform")
def test_lapack(self):
f = FindDependenciesLdd()
deps = f.grep_dependencies(lapack_lite.__file__,
asbytes_nested(['libg2c', 'libgfortran']))
self.assertFalse(len(deps) > 1,
"""Both g77 and gfortran runtimes linked in lapack_lite ! This is likely to
cause random crashes and wrong results. See numpy INSTALL.txt for more
information.""")
3
Example 10
@dec.skipif(pil_missing, msg="The Python Image Library could not be found.")
def test_imread():
lp = os.path.join(os.path.dirname(__file__), 'dots.png')
with warnings.catch_warnings(record=True): # Py3k ResourceWarning
img = ndi.imread(lp, mode="RGB")
assert_array_equal(img.shape, (300, 420, 3))
with warnings.catch_warnings(record=True): # PIL ResourceWarning
img = ndi.imread(lp, flatten=True)
assert_array_equal(img.shape, (300, 420))
with open(lp, 'rb') as fobj:
img = ndi.imread(fobj, mode="RGB")
assert_array_equal(img.shape, (300, 420, 3))
3
Example 11
Project: statsmodels Source File: test_tsaplots.py
@dec.skipif(not have_matplotlib)
def test_plot_acf():
# Just test that it runs.
fig = plt.figure()
ax = fig.add_subplot(111)
ar = np.r_[1., -0.9]
ma = np.r_[1., 0.9]
armaprocess = tsp.ArmaProcess(ar, ma)
rs = np.random.RandomState(1234)
acf = armaprocess.generate_sample(100, distrvs=rs.standard_normal)
plot_acf(acf, ax=ax, lags=10)
plot_acf(acf, ax=ax)
plot_acf(acf, ax=ax, alpha=None)
plt.close(fig)
3
Example 12
Project: statsmodels Source File: test_regressionplots.py
@dec.skipif(not have_matplotlib)
def test_abline_model(self):
fig = abline_plot(model_results=self.mod)
ax = fig.axes[0]
ax.scatter(self.X[:,1], self.y)
close_or_save(pdf, fig)
3
Example 13
@dec.skipif(not has_matplotlib, "Matplotlib not available")
def test_convex_hull(self):
# Smoke test
fig = plt.figure()
tri = ConvexHull(self.points)
r = convex_hull_plot_2d(tri, ax=fig.gca())
assert_(r is fig)
convex_hull_plot_2d(tri)
3
Example 14
Project: statsmodels Source File: test_tsaplots.py
@dec.skipif(not have_matplotlib)
def test_seasonal_plot():
rs = np.random.RandomState(1234)
data = rs.randn(20,12)
data += 6*np.sin(np.arange(12.0)/11*np.pi)[None,:]
data = data.ravel()
months = np.tile(np.arange(1,13),(20,1))
months = months.ravel()
df = pd.DataFrame([data,months],index=['data','months']).T
grouped = df.groupby('months')['data']
labels = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
fig = seasonal_plot(grouped, labels)
ax = fig.get_axes()[0]
output = [tl.get_text() for tl in ax.get_xticklabels()]
assert_equal(labels, output)
plt.close('all')
3
Example 15
@dec.skipif(_ctypes_missing or _ctypes_multivariate_fail,
msg="Compiled test functions not loaded")
def test_indefinite(self):
# 2) Infinite integration limits --- Euler's constant
assert_quad(quad(self.lib._multivariate_indefinite, 0, Inf),
0.577215664901532860606512)
3
Example 16
Project: statsmodels Source File: test_mice.py
@dec.skipif(not have_matplotlib)
def test_plot_imputed_hist(self):
df = gendat()
imp_data = mice.MICEData(df)
imp_data.update_all()
plt.clf()
for plot_points in False, True:
fig = imp_data.plot_imputed_hist('x4')
fig.get_axes()[0].set_title('plot_imputed_hist')
close_or_save(pdf, fig)
3
Example 17
Project: statsmodels Source File: test_gofplots.py
@dec.skipif(not have_matplotlib)
def test_ppplot_pltkwargs(self):
self.fig = self.prbplt.ppplot(ax=self.ax, line=self.line,
marker='d',
markerfacecolor='cornflowerblue',
markeredgecolor='white',
alpha=0.5)
3
Example 18
Project: sima Source File: test_sequence.py
@dec.skipif(not h5py_available)
def test_export_hdf5(self):
self.tiff_seq.export(
os.path.join(self.tmp_dir, 'test_export.h5'), fmt='HDF5',
fill_gaps=False, channel_names=['Ch1', 'Ch2'], compression=None)
with h5py.File(os.path.join(self.tmp_dir, 'test_export.h5'), 'r') as f:
dims = [str(dim.label) for dim in f['imaging'].dims]
channel_names = f['imaging'].attrs['channel_names']
data = np.array(f['imaging'])
assert_array_equal(['t', 'z', 'y', 'x', 'c'], dims)
assert_array_equal(['Ch1', 'Ch2'], channel_names.astype('str'))
assert_array_equal(np.array(self.tiff_seq), data)
3
Example 19
Project: attention-lvcsr Source File: test_complex.py
@dec.skipif(True, "Complex grads not enabled, see #178")
def test_polar_grads(self):
def f(m):
c = complex_from_polar(abs(m[0]), m[1])
return .5 * real(c) + .9 * imag(c)
rng = numpy.random.RandomState(9333)
mval = numpy.asarray(rng.randn(2, 5))
utt.verify_grad(f, [mval])
3
Example 20
Project: AWS-Lambda-ML-Microservice-Skeleton Source File: test_utils.py
@dec.skipif(sys.flags.optimize == 2)
def test_lookfor():
out = StringIO()
utils.lookfor('eigenvalue', module='numpy', output=out,
import_modules=False)
out = out.getvalue()
assert_('numpy.linalg.eig' in out)
3
Example 21
Project: statsmodels Source File: test_mosaicplot.py
@dec.skipif(not have_matplotlib)
def test_axes_labeling():
from numpy.random import rand
key_set = (['male', 'female'], ['old', 'adult', 'young'],
['worker', 'unemployed'], ['yes', 'no'])
# the cartesian product of all the categories is
# the complete set of categories
keys = list(product(*key_set))
data = OrderedDict(zip(keys, rand(len(keys))))
lab = lambda k: ''.join(s[0] for s in k)
fig, (ax1, ax2) = pylab.subplots(1, 2, figsize=(16, 8))
mosaic(data, ax=ax1, labelizer=lab, horizontal=True, label_rotation=45)
mosaic(data, ax=ax2, labelizer=lab, horizontal=False,
label_rotation=[0, 45, 90, 0])
#fig.tight_layout()
fig.suptitle("correct alignment of the axes labels")
#pylab.show()
pylab.close('all')
3
Example 22
Project: statsmodels Source File: test_mosaicplot.py
@dec.skipif(not have_matplotlib or pandas_old)
def test_default_arg_index():
# 2116
import pandas as pd
df = pd.DataFrame({'size' : ['small', 'large', 'large', 'small', 'large',
'small'],
'length' : ['long', 'short', 'short', 'long', 'long',
'short']})
assert_raises(ValueError, mosaic, data=df, title='foobar')
pylab.close('all')
3
Example 23
Project: attention-lvcsr Source File: test_complex.py
@dec.skipif(True, "Complex grads not enabled, see #178")
def test_abs_grad(self):
def f(m):
c = complex(m[0], m[1])
return .5 * abs(c)
rng = numpy.random.RandomState(9333)
mval = numpy.asarray(rng.randn(2, 5))
utt.verify_grad(f, [mval])
3
Example 24
Project: statsmodels Source File: test_regressionplots.py
@dec.skipif(not have_matplotlib)
def test_one_column_exog(self):
from statsmodels.formula.api import ols
res = ols("y~var1-1", data=self.data).fit()
plot_regress_exog(res, "var1")
plt.close('all')
res = ols("y~var1", data=self.data).fit()
plot_regress_exog(res, "var1")
plt.close('all')
3
Example 25
Project: scipy Source File: test_sparsetools.py
@dec.skipif(True, "64-bit indices in sparse matrices not available")
def test_csr_matmat_int64_overflow():
n = 3037000500
assert n**2 > np.iinfo(np.int64).max
# the test would take crazy amounts of memory
check_free_memory(n * (8*2 + 1) * 3 / 1e6)
# int64 overflow
data = np.ones((n,), dtype=np.int8)
indptr = np.arange(n+1, dtype=np.int64)
indices = np.zeros(n, dtype=np.int64)
a = csr_matrix((data, indices, indptr))
b = a.T
assert_raises(RuntimeError, a.dot, b)
3
Example 26
Project: statsmodels Source File: test_regressionplots.py
@dec.skipif(not have_matplotlib)
def test_abline_ab_ax(self):
mod = self.mod
intercept, slope = mod.params
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(self.X[:,1], self.y)
fig = abline_plot(intercept=intercept, slope=slope, ax=ax)
close_or_save(pdf, fig)
3
Example 27
Project: statsmodels Source File: test_regressionplots.py
@dec.skipif(not have_matplotlib)
def test_abline_model_ax(self):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(self.X[:,1], self.y)
fig = abline_plot(model_results=self.mod, ax=ax)
close_or_save(pdf, fig)
3
Example 28
@dec.skipif(not has_matplotlib, "Matplotlib not available")
def test_voronoi(self):
# Smoke test
fig = plt.figure()
obj = Voronoi(self.points)
r = voronoi_plot_2d(obj, ax=fig.gca())
assert_(r is fig)
voronoi_plot_2d(obj)
voronoi_plot_2d(obj, show_vertices=False)
3
Example 29
Project: statsmodels Source File: test_tsaplots.py
@dec.skipif(not have_matplotlib)
def test_plot_acf_irregular():
# Just test that it runs.
fig = plt.figure()
ax = fig.add_subplot(111)
ar = np.r_[1., -0.9]
ma = np.r_[1., 0.9]
armaprocess = tsp.ArmaProcess(ar, ma)
rs = np.random.RandomState(1234)
acf = armaprocess.generate_sample(100, distrvs=rs.standard_normal)
plot_acf(acf, ax=ax, lags=np.arange(1, 11))
plot_acf(acf, ax=ax, lags=10, zero=False)
plot_acf(acf, ax=ax, alpha=None, zero=False)
plt.close(fig)
3
Example 30
@dec.skipif(_ctypes_missing or _ctypes_multivariate_fail,
msg="Compiled test functions not loaded")
def test_typical(self):
# 1) Typical function with two extra arguments:
assert_quad(quad(self.lib._multivariate_typical, 0, pi, (2, 1.8)),
0.30614353532540296487)
3
Example 31
Project: statsmodels Source File: test_tsaplots.py
@dec.skipif(not have_matplotlib)
def test_plot_pacf_irregular():
# Just test that it runs.
fig = plt.figure()
ax = fig.add_subplot(111)
ar = np.r_[1., -0.9]
ma = np.r_[1., 0.9]
armaprocess = tsp.ArmaProcess(ar, ma)
rs = np.random.RandomState(1234)
pacf = armaprocess.generate_sample(100, distrvs=rs.standard_normal)
plot_pacf(pacf, ax=ax, lags=np.arange(1, 11))
plot_pacf(pacf, ax=ax, lags=10, zero=False)
plot_pacf(pacf, ax=ax, alpha=None, zero=False)
plt.close(fig)
3
Example 32
Project: statsmodels Source File: test_correlation.py
@dec.skipif(not have_matplotlib)
def test_plot_corr():
hie_data = randhie.load_pandas()
corr_matrix = np.corrcoef(hie_data.data.values.T)
fig = plot_corr(corr_matrix, xnames=hie_data.names)
plt.close(fig)
fig = plot_corr(corr_matrix, xnames=[], ynames=hie_data.names)
plt.close(fig)
fig = plot_corr(corr_matrix, normcolor=True, title='', cmap='jet')
plt.close(fig)
3
Example 33
Project: statsmodels Source File: test_mice.py
@dec.skipif(not have_matplotlib)
def test_plot_missing_pattern(self):
df = gendat()
imp_data = mice.MICEData(df)
for row_order in "pattern", "raw":
for hide_complete_rows in False, True:
for color_row_patterns in False, True:
plt.clf()
fig = imp_data.plot_missing_pattern(row_order=row_order,
hide_complete_rows=hide_complete_rows,
color_row_patterns=color_row_patterns)
close_or_save(pdf, fig)
3
Example 34
Project: attention-lvcsr Source File: test_complex.py
@dec.skipif(True, "Complex grads not enabled, see #178")
def test_mul_mixed(self):
def f(a, b):
ac = complex(a[0], a[1])
return abs((ac*b)**2).sum()
rng = numpy.random.RandomState(9333)
aval = numpy.asarray(rng.randn(2, 5))
bval = rng.randn(5)
try:
utt.verify_grad(f, [aval, bval])
except utt.verify_grad.E_grad as e:
print(e.num_grad.gf)
print(e.analytic_grad)
raise
3
Example 35
Project: statsmodels Source File: test_mice.py
@dec.skipif(not have_matplotlib)
def test_fit_obs(self):
df = gendat()
imp_data = mice.MICEData(df)
imp_data.update_all()
plt.clf()
for plot_points in False, True:
fig = imp_data.plot_fit_obs('x4', plot_points=plot_points)
fig.get_axes()[0].set_title('plot_fit_scatterplot')
close_or_save(pdf, fig)
3
Example 36
Project: statsmodels Source File: test_gofplots.py
@dec.skipif(not have_matplotlib)
def test_qqplot_pltkwargs(self):
self.fig = self.prbplt.qqplot(ax=self.ax, line=self.line,
marker='d',
markerfacecolor='cornflowerblue',
markeredgecolor='white',
alpha=0.5)
3
Example 37
Project: vispy Source File: _testing.py
def requires_application(backend=None, has=(), capable=()):
"""Return a decorator for tests that require an application"""
good, msg = has_application(backend, has, capable)
dec_backend = np.testing.dec.skipif(not good, "Skipping test: %s" % msg)
try:
import pytest
except Exception:
return dec_backend
dec_app = pytest.mark.vispy_app_test
return composed(dec_app, dec_backend)
3
Example 38
@dec.skipif(_ctypes_missing or _ctypes_multivariate_fail,
msg="Compiled test functions not loaded")
def test_threadsafety(self):
# Ensure multivariate ctypes are threadsafe
def threadsafety(y):
return y + quad(self.lib._multivariate_sin, 0, 1)[0]
assert_quad(quad(threadsafety, 0, 1), 0.9596976941318602)
3
Example 39
Project: sima Source File: test_segment.py
@dec.skipif(not cv2_available)
def test_PlaneNormalizedCuts():
ds = ImagingDataset.load(example_data())[:, :, :, :50, :50]
affinty_method = segment.BasicAffinityMatrix(num_pcs=5)
method = segment.PlaneWiseSegmentation(
segment.PlaneNormalizedCuts(affinty_method))
ds.segment(method)
3
Example 40
Project: statsmodels Source File: test_gofplots.py
@dec.skipif(not have_matplotlib)
def test_probplot_pltkwargs(self):
self.fig = self.prbplt.probplot(ax=self.ax, line=self.line,
marker='d',
markerfacecolor='cornflowerblue',
markeredgecolor='white',
alpha=0.5)
3
Example 41
Project: sima Source File: test_sequence.py
@dec.skipif(not h5py_available)
def test_export_commpressed_hdf5(self):
self.tiff_seq.export(
os.path.join(self.tmp_dir, 'test_export_compressed.h5'),
fmt='HDF5', channel_names=['Ch1', 'Ch2'], compression='gzip')
with h5py.File(os.path.join(
self.tmp_dir, 'test_export_compressed.h5'), 'r') as f:
dims = [str(dim.label) for dim in f['imaging'].dims]
channel_names = f['imaging'].attrs['channel_names']
data = np.array(f['imaging'])
assert_array_equal(['t', 'z', 'y', 'x', 'c'], dims)
assert_array_equal(['Ch1', 'Ch2'], channel_names.astype('str'))
assert_array_equal(np.array(self.tiff_seq), data)
3
Example 42
Project: attention-lvcsr Source File: test_complex.py
@dec.skipif(True, "Complex grads not enabled, see #178")
def test_mul_mixed0(self):
def f(a):
ac = complex(a[0], a[1])
return abs((ac)**2).sum()
rng = numpy.random.RandomState(9333)
aval = numpy.asarray(rng.randn(2, 5))
try:
utt.verify_grad(f, [aval])
except utt.verify_grad.E_grad as e:
print(e.num_grad.gf)
print(e.analytic_grad)
raise
3
Example 43
Project: AWS-Lambda-ML-Microservice-Skeleton Source File: test_errstate.py
@dec.skipif(platform.machine() == "armv5tel", "See gh-413.")
def test_invalid(self):
with np.errstate(all='raise', under='ignore'):
a = -np.arange(3)
# This should work
with np.errstate(invalid='ignore'):
np.sqrt(a)
# While this should fail!
try:
np.sqrt(a)
except FloatingPointError:
pass
else:
self.fail("Did not raise an invalid error")
3
Example 44
Project: statsmodels Source File: test_gofplots.py
@dec.skipif(not have_matplotlib)
def test_qqplot_2samples_arrays(self):
# also tests all values for line
for line in ['r', 'q', '45', 's']:
# test with arrays
fig = sm.qqplot_2samples(self.res, self.other_array, line=line)
plt.close('all')
3
Example 45
@dec.skipif(not(sys.platform[:5] == 'linux'),
"Skipping fortran compiler mismatch on non Linux platform")
def test_lapack(self):
f = FindDependenciesLdd()
deps = f.grep_dependencies(flapack.__file__,
['libg2c', 'libgfortran'])
self.assertFalse(len(deps) > 1,
"""Both g77 and gfortran runtimes linked in scipy.linalg.flapack ! This is
likely to cause random crashes and wrong results. See numpy INSTALL.rst.txt for
more information.""")
3
Example 46
Project: attention-lvcsr Source File: test_complex.py
@dec.skipif(True, "Complex grads not enabled, see #178")
def test_complex_grads(self):
def f(m):
c = complex(m[0], m[1])
return .5 * real(c) + .9 * imag(c)
rng = numpy.random.RandomState(9333)
mval = numpy.asarray(rng.randn(2, 5))
utt.verify_grad(f, [mval])
3
Example 47
Project: attention-lvcsr Source File: test_complex.py
@dec.skipif(True, "Complex grads not enabled, see #178")
def test_mul_mixed1(self):
def f(a):
ac = complex(a[0], a[1])
return abs(ac).sum()
rng = numpy.random.RandomState(9333)
aval = numpy.asarray(rng.randn(2, 5))
try:
utt.verify_grad(f, [aval])
except utt.verify_grad.E_grad as e:
print(e.num_grad.gf)
print(e.analytic_grad)
raise
3
Example 48
@dec.skipif(_ctypes_missing or _ctypes_multivariate_fail,
msg="Compiled test functions not loaded")
def setUp(self):
self.lib = ctypes.CDLL(clib_test.__file__)
restype = ctypes.c_double
argtypes = (ctypes.c_int, ctypes.c_double)
for name in ['_multivariate_typical', '_multivariate_indefinite',
'_multivariate_sin']:
func = getattr(self.lib, name)
func.restype = restype
func.argtypes = argtypes
3
Example 49
@dec.skipif(not has_matplotlib, "Matplotlib not available")
def test_delaunay(self):
# Smoke test
fig = plt.figure()
obj = Delaunay(self.points)
s_before = obj.simplices.copy()
r = delaunay_plot_2d(obj, ax=fig.gca())
assert_array_equal(obj.simplices, s_before) # shouldn't modify
assert_(r is fig)
delaunay_plot_2d(obj, ax=fig.gca())
3
Example 50
Project: statsmodels Source File: test_regressionplots.py
@dec.skipif(not have_matplotlib)
def test_abline_ab(self):
mod = self.mod
intercept, slope = mod.params
fig = abline_plot(intercept=intercept, slope=slope)
close_or_save(pdf, fig)