pytket examples#

Building a circuit with the Circuit class#

You can create a circuit by creating an instance of the Circuit class and adding gates manually.

from pytket import Circuit

ghz_circ = Circuit(3)
ghz_circ.CX(0, 1)
ghz_circ.CX(1, 2)
[H q[0]; CX q[0], q[1]; CX q[1], q[2]; Barrier q[0], q[1], q[2]; Measure q[0] --> c[0]; Measure q[1] --> c[1]; Measure q[2] --> c[2]; ]

Now let’s draw a nice picture of the circuit with the circuit renderer

from pytket.circuit.display import render_circuit_jupyter


See also the Circuit construction section of the user manual.

Build a Circuit from a QASM file#

Alternatively we can import a circuit from a QASM file using pytket.qasm. There are also functions for generating a circuit from a QASM string or exporting to a qasm file.

Note that its also possible to import a circuit from quipper using pytket.quipper module.

from pytket.qasm import circuit_from_qasm

w_state_circ = circuit_from_qasm("qasm/W-state.qasm")

Import a circuit from qiskit (or other SDK)#

Its possible to generate a circuit directly from a qiskit QuantumCircuit using the qiskit_to_tk function.

from qiskit import QuantumCircuit

qiskit_circ = QuantumCircuit(3)
qiskit_circ.ccx(2, 1 ,0), 1)
q_0: ┤ H ├┤ X ├──■──
q_1: ┤ H ├──■──┤ X ├
     ├───┤  │  └───┘
q_2: ┤ H ├──■───────
from pytket.extensions.qiskit import qiskit_to_tk

tket_circ = qiskit_to_tk(qiskit_circ)


Note that pytket and qiskit use opposite qubit ordering conventions. So circuits which look identical may correspond to different unitary operations.

Circuit conversion functions are also available for pytket-cirq, pytket-pennylane, pytket-braket and more.

Using Backends#

In pytket a Backend represents an interface to a quantum device or simulator.

We will show a simple example of running the ghz_circ defined above on the AerBackend simulator.

from pytket.extensions.qiskit import AerBackend

backend = AerBackend()
result = backend.run_circuit(ghz_circ)
Counter({(0, 0, 0): 530, (1, 1, 1): 494})

The AerBackend simulator is highly idealised having a broad gateset, and no restrictive connectivity or device noise.

The Hadamard and CX gate are supported operations of the simulator so we can run the GHZ circuit without changing any of the operations. For more realistic cases a compiler will have to solve for the limited gateset of the target backend as well as other backend requirements.

See the Running on Backends section of the user manual and the backends example notebook for more.