ProjectQ-Framework / ProjectQ

ProjectQ: An open source software framework for quantum computing
https://projectq.ch
Apache License 2.0
876 stars 271 forks source link

Qubit index wrong changed by the garbage collection system. #336

Closed DechinPhy closed 4 years ago

DechinPhy commented 4 years ago

Document Statement

In this file I will show a Bell's state with a unoperated qubit. This unoperated qubits seems collected by the garbage system? With the default setting this unoperated qubit shouldn't change its index or collected by the garbage system I think. Such we can directly use the quantum state generated otherwise we can only use the measurement results.

from projectq import MainEngine
from projectq.ops import X, Z, H, Rx, Ry, Rz, Measure, All, CX, StatePreparation, T, Swap
from projectq.meta import Control
from projectq.cengines import ManualMapper
import numpy as np
import math
import matplotlib.pyplot as plt

The wrong result

$\left(\left|00\right>+\left|11\right>\right)\otimes\left|0\right>$

eng = MainEngine()
qubits = eng.allocate_qureg(3)
H | qubits[0]
CX | (qubits[0], qubits[2])
eng.flush()
amplitudes = np.array(eng.backend.cheat()[1])
amplitudes = np.abs(amplitudes)
All(Measure) | qubits
plt.figure()
plt.plot(amplitudes)
plt.show()

output_3_0

The right result

$\left|000\right>+\left|101\right>$

def mapping(qubit_id):
    return qubit_id
engine_list=[ManualMapper(mapping)]
eng = MainEngine(engine_list = [ManualMapper(mapping)])
qubits = eng.allocate_qureg(3)
H | qubits[0]
CX | (qubits[0], qubits[2])
eng.flush()
amplitudes = np.array(eng.backend.cheat()[1])
amplitudes = np.abs(amplitudes)
All(Measure) | qubits
plt.figure()
plt.plot(amplitudes)
plt.show()

output_5_0

DechinPhy commented 4 years ago

For a manual operation you can just add a mapper like what I have done. But I think this problem should be fixed.

Takishima commented 4 years ago

The order of the qubit stored inside the internal representation of the wavefunction does not necessarily reflects the order in which the qubits were created. This behaviour is documented here.

If you plan on using the cheat() method of the simulator in your code, you need to manually make the conversion between the logical qubit IDs and the order of the qubits stored in the second element of the return value of cheat()

References:

Takishima commented 4 years ago

Since this behaviour is properly documented, I'm closing this issue.