tencent-quantum-lab / tensorcircuit

Tensor network based quantum software framework for the NISQ era
https://tensorcircuit.readthedocs.io
Apache License 2.0
252 stars 75 forks source link

Bug in qiskit circuit parsing #199

Closed yangcal closed 6 months ago

yangcal commented 6 months ago

Hello, I found some issues in tensorcircuit.Circuit.from_qiskit. For some qiskit circuit, the state vector computed by qiskit and tensorcircuit differs. Reproducer below:

import numpy as np
import tensorcircuit as tc
import qiskit
from qiskit.circuit.random import random_circuit

def get_sv_qiskit(circuit, precision='double'):
    num_qubits = len(circuit.qubits)
    simulator = qiskit.Aer.get_backend('aer_simulator_statevector', precision=precision)
    circuit = qiskit.transpile(circuit, simulator)
    circuit.save_statevector()
    result = simulator.run(circuit).result()
    sv = np.asarray(result.get_statevector()).reshape((2,)*num_qubits)
    # statevector returned by qiskit's simulator is labelled by the inverse of :attr:`qiskit.QuantumCircuit.qubits`
    sv = sv.transpose(list(range(num_qubits))[::-1])
    return sv

# create a random quantum circuit
num_qubits = 8
depth = 4
dtype = 'complex64'
circuit_qiskit = random_circuit(num_qubits, depth, seed=0)

# compute sv from qiskit
sv_qiskit = get_sv_qiskit(circuit_qiskit, precision='double')

# compute sv from tc.from_qiskit
circuit_tc = tc.Circuit.from_qiskit(circuit_qiskit)
sv_tc = circuit_tc.state().reshape((2,)*num_qubits)
print("qiskit versus tc err",abs(sv_qiskit-sv_tc).sum()) 

with qiskit 0.45.0, I'm seeing qiskit versus tc err 0.024371880366666862

refraction-ray commented 6 months ago

thanks for the report. identified as a bug in qiskit for cu gate: the base gate matrix is not consistent with the gate matrix provided by cu, and this will induce error in the translation.

qc = qiskit.QuantumCircuit(2)
qc.cu(5.868768495722669, 2.24809352294186, 3.59102783505607, 2.0223650288392, 1, 0)
print(qc.data[0][0].to_matrix(), qc.data[0][0].base_gate.to_matrix())

Therefore, CU gate in qiskit may fail tc translation due to this inconsistent bug in qiskit. I am considering to take special care in tc on this case for new releases to avoid the qiskit bug.

refraction-ray commented 6 months ago

fixed in fc2fb0650e40a019ae18ec4cabd0a79cc2b0f041