def test_backend_network(backend): a = np.random.randn(2, 2, 2) nodes, _, out_edges = ncon_interface.ncon_network([a, a, a], [(-1, 1, 2), (1, 2, 3), (3, -2, -3)], backend=backend) res = greedy(nodes, out_edges).tensor res_np = a.reshape((2, 4)) @ a.reshape((4, 2)) @ a.reshape((2, 4)) res_np = res_np.reshape((2, 2, 2)) np.testing.assert_allclose(res, res_np)
def test_cnot_gate(): # Prepare input state: |11> q0_in = Node(np.array([0, 1], dtype=np.float64)) q1_in = Node(np.array([0, 1], dtype=np.float64)) # Prepare output state: |10> q0_out = Node(np.array([0, 1], dtype=np.float64)) q1_out = Node(np.array([1, 0], dtype=np.float64)) # Build quantum circuit copy_node, q0_t1, q1_t1 = add_cnot(q0_in[0], q1_in[0]) network_components.connect(q0_t1, q0_out[0]) network_components.connect(q1_t1, q1_out[0]) # Contract the network, first using Bucket Elimination, then once # no more copy tensors are left to exploit, fall back to the naive # contractor. contraction_order = (copy_node,) net = bucket([q0_in, q1_in, q0_out, q1_out, copy_node], contraction_order) result = greedy(net) # Verify that CNOT has turned |11> into |10>. np.testing.assert_allclose(result.get_tensor(), 1.0)
def test_swap_gate(): # Prepare input state: 0.6|00> + 0.8|10> q0_in = Node(np.array([0.6, 0.8], dtype=np.float64), backend="jax") q1_in = Node(np.array([1, 0], dtype=np.float64), backend="jax") # Prepare output state: 0.6|00> + 0.8|01> q0_out = Node(np.array([1, 0], dtype=np.float64), backend="jax") q1_out = Node(np.array([0.6, 0.8], dtype=np.float64), backend="jax") # Build quantum circuit: three CNOTs implement a SWAP copy_node_1, q0_t1, q1_t1 = add_cnot(q0_in[0], q1_in[0], backend="jax") copy_node_2, q1_t2, q0_t2 = add_cnot(q1_t1, q0_t1, backend="jax") copy_node_3, q0_t3, q1_t3 = add_cnot(q0_t2, q1_t2, backend="jax") network_components.connect(q0_t3, q0_out[0]) network_components.connect(q1_t3, q1_out[0]) # Contract the network, first Bucket Elimination, then greedy to complete. contraction_order = (copy_node_1, copy_node_2, copy_node_3) nodes = [q0_in, q0_out, q1_in, q1_out, copy_node_1, copy_node_2, copy_node_3] net = bucket(nodes, contraction_order) result = greedy(net) # Verify that SWAP has turned |10> into |01> and kept |00> unchanged. np.testing.assert_allclose(result.get_tensor(), 1.0)
def contract_network(edges: Sequence[tn.Edge]) -> tn.Node: network = set() for edge in edges: network |= tn.reachable(edge) return cn.greedy(network, output_edge_order=edges)