Skip to content

Commit

Permalink
feat: simplified _Queue append
Browse files Browse the repository at this point in the history
  • Loading branch information
BrunoLiegiBastonLiegi committed Mar 8, 2024
1 parent d559a61 commit 67bd842
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 23 deletions.
44 changes: 22 additions & 22 deletions src/qibo/models/circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,6 @@ class _Queue(list):
def __init__(self, nqubits):
super().__init__(self)
self.nqubits = nqubits
self.moments = [nqubits * [None]]
self.moment_index = nqubits * [0]
self.nmeasurements = 0

def to_fused(self):
"""Transform all gates in queue to :class:`qibo.gates.FusedGate`."""
Expand Down Expand Up @@ -88,24 +85,27 @@ def from_fused(self):
queue.append(gate.gates[0])
return queue

def append(self, gate: gates.Gate):
super().append(gate)
if gate.qubits:
qubits = gate.qubits
else: # special gate acting on all qubits
qubits = tuple(range(self.nqubits))

if isinstance(gate, gates.M):
self.nmeasurements += 1
def nmeasurements(self):
return len([1 for gate in self if isinstance(gate, gates.M)])

# calculate moment index for this gate
idx = max(self.moment_index[q] for q in qubits)
for q in qubits:
if idx >= len(self.moments):
# Add a moment
self.moments.append(len(self.moments[-1]) * [None])
self.moments[idx][q] = gate
self.moment_index[q] = idx + 1
def moments(self):
moments = [self.nqubits * [None]]
moment_index = self.nqubits * [0]
for gate in self:
if gate.qubits:
qubits = gate.qubits
else: # special gate acting on all qubits
qubits = tuple(range(self.nqubits))

# calculate moment index for this gate
idx = max(moment_index[q] for q in qubits)
for q in qubits:
if idx >= len(moments):
# Add a moment
moments.append(len(moments[-1]) * [None])
moments[idx][q] = gate
moment_index[q] = idx + 1
return moments


class Circuit:
Expand Down Expand Up @@ -658,7 +658,7 @@ def add(self, gate):
self.queue.append(gate)
if gate.register_name is None:
# add default register name
nreg = self.queue.nmeasurements - 1
nreg = self.queue.nmeasurements() - 1
gate.register_name = f"register{nreg}"
else:
registers = self.measurement_tuples
Expand Down Expand Up @@ -712,7 +712,7 @@ def ngates(self) -> int:
def depth(self) -> int:
"""Circuit depth if each gate is placed at the earliest possible
position."""
return len(self.queue.moments)
return len(self.queue.moments())

@property
def gate_types(self) -> collections.Counter:
Expand Down
2 changes: 1 addition & 1 deletion tests/test_models_circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def test_queue_class():
]
for g in gatelist:
queue.append(g)
assert queue.moments == [
assert queue.moments() == [
[gatelist[0], gatelist[1], gatelist[3], gatelist[5]],
[gatelist[2], gatelist[4], gatelist[4], None],
]
Expand Down

0 comments on commit 67bd842

Please sign in to comment.