def test_fetWT_multichannel_labels(self): # tests whether features are properly labeled, based on linearity of # Wavelet Transform spike1, spike2 = self.cells ch0_spikes = np.vstack((spike1, spike2)).T ch1_spikes = np.vstack((spike1 + spike2, spike1 - spike2)).T spikes = np.empty((ch0_spikes.shape[0], ch0_spikes.shape[1], 2)) spikes[:, :, 0] = ch0_spikes spikes[:, :, 1] = ch1_spikes spikes_dict = {'data' : spikes} features = ss.features.fetWT(spikes_dict, 3, wavelet='haar', select_method=None) names = features['names'] ch0_feats = np.empty((3, 2)) ch1_feats = np.empty((3, 2)) # sort features by channel using labels for fidx in range(3): i0 = names.index('Ch%d:haarWC%d' % (0, fidx)) i1 = names.index('Ch%d:haarWC%d' % (1, fidx)) ch0_feats[fidx, :] = features['data'][:, i0] ch1_feats[fidx, :] = features['data'][:, i1] almost_equal(ch1_feats[:, 0], ch0_feats[:, 0] + ch0_feats[:, 1]) almost_equal(ch1_feats[:, 1], ch0_feats[:, 0] - ch0_feats[:, 1])
def test_fetPCA_multichannel_labels(self): # tests whether features are properly labeled, based on the linearity # of PCA spike1, spike2 = self.cells ch0_spikes = np.vstack((spike1, spike2, spike1 + spike2)).T ch1_spikes = np.vstack((spike1*2, spike2/2., spike1*2 - spike2/2.)).T spikes = np.empty((ch0_spikes.shape[0], ch0_spikes.shape[1], 2)) spikes[:, :, 0] = ch0_spikes spikes[:, :, 1] = ch1_spikes spikes_dict = {'data' : spikes} features = ss.features.fetPCA(spikes_dict, ncomps=3) names = features['names'] ch0_feats = np.empty((3, 3)) ch1_feats = np.empty((3, 3)) # sort features by channel using labels for fidx in range(3): i0 = names.index('Ch%d:PC%d' % (0, fidx)) i1 = names.index('Ch%d:PC%d' % (1, fidx)) ch0_feats[fidx, :] = features['data'][:, i0] ch1_feats[fidx, :] = features['data'][:, i1] # spike combinations on channel 0 almost_equal(ch0_feats[:, 2], ch0_feats[:, 0] + ch0_feats[:, 1]) # spike combinations on channel 1 almost_equal(ch1_feats[:, 2], ch1_feats[:, 0] - ch1_feats[:, 1])
def test_unitary_infid_projection_5() -> None: """Testing higher levels and subspaces.""" actual = np.kron( np.array([[0 + 0j, 1, 0], [1, 0, 0], [0, 0, 34345j]], ), Id, ) almost_equal(unitary_infid(ideal=X, actual=actual, index=[0], dims=[3, 2]), 0)
def test_basis(get_test_dimensions) -> None: """Testing orthonormality of basis vectors.""" for dim in get_test_dimensions: pairs = [(i, j) for i in range(dim) for j in range(dim)] for (i, j) in pairs: vi = basis(dim, i) vj = basis(dim, j) almost_equal(vi.T @ vj, 1 if i == j else 0)
def test_extract_truncated_spike_end(self): zero_crossing = np.array([-self.period * 0.5]) spt_dict = {"data": zero_crossing} sp_win = [0, self.period] sp_waves = ss.extract.extract_spikes(self.spk_data, spt_dict, sp_win) ref_sp = -np.sin(2 * np.pi / self.period * sp_waves['time']) ref_sp[:len(ref_sp) / 2] = 0 almost_equal(sp_waves['data'][:, 0, 0], ref_sp)
def test_rotation() -> None: """Testing trace and determinant of general rotation matrix""" phase = 2 * np.pi * np.random.random() xyz = np.random.random(3) xyz /= np.linalg.norm(xyz) matrix = rotation(phase, xyz) almost_equal(np.trace(matrix), 2 * np.cos(0.5 * phase)) almost_equal(np.linalg.det(matrix), 1)
def test_set_unitary() -> None: propagators = {"rxp": X, "ryp": Y} instructions = {"rxp": Instruction("rxp"), "ryp": Instruction("ryp")} goal = unitary_infid_set( propagators=propagators, instructions=instructions, index=[0], dims=[2], n_eval=136, ) almost_equal(goal, 0)
def test_WT(self): "simple test for linearity of wavelet transform" spike1, spike2 = self.cells spike3 = 0.1 * spike1 + 0.7 * spike2 spikes = np.vstack((spike1, spike2, spike3)).T spikes = spikes[:, :, np.newaxis] # WT only accepts 3D arrays wavelet = 'db3' wt = ss.features.WT(spikes, wavelet) wt1, wt2, wt3 = wt.squeeze().T almost_equal(wt3, 0.1 * wt1 + 0.7 * wt2)
def test_set_states() -> None: propagators = {"rxp": X, "ryp": Y} instructions = {"rxp": Instruction("rxp"), "ryp": Instruction("ryp")} psi_0 = np.array([[1], [0]]) goal = state_transfer_infid_set( propagators=propagators, instructions=instructions, index=[0], dims=[2], psi_0=psi_0, n_eval=136, ) almost_equal(goal, 0)
def test_basis_matrices(get_test_dimensions) -> None: """Testing orthogonality and normalisation of basis matrices.""" for dim in get_test_dimensions[:3]: matrices = get_basis_matrices(dim) # orthogonality pairs = [(a, b) for a in matrices for b in matrices if b is not a] for (a, b) in pairs: almost_equal(np.linalg.norm(np.multiply(a, b)), 0) # normalisation for a in matrices: almost_equal(np.linalg.norm(np.multiply(a, a)), 1)
def test_running_stats(): from numpy.testing import assert_almost_equal as almost_equal from numpy.random import randint arr = numpy.random.randn((30 * 8 * 12)).reshape((30, 8, 12)) varsize_arr = [] for el in arr: s = el.shape varsize_arr.append(el[:randint(s[0] - 2) + 2, :randint(s[1] - 2) + 2]) # test per dimension statistics perdim_runner = RunningStats() for i, el in enumerate(arr, 1): perdim_runner.push(el) if i == 1: # arr[:i] has no axis 0 continue almost_equal(arr[:i].mean(axis=0), perdim_runner.mean()) almost_equal(arr[:i].std(axis=0), perdim_runner.std()) # test single number statistics runner = RunningStats() for i, el in enumerate(varsize_arr, 1): runner.push(el, False) cum_arr = [] for im in varsize_arr[:i]: cum_arr = numpy.concatenate([im.flatten(), cum_arr]) almost_equal(numpy.array(cum_arr).mean(), runner.mean()) almost_equal(numpy.array(cum_arr).std(), runner.std())
def test_running_stats(): from numpy.testing import assert_almost_equal as almost_equal from numpy.random import randint arr = numpy.random.randn((30*8*12)).reshape((30, 8, 12)) varsize_arr = [] for el in arr: s = el.shape varsize_arr.append(el[:randint(s[0]-2)+2, :randint(s[1]-2)+2]) # test per dimension statistics perdim_runner = RunningStats() for i, el in enumerate(arr, 1): perdim_runner.push(el) if i == 1: # arr[:i] has no axis 0 continue almost_equal(arr[:i].mean(axis=0), perdim_runner.mean()) almost_equal(arr[:i].std(axis=0), perdim_runner.std()) # test single number statistics runner = RunningStats() for i, el in enumerate(varsize_arr, 1): runner.push(el, False) cum_arr = [] for im in varsize_arr[:i]: cum_arr = numpy.concatenate([im.flatten(), cum_arr]) almost_equal(numpy.array(cum_arr).mean(), runner.mean()) almost_equal(numpy.array(cum_arr).std(), runner.std())
def test_kron_ids() -> None: """Testing Kronecker product with identities""" # create Kronecker product for some random dimensions and indices indices = np.where(np.random.rand(len(DIMS)) > 0.5)[0] remaining_indices = np.delete(np.arange(len(DIMS)), indices) matrices = [np.random.rand(dim, dim) for dim in DIMS[indices]] result = kron_ids(DIMS, indices, matrices) # expected dimensions assert result.shape[0] == result.shape[1] assert result.shape[0] == DIMS.prod() # trace traces = np.array([np.trace(X) for X in matrices]) almost_equal(np.trace(result), traces.prod() * np.prod(DIMS[remaining_indices]))
def test_perfect_parametric_gate() -> None: """Testing shape and unitarity of the gate matrix""" possible_gates = ["X", "Y", "Z", "Id"] num_gates = len(DIMS) gates_str = ":".join( np.take(possible_gates, np.random.randint(0, len(possible_gates), num_gates)) ) angle = 2 * np.pi * np.random.rand() result = perfect_parametric_gate(gates_str, angle, DIMS) # dimension assert result.shape[0] == result.shape[1] assert result.shape[0] == DIMS.prod() # unitarity almost_equal(result * np.matrix(result).H, np.eye(DIMS.prod()))
def test_np_kron_n(get_test_dimensions) -> None: """Testing properties of Kronecker product""" for dim in get_test_dimensions: (A, B, C, D) = [np.random.rand(dim, dim) for _ in range(4)] # associativity and mixed product almost_equal(np_kron_n([A, B + C]), np_kron_n([A, B]) + np_kron_n([A, C])) almost_equal(np_kron_n([A, B]) * np_kron_n([C, D]), np_kron_n([A * C, B * D])) # trace and determinant almost_equal(np.trace(np_kron_n([A, B])), np.trace(A) * np.trace(B)) almost_equal( np.linalg.det(np_kron_n([A, B])), np.linalg.det(A) ** dim * np.linalg.det(B) ** dim, )
def test_pad_matrix(get_test_dimensions) -> None: """Testing shape, trace, and determinant of matrices after padding""" for dim in get_test_dimensions: M = np.random.rand(dim, dim) padding_dim = np.random.randint(1, 10) # padding with unity padded_ones = pad_matrix(M, padding_dim, "fulluni") assert padded_ones.shape[0] == padded_ones.shape[1] almost_equal(padded_ones.shape[0], M.shape[0] + padding_dim) almost_equal(np.linalg.det(padded_ones), np.linalg.det(M)) almost_equal(np.trace(padded_ones), np.trace(M) + padding_dim) # padding with zeros padded_zeros = pad_matrix(M, padding_dim, "wzeros") assert padded_zeros.shape[0] == padded_zeros.shape[1] almost_equal(padded_ones.shape[0], M.shape[0] + padding_dim) almost_equal(np.linalg.det(padded_zeros), 0) almost_equal(np.trace(padded_zeros), np.trace(M))
def test_unitary_infid_projection_4() -> None: """Testing higher levels.""" actual = np.array([[0 + 0j, 1, 0], [1, 0, 0], [0, 0, 34345j]], ) almost_equal(unitary_infid(ideal=X, actual=actual, index=[0], dims=[3]), 0)
def test_tf_expm(get_exp_problem) -> None: """Testing tf_expm with fixed number of terms""" rot, res = get_exp_problem terms = 100 almost_equal(tf_expm(1j * rot, terms), res)
def test_fid(get_average_fidelitiy): """ Check that the average fideltiy of an identity is maximal. """ almost_equal(get_average_fidelitiy, 1)
def test_unitary_infid_1() -> None: """Testing that a matrix has no error with itself.""" almost_equal(unitary_infid(X, X, dims=[2]), 0)
def test_average_infid_projection() -> None: """Testing only one subspace.""" actual = np.kron(X, Id) almost_equal(average_infid(X, actual, index=[0], dims=[2, 2]), 0)
def test_average_infid_projection_2() -> None: """Testing another subspace.""" actual = np.kron(Id, X) almost_equal(average_infid(X, actual, index=[1], dims=[2, 2]), 0)
def test_hamiltonians() -> None: assert (hdrift.numpy() - test_data["hdrift"].numpy() < 1).any() for key in hks: almost_equal(hks[key], test_data["hks"][key])
def test_average_infid_1() -> None: """Testing that a matrix has no error with itself.""" almost_equal(average_infid(X, X), 0)
def test_propagation() -> None: almost_equal(propagator, test_data["propagator"])
def test_xy_basis(get_test_dimensions) -> None: """Testing properties of basis vectors.""" names = ["x", "y", "z"] for dim in get_test_dimensions: # orthonormality of +/- vectors for i in names: vi_p = xy_basis(dim, i + "p") vi_m = xy_basis(dim, i + "m") almost_equal(np.linalg.norm(vi_p), 1) almost_equal(np.linalg.norm(vi_m), 1) almost_equal(np.vdot(vi_p.T, vi_m), 0) # overlap pairs = [(a, b) for a in names for b in names if b is not a] for (a, b) in pairs: va_p = xy_basis(dim, a + "p") va_m = xy_basis(dim, a + "m") vb_p = xy_basis(dim, b + "p") vb_m = xy_basis(dim, b + "m") almost_equal(np.linalg.norm(np.vdot(va_p.T, vb_p)), 1.0 / np.sqrt(2)) almost_equal(np.linalg.norm(np.vdot(va_p.T, vb_m)), 1.0 / np.sqrt(2)) almost_equal(np.linalg.norm(np.vdot(va_m.T, vb_p)), 1.0 / np.sqrt(2)) almost_equal(np.linalg.norm(np.vdot(va_m.T, vb_m)), 1.0 / np.sqrt(2))
def test_tf_exponentiation(get_exp_problem) -> None: """Testing with the TF exponentiation method""" rot, res = get_exp_problem almost_equal(tf.linalg.expm(1j * rot), res)
def test_expm_dynamic(get_exp_problem) -> None: """Testing dynamically adjusted exp method""" rot, res = get_exp_problem almost_equal(tf_expm_dynamic(1j * rot), res)
def test_unitary_infid_3() -> None: """Testing that a matrix has no error with itself.""" actual = np.kron(X, Id) almost_equal(unitary_infid(actual, actual, index=[0, 1], dims=[2, 2]), 0)
def test_average_infid_2() -> None: """Testing that X and Y have maximal error.""" almost_equal(average_infid(X, Y), np.array(2.0 / 3))
def test_average_infid_projection_3() -> None: """Testing higher levels.""" actual = np.array([[0 + 0j, 1, 0], [1, 0, 0], [0, 0, 0]], ) almost_equal(average_infid(ideal=X, actual=actual, index=[0], dims=[3]), 0)