Qiskit / qiskit-aer

Aer is a high performance simulator for quantum circuits that includes noise models
https://qiskit.github.io/qiskit-aer/
Apache License 2.0
504 stars 361 forks source link

'QuantumCircuit' object has no attribute 'set_statevector' #2241

Closed balewski closed 1 month ago

balewski commented 1 month ago

Informations

What is the current behavior?

This example code https://qiskit.github.io/qiskit-aer/tutorials/1_aersimulator.html#Setting-a-Custom-Statevector throws the error: AttributeError: 'QuantumCircuit' object has no attribute 'set_statevector'

Steps to reproduce the problem

just run your example

What is the expected behavior?

it should run

Suggested solutions

balewski commented 1 month ago

when working on this ticket you may as well fix the next example https://qiskit.github.io/qiskit-aer/tutorials/1_aersimulator.html#Setting-a-custom-density-matrix it throws the error: AttributeError: 'QuantumCircuit' object has no attribute 'set_density_matrix'

jakelishman commented 1 month ago

After inserting the imports that you also need, it runs fine:

from qiskit import QuantumCircuit, transpile
from qiskit import quantum_info as qi
from qiskit_aer import AerSimulator

# Generate a random statevector
num_qubits = 2
psi = qi.random_statevector(2 ** num_qubits, seed=100)

# Set initial state to generated statevector
circ = QuantumCircuit(num_qubits)
circ.set_statevector(psi)
circ.save_state()

# Transpile for simulator
simulator = AerSimulator(method='statevector')
circ = transpile(circ, simulator)

# Run and get saved data
result = simulator.run(circ).result()
result.data(0)

Are you sure you imported Aer before running these? For better or worse, Aer monkey-patches methods onto QuantumCircuit, of which set_statevector and set_density_matrix are two. You must have Aer imported for those to work.

balewski commented 1 month ago

my bad. I'm not using Jupyter and just copied the portion of the code. It was not obvious one needs to import AerSimulator for circ.set_statevector(psi) to work. Thanks for clarification

jakelishman commented 1 month ago

Yeah, I'm personally not a fan of it, but at this point it'd probably cause more harm than good to try and unpick.