Skip to content

Commit

Permalink
Circuit depth (#159)
Browse files Browse the repository at this point in the history
* Depth method for Circuit class
  • Loading branch information
ValentinS4t1qbit authored Jun 7, 2022
1 parent 3e7c516 commit c6e8f41
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
27 changes: 27 additions & 0 deletions tangelo/linq/circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,33 @@ def check_index_valid(index):
# Keep track of the total gate count
self._gate_counts[gate.name] = self._gate_counts.get(gate.name, 0) + 1

def depth(self):
""" Return the depth of the quantum circuit, by computing the number of moments. Does not count
qubit initialization as a moment (unlike Cirq, for example).
"""
moments = list()

for g in self._gates:
qubits = set(g.target) if g.control is None else set(g.target + g.control)

if not moments:
moments.append(qubits)
else:
# Find latest moment involving at least one of the qubits targeted by the current gate
# The current gate is part of the moment following that one
for i, m in reversed(list(enumerate(moments))):
if m & qubits:
if (i+1) < len(moments):
moments[i+1] = moments[i+1] | qubits
else:
moments.append(qubits)
break
# Case where none of the target qubits have been used before
elif i == 0:
moments[0] = moments[0] | qubits

return len(moments)

def trim_qubits(self):
"""Trim unnecessary qubits and update indices with the lowest values possible.
"""
Expand Down
12 changes: 12 additions & 0 deletions tangelo/linq/tests/test_circuits.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,18 @@ def test_inverse(self):
ts_circuit_inverse = Circuit([Gate("PHASE", 0, parameter=-pi/4), Gate("PHASE", 0, parameter=-pi/2)])
self.assertTrue(ts_circuit.inverse(), ts_circuit_inverse)

def test_depth(self):
""" Test depth method on a few circuits """

c1 = Circuit([Gate("H", 0)]*3 + [Gate("X", 1)])
self.assertTrue(c1.depth() == 3)

c2 = Circuit([Gate("H", 0), Gate("CNOT", 1, 0), Gate("CNOT", 2, 1), Gate("H", 0), Gate("CNOT", 0, 2)])
self.assertTrue(c2.depth() == 4)

c3 = Circuit()
self.assertTrue(c3.depth() == 0)

def test_simple_optimization_functions(self):
""" Test if removing small rotations and redundant gates return the
proper set of gates.
Expand Down

0 comments on commit c6e8f41

Please sign in to comment.