# How to define a custom gate from a matrix in TKET

I'm currently learning all about different quantum tools such as qiskit, tket, cirq, Forest SDK and so on. I just want to create a circuit that gets executed given a matrix, because a circuit can be written as a matrix and the other way around. In qiskit, cirq and pyquil (Forest SDK) there is no problem in defining an own gate. I don't find any function in tket which could help with this.

For example I want to define an AND gate. For those who don't know, an AND gate is actually just the CCNOT or CCX Gate. Tket does support the CCX gate but if I want to create maybe an AND Gate with 3 or 4 Qubits (CCCX or CCCCX) Gate the tket framework doesn't help.

Can somebody help me with this? I understand that you can define own gates in Tket but that just include gates that are created from native gates.

You can define custom parametrised gates in pytket using CustomGateDef. Here the CustomGate is defined using a circuit which implements the desired unitary instead of the matrix itself. Here is an example for how to do this taken from the user manual.

from pytket.circuit import Circuit, CustomGateDef
from sympy import symbols

a, b = symbols("a b")
def_circ = Circuit(2)
def_circ.CZ(0, 1)
def_circ.Rx(a, 1)
def_circ.CZ(0, 1)
def_circ.Rx(-a, 1)
def_circ.Rz(b, 0)

gate_def = CustomGateDef.define("MyCRx", def_circ, [a])


Its also possible to define a custom subroutine from a circuit using CircBox. The Custom parameterised gates shown above are useful when you want to define a parametrised gate in terms of lower level gates which you can then use repeatedly with different parameter values.

If the unitary represents a one, two or three qubit operation it is possible to synthesise a circuit to implement the unitary. See the manual section on unitary synthesis.

If you're interested in multi-controlled X operations you can add these to your Circuit as a CnX. You can have as many controls as you like. Here the we pass in the qubit indices as a list with the last element being the target qubit.

from pytket import Circuit, OpType

circ = Circuit(4)
circ.add_gate(OpType.CnX, [0, 1, 2, 3]) # CCCX gate


You may also wish to check out the ToffoliBox feature which implements an arbitrary permutation of the computational basis states using either {X, CnX} gates or a sequence of multiplexor operations.

• Arbitrary unitary synthesis in not implemented in TKET for > 3 qubits. A decision was made not to include this as the algorithms scale badly with respect to two-qubit gate count and runtime. As a workaround you could define your gate in qiskit and convert it to TKET using the qiskit_to_tk function from the pytket-qiskit extension. You may need to supply a method to decompose your new gate first. There are special box types that can be decomposed efficiently for a larger number of qubits. See ToffoliBox and PauliExpBox. Depending on what you are doing these could be useful. Dec 5, 2022 at 17:00