quantumlib / Cirq

A Python framework for creating, editing, and invoking Noisy Intermediate Scale Quantum (NISQ) circuits.
Apache License 2.0
4.24k stars 1.01k forks source link

Optimise QubitPermutationGate decomposition #6588

Closed migueltorrescosta closed 4 months ago

migueltorrescosta commented 4 months ago

Solves https://github.com/quantumlib/Cirq/issues/5097 as per comment https://github.com/quantumlib/Cirq/issues/5097#issuecomment-2097041496 .

codecov[bot] commented 4 months ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Project coverage is 97.79%. Comparing base (9ddb8c8) to head (8b5a61f).

Additional details and impacted files ```diff @@ Coverage Diff @@ ## main #6588 +/- ## ======================================= Coverage 97.79% 97.79% ======================================= Files 1126 1126 Lines 95784 95781 -3 ======================================= + Hits 93670 93671 +1 + Misses 2114 2110 -4 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

migueltorrescosta commented 4 months ago

Suggestions applied. The shorter code feels easier to follow:

remaining_permutations = {v: i for i, v in enumerate(self.permutation)}

while remaining_permutations:
    a = next(iter(remaining_permutations))
    b = remaining_permutations.pop(a)
    while b in remaining_permutations.keys():
        yield swap_gates.SWAP(qubits[a], qubits[b])
        (a, b) = (b, remaining_permutations.pop(b))

vs

permutation = [p for p in self.permutation]

for i in range(len(permutation)):

    if permutation[i] == -1:
        continue
    cycle = [i]
    while permutation[cycle[-1]] != i:
        cycle.append(permutation[cycle[-1]])

    for j in cycle:
        permutation[j] = -1

    for idx in cycle[1:]:
        yield swap_gates.SWAP(qubits[cycle[0]], qubits[idx])

It might be a question of personal taste, so I am happy to have either merged