def test_fetch_data(): symmetric362 = SPHERE_FILES['symmetric362'] with TemporaryDirectory() as tmpdir: md5 = fetcher._get_file_md5(symmetric362) bad_md5 = '8' * len(md5) newfile = path.join(tmpdir, "testfile.txt") # Test that the fetcher can get a file testfile_url = pathname2url(symmetric362) testfile_url = urljoin("file:", testfile_url) files = {"testfile.txt" : (testfile_url, md5)} fetcher.fetch_data(files, tmpdir) npt.assert_(path.exists(newfile)) # Test that the file is replaced when the md5 doesn't match with open(newfile, 'a') as f: f.write("some junk") fetcher.fetch_data(files, tmpdir) npt.assert_(path.exists(newfile)) npt.assert_equal(fetcher._get_file_md5(newfile), md5) # Test that an error is raised when the md5 checksum of the download # file does not match the expected value files = {"testfile.txt" : (testfile_url, bad_md5)} npt.assert_raises(fetcher.FetcherError, fetcher.fetch_data, files, tmpdir)
def test_plot_acf_kwargs(): # 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) buff = BytesIO() plot_acf(acf, ax=ax) fig.savefig(buff, format='rgba') plt.close(fig) buff_with_vlines = BytesIO() fig_with_vlines = plt.figure() ax = fig_with_vlines.add_subplot(111) vlines_kwargs = {'linestyles': 'dashdot'} plot_acf(acf, ax=ax, vlines_kwargs=vlines_kwargs) fig_with_vlines.savefig(buff_with_vlines, format='rgba') plt.close(fig_with_vlines) buff.seek(0) buff_with_vlines.seek(0) plain = buff.read() with_vlines = buff_with_vlines.read() assert_(with_vlines != plain)
def test_random_data(self): np.random.seed(1234) a = np.random.rand(1233) + 1j*np.random.rand(1233) b = np.random.rand(1321) + 1j*np.random.rand(1321) c = signal.fftconvolve(a, b, 'full') d = np.convolve(a, b, 'full') assert_(np.allclose(c, d, rtol=1e-10))
def test_remove_data_pickle(self): results = self.results xf = self.xf pred_kwds = self.predict_kwds pred1 = results.predict(xf, **pred_kwds) #create some cached attributes results.summary() #check pickle unpickle works on full results #TODO: drop of load save is tested res, l = check_pickle(results._results) #remove data arrays, check predict still works results.remove_data() pred2 = results.predict(xf, **pred_kwds) np.testing.assert_equal(pred2, pred1) #pickle, unpickle reduced array res, l = check_pickle(results._results) #for testing attach res self.res = res #Note: 10000 is just a guess for the limit on the length of the pickle assert_(l < 10000, msg='pickle length not %d < %d' % (l, 10000)) pred3 = results.predict(xf, **pred_kwds) np.testing.assert_equal(pred3, pred1)
def test_array_richcompare_legacy_weirdness(self): # It doesn't really work to use assert_deprecated here, b/c part of # the point of assert_deprecated is to check that when warnings are # set to "error" mode then the error is propagated -- which is good! # But here we are testing a bunch of code that is deprecated *because* # it has the habit of swallowing up errors and converting them into # different warnings. So assert_warns will have to be sufficient. assert_warns(FutureWarning, lambda: np.arange(2) == "a") assert_warns(FutureWarning, lambda: np.arange(2) != "a") # No warning for scalar comparisons with warnings.catch_warnings(): warnings.filterwarnings("error") assert_(not (np.array(0) == "a")) assert_(np.array(0) != "a") assert_(not (np.int16(0) == "a")) assert_(np.int16(0) != "a") for arg1 in [np.asarray(0), np.int16(0)]: struct = np.zeros(2, dtype="i4,i4") for arg2 in [struct, "a"]: for f in [operator.lt, operator.le, operator.gt, operator.ge]: if sys.version_info[0] >= 3: # py3 with warnings.catch_warnings() as l: warnings.filterwarnings("always") assert_raises(TypeError, f, arg1, arg2) assert_(not l) else: # py2 assert_warns(DeprecationWarning, f, arg1, arg2)
def check_kurt_expect(distfn, arg, m, v, k, msg): if np.isfinite(k): m4e = distfn.expect(lambda x: np.power(x-m, 4), arg) npt.assert_allclose(m4e, (k + 3.) * np.power(v, 2), atol=1e-5, rtol=1e-5, err_msg=msg + ' - kurtosis') else: npt.assert_(np.isnan(k))
def test_unbounded_approximated(self): """ SLSQP: unbounded, approximated jacobian. """ res = fmin_slsqp(self.fun, [-1.0, 1.0], args = (-1.0, ), iprint = 0, full_output = 1) x, fx, its, imode, smode = res assert_(imode == 0, imode) assert_array_almost_equal(x, [2, 1])
def test_singular(self): A = csc_matrix((5,5), dtype='d') b = array([1, 2, 3, 4, 5],dtype='d') with suppress_warnings() as sup: sup.filter(MatrixRankWarning, "Matrix is exactly singular") x = spsolve(A, b) assert_(not np.isfinite(x).any())
def check_skew_expect(distfn, arg, m, v, s, msg): if np.isfinite(s): m3e = distfn.expect(lambda x: np.power(x-m, 3), arg) npt.assert_almost_equal(m3e, s * np.power(v, 1.5), decimal=5, err_msg=msg + ' - skew') else: npt.assert_(np.isnan(s))
def test_user(path): if sys.platform != 'win32': in_path = '~' path = catalog.catalog_path(in_path) d,f = os.path.split(path) assert_(d == os.path.expanduser(in_path)) assert_(f == catalog.os_dependent_catalog_name())
def test_module(self): # hand it a module and see if it uses the parent directory # of the module. path = catalog.catalog_path(os.__file__) d,f = os.path.split(os.__file__) d2,f = os.path.split(path) assert_(d2 == d)
def test_build_search_order3(self): """ If MODULE is absent, module_dir shouldn't be in search path. """ q = catalog.catalog(['first','second']) q.set_module_directory('third') order = q.build_search_order() assert_(order == ['first','second',catalog.default_dir()])
def test_catalog_files2(self): """ Ignore bad paths in the path. """ q = catalog.catalog() os.environ['PYTHONCOMPILED'] = '_some_bad_path_' files = q.get_catalog_files() assert_(len(files) == 1)
def test_get_environ_path(self): if sys.platform == 'win32': sep = ';' else: sep = ':' os.environ['PYTHONCOMPILED'] = sep.join(('path1','path2','path3')) q = catalog.catalog() path = q.get_environ_path() assert_(path == ['path1','path2','path3'])
def test_build_search_order1(self): """ MODULE in search path should be replaced by module_dir. """ q = catalog.catalog(['first','MODULE','third']) q.set_module_directory('second') order = q.build_search_order() assert_(order == ['first','second','third',catalog.default_dir()])
def test_true(self): class Foo: def __call__(self): return 0 a= Foo() res = inline_tools.inline('return_val = a.is_callable();',['a']) assert_(res)
def test_clear_module_directory(self): q = catalog.catalog() r = q.get_module_directory() assert_(r is None) q.set_module_directory('bob') r = q.clear_module_directory() assert_(r is None)
def test_float_modulus_corner_cases(self): # Check remainder magnitude. for dt in np.typecodes['Float']: b = np.array(1.0, dtype=dt) a = np.nextafter(np.array(0.0, dtype=dt), -b) rem = self.mod(a, b) assert_(rem <= b, 'dt: %s' % dt) rem = self.mod(-a, -b) assert_(rem >= -b, 'dt: %s' % dt) # Check nans, inf with suppress_warnings() as sup: sup.filter(RuntimeWarning, "invalid value encountered in remainder") for dt in np.typecodes['Float']: fone = np.array(1.0, dtype=dt) fzer = np.array(0.0, dtype=dt) finf = np.array(np.inf, dtype=dt) fnan = np.array(np.nan, dtype=dt) rem = self.mod(fone, fzer) assert_(np.isnan(rem), 'dt: %s' % dt) # MSVC 2008 returns NaN here, so disable the check. #rem = self.mod(fone, finf) #assert_(rem == fone, 'dt: %s' % dt) rem = self.mod(fone, fnan) assert_(np.isnan(rem), 'dt: %s' % dt) rem = self.mod(finf, fone) assert_(np.isnan(rem), 'dt: %s' % dt)
def test_blasdot_used(): from numpy.core import dot, vdot, inner, alterdot, restoredot assert_(dot is _dotblas.dot) assert_(vdot is _dotblas.vdot) assert_(inner is _dotblas.inner) assert_(alterdot is _dotblas.alterdot) assert_(restoredot is _dotblas.restoredot)
def test_rand(self): # Simple distributional checks for sparse.rand. for random_state in None, 4321, np.random.RandomState(): x = sprand(10, 20, density=0.5, dtype=np.float64, random_state=random_state) assert_(np.all(np.less_equal(0, x.data))) assert_(np.all(np.less_equal(x.data, 1)))
def test_version_2_0_memmap(): # requires more than 2 byte for header dt = [(("%d" % i) * 100, float) for i in range(500)] d = np.ones(1000, dtype=dt) tf = tempfile.mktemp('', 'mmap', dir=tempdir) # 1.0 requested but data cannot be saved this way assert_raises(ValueError, format.open_memmap, tf, mode='w+', dtype=d.dtype, shape=d.shape, version=(1, 0)) ma = format.open_memmap(tf, mode='w+', dtype=d.dtype, shape=d.shape, version=(2, 0)) ma[...] = d del ma with warnings.catch_warnings(record=True) as w: warnings.filterwarnings('always', '', UserWarning) ma = format.open_memmap(tf, mode='w+', dtype=d.dtype, shape=d.shape, version=None) assert_(w[0].category is UserWarning) ma[...] = d del ma ma = format.open_memmap(tf, mode='r') assert_array_equal(ma, d)
def test_al_mohy_higham_2012_experiment_1_funm_log(self): # The raw funm with np.log does not complete the round trip. # Note that the expm leg of the round trip is badly conditioned. A = _get_al_mohy_higham_2012_experiment_1() A_funm_log, info = funm(A, np.log, disp=False) A_round_trip = expm(A_funm_log) assert_(not np.allclose(A_round_trip, A, rtol=1e-5, atol=1e-14))
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)
def check_ppf_dtype(distfn, arg): q0 = np.asarray([0.25, 0.5, 0.75]) q_cast = [q0.astype(tp) for tp in (np.float16, np.float32, np.float64)] for q in q_cast: for meth in [distfn.ppf, distfn.isf]: val = meth(q, *arg) npt.assert_(val.dtype == np.float_)
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)
def test_testMasked(self): # Test of masked element xx = arange(6) xx[1] = masked assert_(str(masked) == '--') assert_(xx[1] is masked) assert_equal(filled(xx[1], 0), 0)
def test_trace(self): (x, X, XX, m, mx, mX, mXX,) = self.d mXdiag = mX.diagonal() assert_equal(mX.trace(), mX.diagonal().compressed().sum()) assert_(eq(mX.trace(), X.trace() - sum(mXdiag.mask * X.diagonal(), axis=0)))
def test_repeatability(self): import hashlib # We use a md5 hash of generated sequences of 1000 samples # in the range [0, 6) for all but np.bool, where the range # is [0, 2). Hashes are for little endian numbers. tgt = {'bool': '7dd3170d7aa461d201a65f8bcf3944b0', 'int16': '1b7741b80964bb190c50d541dca1cac1', 'int32': '4dc9fcc2b395577ebb51793e58ed1a05', 'int64': '17db902806f448331b5a758d7d2ee672', 'int8': '27dd30c4e08a797063dffac2490b0be6', 'uint16': '1b7741b80964bb190c50d541dca1cac1', 'uint32': '4dc9fcc2b395577ebb51793e58ed1a05', 'uint64': '17db902806f448331b5a758d7d2ee672', 'uint8': '27dd30c4e08a797063dffac2490b0be6'} for dt in self.itype[1:]: np.random.seed(1234) # view as little endian for hash if sys.byteorder == 'little': val = self.rfunc(0, 6, size=1000, dtype=dt) else: val = self.rfunc(0, 6, size=1000, dtype=dt).byteswap() res = hashlib.md5(val.view(np.int8)).hexdigest() assert_(tgt[np.dtype(dt).name] == res) # bools do not depend on endianess np.random.seed(1234) val = self.rfunc(0, 2, size=1000, dtype=np.bool).view(np.int8) res = hashlib.md5(val).hexdigest() assert_(tgt[np.dtype(np.bool).name] == res)
def test_disperse_charges(): charges = np.array([[1., 0, 0], [0, 1., 0], [0, 0, 1.]]) d_sphere, pot = disperse_charges(HemiSphere(xyz=charges), 10) nt.assert_array_almost_equal(charges, d_sphere.vertices) a = np.sqrt(3)/2 charges = np.array([[3./5, 4./5, 0], [4./5, 3./5, 0]]) expected_charges = np.array([[0, 1., 0], [1., 0, 0]]) d_sphere, pot = disperse_charges(HemiSphere(xyz=charges), 1000, .2) nt.assert_array_almost_equal(expected_charges, d_sphere.vertices) 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 function seems to work with a larger number of charges 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_f2py(): # test that we can run f2py script if sys.platform == 'win32': exe_dir = dirname(sys.executable) if exe_dir.endswith('Scripts'): # virtualenv f2py_cmd = r"%s\f2py.py" % exe_dir else: f2py_cmd = r"%s\Scripts\f2py.py" % exe_dir code, stdout, stderr = run_command([sys.executable, f2py_cmd, '-v']) success = stdout.strip() == b'2' assert_(success, "Warning: f2py not found in path") else: version = sys.version_info major = str(version.major) minor = str(version.minor) f2py_cmds = ('f2py', 'f2py' + major, 'f2py' + major + '.' + minor) success = False for f2py_cmd in f2py_cmds: try: code, stdout, stderr = run_command([f2py_cmd, '-v']) assert_equal(stdout.strip(), b'2') success = True break except Exception: pass msg = "Warning: neither %s nor %s nor %s found in path" % f2py_cmds assert_(success, msg)
def check_id(self, dtype): # Test ID routines on a Hilbert matrix. # set parameters n = 300 eps = 1e-12 # construct Hilbert matrix A = hilbert(n).astype(dtype) if np.issubdtype(dtype, np.complexfloating): A = A * (1 + 1j) L = aslinearoperator(A) # find rank S = np.linalg.svd(A, compute_uv=False) try: rank = np.nonzero(S < eps)[0][0] except: rank = n # print input summary _debug_print("Hilbert matrix dimension: %8i" % n) _debug_print("Working precision: %8.2e" % eps) _debug_print("Rank to working precision: %8i" % rank) # set print format fmt = "%8.2e (s) / %5s" # test real ID routines _debug_print("-----------------------------------------") _debug_print("Real ID routines") _debug_print("-----------------------------------------") # fixed precision _debug_print("Calling iddp_id / idzp_id ...", ) t0 = time.time() k, idx, proj = pymatrixid.interp_decomp(A, eps, rand=False) t = time.time() - t0 B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) _debug_print("Calling iddp_aid / idzp_aid ...", ) t0 = time.time() k, idx, proj = pymatrixid.interp_decomp(A, eps) t = time.time() - t0 B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) _debug_print("Calling iddp_rid / idzp_rid ...", ) t0 = time.time() k, idx, proj = pymatrixid.interp_decomp(L, eps) t = time.time() - t0 B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) # fixed rank k = rank _debug_print("Calling iddr_id / idzr_id ...", ) t0 = time.time() idx, proj = pymatrixid.interp_decomp(A, k, rand=False) t = time.time() - t0 B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) _debug_print("Calling iddr_aid / idzr_aid ...", ) t0 = time.time() idx, proj = pymatrixid.interp_decomp(A, k) t = time.time() - t0 B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) _debug_print("Calling iddr_rid / idzr_rid ...", ) t0 = time.time() idx, proj = pymatrixid.interp_decomp(L, k) t = time.time() - t0 B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) # check skeleton and interpolation matrices idx, proj = pymatrixid.interp_decomp(A, k, rand=False) P = pymatrixid.reconstruct_interp_matrix(idx, proj) B = pymatrixid.reconstruct_skel_matrix(A, k, idx) assert_(np.allclose(B, A[:, idx[:k]], eps)) assert_(np.allclose(B.dot(P), A, eps)) # test SVD routines _debug_print("-----------------------------------------") _debug_print("SVD routines") _debug_print("-----------------------------------------") # fixed precision _debug_print("Calling iddp_svd / idzp_svd ...", ) t0 = time.time() U, S, V = pymatrixid.svd(A, eps, rand=False) t = time.time() - t0 B = np.dot(U, np.dot(np.diag(S), V.T.conj())) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) _debug_print("Calling iddp_asvd / idzp_asvd...", ) t0 = time.time() U, S, V = pymatrixid.svd(A, eps) t = time.time() - t0 B = np.dot(U, np.dot(np.diag(S), V.T.conj())) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) _debug_print("Calling iddp_rsvd / idzp_rsvd...", ) t0 = time.time() U, S, V = pymatrixid.svd(L, eps) t = time.time() - t0 B = np.dot(U, np.dot(np.diag(S), V.T.conj())) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) # fixed rank k = rank _debug_print("Calling iddr_svd / idzr_svd ...", ) t0 = time.time() U, S, V = pymatrixid.svd(A, k, rand=False) t = time.time() - t0 B = np.dot(U, np.dot(np.diag(S), V.T.conj())) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) _debug_print("Calling iddr_asvd / idzr_asvd ...", ) t0 = time.time() U, S, V = pymatrixid.svd(A, k) t = time.time() - t0 B = np.dot(U, np.dot(np.diag(S), V.T.conj())) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) _debug_print("Calling iddr_rsvd / idzr_rsvd ...", ) t0 = time.time() U, S, V = pymatrixid.svd(L, k) t = time.time() - t0 B = np.dot(U, np.dot(np.diag(S), V.T.conj())) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) # ID to SVD idx, proj = pymatrixid.interp_decomp(A, k, rand=False) Up, Sp, Vp = pymatrixid.id_to_svd(A[:, idx[:k]], idx, proj) B = U.dot(np.diag(S).dot(V.T.conj())) assert_(np.allclose(A, B, eps)) # Norm estimates s = svdvals(A) norm_2_est = pymatrixid.estimate_spectral_norm(A) assert_(np.allclose(norm_2_est, s[0], 1e-6)) B = A.copy() B[:, 0] *= 1.2 s = svdvals(A - B) norm_2_est = pymatrixid.estimate_spectral_norm_diff(A, B) assert_(np.allclose(norm_2_est, s[0], 1e-6)) # Rank estimates B = np.array([[1, 1, 0], [0, 0, 1], [0, 0, 1]], dtype=dtype) for M in [A, B]: ML = aslinearoperator(M) rank_tol = 1e-9 rank_np = np.linalg.matrix_rank(M, norm(M, 2) * rank_tol) rank_est = pymatrixid.estimate_rank(M, rank_tol) rank_est_2 = pymatrixid.estimate_rank(ML, rank_tol) assert_(rank_est >= rank_np) assert_(rank_est <= rank_np + 10) assert_(rank_est_2 >= rank_np - 4) assert_(rank_est_2 <= rank_np + 4)
def test_update(self): a,b = {},{} a["hello"] = 1 b["hello"] = 2 inline_tools.inline("a.update(b);",['a','b']) assert_(a == b)
def test_keys(self): a = {"hello": 1} keys = inline_tools.inline("return_val = a.keys();",['a']) assert_(keys == a.keys())
def test_values(self): a = {"hello": 1} values = inline_tools.inline("return_val = a.values();",['a']) assert_(values == a.values())
def test_items(self): a = {"hello": 1} items = inline_tools.inline("return_val = a.items();",['a']) assert_(items == a.items())
def test_clear(self): a = {"hello": 1} inline_tools.inline("a.clear();",['a']) assert_(not a)
def generic_get(self,code,args=['a']): a = {'b': 12345} res = inline_tools.inline(code,args) assert_(res == a['b'])
def check_function(self, t): assert_(t(True) == 1, repr(t(True))) assert_(t(False) == 0, repr(t(False))) assert_(t(0) == 0) assert_(t(None) == 0) assert_(t(0.0) == 0) assert_(t(0j) == 0) assert_(t(1j) == 1) assert_(t(234) == 1) assert_(t(234.6) == 1) assert_(t(long(234)) == 1) assert_(t(234.6 + 3j) == 1) assert_(t("234") == 1) assert_(t("aaa") == 1) assert_(t("") == 0) assert_(t([]) == 0) assert_(t(()) == 0) assert_(t({}) == 0) assert_(t(t) == 1) assert_(t(-234) == 1) assert_(t(10**100) == 1) assert_(t([234]) == 1) assert_(t((234, )) == 1) assert_(t(array(234)) == 1) assert_(t(array([234])) == 1) assert_(t(array([[234]])) == 1) assert_(t(array([234], "b")) == 1) assert_(t(array([234], "h")) == 1) assert_(t(array([234], "i")) == 1) assert_(t(array([234], "l")) == 1) assert_(t(array([234], "f")) == 1) assert_(t(array([234], "d")) == 1) assert_(t(array([234 + 3j], "F")) == 1) assert_(t(array([234], "D")) == 1) assert_(t(array(0)) == 0) assert_(t(array([0])) == 0) assert_(t(array([[0]])) == 0) assert_(t(array([0j])) == 0) assert_(t(array([1])) == 1) assert_raises(ValueError, t, array([0, 0]))
def test_nonzero(self): for t in "?bhilqpBHILQPfdgFDGO": x = array([1, 0, 2, 0], mask=[0, 0, 1, 1]) assert_(eq(nonzero(x), [0]))
def test_einsum_views(self): # pass-through for do_opt in [True, False]: a = np.arange(6) a.shape = (2, 3) b = np.einsum("...", a, optimize=do_opt) assert_(b.base is a) b = np.einsum(a, [Ellipsis], optimize=do_opt) assert_(b.base is a) b = np.einsum("ij", a, optimize=do_opt) assert_(b.base is a) assert_equal(b, a) b = np.einsum(a, [0, 1], optimize=do_opt) assert_(b.base is a) assert_equal(b, a) # output is writeable whenever input is writeable b = np.einsum("...", a, optimize=do_opt) assert_(b.flags["WRITEABLE"]) a.flags["WRITEABLE"] = False b = np.einsum("...", a, optimize=do_opt) assert_(not b.flags["WRITEABLE"]) # transpose a = np.arange(6) a.shape = (2, 3) b = np.einsum("ji", a, optimize=do_opt) assert_(b.base is a) assert_equal(b, a.T) b = np.einsum(a, [1, 0], optimize=do_opt) assert_(b.base is a) assert_equal(b, a.T) # diagonal a = np.arange(9) a.shape = (3, 3) b = np.einsum("ii->i", a, optimize=do_opt) assert_(b.base is a) assert_equal(b, [a[i, i] for i in range(3)]) b = np.einsum(a, [0, 0], [0], optimize=do_opt) assert_(b.base is a) assert_equal(b, [a[i, i] for i in range(3)]) # diagonal with various ways of broadcasting an additional dimension a = np.arange(27) a.shape = (3, 3, 3) b = np.einsum("...ii->...i", a, optimize=do_opt) assert_(b.base is a) assert_equal(b, [[x[i, i] for i in range(3)] for x in a]) b = np.einsum(a, [Ellipsis, 0, 0], [Ellipsis, 0], optimize=do_opt) assert_(b.base is a) assert_equal(b, [[x[i, i] for i in range(3)] for x in a]) b = np.einsum("ii...->...i", a, optimize=do_opt) assert_(b.base is a) assert_equal(b, [[x[i, i] for i in range(3)] for x in a.transpose(2, 0, 1)]) b = np.einsum(a, [0, 0, Ellipsis], [Ellipsis, 0], optimize=do_opt) assert_(b.base is a) assert_equal(b, [[x[i, i] for i in range(3)] for x in a.transpose(2, 0, 1)]) b = np.einsum("...ii->i...", a, optimize=do_opt) assert_(b.base is a) assert_equal(b, [a[:, i, i] for i in range(3)]) b = np.einsum(a, [Ellipsis, 0, 0], [0, Ellipsis], optimize=do_opt) assert_(b.base is a) assert_equal(b, [a[:, i, i] for i in range(3)]) b = np.einsum("jii->ij", a, optimize=do_opt) assert_(b.base is a) assert_equal(b, [a[:, i, i] for i in range(3)]) b = np.einsum(a, [1, 0, 0], [0, 1], optimize=do_opt) assert_(b.base is a) assert_equal(b, [a[:, i, i] for i in range(3)]) b = np.einsum("ii...->i...", a, optimize=do_opt) assert_(b.base is a) assert_equal(b, [a.transpose(2, 0, 1)[:, i, i] for i in range(3)]) b = np.einsum(a, [0, 0, Ellipsis], [0, Ellipsis], optimize=do_opt) assert_(b.base is a) assert_equal(b, [a.transpose(2, 0, 1)[:, i, i] for i in range(3)]) b = np.einsum("i...i->i...", a, optimize=do_opt) assert_(b.base is a) assert_equal(b, [a.transpose(1, 0, 2)[:, i, i] for i in range(3)]) b = np.einsum(a, [0, Ellipsis, 0], [0, Ellipsis], optimize=do_opt) assert_(b.base is a) assert_equal(b, [a.transpose(1, 0, 2)[:, i, i] for i in range(3)]) b = np.einsum("i...i->...i", a, optimize=do_opt) assert_(b.base is a) assert_equal(b, [[x[i, i] for i in range(3)] for x in a.transpose(1, 0, 2)]) b = np.einsum(a, [0, Ellipsis, 0], [Ellipsis, 0], optimize=do_opt) assert_(b.base is a) assert_equal(b, [[x[i, i] for i in range(3)] for x in a.transpose(1, 0, 2)]) # triple diagonal a = np.arange(27) a.shape = (3, 3, 3) b = np.einsum("iii->i", a, optimize=do_opt) assert_(b.base is a) assert_equal(b, [a[i, i, i] for i in range(3)]) b = np.einsum(a, [0, 0, 0], [0], optimize=do_opt) assert_(b.base is a) assert_equal(b, [a[i, i, i] for i in range(3)]) # swap axes a = np.arange(24) a.shape = (2, 3, 4) b = np.einsum("ijk->jik", a, optimize=do_opt) assert_(b.base is a) assert_equal(b, a.swapaxes(0, 1)) b = np.einsum(a, [0, 1, 2], [1, 0, 2], optimize=do_opt) assert_(b.base is a) assert_equal(b, a.swapaxes(0, 1))
def test_testAPI(self): assert_(not [ m for m in dir(np.ndarray) if m not in dir(MaskedArray) and not m.startswith('_') ])
def test_varstd(self): ( x, X, XX, m, mx, mX, mXX, ) = self.d assert_(eq(mX.var(axis=None), mX.compressed().var())) assert_(eq(mX.std(axis=None), mX.compressed().std())) assert_(eq(mXX.var(axis=3).shape, XX.var(axis=3).shape)) assert_(eq(mX.var().shape, X.var().shape)) (mXvar0, mXvar1) = (mX.var(axis=0), mX.var(axis=1)) for k in range(6): assert_(eq(mXvar1[k], mX[k].compressed().var())) assert_(eq(mXvar0[k], mX[:, k].compressed().var())) assert_(eq(np.sqrt(mXvar0[k]), mX[:, k].compressed().std()))
def test_testScalarArithmetic(self): xm = array(0, mask=1) #TODO FIXME: Find out what the following raises a warning in r8247 with np.errstate(divide='ignore'): assert_((1 / array(0)).mask) assert_((1 + xm).mask) assert_((-xm).mask) assert_((-xm).mask) assert_(maximum(xm, xm).mask) assert_(minimum(xm, xm).mask) assert_(xm.filled().dtype is xm._data.dtype) x = array(0, mask=0) assert_(x.filled() == x._data) assert_equal(str(xm), str(masked_print_option))
def test_reduce(self): a = self.d[0] assert_(not alltrue(a, axis=0)) assert_(sometrue(a, axis=0)) assert_equal(sum(a[:3], axis=0), 0) assert_equal(product(a, axis=0), 0)
def test_testAverage1(self): # Test of average. ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0]) assert_(eq(2.0, average(ott, axis=0))) assert_(eq(2.0, average(ott, weights=[1., 1., 2., 1.]))) result, wts = average(ott, weights=[1., 1., 2., 1.], returned=1) assert_(eq(2.0, result)) assert_(wts == 4.0) ott[:] = masked assert_(average(ott, axis=0) is masked) ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0]) ott = ott.reshape(2, 2) ott[:, 1] = masked assert_(eq(average(ott, axis=0), [2.0, 0.0])) assert_(average(ott, axis=1)[0] is masked) assert_(eq([2., 0.], average(ott, axis=0))) result, wts = average(ott, axis=0, returned=1) assert_(eq(wts, [1., 0.]))
def test_testArrayMethods(self): a = array([1, 3, 2]) assert_(eq(a.any(), a._data.any())) assert_(eq(a.all(), a._data.all())) assert_(eq(a.argmax(), a._data.argmax())) assert_(eq(a.argmin(), a._data.argmin())) assert_(eq(a.choose(0, 1, 2, 3, 4), a._data.choose(0, 1, 2, 3, 4))) assert_(eq(a.compress([1, 0, 1]), a._data.compress([1, 0, 1]))) assert_(eq(a.conj(), a._data.conj())) assert_(eq(a.conjugate(), a._data.conjugate())) m = array([[1, 2], [3, 4]]) assert_(eq(m.diagonal(), m._data.diagonal())) assert_(eq(a.sum(), a._data.sum())) assert_(eq(a.take([1, 2]), a._data.take([1, 2]))) assert_(eq(m.transpose(), m._data.transpose()))
def test_testTakeTransposeInnerOuter(self): # Test of take, transpose, inner, outer products x = arange(24) y = np.arange(24) x[5:6] = masked x = x.reshape(2, 3, 4) y = y.reshape(2, 3, 4) assert_(eq(np.transpose(y, (2, 0, 1)), transpose(x, (2, 0, 1)))) assert_(eq(np.take(y, (2, 0, 1), 1), take(x, (2, 0, 1), 1))) assert_(eq(np.inner(filled(x, 0), filled(y, 0)), inner(x, y))) assert_(eq(np.outer(filled(x, 0), filled(y, 0)), outer(x, y))) y = array(['abc', 1, 'def', 2, 3], object) y[2] = masked t = take(y, [0, 3, 4]) assert_(t[0] == 'abc') assert_(t[1] == 2) assert_(t[2] == 3)
def test_testAverage2(self): # More tests of average. w1 = [0, 1, 1, 1, 1, 0] w2 = [[0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 1]] x = arange(6) assert_(allclose(average(x, axis=0), 2.5)) assert_(allclose(average(x, axis=0, weights=w1), 2.5)) y = array([arange(6), 2.0 * arange(6)]) assert_( allclose(average(y, None), np.add.reduce(np.arange(6)) * 3. / 12.)) assert_(allclose(average(y, axis=0), np.arange(6) * 3. / 2.)) assert_( allclose(average(y, axis=1), [average(x, axis=0), average(x, axis=0) * 2.0])) assert_(allclose(average(y, None, weights=w2), 20. / 6.)) assert_( allclose(average(y, axis=0, weights=w2), [0., 1., 2., 3., 4., 10.])) assert_( allclose(average(y, axis=1), [average(x, axis=0), average(x, axis=0) * 2.0])) m1 = zeros(6) m2 = [0, 0, 1, 1, 0, 0] m3 = [[0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0]] m4 = ones(6) m5 = [0, 1, 1, 1, 1, 1] assert_(allclose(average(masked_array(x, m1), axis=0), 2.5)) assert_(allclose(average(masked_array(x, m2), axis=0), 2.5)) assert_(average(masked_array(x, m4), axis=0) is masked) assert_equal(average(masked_array(x, m5), axis=0), 0.0) assert_equal(count(average(masked_array(x, m4), axis=0)), 0) z = masked_array(y, m3) assert_(allclose(average(z, None), 20. / 6.)) assert_(allclose(average(z, axis=0), [0., 1., 99., 99., 4.0, 7.5])) assert_(allclose(average(z, axis=1), [2.5, 5.0])) assert_( allclose(average(z, axis=0, weights=w2), [0., 1., 99., 99., 4.0, 10.0])) a = arange(6) b = arange(6) * 3 r1, w1 = average([[a, b], [b, a]], axis=1, returned=1) assert_equal(shape(r1), shape(w1)) assert_equal(r1.shape, w1.shape) r2, w2 = average(ones((2, 2, 3)), axis=0, weights=[3, 1], returned=1) assert_equal(shape(w2), shape(r2)) r2, w2 = average(ones((2, 2, 3)), returned=1) assert_equal(shape(w2), shape(r2)) r2, w2 = average(ones((2, 2, 3)), weights=ones((2, 2, 3)), returned=1) assert_(shape(w2) == shape(r2)) a2d = array([[1, 2], [0, 4]], float) a2dm = masked_array(a2d, [[0, 0], [1, 0]]) a2da = average(a2d, axis=0) assert_(eq(a2da, [0.5, 3.0])) a2dma = average(a2dm, axis=0) assert_(eq(a2dma, [1.0, 3.0])) a2dma = average(a2dm, axis=None) assert_(eq(a2dma, 7. / 3.)) a2dma = average(a2dm, axis=1) assert_(eq(a2dma, [1.5, 4.0]))
def test_testOddFeatures(self): # Test of other odd features x = arange(20) x = x.reshape(4, 5) x.flat[5] = 12 assert_(x[1, 0] == 12) z = x + 10j * x assert_(eq(z.real, x)) assert_(eq(z.imag, 10 * x)) assert_(eq((z * conjugate(z)).real, 101 * x * x)) z.imag[...] = 0.0 x = arange(10) x[3] = masked assert_(str(x[3]) == str(masked)) c = x >= 8 assert_(count(where(c, masked, masked)) == 0) assert_(shape(where(c, masked, masked)) == c.shape) z = where(c, x, masked) assert_(z.dtype is x.dtype) assert_(z[3] is masked) assert_(z[4] is masked) assert_(z[7] is masked) assert_(z[8] is not masked) assert_(z[9] is not masked) assert_(eq(x, z)) z = where(c, masked, x) assert_(z.dtype is x.dtype) assert_(z[3] is masked) assert_(z[4] is not masked) assert_(z[7] is not masked) assert_(z[8] is masked) assert_(z[9] is masked) z = masked_where(c, x) assert_(z.dtype is x.dtype) assert_(z[3] is masked) assert_(z[4] is not masked) assert_(z[7] is not masked) assert_(z[8] is masked) assert_(z[9] is masked) assert_(eq(x, z)) x = array([1., 2., 3., 4., 5.]) c = array([1, 1, 1, 0, 0]) x[2] = masked z = where(c, x, -x) assert_(eq(z, [1., 2., 0., -4., -5])) c[0] = masked z = where(c, x, -x) assert_(eq(z, [1., 2., 0., -4., -5])) assert_(z[0] is masked) assert_(z[1] is not masked) assert_(z[2] is masked) assert_(eq(masked_where(greater(x, 2), x), masked_greater(x, 2))) assert_( eq(masked_where(greater_equal(x, 2), x), masked_greater_equal(x, 2))) assert_(eq(masked_where(less(x, 2), x), masked_less(x, 2))) assert_(eq(masked_where(less_equal(x, 2), x), masked_less_equal(x, 2))) assert_(eq(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2))) assert_(eq(masked_where(equal(x, 2), x), masked_equal(x, 2))) assert_(eq(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2))) assert_(eq(masked_inside(list(range(5)), 1, 3), [0, 199, 199, 199, 4])) assert_(eq(masked_outside(list(range(5)), 1, 3), [199, 1, 2, 3, 199])) assert_( eq( masked_inside(array(list(range(5)), mask=[1, 0, 0, 0, 0]), 1, 3).mask, [1, 1, 1, 1, 0])) assert_( eq( masked_outside(array(list(range(5)), mask=[0, 1, 0, 0, 0]), 1, 3).mask, [1, 1, 0, 0, 1])) assert_( eq( masked_equal(array(list(range(5)), mask=[1, 0, 0, 0, 0]), 2).mask, [1, 0, 1, 0, 0])) assert_( eq( masked_not_equal(array([2, 2, 1, 2, 1], mask=[1, 0, 0, 0, 0]), 2).mask, [1, 0, 1, 0, 1])) assert_( eq(masked_where([1, 1, 0, 0, 0], [1, 2, 3, 4, 5]), [99, 99, 3, 4, 5])) atest = ones((10, 10, 10), dtype=np.float32) btest = zeros(atest.shape, MaskType) ctest = masked_where(btest, atest) assert_(eq(atest, ctest)) z = choose(c, (-x, x)) assert_(eq(z, [1., 2., 0., -4., -5])) assert_(z[0] is masked) assert_(z[1] is not masked) assert_(z[2] is masked) x = arange(6) x[5] = masked y = arange(6) * 10 y[2] = masked c = array([1, 1, 1, 0, 0, 0], mask=[1, 0, 0, 0, 0, 0]) cm = c.filled(1) z = where(c, x, y) zm = where(cm, x, y) assert_(eq(z, zm)) assert_(getmask(zm) is nomask) assert_(eq(zm, [0, 1, 2, 30, 40, 50])) z = where(c, masked, 1) assert_(eq(z, [99, 99, 99, 1, 1, 1])) z = where(c, 1, masked) assert_(eq(z, [99, 1, 1, 99, 99, 99]))
def test_testInplace(self): # Test of inplace operations and rich comparisons y = arange(10) x = arange(10) xm = arange(10) xm[2] = masked x += 1 assert_(eq(x, y + 1)) xm += 1 assert_(eq(x, y + 1)) x = arange(10) xm = arange(10) xm[2] = masked x -= 1 assert_(eq(x, y - 1)) xm -= 1 assert_(eq(xm, y - 1)) x = arange(10) * 1.0 xm = arange(10) * 1.0 xm[2] = masked x *= 2.0 assert_(eq(x, y * 2)) xm *= 2.0 assert_(eq(xm, y * 2)) x = arange(10) * 2 xm = arange(10) xm[2] = masked x //= 2 assert_(eq(x, y)) xm //= 2 assert_(eq(x, y)) x = arange(10) * 1.0 xm = arange(10) * 1.0 xm[2] = masked x /= 2.0 assert_(eq(x, y / 2.0)) xm /= arange(10) assert_(eq(xm, ones((10, )))) x = arange(10).astype(np.float32) xm = arange(10) xm[2] = masked x += 1. assert_(eq(x, y + 1.))
def test_testPut2(self): # Test of put d = arange(5) x = array(d, mask=[0, 0, 0, 0, 0]) z = array([10, 40], mask=[1, 0]) assert_(x[2] is not masked) assert_(x[3] is not masked) x[2:4] = z assert_(x[2] is masked) assert_(x[3] is not masked) assert_(eq(x, [0, 1, 10, 40, 4])) d = arange(5) x = array(d, mask=[0, 0, 0, 0, 0]) y = x[2:4] z = array([10, 40], mask=[1, 0]) assert_(x[2] is not masked) assert_(x[3] is not masked) y[:] = z assert_(y[0] is masked) assert_(y[1] is not masked) assert_(eq(y, [10, 40])) assert_(x[2] is masked) assert_(x[3] is not masked) assert_(eq(x, [0, 1, 10, 40, 4]))
def test_testMinMax2(self): # Test of minimum, maximum. assert_(eq(minimum([1, 2, 3], [4, 0, 9]), [1, 0, 3])) assert_(eq(maximum([1, 2, 3], [4, 0, 9]), [4, 2, 9])) x = arange(5) y = arange(5) - 2 x[3] = masked y[0] = masked assert_(eq(minimum(x, y), where(less(x, y), x, y))) assert_(eq(maximum(x, y), where(greater(x, y), x, y))) assert_(minimum.reduce(x) == 0) assert_(maximum.reduce(x) == 4)
def test_testCopySize(self): # Tests of some subtle points of copying and sizing. n = [0, 0, 1, 0, 0] m = make_mask(n) m2 = make_mask(m) assert_(m is m2) m3 = make_mask(m, copy=1) assert_(m is not m3) x1 = np.arange(5) y1 = array(x1, mask=m) assert_(y1._data is not x1) assert_(allequal(x1, y1._data)) assert_(y1.mask is m) y1a = array(y1, copy=0) # For copy=False, one might expect that the array would just # passed on, i.e., that it would be "is" instead of "==". # See gh-4043 for discussion. assert_(y1a._mask.__array_interface__ == y1._mask.__array_interface__) y2 = array(x1, mask=m3, copy=0) assert_(y2.mask is m3) assert_(y2[2] is masked) y2[2] = 9 assert_(y2[2] is not masked) assert_(y2.mask is m3) assert_(allequal(y2.mask, 0)) y2a = array(x1, mask=m, copy=1) assert_(y2a.mask is not m) assert_(y2a[2] is masked) y2a[2] = 9 assert_(y2a[2] is not masked) assert_(y2a.mask is not m) assert_(allequal(y2a.mask, 0)) y3 = array(x1 * 1.0, mask=m) assert_(filled(y3).dtype is (x1 * 1.0).dtype) x4 = arange(4) x4[2] = masked y4 = resize(x4, (8, )) assert_(eq(concatenate([x4, x4]), y4)) assert_(eq(getmask(y4), [0, 0, 1, 0, 0, 0, 1, 0])) y5 = repeat(x4, (2, 2, 2, 2), axis=0) assert_(eq(y5, [0, 0, 1, 1, 2, 2, 3, 3])) y6 = repeat(x4, 2, axis=0) assert_(eq(y5, y6))
def test_testMaPut(self): (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1] i = np.nonzero(m)[0] put(ym, i, zm) assert_(all(take(ym, i, axis=0) == zm))
def test_testAddSumProd(self): # Test add, sum, product. (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d assert_(eq(np.add.reduce(x), add.reduce(x))) assert_(eq(np.add.accumulate(x), add.accumulate(x))) assert_(eq(4, sum(array(4), axis=0))) assert_(eq(4, sum(array(4), axis=0))) assert_(eq(np.sum(x, axis=0), sum(x, axis=0))) assert_(eq(np.sum(filled(xm, 0), axis=0), sum(xm, axis=0))) assert_(eq(np.sum(x, 0), sum(x, 0))) assert_(eq(np.product(x, axis=0), product(x, axis=0))) assert_(eq(np.product(x, 0), product(x, 0))) assert_(eq(np.product(filled(xm, 1), axis=0), product(xm, axis=0))) if len(s) > 1: assert_(eq(np.concatenate((x, y), 1), concatenate((xm, ym), 1))) assert_(eq(np.add.reduce(x, 1), add.reduce(x, 1))) assert_(eq(np.sum(x, 1), sum(x, 1))) assert_(eq(np.product(x, 1), product(x, 1)))
def test_testPut(self): # Test of put d = arange(5) n = [0, 0, 0, 1, 1] m = make_mask(n) m2 = m.copy() x = array(d, mask=m) assert_(x[3] is masked) assert_(x[4] is masked) x[[1, 4]] = [10, 40] assert_(x.mask is m) assert_(x[3] is masked) assert_(x[4] is not masked) assert_(eq(x, [0, 10, 2, -1, 40])) x = array(d, mask=m2, copy=True) x.put([0, 1, 2], [-1, 100, 200]) assert_(x.mask is not m2) assert_(x[3] is masked) assert_(x[4] is masked) assert_(eq(x, [-1, 100, 200, 0, 0]))
def test_testUfuncs1(self): # Test various functions such as sin, cos. (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d assert_(eq(np.cos(x), cos(xm))) assert_(eq(np.cosh(x), cosh(xm))) assert_(eq(np.sin(x), sin(xm))) assert_(eq(np.sinh(x), sinh(xm))) assert_(eq(np.tan(x), tan(xm))) assert_(eq(np.tanh(x), tanh(xm))) with np.errstate(divide='ignore', invalid='ignore'): assert_(eq(np.sqrt(abs(x)), sqrt(xm))) assert_(eq(np.log(abs(x)), log(xm))) assert_(eq(np.log10(abs(x)), log10(xm))) assert_(eq(np.exp(x), exp(xm))) assert_(eq(np.arcsin(z), arcsin(zm))) assert_(eq(np.arccos(z), arccos(zm))) assert_(eq(np.arctan(z), arctan(zm))) assert_(eq(np.arctan2(x, y), arctan2(xm, ym))) assert_(eq(np.absolute(x), absolute(xm))) assert_(eq(np.equal(x, y), equal(xm, ym))) assert_(eq(np.not_equal(x, y), not_equal(xm, ym))) assert_(eq(np.less(x, y), less(xm, ym))) assert_(eq(np.greater(x, y), greater(xm, ym))) assert_(eq(np.less_equal(x, y), less_equal(xm, ym))) assert_(eq(np.greater_equal(x, y), greater_equal(xm, ym))) assert_(eq(np.conjugate(x), conjugate(xm))) assert_(eq(np.concatenate((x, y)), concatenate((xm, ym)))) assert_(eq(np.concatenate((x, y)), concatenate((x, y)))) assert_(eq(np.concatenate((x, y)), concatenate((xm, y)))) assert_(eq(np.concatenate((x, y, x)), concatenate((x, ym, x))))
def test_testCI(self): # Test of conversions and indexing x1 = np.array([1, 2, 4, 3]) x2 = array(x1, mask=[1, 0, 0, 0]) x3 = array(x1, mask=[0, 1, 0, 1]) x4 = array(x1) # test conversion to strings str(x2) # raises? repr(x2) # raises? assert_(eq(np.sort(x1), sort(x2, fill_value=0))) # tests of indexing assert_(type(x2[1]) is type(x1[1])) assert_(x1[1] == x2[1]) assert_(x2[0] is masked) assert_(eq(x1[2], x2[2])) assert_(eq(x1[2:5], x2[2:5])) assert_(eq(x1[:], x2[:])) assert_(eq(x1[1:], x3[1:])) x1[2] = 9 x2[2] = 9 assert_(eq(x1, x2)) x1[1:3] = 99 x2[1:3] = 99 assert_(eq(x1, x2)) x2[1] = masked assert_(eq(x1, x2)) x2[1:3] = masked assert_(eq(x1, x2)) x2[:] = x1 x2[1] = masked assert_(allequal(getmask(x2), array([0, 1, 0, 0]))) x3[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0]) assert_(allequal(getmask(x3), array([0, 1, 1, 0]))) x4[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0]) assert_(allequal(getmask(x4), array([0, 1, 1, 0]))) assert_(allequal(x4, array([1, 2, 3, 4]))) x1 = np.arange(5) * 1.0 x2 = masked_values(x1, 3.0) assert_(eq(x1, x2)) assert_(allequal(array([0, 0, 0, 1, 0], MaskType), x2.mask)) assert_(eq(3.0, x2.fill_value)) x1 = array([1, 'hello', 2, 3], object) x2 = np.array([1, 'hello', 2, 3], object) s1 = x1[1] s2 = x2[1] assert_equal(type(s2), str) assert_equal(type(s1), str) assert_equal(s1, s2) assert_(x1[1:1].shape == (0, ))
def test_testMixedArithmetic(self): na = np.array([1]) ma = array([1]) assert_(isinstance(na + ma, MaskedArray)) assert_(isinstance(ma + na, MaskedArray))
def test_xtestCount(self): # Test count ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0]) assert_(count(ott).dtype.type is np.intp) assert_equal(3, count(ott)) assert_equal(1, count(1)) assert_(eq(0, array(1, mask=[1]))) ott = ott.reshape((2, 2)) assert_(count(ott).dtype.type is np.intp) assert_(isinstance(count(ott, 0), np.ndarray)) assert_(count(ott).dtype.type is np.intp) assert_(eq(3, count(ott))) assert_(getmask(count(ott, 0)) is nomask) assert_(eq([1, 2], count(ott, 0)))