def test_conditions() -> None: box_c = Circuit(2, 2) box_c.Z(0) box_c.Y(1, condition_bits=[0, 1], condition_value=1) box_c.Measure(0, 0, condition_bits=[0, 1], condition_value=0) box = CircBox(box_c) u = np.asarray([[0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0]]) ubox = Unitary2qBox(u) c = Circuit(2, 2, name="c") b = c.add_c_register("b", 1) c.add_circbox( box, [Qubit(0), Qubit(1), Bit(0), Bit(1)], condition_bits=[b[0]], condition_value=1, ) c.add_unitary2qbox(ubox, Qubit(0), Qubit(1), condition_bits=[b[0]], condition_value=0) c2 = c.copy() qc = tk_to_qiskit(c) c1 = qiskit_to_tk(qc) assert len(c1.get_commands()) == 2 DecomposeBoxes().apply(c) DecomposeBoxes().apply(c1) assert c == c1 c2.Z(1, condition=reg_eq(b, 1)) qc = tk_to_qiskit(c2) c1 = qiskit_to_tk(qc) assert len(c1.get_commands()) == 3
def test_customgate() -> None: a = Symbol("a") def_circ = Circuit(2) def_circ.CZ(0, 1) def_circ.Rx(a, 1) gate_def = CustomGateDef.define("MyCRx", def_circ, [a]) circ = Circuit(3) circ.Rx(0.1, 0) circ.Rx(0.4, 2) circ.add_custom_gate(gate_def, [0.2], [0, 1]) qc1 = tk_to_qiskit(circ) newcirc = qiskit_to_tk(qc1) print(repr(newcirc)) qc2 = tk_to_qiskit(newcirc) correct_circ = Circuit(3).Rx(0.1, 0).Rx(0.4, 2).CZ(0, 1).Rx(0.2, 1) correct_qc = tk_to_qiskit(correct_circ) backend = Aer.get_backend("statevector_simulator") states = [] for qc in (qc1, qc2, correct_qc): job = execute([qc], backend) states.append(job.result().get_statevector(qc)) assert compare_statevectors(states[0], states[1]) assert compare_statevectors(states[1], states[2])
def test_symbolic() -> None: pi2 = Symbol("pi2") pi3 = Symbol("pi3") tkc = Circuit(3, 3, name="test").Ry(pi2, 1).Rx(pi3, 1).CX(1, 0) USquashIBM().apply(tkc) qc = tk_to_qiskit(tkc) tkc2 = qiskit_to_tk(qc) assert tkc2.free_symbols() == {pi2, pi3} tkc2.symbol_substitution({pi2: pi / 2, pi3: pi / 3}) backend = Aer.get_backend("statevector_simulator") qc = tk_to_qiskit(tkc2) assert qc.name == tkc.name job = execute([qc], backend) state1 = job.result().get_statevector(qc) state0 = np.array([[ 0.6252345 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, -0.78000172 + 0.02606021j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, ]]) assert np.allclose(state0, state1, atol=1e-10)
def test_convert() -> None: qc = get_test_circuit(False) backend = Aer.get_backend("statevector_simulator") job = execute([qc], backend) state0 = job.result().get_statevector(qc) tkc = qiskit_to_tk(qc) assert qc.name == tkc.name qc = tk_to_qiskit(tkc) assert qc.name == tkc.name job = execute([qc], backend) state1 = job.result().get_statevector(qc) assert np.allclose(state0, state1, atol=1e-10)
def test_cnx() -> None: qr = QuantumRegister(5) qc = QuantumCircuit(qr, name="cnx_circuit") qc.mcx([0, 1, 2, 3], 4) c = qiskit_to_tk(qc) cmds = c.get_commands() assert len(cmds) == 1 cmd = cmds[0] assert cmd.op.type == OpType.CnX assert len(cmd.qubits) == 5 qregname = qc.qregs[0].name assert cmd.qubits[4] == Qubit(qregname, 4)
def test_routing_measurements() -> None: qc = get_test_circuit(True) circ = qiskit_to_tk(qc) sim = AerBackend() original_results = sim.get_shots(circ, 10, seed=4) coupling = [[1, 0], [2, 0], [2, 1], [3, 2], [3, 4], [4, 2]] arc = Architecture(coupling) physical_c = route(circ, arc) Transform.DecomposeSWAPtoCX().apply(physical_c) Transform.DecomposeCXDirected(arc).apply(physical_c) Transform.OptimisePostRouting().apply(physical_c) assert (sim.get_shots(physical_c, 10) == original_results).all()
def test_measures() -> None: qc = get_test_circuit(True) backend = Aer.get_backend("qasm_simulator") job = execute([qc], backend, seed_simulator=7) counts0 = job.result().get_counts(qc) tkc = qiskit_to_tk(qc) qc = tk_to_qiskit(tkc) job = execute([qc], backend, seed_simulator=7) counts1 = job.result().get_counts(qc) for result, count in counts1.items(): result_str = result.replace(" ", "") if counts0[result_str] != count: assert False
def test_instruction() -> None: # TKET-446 qreg = QuantumRegister(3) paulis = list(map(Pauli.from_label, ["XXI", "YYI", "ZZZ"])) weights = [0.3, 0.5 + 1j * 0.2, -0.4] op = WeightedPauliOperator.from_list(paulis, weights) evolution_circ = op.evolve(None, 1.2, num_time_slices=1, quantum_registers=qreg) tk_circ = qiskit_to_tk(evolution_circ) cmds = tk_circ.get_commands() assert len(cmds) == 1 assert cmds[0].op.type == OpType.CircBox
def transpile(self): if self.level != 0: qc = transpile(self.qc, basis_gates=['id', 'x', 'sx', 'rz', 'cx', 'reset']) tket_qc = qiskit_to_tk(qc) self.backend_tket.compile_circuit(tket_qc, optimisation_level=2) qc = tk_to_qiskit(tket_qc) else: qc = self.qc transpiled_qc = transpile(circuits=qc, backend=self.backend, basis_gates=None, seed_transpiler=1, optimization_level=self.level) return transpiled_qc
def test_tketpass() -> None: qc = get_test_circuit(False, False) tkpass = FullPeepholeOptimise() back = Aer.get_backend("unitary_simulator") for _ in range(12): tkc = qiskit_to_tk(qc) print(tkc.phase) tkpass.apply(tkc) print(tkc.phase) qc1 = tk_to_qiskit(tkc) res = execute(qc1, back).result() u1 = res.get_unitary(qc1) qispass = TketPass(tkpass) pm = PassManager(qispass) qc2 = pm.run(qc) res = execute(qc2, back).result() u2 = res.get_unitary(qc2) assert np.allclose(u1, u2)
def test_boxes() -> None: c = Circuit(2) c.S(0) c.H(1) c.CX(0, 1) cbox = CircBox(c) d = Circuit(3, name="d") d.add_circbox(cbox, [0, 1]) d.add_circbox(cbox, [1, 2]) u = np.asarray([[0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0]]) ubox = Unitary2qBox(u) d.add_unitary2qbox(ubox, 0, 1) qsc = tk_to_qiskit(d) d1 = qiskit_to_tk(qsc) assert len(d1.get_commands()) == 3 DecomposeBoxes().apply(d) DecomposeBoxes().apply(d1) assert d == d1
def assert_equivalence( circuits: List[Union[Circuit, QuantumCircuit]], require_qk_conversions_equality: bool = True, require_tk_equality: bool = True, ) -> None: """Given a list of circuits (either tket or qiskit), simulate them to calculate unitary matrices, and fail if they are not all almost equal. Also, (unless require_tk_equality is false), assert that all tket circuits are equal. If require_qk_conversions_equality is true, treat qk->tk conversions as if they were originally tk circuits and test for equality (rather than just equivalence), if require_tk_equality is true. """ assert len(circuits) >= 2 tk_circuits = [] # We want unique circuit names, otherwise it confuses the Qiskit backend. names: Set[str] = set() for nn in range(len(circuits)): if isinstance(circuits[nn], Circuit): if require_tk_equality: tk_circuits.append(circuits[nn]) # Of course, use the tket simulator directly once available. # But not yet, so need to convert to qiskit circuits. circuits[nn] = tk_to_qiskit(circuits[nn]) elif require_qk_conversions_equality and require_tk_equality: tk_circuits.append(qiskit_to_tk(circuits[nn])) names.add(circuits[nn].name) assert len(names) == len(circuits) assert_tket_circuits_identical(tk_circuits) backend = Aer.get_backend("unitary_simulator") job = execute(circuits, backend) unitaries = [job.result().get_unitary(circ) for circ in circuits] for nn in range(1, len(circuits)): # Default np.allclose is very lax here, so use strict tolerances assert np.allclose(unitaries[0], unitaries[nn], atol=1e-14, rtol=0.0)
from qiskit.opflow.primitive_ops import PauliSumOp from qiskit.quantum_info import Pauli duration = 1.2 op = PauliSumOp.from_list([("XXI", 0.3), ("YYI", 0.5 + 1j * 0.2), ("ZZZ", -0.4)]) evolved_op = (duration * op).exp_i() evolution_circ = PauliTrotterEvolution(reps=1).convert(evolved_op).to_circuit() print(evolution_circ) state_prep_circ += evolution_circ # Now that we have a circuit, `pytket` can take this and start operating on it directly. For example, we can apply some basic compilation passes to simplify it. from pytket.extensions.qiskit import qiskit_to_tk, tk_to_qiskit tk_circ = qiskit_to_tk(state_prep_circ) from pytket.passes import ( SequencePass, CliffordSimp, DecomposeBoxes, KAKDecomposition, SynthesiseIBM, ) DecomposeBoxes().apply(tk_circ) optimise = SequencePass([KAKDecomposition(), CliffordSimp(False), SynthesiseIBM()]) optimise.apply(tk_circ) # Display the optimised circuit:
def qcirc_to_tcirc(qcirc: QuantumCircuit) -> Circuit: """Changes the name also, to avoid backend result clashes.""" tcirc = qiskit_to_tk(qcirc) tcirc.name = "new tket circ from " + qcirc.name return tcirc
def test_counts() -> None: qc = get_test_circuit(True) circ = qiskit_to_tk(qc) sim = AerBackend() counts = sim.get_counts(circ, 10, seed=4) assert counts == {(1, 0, 1, 1, 0): 10}