Skip to content

Instantly share code, notes, and snippets.

@nelimee
Created March 30, 2018 08:02
Show Gist options
  • Save nelimee/c4b5beb45e4134465515daeb14ef9be5 to your computer and use it in GitHub Desktop.
Save nelimee/c4b5beb45e4134465515daeb14ef9be5 to your computer and use it in GitHub Desktop.
An implementation idea for the Gate hierarchy of QISKit
# Base class for each gate
class Gate:
def __init__(self, name: str, qubits):
self._name = name
if isinstance(qubits, list):
self._qubits = qubits
else:
self._qubits = [qubits]
def qasm(self) -> str:
return "{} {}".format(self._name, ",".join(self._registers))
# Other methods
# Base class for reversible gates
class ReversibleGate(Gate):
def inverse(self):
raise NotImplementedError("You should redefine the inverse() function "
"for each ReversibleGate.")
# Base class for custom gates
class CompositeGateBase(Gate):
def __init__(self, name: str, registers):
super().__init__(name, registers)
self._gate_list = list()
def append(self, gate):
self._gate_list.append(gate)
# Operator +=
def __iadd__(self, gate: Gate):
self.append(gate)
class CompositeGate(CompositeGateBase):
def __init__(self, name: str, qubits):
super().__init__(name, qubits)
class ReversibleCompositeGate(CompositeGateBase):
def __init__(self, name: str, qubits):
super().__init__(name, qubits)
self._gate_list = list()
def inverse(self):
self._gate_list = [gate.inverse() for gate in reversed(self._gate_list)]
return self
# Base gate implementation example
class HGate(ReversibleGate):
def __init__(self, qubit):
super().__init__("H", qubit)
def inverse(self):
return HGate(self._qubits)
class CNOTGate(ReversibleGate):
def __init__(self, control, target):
super().__init__("CNOT", [control, target])
def inverse(self):
return CNOTGate(*self._qubits)
# Custom gate definition
class MyCustomGate(ReversibleCompositeGate):
def __init__(self, qbyte):
for i in range(len(qbyte)):
self += HGate(qbyte[i])
self += CNOTGate(qbyte[0], qbyte[1])
# Custom gate creation at runtime
qbyte = [("qreg", i) for i in range(8)]
my_custom_gate = ReversibleCompositeGate("MyCustomGate", qbyte)
for i in range(len(qbyte)):
my_custom_gate += HGate(qbyte[i])
my_custom_gate += CNOTGate(qbyte[0], qbyte[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment