def test_empty_tuple_index(self):
# Empty tuple index creates a view
a = np.array([1, 2, 3])
assert_equal(a[()], a)
assert_(a[()].base is a)
a = np.array(0)
assert_(isinstance(a[()], np.int_))
# Regression, it needs to fall through integer and fancy indexing
# cases, so need the with statement to ignore the non-integer error.
with warnings.catch_warnings():
warnings.filterwarnings('ignore', '', DeprecationWarning)
a = np.array([1.])
assert_(isinstance(a[0.], np.float_))
a = np.array([np.array(1)], dtype=object)
assert_(isinstance(a[0.], np.ndarray))
python类float_()的实例源码
def approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8):
"""
Returns true if all components of a and b are equal to given tolerances.
If fill_value is True, masked values considered equal. Otherwise,
masked values are considered unequal. The relative error rtol should
be positive and << 1.0 The absolute error atol comes into play for
those elements of b that are very small or zero; it says how small a
must be also.
"""
m = mask_or(getmask(a), getmask(b))
d1 = filled(a)
d2 = filled(b)
if d1.dtype.char == "O" or d2.dtype.char == "O":
return np.equal(d1, d2).ravel()
x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y))
return d.ravel()
def prepare_2D_x(L, viz_type=None, fs=None):
# X vector: samples or time
x = _np.arange(L - 1, dtype=_np.float_)
if viz_type == 'time':
x /= fs
elif viz_type == 'linFFT':
x = _np.fft.rfftfreq(x.shape[0] * 2 - 1, 1 / fs)
elif viz_type == 'logFFT':
x = _np.fft.rfftfreq(x.shape[0] * 2 - 1, 1 / fs)
return x
def sph_harm(m, n, az, el, type='complex'):
'''Compute sphercial harmonics
Parameters
----------
m : (int)
Order of the spherical harmonic. abs(m) <= n
n : (int)
Degree of the harmonic, sometimes called l. n >= 0
az: (float)
Azimuthal (longitudinal) coordinate [0, 2pi], also called Theta.
el : (float)
Elevation (colatitudinal) coordinate [0, pi], also called Phi.
Returns
-------
y_mn : (complex float)
Complex spherical harmonic of order m and degree n,
sampled at theta = az, phi = el
'''
if type == 'legacy':
return scy.sph_harm(m, n, az, el)
elif type == 'real':
Lnm = scy.lpmv(_np.abs(m), n, _np.cos(el))
factor_1 = (2 * n + 1) / (4 * _np.pi)
factor_2 = scy.factorial(n - _np.abs(m)) / scy.factorial(n + abs(m))
if m != 0:
factor_1 = 2 * factor_1
if m < 0:
return (-1) ** m * _np.sqrt(factor_1 * factor_2) * Lnm * _np.sin(m * az)
else:
return (-1) ** m * _np.sqrt(factor_1 * factor_2) * Lnm * _np.cos(m * az)
else:
# For the correct Condon–Shortley phase, all m>0 need to be increased by 1
return (-1) ** _np.float_(m - (m < 0) * (m % 2)) * scy.sph_harm(m, n, az, el)
def random_lowrank(rows, cols, rank, randstate=np.random, dtype=np.float_):
"""Returns a random lowrank matrix of given shape and dtype"""
if dtype == np.float_:
A = randstate.randn(rows, rank)
B = randstate.randn(cols, rank)
elif dtype == np.complex_:
A = randstate.randn(rows, rank) + 1.j * randstate.randn(rows, rank)
B = randstate.randn(cols, rank) + 1.j * randstate.randn(cols, rank)
else:
raise ValueError("{} is not a valid dtype".format(dtype))
C = A.dot(B.conj().T)
return C / np.linalg.norm(C)
def test_inner_fast(nr_sites, local_dim, rank, benchmark, rgen):
mpa1 = factory.random_mpa(nr_sites, local_dim, 1, dtype=np.float_,
randstate=rgen, normalized=True)
mpa2 = factory.random_mpa(nr_sites, local_dim, rank, dtype=np.float_,
randstate=rgen, normalized=True)
benchmark(mpsp.inner_prod_mps, mpa1, mpa2)
def pytest_namespace():
return dict(
# nr_sites, local_dim, rank
MP_TEST_PARAMETERS=[(1, 7, np.nan), (2, 3, 3), (3, 2, 4), (6, 2, 4),
(4, 3, 5), (5, 2, 1)],
MP_TEST_DTYPES=[np.float_, np.complex_]
)
def test_numpy_float_python_long_addition(self):
# Check that numpy float and python longs can be added correctly.
a = np.float_(23.) + 2**135
assert_equal(a, 23. + 2**135)
def test_scalar_return_type(self):
# Full scalar indices should return scalars and object
# arrays should not call PyArray_Return on their items
class Zero(object):
# The most basic valid indexing
def __index__(self):
return 0
z = Zero()
class ArrayLike(object):
# Simple array, should behave like the array
def __array__(self):
return np.array(0)
a = np.zeros(())
assert_(isinstance(a[()], np.float_))
a = np.zeros(1)
assert_(isinstance(a[z], np.float_))
a = np.zeros((1, 1))
assert_(isinstance(a[z, np.array(0)], np.float_))
assert_(isinstance(a[z, ArrayLike()], np.float_))
# And object arrays do not call it too often:
b = np.array(0)
a = np.array(0, dtype=object)
a[()] = b
assert_(isinstance(a[()], np.ndarray))
a = np.array([b, None])
assert_(isinstance(a[z], np.ndarray))
a = np.array([[b, None]])
assert_(isinstance(a[z, np.array(0)], np.ndarray))
assert_(isinstance(a[z, ArrayLike()], np.ndarray))
def test_non_integer_sequence_multiplication(self):
# Numpy scalar sequence multiply should not work with non-integers
def mult(a, b):
return a * b
self.assert_deprecated(mult, args=([1], np.float_(3)))
self.assert_not_deprecated(mult, args=([1], np.int_(3)))
def test_ptp(self):
(x, X, XX, m, mx, mX, mXX,) = self.d
(n, m) = X.shape
self.assertEqual(mx.ptp(), mx.compressed().ptp())
rows = np.zeros(n, np.float_)
cols = np.zeros(m, np.float_)
for k in range(m):
cols[k] = mX[:, k].compressed().ptp()
for k in range(n):
rows[k] = mX[k].compressed().ptp()
self.assertTrue(eq(mX.ptp(0), cols))
self.assertTrue(eq(mX.ptp(1), rows))
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, dtype=np.float_)
assert_equal(average(x, axis=0), 2.5)
assert_equal(average(x, axis=0, weights=w1), 2.5)
y = array([arange(6, dtype=np.float_), 2.0 * arange(6)])
assert_equal(average(y, None), np.add.reduce(np.arange(6)) * 3. / 12.)
assert_equal(average(y, axis=0), np.arange(6) * 3. / 2.)
assert_equal(average(y, axis=1),
[average(x, axis=0), average(x, axis=0) * 2.0])
assert_equal(average(y, None, weights=w2), 20. / 6.)
assert_equal(average(y, axis=0, weights=w2),
[0., 1., 2., 3., 4., 10.])
assert_equal(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_equal(average(masked_array(x, m1), axis=0), 2.5)
assert_equal(average(masked_array(x, m2), axis=0), 2.5)
assert_equal(average(masked_array(x, m4), axis=0).mask, [True])
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_equal(average(z, None), 20. / 6.)
assert_equal(average(z, axis=0), [0., 1., 99., 99., 4.0, 7.5])
assert_equal(average(z, axis=1), [2.5, 5.0])
assert_equal(average(z, axis=0, weights=w2),
[0., 1., 99., 99., 4.0, 10.0])
def __iter__(self):
lengths = np.array(
[(-l[0], -l[1], np.random.random()) for l in self.lengths],
dtype=[('l1', np.int_), ('l2', np.int_), ('rand', np.float_)]
)
indices = np.argsort(lengths, order=('l1', 'l2', 'rand'))
batches = [indices[i:i + self.batch_size]
for i in range(0, len(indices), self.batch_size)]
if self.shuffle:
np.random.shuffle(batches)
return iter([i for batch in batches for i in batch])
def scale(X, n):
Xn = unfold(X, n)
m = np.float_(np.sqrt((Xn ** 2).sum(axis=1)))
m[m == 0] = 1
for i in range(Xn.shape[0]):
Xn[i, :] = Xn[i] / m[i]
return fold(Xn, n, X.shape)
# TODO more efficient cython implementation
def __init__(self, *systems):
"""
Initialize a BlockDiagram, with an optional list of systems to start
the diagram.
"""
if len(systems) == 0:
self.systems = np.array([], dtype=object)
self.connections = np.array([], dtype=np.bool_).reshape((0, 0))
self.dts = np.array([], dtype=np.float_)
self.events = np.array([], dtype=np.bool_)
self.cum_inputs = np.array([0], dtype=np.int_)
self.cum_outputs = np.array([0], dtype=np.int_)
self.cum_states = np.array([0], dtype=np.int_)
self.cum_events = np.array([0], dtype=np.int_)
else:
self.systems = np.array(systems, dtype=object)
self.dts = np.zeros_like(self.systems, dtype=np.float_)
self.events = np.zeros_like(self.systems, dtype=np.bool_)
self.cum_inputs = np.zeros(self.systems.size+1, dtype=np.int_)
self.cum_outputs = np.zeros(self.systems.size+1, dtype=np.int_)
self.cum_states = np.zeros(self.systems.size+1, dtype=np.int_)
self.cum_events = np.zeros(self.systems.size+1, dtype=np.int_)
for i, sys in enumerate(self.systems):
self.dts[i] = sys.dt
self.events[i] = (
getattr(sys, 'event_equation_function', None) and
getattr(sys, 'update_equation_function', None)
)
self.cum_inputs[i+1] = self.cum_inputs[i] + sys.dim_input
self.cum_outputs[i+1] = self.cum_outputs[i] + sys.dim_output
self.cum_states[i+1] = self.cum_states[i] + sys.dim_state
self.cum_events[i+1] = self.cum_events[i] + self.events[i]
self.connections = np.zeros(
(self.cum_outputs[-1], self.cum_inputs[-1]),
dtype=np.bool_)
def test_numpy_float_python_long_addition(self):
# Check that numpy float and python longs can be added correctly.
a = np.float_(23.) + 2**135
assert_equal(a, 23. + 2**135)
def test_scalar_return_type(self):
# Full scalar indices should return scalars and object
# arrays should not call PyArray_Return on their items
class Zero(object):
# The most basic valid indexing
def __index__(self):
return 0
z = Zero()
class ArrayLike(object):
# Simple array, should behave like the array
def __array__(self):
return np.array(0)
a = np.zeros(())
assert_(isinstance(a[()], np.float_))
a = np.zeros(1)
assert_(isinstance(a[z], np.float_))
a = np.zeros((1, 1))
assert_(isinstance(a[z, np.array(0)], np.float_))
assert_(isinstance(a[z, ArrayLike()], np.float_))
# And object arrays do not call it too often:
b = np.array(0)
a = np.array(0, dtype=object)
a[()] = b
assert_(isinstance(a[()], np.ndarray))
a = np.array([b, None])
assert_(isinstance(a[z], np.ndarray))
a = np.array([[b, None]])
assert_(isinstance(a[z, np.array(0)], np.ndarray))
assert_(isinstance(a[z, ArrayLike()], np.ndarray))
def test_non_integer_sequence_multiplication(self):
# Numpy scalar sequence multiply should not work with non-integers
def mult(a, b):
return a * b
self.assert_deprecated(mult, args=([1], np.float_(3)))
self.assert_not_deprecated(mult, args=([1], np.int_(3)))
def test_ptp(self):
(x, X, XX, m, mx, mX, mXX,) = self.d
(n, m) = X.shape
self.assertEqual(mx.ptp(), mx.compressed().ptp())
rows = np.zeros(n, np.float_)
cols = np.zeros(m, np.float_)
for k in range(m):
cols[k] = mX[:, k].compressed().ptp()
for k in range(n):
rows[k] = mX[k].compressed().ptp()
self.assertTrue(eq(mX.ptp(0), cols))
self.assertTrue(eq(mX.ptp(1), rows))
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, dtype=np.float_)
assert_equal(average(x, axis=0), 2.5)
assert_equal(average(x, axis=0, weights=w1), 2.5)
y = array([arange(6, dtype=np.float_), 2.0 * arange(6)])
assert_equal(average(y, None), np.add.reduce(np.arange(6)) * 3. / 12.)
assert_equal(average(y, axis=0), np.arange(6) * 3. / 2.)
assert_equal(average(y, axis=1),
[average(x, axis=0), average(x, axis=0) * 2.0])
assert_equal(average(y, None, weights=w2), 20. / 6.)
assert_equal(average(y, axis=0, weights=w2),
[0., 1., 2., 3., 4., 10.])
assert_equal(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_equal(average(masked_array(x, m1), axis=0), 2.5)
assert_equal(average(masked_array(x, m2), axis=0), 2.5)
assert_equal(average(masked_array(x, m4), axis=0).mask, [True])
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_equal(average(z, None), 20. / 6.)
assert_equal(average(z, axis=0), [0., 1., 99., 99., 4.0, 7.5])
assert_equal(average(z, axis=1), [2.5, 5.0])
assert_equal(average(z, axis=0, weights=w2),
[0., 1., 99., 99., 4.0, 10.0])