charges = np.arange(21).reshape(7,3) norms = np.sqrt((charges*charges).sum(-1)) charges = charges / norms[:, None] d_sphere, pot = disperse_charges(HemiSphere(xyz=charges), 1000, .05) for ii in xrange(1, len(pot)): #check that the potential of the system is either going down or #stayting almost the same nt.assert_(pot[ii] - pot[ii-1] < 1e-12) #check that the resulting charges all lie on the unit sphere d_charges = d_sphere.vertices norms = np.sqrt((d_charges*d_charges).sum(-1)) nt.assert_array_almost_equal(norms, 1) def test_interp_rbf(): from dipy.core.sphere import Sphere, interp_rbf from dipy.core.subdivide_octahedron import create_unit_hemisphere import numpy as np s0 = create_unit_hemisphere(2) s1 = create_unit_hemisphere(3) data = np.cos(s0.theta) + np.sin(s0.phi) expected = np.cos(s1.theta) + np.sin(s1.phi) interp_data = interp_rbf(data, s0, s1) nt.assert_(np.mean(np.abs(interp_data - expected)) < 0.1) if __name__ == "__main__": nt.run_module_suite()
tracks, _ = load_dpy(fname) npt.assert_equal(len(tracks), len(streamlines)) npt.assert_array_almost_equal(tracks[1], streamline, decimal=4) def test_trackvis(): with InTemporaryDirectory(): fname = 'trackvis_test.trk' affine = np.eye(4) # Test save trackvis_save_trk(fname, streamlines, affine, np.array([50, 50, 50])) tfile = nib.streamlines.load(fname) npt.assert_array_equal(affine, tfile.affine) npt.assert_array_equal(np.array([1., 1., 1.]), tfile.header.get('voxel_sizes')) npt.assert_array_equal(np.array([50, 50, 50]), tfile.header.get('dimensions')) npt.assert_equal(len(tfile.streamlines), len(streamlines)) npt.assert_array_almost_equal(tfile.streamlines[1], streamline, decimal=4) # Test Deprecations npt.assert_warns(DeprecationWarning, trackvis_save_trk, fname, streamlines, affine, np.array([50, 50, 50])) if __name__ == '__main__': npt.run_module_suite()
ant.input = 2.3 assert ant.input == 2.3, "Value is %s" % ant.input assert ant.crisp_value == 2.3, "Value is %s" % ant.crisp_value @nose.with_setup(setup) def test_add_bad_mf(): global ant global con tst.assert_raises(ValueError, ant.__setitem__, 'new_mf', np.ones(30)) tst.assert_raises(ValueError, ant.__setitem__, 'low', np.arange(6)) tst.assert_raises(ValueError, con.__setitem__, 'new_mf', np.ones(30)) tst.assert_raises(ValueError, con.__setitem__, 'low', np.arange(10)) @nose.with_setup(setup) def test_cannot_compute(): global ant global con with tst.assert_raises(ValueError): ant.input with tst.assert_raises(ValueError): con.output if __name__ == '__main__': tst.run_module_suite()
sorted_data = sorted(data) for i, val in enumerate(s_list.iterate()): assert sorted_data[i] == val out = [[ 32], [ 17, 32], [1, 17, 32], [1, 3, 5, 17, 32]] _skip_list_structure(s_list, out) node = s_list.find(13) assert node is None node = s_list.find(17) assert node.down is None assert node.value==17 out = [[ 32], [ 32], [1, 32], [1, 3, 5, 32]] s_list.delete(17) _skip_list_structure(s_list, out) s_list.reset() test_skip_list(s_list=s_list) if __name__ == "__main__": np_test.run_module_suite()
y = tf.placeholder(tf.float32, shape=(None, None, 1)) loss = mse_loss(y_hat, y) optimizer = tf.train.RMSPropOptimizer(learning_rate=0.01) train_step = optimizer.minimize(loss) session = tf.Session() session.run(tf.initialize_all_variables()) batch_size = 5 n_batch = X_train.shape[0] // batch_size n_epochs = 20 for epoch in range(n_epochs): for batch in range(n_batch): X_batch = X_train[batch * batch_size:(batch + 1) * batch_size] Y_batch = Y_train[batch * batch_size:(batch + 1) * batch_size] session.run(train_step, feed_dict={x: X_batch, y: Y_batch}) mse = session.run(loss, feed_dict={x: X_test, y: Y_test}) # Theoretically achievable RMSE is 0.1. assert_(mse**0.5 < 0.115) session.close() if __name__ == '__main__': run_module_suite(argv=["", "--nologcapture"])
# Regression gh-3898 in_ = np.arange(10) out = sndi.minimum_filter1d(in_, 1) assert_equal(in_, out) out = sndi.maximum_filter1d(in_, 1) assert_equal(in_, out) # Test reflect out = sndi.minimum_filter1d(in_, 5, mode='reflect') assert_equal([0, 0, 0, 1, 2, 3, 4, 5, 6, 7], out) out = sndi.maximum_filter1d(in_, 5, mode='reflect') assert_equal([2, 3, 4, 5, 6, 7, 8, 9, 9, 9], out) #Test constant out = sndi.minimum_filter1d(in_, 5, mode='constant', cval=-1) assert_equal([-1, -1, 0, 1, 2, 3, 4, 5, -1, -1], out) out = sndi.maximum_filter1d(in_, 5, mode='constant', cval=10) assert_equal([10, 10, 4, 5, 6, 7, 8, 9, 10, 10], out) # Test nearest out = sndi.minimum_filter1d(in_, 5, mode='nearest') assert_equal([0, 0, 0, 1, 2, 3, 4, 5, 6, 7], out) out = sndi.maximum_filter1d(in_, 5, mode='nearest') assert_equal([2, 3, 4, 5, 6, 7, 8, 9, 9, 9], out) # Test wrap out = sndi.minimum_filter1d(in_, 5, mode='wrap') assert_equal([0, 0, 0, 1, 2, 3, 4, 5, 0, 0], out) out = sndi.maximum_filter1d(in_, 5, mode='wrap') assert_equal([9, 9, 4, 5, 6, 7, 8, 9, 9, 9], out) if __name__ == "__main__": run_module_suite(argv=sys.argv)
toc = [] for classname in classnames: class_ = eval(classname) doc_str = getattr(class_, '__doc__') setattr(class_, '__doc__', doc_str + table_of_parameters(class_)) if hasattr(class_, 'quick_description'): toc.append((classname, getattr(class_, 'quick_description'))) # Make tables of solver name and quick description __doc__ = __doc__ + typeset_toc(toc) + _tutorial # Do not pollute namespace del class_, doc_str, classname, classnames, toc, typeset_toc, \ table_of_parameters, name, obj, inspect if __name__ == '__main__': from os.path import join from numpy.testing import rundocs, run_module_suite import odespy path = odespy.__path__[0] # Doctests rundocs(join(path, 'ODE.py')) rundocs(join(path,'RungeKutta.py')) # Basic tests path = join(path, 'tests') run_module_suite(join(path, 'test_basics.py'))
the two FFT implementations. Because this simply inspects source files, we only need to run the test on one version of Python. """ import sys if sys.version_info >= (3, 4): from pathlib import Path import re import tokenize from numpy.testing import TestCase, assert_, run_module_suite import scipy class TestFFTPackImport(TestCase): def test_fftpack_import(self): base = Path(scipy.__file__).parent regexp = r"\s*from.+\.fftpack import .*\n" for path in base.rglob("*.py"): if base / "fftpack" in path.parents: continue # use tokenize to auto-detect encoding on systems where no # default encoding is defined (e.g. LANG='C') with tokenize.open(str(path)) as file: assert_( all(not re.fullmatch(regexp, line) for line in file), "{0} contains an import from fftpack".format(path)) if __name__ == "__main__": run_module_suite(argv=sys.argv)
profile = afq_profile(data, bundle, np.eye(4), n_points=10, weights=np.ones((2, 10)) * 0.5) npt.assert_equal(profile, np.ones(10)) # Disallow setting weights that don't sum to 1 across fibers/nodes: npt.assert_raises(ValueError, afq_profile, data, bundle, np.eye(4), n_points=10, weights=np.ones((2, 10)) * 0.6) # Test using an affine: affine = np.eye(4) affine[:, 3] = [-1, 100, -20, 1] # Transform the streamlines: bundle._data = bundle._data + affine[:3, 3] profile = afq_profile(data, bundle, affine, n_points=10, weights=None) npt.assert_equal(profile, np.ones(10)) # Test for error-handling: empty_bundle = Streamlines([]) npt.assert_raises(ValueError, afq_profile, data, empty_bundle, np.eye(4)) if __name__ == '__main__': npt.run_module_suite()
assert_array_almost_equal(output[0], expected1) assert_array_almost_equal(output[1], expected2) def test_stat_funcs_2d(): """Apply the stat funcs to a 2-d array.""" a = np.array([[5, 6, 0, 0, 0], [8, 9, 0, 0, 0], [0, 0, 0, 3, 5]]) lbl = np.array([[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 2, 2]]) mean = ndimage.mean(a, labels=lbl, index=[1, 2]) assert_array_equal(mean, [7.0, 4.0]) var = ndimage.variance(a, labels=lbl, index=[1, 2]) assert_array_equal(var, [2.5, 1.0]) std = ndimage.standard_deviation(a, labels=lbl, index=[1, 2]) assert_array_almost_equal(std, np.sqrt([2.5, 1.0])) med = ndimage.median(a, labels=lbl, index=[1, 2]) assert_array_equal(med, [7.0, 4.0]) min = ndimage.minimum(a, labels=lbl, index=[1, 2]) assert_array_equal(min, [5, 3]) max = ndimage.maximum(a, labels=lbl, index=[1, 2]) assert_array_equal(max, [9, 5]) if __name__ == "__main__": run_module_suite()
ts, tv = get_ts_tv(codons) syn, nonsyn = get_syn_nonsyn(code, codons) compo = get_compo(codons) asym_compo = get_asym_compo(codons) ham = get_hamming(codons) gtr = get_gtr(codons) # check some invariants testing.assert_equal(len(all_codons), 64) testing.assert_equal(len(codons), 64 - len(stop)) testing.assert_equal(numpy.unique(ts), [0, 1]) testing.assert_equal(numpy.unique(tv), [0, 1]) testing.assert_equal(numpy.unique(gtr), [0, 1]) # check the genetic code for typos table_codons = list(c for cs in code for c in cs) testing.assert_equal(len(code), 21) testing.assert_equal(len(table_codons), len(set(table_codons))) if set(codons) - set(table_codons): raise Exception(set(all_codons) - set(table_codons)) if set(table_codons) - set(all_codons): raise Exception(set(table_codons) - set(all_codons)) def test_mito_invariants(self): self._help_test_invariants(g_code_mito, g_stop_mito) def test_plain_invariants(self): self._help_test_invariants(g_code, g_stop) if __name__ == '__main__': testing.run_module_suite()
norms = np.sqrt((charges*charges).sum(-1)) charges = charges / norms[:, None] d_sphere, pot = disperse_charges(HemiSphere(xyz=charges), 1000, .05) for ii in xrange(1, len(pot)): #check that the potential of the system is going down nt.assert_(pot[ii] - pot[ii-1] <= 0) #check that the resulting charges all lie on the unit sphere d_charges = d_sphere.vertices norms = np.sqrt((d_charges*d_charges).sum(-1)) nt.assert_array_almost_equal(norms, 1) def test_interp_rbf(): from dipy.core.sphere import Sphere, interp_rbf from dipy.core.subdivide_octahedron import create_unit_hemisphere import numpy as np s0 = create_unit_hemisphere(2) s1 = create_unit_hemisphere(3) data = np.cos(s0.theta) + np.sin(s0.phi) expected = np.cos(s1.theta) + np.sin(s1.phi) interp_data_en = interp_rbf(data, s0, s1, norm = "euclidean_norm") interp_data_a = interp_rbf(data, s0, s1, norm = "angle") nt.assert_(np.mean(np.abs(interp_data_en - expected)) < 0.1) nt.assert_(np.mean(np.abs(interp_data_a - expected)) < 0.1) if __name__ == "__main__": nt.run_module_suite()
# Build a system with three rules targeting the same Consequent Term, # and then an equivalent system with those three rules combined into one. cs0 = ctrl.ControlSystem([r1, r2, r3, r4, r5, r6]) cs1 = ctrl.ControlSystem([r123, r4, r5, r6]) expected_results = [ 0.438372093023, 0.443962536855, 0.461436409933, 0.445290345769, 1.575, 1.15, 1.86162790698 ] # Ensure the results are equivalent within error for inst, expected in zip(range(7), expected_results): sim0 = ctrl.ControlSystemSimulation(cs0) sim1 = ctrl.ControlSystemSimulation(cs1) sim0.input["x1"] = x1_inputs[inst] sim0.input["x2"] = x2_inputs[inst] sim1.input["x1"] = x1_inputs[inst] sim1.input["x2"] = x2_inputs[inst] sim0.compute() sim1.compute() tst.assert_allclose(sim0.output['y'], sim1.output['y']) tst.assert_allclose(expected, sim0.output['y'], atol=1e-4, rtol=1e-4) if __name__ == '__main__': tst.run_module_suite()
def test_invalid_seed(): seed = np.ones((5, 5)) mask = np.ones((5, 5)) assert_raises(ValueError, reconstruction, seed * 2, mask, method='dilation') assert_raises(ValueError, reconstruction, seed * 0.5, mask, method='erosion') def test_invalid_selem(): seed = np.ones((5, 5)) mask = np.ones((5, 5)) assert_raises(ValueError, reconstruction, seed, mask, selem=np.ones((4, 4))) assert_raises(ValueError, reconstruction, seed, mask, selem=np.ones((3, 4))) reconstruction(seed, mask, selem=np.ones((3, 3))) def test_invalid_method(): seed = np.array([0, 8, 8, 8, 8, 8, 8, 8, 8, 0]) mask = np.array([0, 3, 6, 2, 1, 1, 1, 4, 2, 0]) assert_raises(ValueError, reconstruction, seed, mask, method='foo') if __name__ == '__main__': from numpy import testing testing.run_module_suite()
# monotonically increasing data for i in range(len(arr)): arr[i] attributes = dict(type=ReadIM.BUFFER_FORMATS[tp]) atts = ReadIM.load_AttributeList(attributes) ReadIM.WriteIM7('packed_im{0}.im7'.format(tp), True, buff, atts.next) ReadIM.WriteIM7('not_packed_im{0}.im7'.format(tp), False, buff, atts.next) ReadIM.DestroyBuffer(buff) ReadIM.DestroyAttributeListSafe(atts) def test_bufferAlt(self): import numpy as np window = [(0,10),(10,0)] buffAlt = ReadIM.newBuffer(window,3,3,2) buffAlt.scaleX.offset = np.array(1) buffNew = ReadIM.BufferTypeAlt(buffAlt) assert not (buffAlt is buffNew) assert type(buffNew.scaleX.offset) is float, "{0}".format(type(buffAlt.scaleX.offset)) pass if __name__ == "__main__": test = TestIM7('test_bufferAlt') test.debug() run_module_suite(argv=['-f',])
kwargs = {'width': 2} self.message = ("Insufficient bit width provided. This behavior " "will raise an error in the future.") self.assert_deprecated(np.binary_repr, args=args, kwargs=kwargs) def test_insufficient_width_negative(self): args = (-5,) kwargs = {'width': 2} self.message = ("Insufficient bit width provided. This behavior " "will raise an error in the future.") self.assert_deprecated(np.binary_repr, args=args, kwargs=kwargs) class TestTestDeprecated(object): def test_assert_deprecated(self): test_case_instance = _DeprecationTestCase() test_case_instance.setUp() assert_raises(AssertionError, test_case_instance.assert_deprecated, lambda: None) def foo(): warnings.warn("foo", category=DeprecationWarning) test_case_instance.assert_deprecated(foo) if __name__ == "__main__": run_module_suite()
from numpy.testing import run_module_suite import sys from test_simulator import * from test_fullchain import * if __name__ == "__main__": # Run tests args = sys.argv # If no args were specified, add arg to only do non-slow tests if len(args) == 1: print("Running tests that are not tagged as 'slow'. " "Use '--all' to run all tests.") args.append("-a!slow") run_module_suite(argv=args)