def _local_add(ltenss):
"""Computes the local tensors of a sum of MPArrays (except for the boundary
tensors)
:param ltenss: List of arrays with `ndim > 1`
:returns: Correct local tensor representation
"""
shape = ltenss[0].shape
# NOTE These are currently disabled due to real speed issues.
# if __debug__:
# for lt in ltenss[1:]:
# assert_array_equal(shape[1:-1], lt.shape[1:-1])
# FIXME: Find out whether the following code does the same as
# :func:`block_diag()` used by :func:`_local_sum_identity` and
# which implementation is faster if so.
newshape = (sum(lt.shape[0] for lt in ltenss), )
newshape += shape[1:-1]
newshape += (sum(lt.shape[-1] for lt in ltenss), )
res = np.zeros(newshape, dtype=max(lt.dtype for lt in ltenss))
pos_l, pos_r = 0, 0
for lt in ltenss:
pos_l_new, pos_r_new = pos_l + lt.shape[0], pos_r + lt.shape[-1]
res[pos_l:pos_l_new, ..., pos_r:pos_r_new] = lt
pos_l, pos_r = pos_l_new, pos_r_new
return res
python类assert_array_equal()的实例源码
def test_call(self):
strmod = SimpleStr(self.Cu_coeff)
epsilon = np.array([1E-3, 2E-4])
epsilon_dot = np.array([1E-2, 2E-2])
sigma = strmod(epsilon, epsilon_dot)
np.testing.assert_array_equal(
sigma,
self.Cu_coeff[0] * epsilon + self.Cu_coeff[1] * epsilon_dot
)
def test_call(self):
rproc = RandomProcess(self.mean, self.var)
npt.assert_array_equal(rproc(), self.mean)
def test_sigma(self):
"""Test the variance is obtained correctly
"""
rproc = RandomProcess(self.mean, self.var)
sig = rproc.get_sigma()
self.assertTupleEqual(sig.shape, (3,3))
npt.assert_array_equal(np.diag(sig),
[0.5**2, 0.25**2, 0.125**2])
def test_spline_new_c(self):
"""Test spline interaction method, set new coefficients
"""
eos = EOSModel(self.p_fun)
# get c
c_list = eos.get_dof()
# add 0.1 to all c
# get a new spline with updated c
new_eos = eos.update_dof(c_list + 0.1)
# check it matches
npt.assert_array_equal(new_eos.get_dof(), c_list + 0.1)
npt.assert_array_equal(c_list, eos.get_dof())
self.assertEqual(c_list[0] + 0.1, new_eos._eval_args[1][0])
self.assertEqual(c_list[1] + 0.1, new_eos._eval_args[1][1])
self.assertEqual(c_list[2] + 0.1, new_eos._eval_args[1][2])
self.assertEqual(c_list[3]+ 0.1, new_eos._eval_args[1][3])
self.assertEqual(c_list[-1] + 0.1, new_eos._eval_args[1][-5])
self.assertEqual(0.0, new_eos._eval_args[1][-1])
self.assertEqual(0.0, new_eos._eval_args[1][-2])
self.assertEqual(0.0, new_eos._eval_args[1][-3])
self.assertEqual(0.0, new_eos._eval_args[1][-4])
def test_eos_get_sigma(self):
""" Tests that the co-variance matrix is generated correctly
"""
eos = EOSModel(self.p_fun)
sigma_eos = eos.get_sigma()
n_spline = eos.get_option('spline_N')
spline_var = eos.get_option('spline_sigma')
self.assertEqual(sigma_eos.shape, (n_spline, n_spline))
npt.assert_array_equal(np.diag(sigma_eos),
(eos.get_c() * spline_var)**2)
def test_pq(self):
"""Tests that the experiment can generate the p and q matrix
"""
exp = SimpleExperiment()
# Generate some simulation data
sim_data = self.simSimp(self.models)
# Align the data so that it is evaluated at the same time steps as
# the experiment
aligned_data = exp.align(sim_data)
# Get the sensitivity matrix
sens_matrix = self.simSimp.get_sens(self.models, ['simp'], aligned_data)
# Get the error between the sim and experiment
epsilon = exp.compare(sim_data)
p_mat, q_vec = exp.get_pq(self.models, ['simp'], sim_data, sens_matrix,
scale=False)
sigma_mat = exp.get_sigma()
p_mat_hat = np.dot(np.dot(sens_matrix.T, np.linalg.inv(sigma_mat)),
sens_matrix)
npt.assert_array_equal(p_mat, p_mat_hat,
err_msg="P matrix calculated incorrectly")
q_vec_hat = -np.dot(np.dot(epsilon, np.linalg.inv(sigma_mat)),
sens_matrix)
npt.assert_array_equal(q_vec, q_vec_hat,
err_msg="q vector calculated incorrectly")
def test_multi_solve(models, sim):
dofs = []
for i in range(4):
dofs.append(models['simp'].get_dof() + i)
# end
results = sim.multi_solve(models, ['simp',], dofs)
for i, res in enumerate(results):
npt.assert_array_equal(
res[1][0],
np.arange(10) * (np.arange(10) + i + 1)
)
def check_get(self, f, stream):
a_gpu = f(cupy)
a_cpu = a_gpu.get(stream)
if stream:
stream.synchronize()
b_cpu = f(numpy)
np_testing.assert_array_equal(a_cpu, b_cpu)
def test_get_multigpu(self, dtype):
with cuda.Device(1):
src = testing.shaped_arange((2, 3), xp=cupy, dtype=dtype)
src = cupy.asfortranarray(src)
with cuda.Device(0):
dst = src.get()
expected = testing.shaped_arange((2, 3), xp=numpy, dtype=dtype)
np_testing.assert_array_equal(dst, expected)
def test_pairwise_distances_argmin_min(X_blobs):
centers = X_blobs[::100].compute()
a_, b_ = sm.pairwise_distances_argmin_min(X_blobs.compute(), centers)
a, b = dm.pairwise_distances_argmin_min(X_blobs, centers)
npt.assert_array_equal(a.compute(), a_)
npt.assert_array_equal(b.compute(), b_)
def check_arrays(x, y, err_msg='', verbose=True, check_dtypes=True):
"""
Wrapper around np.testing.assert_array_equal that also verifies that inputs
are ndarrays.
See Also
--------
np.assert_array_equal
"""
assert type(x) == type(y), "{x} != {y}".format(x=type(x), y=type(y))
assert x.dtype == y.dtype, "{x.dtype} != {y.dtype}".format(x=x, y=y)
if isinstance(x, LabelArray):
# Check that both arrays have missing values in the same locations...
assert_array_equal(
x.is_missing(),
y.is_missing(),
err_msg=err_msg,
verbose=verbose,
)
# ...then check the actual values as well.
x = x.as_string_array()
y = y.as_string_array()
elif x.dtype.kind in 'mM':
x_isnat = isnat(x)
y_isnat = isnat(y)
assert_array_equal(
x_isnat,
y_isnat,
err_msg="NaTs not equal",
verbose=verbose,
)
# Fill NaTs with zero for comparison.
x = np.where(x_isnat, np.zeros_like(x), x)
y = np.where(y_isnat, np.zeros_like(y), y)
return assert_array_equal(x, y, err_msg=err_msg, verbose=verbose)
def test_symarray():
"""Test creation of numpy arrays of sympy symbols."""
import numpy as np
import numpy.testing as npt
syms = symbols('_0,_1,_2')
s1 = symarray("", 3)
s2 = symarray("", 3)
npt.assert_array_equal(s1, np.array(syms, dtype=object))
assert s1[0] == s2[0]
a = symarray('a', 3)
b = symarray('b', 3)
assert not(a[0] == b[0])
asyms = symbols('a_0,a_1,a_2')
npt.assert_array_equal(a, np.array(asyms, dtype=object))
# Multidimensional checks
a2d = symarray('a', (2, 3))
assert a2d.shape == (2, 3)
a00, a12 = symbols('a_0_0,a_1_2')
assert a2d[0, 0] == a00
assert a2d[1, 2] == a12
a3d = symarray('a', (2, 3, 2))
assert a3d.shape == (2, 3, 2)
a000, a120, a121 = symbols('a_0_0_0,a_1_2_0,a_1_2_1')
assert a3d[0, 0, 0] == a000
assert a3d[1, 2, 0] == a120
assert a3d[1, 2, 1] == a121
def test_state_equations_functions_kwarg(switch_fixture):
with pytest.raises(ValueError, match=need_state_equation_function_msg):
SwitchedSystem(
dim_state=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
output_equations_functions=switch_fixture[2]
)
with pytest.raises(ValueError, match="broadcast"):
SwitchedSystem(
dim_state=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
state_equations_functions=np.array([
lambda t, x, u: cnd*np.ones(x.shape)
for cnd in range(switch_fixture[0].size+2)
]),
output_equations_functions=switch_fixture[2]
)
sys = SwitchedSystem(
dim_state=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
state_equations_functions=switch_fixture[1],
output_equations_functions=switch_fixture[2]
)
npt.assert_array_equal(sys.state_equations_functions, switch_fixture[1])
sys = SwitchedSystem(
dim_state=1,
event_variable_equation_function=event_variable_equation_function,
event_bounds=switch_fixture[0],
state_equations_functions=state_equation_function,
output_equations_functions=switch_fixture[2]
)
npt.assert_array_equal(
sys.state_equations_functions,
state_equation_function
)
def test_to_array_atleast_1d(self):
res = to_array_atleast_1d(1, 2, 3)
exp_res = np.array([1]), np.array([2]), np.array([3])
npt.assert_array_equal(res[0], exp_res[0])
npt.assert_array_equal(res[1], exp_res[1])
npt.assert_array_equal(res[2], exp_res[2])
self.assertEqual(res[0].shape[0], 1)
def test_to_array_atleast_1d_2(self):
res = to_array_atleast_1d(1, 2, None)
exp_res = np.array([1]), np.array([2]), np.array([None])
npt.assert_array_equal(res[0], exp_res[0])
npt.assert_array_equal(res[1], exp_res[1])
npt.assert_array_equal(res[2], exp_res[2])
self.assertEqual(res[0].shape[0], 1)
def test_to_array_atleast_1d_3(self):
res = to_array_atleast_1d([1, 2, 3], 2, None)
exp_res = np.array([1, 2, 3]), np.array([2]), np.array([None])
npt.assert_array_equal(res[0], exp_res[0])
npt.assert_array_equal(res[1], exp_res[1])
npt.assert_array_equal(res[2], exp_res[2])
self.assertEqual(res[0].shape[0], 3)
def test_to_array_with_same_dimension(self):
res = to_array_with_same_dimension([1, 2, 3], 2, None)
exp_res = np.array([1, 2, 3]), np.array([2, 2, 2]), np.array([None, None, None])
npt.assert_array_equal(res[0], exp_res[0])
npt.assert_array_equal(res[1], exp_res[1])
npt.assert_array_equal(res[2], exp_res[2])
self.assertEqual(res[0].shape[0], 3)
def test_to_array_with_same_dimension_2(self):
res = to_array_with_same_dimension(1, 2, 3)
exp_res = np.array([1]), np.array([2]), np.array([3])
npt.assert_array_equal(res[0], exp_res[0])
npt.assert_array_equal(res[1], exp_res[1])
npt.assert_array_equal(res[2], exp_res[2])
self.assertEqual(res[0].shape[0], 1)
def test_to_array_with_same_dimension_5(self):
res = to_array_with_same_dimension([1, 2, 3], 'put', None)
exp_res = np.array([1, 2, 3]), np.array(['put', 'put', 'put']), np.array([None, None, None])
npt.assert_array_equal(res[0], exp_res[0])
npt.assert_array_equal(res[1], exp_res[1])
npt.assert_array_equal(res[2], exp_res[2])