diff --git a/tangelo/linq/circuit.py b/tangelo/linq/circuit.py index bc1c63b7b..f75184768 100644 --- a/tangelo/linq/circuit.py +++ b/tangelo/linq/circuit.py @@ -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. """ diff --git a/tangelo/linq/tests/test_circuits.py b/tangelo/linq/tests/test_circuits.py index 7ed4f6c55..805de7fef 100644 --- a/tangelo/linq/tests/test_circuits.py +++ b/tangelo/linq/tests/test_circuits.py @@ -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.