def test_laplace_2_level_bootstrap(self): """We improve vectors by relaxation -> coarsening creation -> 2-level relaxation cycles. P = SVD interpolation = R^T.""" n = 16 kh = 0 a = hm.linalg.helmholtz_1d_operator(kh, n) x, multilevel = old_code.repetitive.bootstrap_repetitive.generate_test_matrix( a, 0, num_examples=4, num_sweeps=20, num_bootstrap_steps=2) assert x.shape == (16, 4) assert len(multilevel) == 2 # The coarse level should be Galerkin coarsening with piecewise constant interpolation. coarse_level = multilevel[1] p = coarse_level.p.asarray() assert_array_equal(p[0], [[0], [0]]) assert_array_almost_equal(p[1], [[-0.707228], [-0.706985]]) r = coarse_level.r.asarray() assert_array_almost_equal(r, [[-0.707228, -0.706985]]) ac_0 = coarse_level.a[0] coarse_level.print() assert_array_equal(ac_0.nonzero()[1], [0, 1, 7]) assert_array_almost_equal(ac_0.data, [-1., 0.5, 0.5]) # Vectors have much lower residual after 2-level relaxation cycles. assert (hm.linalg.scaled_norm_of_matrix(a.dot(x)) / hm.linalg.scaled_norm_of_matrix(x)).mean() == \ pytest.approx(0.045054, 1e-3)
def test_shaped_dtype(self): c = StringIO("aaaa 1.0 8.0 1 2 3 4 5 6") dt = np.dtype([('name', 'S4'), ('x', float), ('y', float), ('block', int, (2, 3))]) x = textadapter.loadtxt(c, dtype=dt) a = np.array([('aaaa', 1.0, 8.0, [[1, 2, 3], [4, 5, 6]])], dtype=dt) assert_array_equal(x, a)
def test_gft_using_generator(self): def count(): for i in range(10): yield "%d" % i res = textadapter.genfromtxt(count()) assert_array_equal(res, np.arange(10))
def check_chisquare(f_obs, f_exp, ddof, axis, expected_chi2): # Use this only for arrays that have no masked values. f_obs = np.asarray(f_obs) if axis is None: num_obs = f_obs.size else: if axis == 'no': use_axis = 0 else: use_axis = axis b = np.broadcast(f_obs, f_exp) num_obs = b.shape[use_axis] if axis == 'no': chi2, p = mstats.chisquare(f_obs, f_exp=f_exp, ddof=ddof) else: chi2, p = mstats.chisquare(f_obs, f_exp=f_exp, ddof=ddof, axis=axis) assert_array_equal(chi2, expected_chi2) ddof = np.asarray(ddof) expected_p = stats.chisqprob(expected_chi2, num_obs - 1 - ddof) assert_array_equal(p, expected_p) # Also compare to stats.chisquare if axis == 'no': stats_chisq, stats_p = stats.chisquare(f_obs, f_exp=f_exp, ddof=ddof) else: stats_chisq, stats_p = stats.chisquare(f_obs, f_exp=f_exp, ddof=ddof, axis=axis) assert_array_almost_equal(chi2, stats_chisq) assert_array_almost_equal(p, stats_p)
def test_zscore_single_dup(self): """ Test z-score on a single AnalogSignal, asking to return a duplicate. """ signal = neo.AnalogSignal(self.test_seq1, units='mV', t_start=0. * pq.ms, sampling_rate=1000. * pq.Hz, dtype=float) m = np.mean(self.test_seq1) s = np.std(self.test_seq1) target = (self.test_seq1 - m) / s assert_array_equal(target, scipy.stats.zscore(self.test_seq1)) result = elephant.signal_processing.zscore(signal, inplace=False) assert_array_almost_equal(result.magnitude, target.reshape(-1, 1), decimal=9) self.assertEqual(result.units, pq.Quantity(1. * pq.dimensionless)) # Assert original signal is untouched self.assertEqual(signal[0].magnitude, self.test_seq1[0])
def test_setxor1d(self): # Test setxor1d a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1]) b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1]) test = setxor1d(a, b) assert_equal(test, array([3, 4, 7])) # a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1]) b = [1, 2, 3, 4, 5] test = setxor1d(a, b) assert_equal(test, array([3, 4, 7, -1], mask=[0, 0, 0, 1])) # a = array([1, 2, 3]) b = array([6, 5, 4]) test = setxor1d(a, b) assert_(isinstance(test, MaskedArray)) assert_equal(test, [1, 2, 3, 4, 5, 6]) # a = array([1, 8, 2, 3], mask=[0, 1, 0, 0]) b = array([6, 5, 4, 8], mask=[0, 0, 0, 1]) test = setxor1d(a, b) assert_(isinstance(test, MaskedArray)) assert_equal(test, [1, 2, 3, 4, 5, 6]) # assert_array_equal([], setxor1d([], []))
def test_chisquare_masked_arrays(): # The other tests were taken from the tests for stats.chisquare, so # they don't test the function with masked arrays. Here masked arrays # are tested. obs = np.array([[8, 8, 16, 32, -1], [-1, -1, 3, 4, 5]]).T mask = np.array([[0, 0, 0, 0, 1], [1, 1, 0, 0, 0]]).T mobs = ma.masked_array(obs, mask) expected_chisq = np.array([24.0, 0.5]) chisq, p = mstats.chisquare(mobs) assert_array_equal(chisq, expected_chisq) assert_array_almost_equal( p, stats.chisqprob(expected_chisq, mobs.count(axis=0) - 1)) chisq, p = mstats.chisquare(mobs.T, axis=1) assert_array_equal(chisq, expected_chisq) assert_array_almost_equal( p, stats.chisqprob(expected_chisq, mobs.T.count(axis=1) - 1)) # When axis=None, the two values should have type np.float64. chisq, p = mstats.chisquare([1, 2, 3], axis=None) assert_(isinstance(chisq, np.float64)) assert_(isinstance(p, np.float64)) assert_equal(chisq, 1.0) assert_almost_equal(p, stats.chisqprob(1.0, 2))
def testGate(self): verts = array([[-.1,-.1],[-.1,1.1],[1.1,1.1], [1.1,-.1]]) cols = [0,1] g = PolyGate(verts, cols) self.fcms.gate(g) assert_array_equal(self.fcms['test_fcm1'].view(), array([[1,1,1]]), 'Gating failed') assert_array_equal(self.fcms['test_fcm2'].view(), array([[1,1,1]]), 'Gating failed')
def test_generator_source(self): def count(): for i in range(10): yield "%d" % i res = textadapter.loadtxt(count()) assert_array_equal(res, np.arange(10))
def test_3d_shaped_dtype(self): c = StringIO("aaaa 1.0 8.0 1 2 3 4 5 6 7 8 9 10 11 12") dt = np.dtype([('name', 'S4'), ('x', float), ('y', float), ('block', int, (2, 2, 3))]) x = np.loadtxt(c, dtype=dt) a = np.array([('aaaa', 1.0, 8.0, [[[1, 2, 3], [4, 5, 6]],[[7, 8, 9], [10, 11, 12]]])], dtype=dt) assert_array_equal(x, a)
def test_fancy_dtype(self): c = StringIO() c.write(asbytes('1,2,3.0\n4,5,6.0\n')) c.seek(0) dt = np.dtype([('x', int), ('y', [('t', int), ('s', float)])]) x = np.loadtxt(c, dtype=dt, delimiter=',') a = np.array([(1, (2, 3.0)), (4, (5, 6.0))], dt) assert_array_equal(x, a)
def test_comments(self): c = StringIO() c.write(asbytes('# comment\n1,2,3,5\n')) c.seek(0) x = np.loadtxt(c, dtype=int, delimiter=',', \ comments='#') a = np.array([1, 2, 3, 5], int) assert_array_equal(x, a)
def test_missing(self): c = StringIO() c.write(asbytes('1,2,3,,5\n')) c.seek(0) x = np.loadtxt(c, dtype=int, delimiter=',', \ converters={3:lambda s: int(s or - 999)}) a = np.array([1, 2, 3, -999, 5], int) assert_array_equal(x, a)
def test_rad_alt_masked(self): alt_rad = P(name='Altitude Radio', array=np.ma.array([0]*20, mask=[1]*20)) alt_baro = P(name='Altitude STD', array=np.ma.array([0]*20)) gog = M(name='Gear On Ground', array=np.ma.array([1]*20), values_mapping={0:'Air', 1:'Ground'}) alt_aal = P(name='Altitude AAL', array=np.ma.array([10]*20)) alt_agl = AltitudeAGL() alt_agl.derive(alt_rad, alt_aal, alt_baro, gog) assert_array_equal(alt_agl.array, alt_aal.array)
def test_fancy_dtype(self): c = StringIO() c.write('1,2,3.0\n4,5,6.0\n') c.seek(0) dt = np.dtype([('x', int), ('y', [('t', int), ('s', float)])]) x = textadapter.loadtxt(c, dtype=dt, delimiter=',') a = np.array([(1, (2, 3.0)), (4, (5, 6.0))], dt) assert_array_equal(x, a)
def test_addOnes(self): linreg = LinearRegression(self.dataSet.nrInputVars) matrix = self.dataSet.inputs with1 = linreg.addOnes(matrix) assert_array_equal(with1[:, 0], np.ones([ matrix.shape[0], ])) assert_array_equal(with1[:, 1:], matrix)
def test_single_non_masked_value_on_axis(self): data = [[1., 0.], [0., 3.], [0., 0.]] masked_arr = np.ma.masked_equal(data, 0) expected = [1., 3.] assert_array_equal(np.ma.median(masked_arr, axis=0), expected)
def test_comments(self): c = StringIO() c.write('# comment\n1,2,3,5\n') c.seek(0) x = textadapter.loadtxt(c, dtype=int, delimiter=',', \ comments='#') a = np.array([1, 2, 3, 5], int) assert_array_equal(x, a)
def test_missing(self): c = StringIO() c.write('1,2,3,,5\n') c.seek(0) x = textadapter.loadtxt(c, dtype=int, delimiter=',', \ converters={3:lambda s: int(s or - 999)}) a = np.array([1, 2, 3, -999, 5], int) assert_array_equal(x, a)
def test_shaped_dtype(self): c = StringIO("aaaa 1.0 8.0 1 2 3 4 5 6") dt = np.dtype([('name', 'S4'), ('x', float), ('y', float), ('block', int, (2, 3))]) x = np.ndfromtxt(c, dtype=dt) a = np.array([('aaaa', 1.0, 8.0, [[1, 2, 3], [4, 5, 6]])], dtype=dt) assert_array_equal(x, a)
def test_on_ground(self): alt_rad = P(name='Altitude Radio', array=np.ma.array([-1, 0, 6, 0, -1, -1, 0, 6, 0, -1, -1, 0, 6, 0, -1, -1, 0, 6, 0, -1])) alt_baro = P(name='Altitude STD', array=np.ma.array([0]*20)) gog = M(name='Gear On Ground', array=np.ma.array([1]*20), values_mapping={0:'Air', 1:'Ground'}) alt_aal = AltitudeAGL() alt_aal.derive(alt_rad, None, alt_baro, gog) expected = [0]*20 assert_array_equal(alt_aal.array, expected)
def test_h_mult(): X = array([[1, 0, 1], [0, 0, 1], [1, 0, 1], [1, 0, 0], [1, 1, 1], [1, 0, 0]]) theta = array([[1, 0, 3], [0, 2, 1], [2, 3, 1]]) assert_array_equal(h(X, theta), [[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0]])
def test_empty_field_after_tab(self): c = StringIO() c.write('1 \t2 \t3\tstart \n4\t5\t6\t \n7\t8\t9.5\t') c.seek(0) dt = { 'names': ('x', 'y', 'z', 'comment'), 'formats': ('<i4', '<i4', '<f4', '|S8')} x = iopro.loadtxt(c, dtype=dt, delimiter='\t') a = np.array(['start ', ' ', ''], dtype='|S8') assert_array_equal(x['comment'], a)
def test_gzip_loadtxt_from_string(): s = StringIO() f = gzip.GzipFile(fileobj=s, mode="w") f.write(asbytes('1 2 3\n')) f.close() s.seek(0) f = gzip.GzipFile(fileobj=s, mode="r") assert_array_equal(np.loadtxt(f), [1, 2, 3])
def test_converters_with_usecols(self): c = StringIO() c.write(asbytes('1,2,3,,5\n6,7,8,9,10\n')) c.seek(0) x = np.loadtxt(c, dtype=int, delimiter=',', \ converters={3:lambda s: int(s or - 999)}, \ usecols=(1, 3,)) a = np.array([[2, -999], [7, 9]], int) assert_array_equal(x, a)
def test_left_admm(): n, t = 2, 3 beta = .5 ladmm = LeftAdmm(numpy.zeros(t), numpy.zeros(t), beta, t, n) control = ladmm.no_control() assert_array_equal(ladmm.grad(control), numpy.zeros(control.shape)) ladmm = LeftAdmm(numpy.ones(t), numpy.zeros(t), beta, t, n) x = ladmm.fs(control) assert_array_equal(ladmm.jx(x, control), [0, -beta, 0, -beta, 0, -beta])
def test_record_3(self): c = StringIO() c.write(asbytes('1312 foo\n1534 bar\n4444 qux')) c.seek(0) dt = [('num', np.float64)] x = np.fromregex(c, r"(\d+)\s+...", dt) a = np.array([(1312,), (1534,), (4444,)], dtype=dt) assert_array_equal(x, a)
def test_map_reduce(self): data = np.array(range(1, 100)) result1 = map1(data) result2 = map2(data) for n_jobs in [-1, 1, 2]: assert_array_equal(result1, map_reduce(data, split_data, map1, reduce1, n_jobs)) self.assertEqual(result2, map_reduce(data, split_data, map2, reduce2, n_jobs))
def test_converters_with_usecols(self): c = StringIO() c.write('1,2,3,,5\n6,7,8,9,10\n') c.seek(0) x = textadapter.loadtxt(c, dtype=int, delimiter=',', \ converters={3:lambda s: int(s or - 999)}, \ usecols=(1, 3,)) a = np.array([[2, -999], [7, 9]], int) assert_array_equal(x, a)
def test_ctm_adjoint(): scen, control = small_scenario() state = CTMSimulator().simulate(scen, control) hx = CTMAdjoint(scen).hx(state, control) hu = CTMAdjoint(scen).hu(state, control) assert_array_equal(hx, np.tril(hx)) u = np.ones(control.flatten().shape) * 0.01 adjoint = CTMAdjoint(scen) assert_array_almost_equal(adjoint.grad(u), adjoint.grad_fd(u), 3)
def test_basic(self): one = P('Groundspeed (1)', np.ma.array([100, 200, 300]), frequency=0.5, offset=0.0) two = P('Groundspeed (2)', np.ma.array([150, 250, 350]), frequency=0.5, offset=1.0) gs = Groundspeed() gs.derive(one, two) # Note: end samples are not 100 & 350 due to method of merging. assert_array_equal(gs.array[1:-1], np.array([150, 200, 250, 300])) self.assertEqual(gs.frequency, 1.0) self.assertEqual(gs.offset, 0.0)
def test_union1d(self): # Test union1d a = array([1, 2, 5, 7, 5, -1], mask=[0, 0, 0, 0, 0, 1]) b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1]) test = union1d(a, b) control = array([1, 2, 3, 4, 5, 7, -1], mask=[0, 0, 0, 0, 0, 0, 1]) assert_equal(test, control) # assert_array_equal([], union1d([], []))
def test_gzip_loadtxt_from_string(): s = StringIO() f = gzip.GzipFile(fileobj=s, mode="w") f.write(asbytes('1 2 3\n')) f.close() s.seek(0) f = gzip.GzipFile(fileobj=s, mode="r") assert_array_equal(textadapter.loadtxt(f), [1, 2, 3])
def testGate(self): verts = array([[-.1, -.1], [-.1, 1.1], [1.1, 1.1], [1.1, -.1]]) cols = [0, 1] g = PolyGate(verts, cols) self.fcms.gate(g) assert_array_equal(self.fcms['test_fcm1'].view(), array([[1, 1, 1]]), 'Gating failed') assert_array_equal(self.fcms['test_fcm2'].view(), array([[1, 1, 1]]), 'Gating failed')
def test_derive(self): pitch_array = np.ma.arange(20) roll_array = pitch_array[::-1] pitch = P('Cyclic Fore-Aft', pitch_array) roll = P('Cyclic Lateral', roll_array) node = self.node_class() node.derive(pitch, roll) expected_array = np.ma.sqrt(pitch_array ** 2 + roll_array ** 2) assert_array_equal(node.array, expected_array)
def test_record_2(self): c = StringIO() c.write(asbytes('1312 foo\n1534 bar\n4444 qux')) c.seek(0) dt = [('num', np.int32), ('val', 'S3')] x = np.fromregex(c, r"(\d+)\s+(...)", dt) a = np.array([(1312, 'foo'), (1534, 'bar'), (4444, 'qux')], dtype=dt) assert_array_equal(x, a)
def test_record(self): c = StringIO() c.write(asbytes('1.312 foo\n1.534 bar\n4.444 qux')) c.seek(0) dt = [('num', np.float64), ('val', 'S3')] x = np.fromregex(c, r"([0-9.]+)\s+(...)", dt) a = np.array([(1.312, 'foo'), (1.534, 'bar'), (4.444, 'qux')], dtype=dt) assert_array_equal(x, a)
def test_universal_newline(self): f, name = mkstemp() os.write(f, b'1 21\r3 42\r') os.close(f) try: data = textadapter.loadtxt(name) assert_array_equal(data, [[1, 21], [3, 42]]) finally: os.unlink(name)
def test_file_roundtrip(self): f, name = mkstemp() os.close(f) try: a = np.array([(1, 2), (3, 4)]) np.savetxt(name, a) b = np.loadtxt(name) assert_array_equal(a, b) finally: os.unlink(name)
def test_universal_newline(self): f, name = mkstemp() os.write(f, asbytes('1 21\r3 42\r')) os.close(f) try: data = np.loadtxt(name) assert_array_equal(data, [[1, 21], [3, 42]]) finally: os.unlink(name)
def test_matrix(self): # Test consistency with unmasked version. If we ever deprecate # matrix, this test should either still pass, or both actual and # expected should fail to be build. actual = mr_['r', 1, 2, 3] expected = np.ma.array(np.r_['r', 1, 2, 3]) assert_array_equal(actual, expected) # outer type is masked array, inner type is matrix assert_equal(type(actual), type(expected)) assert_equal(type(actual.data), type(expected.data))
def test_derive(self): alt_std = P('Altitude STD', array=np.ma.array([12000, 15000, 3000, 5000, 3500, 2000])) sat = P('SAT', array=np.ma.array([0, -45, 35, 40, 32, 8])) isa = P('SAT International Standard Atmosphere', array=np.ma.array([-9, -15, 9, 5, 8, 11])) node = self.node_class() node.derive(alt_std, sat, isa) expected = [13080, 11400, 6120, 9200, 6380, 1640] assert_array_equal(node.array, expected)
def test_in1d_invert(self): # Test in1d's invert parameter a = array([1, 2, 5, 7, -1], mask=[0, 0, 0, 0, 1]) b = array([1, 2, 3, 4, 5, -1], mask=[0, 0, 0, 0, 0, 1]) assert_equal(np.invert(in1d(a, b)), in1d(a, b, invert=True)) a = array([5, 5, 2, 1, -1], mask=[0, 0, 0, 0, 1]) b = array([1, 5, -1], mask=[0, 0, 1]) assert_equal(np.invert(in1d(a, b)), in1d(a, b, invert=True)) assert_array_equal([], in1d([], [], invert=True))
def testTransform(self): tmp = self.fcms['test_fcm1'][:] self.fcms.log([0,1,2]) ltmp = array([[-1,-1,-1],[-1,-1,-1]]) for i in range(3): ltmp[:,i] = where(tmp[:,i] <= 1, 0, log10(tmp[:,i])) assert_array_equal(self.fcms['test_fcm1'],ltmp , 'Log transform failed') assert_array_equal(self.fcms['test_fcm2'],ltmp , 'Log transform failed') self.fcms.logicle()
def test_1D(self): "Test squeezing to 1D" control = np.array([1, 2, 3, 4], int) # data = StringIO('1\n2\n3\n4\n') test = np.ndfromtxt(data, dtype=int) assert_array_equal(test, control) # data = StringIO('1,2,3,4\n') test = np.ndfromtxt(data, dtype=int, delimiter=asbytes(',')) assert_array_equal(test, control)
def test_array(self): "Test outputing a standard ndarray" data = StringIO('1 2\n3 4') control = np.array([[1, 2], [3, 4]], dtype=int) test = np.ndfromtxt(data, dtype=int) assert_array_equal(test, control) # data.seek(0) control = np.array([[1, 2], [3, 4]], dtype=float) test = np.loadtxt(data, dtype=float) assert_array_equal(test, control)
def test_derive(self): one = P('Nr (1)', np.ma.array([100,200,300]), frequency=0.5, offset=0.0) two = P('Nr (2)', np.ma.array([150,250,350]), frequency=0.5, offset=1.0) node = self.node_class() node.derive(one, two) # Note: end samples are not 100 & 350 due to method of merging. assert_array_equal(node.array[1:-1], np.array([150, 200, 250, 300])) self.assertEqual(node.frequency, 1.0) self.assertEqual(node.offset, 0.0)