def test_spectral_decomposition(self, tol): """Test that the correct spectral decomposition is returned.""" a, P = spectral_decomposition(H) # verify that H = \sum_k a_k P_k assert np.allclose(H, np.einsum("i,ijk->jk", a, P), atol=tol, rtol=0)
def test_spectral_decomposition(self): """Test that the correct spectral decomposition is returned.""" self.logTestName() a, P = spectral_decomposition(H) # verify that H = \sum_k a_k P_k self.assertAllAlmostEqual(H, np.einsum("i,ijk->jk", a, P), delta=self.tol)
def sample(self, observable, wires, par): if not isinstance(observable, list): observable, wires, par = [observable], [wires], [par] matrices = [ self._get_operator_matrix(o, p) for o, p in zip(observable, par) ] decompositions = [spectral_decomposition(A) for A in matrices] eigenvalues, projector_groups = list(zip(*decompositions)) eigenvalues = list(eigenvalues) # Matching each projector with the wires it acts on # while preserving the groupings projectors_with_wires = [[ (proj, wires[idx]) for proj in proj_group ] for idx, proj_group in enumerate(projector_groups)] # The eigenvalue - projector maps are preserved as product() preserves # the previous ordering by creating a lexicographic ordering joint_outcomes = list(product(*eigenvalues)) projector_tensor_products = list(product(*projectors_with_wires)) joint_probabilities = [] for projs in projector_tensor_products: obs_nodes = [] obs_wires = [] for proj, proj_wires in projs: tensor = proj.reshape([2] * len(proj_wires) * 2) obs_nodes.append(self._add_node(tensor, proj_wires)) obs_wires.append(proj_wires) joint_probabilities.append(self.ev(obs_nodes, obs_wires)) outcomes = np.array([np.prod(p) for p in joint_outcomes]) return np.random.choice(outcomes, self.shots, p=joint_probabilities)