This is because you have multiple save_statevector()
instruction in one circuit.
If you only have one instruction of save_statevector()
then this is fine. That is:
from qiskit import transpile
q1 = QuantumCircuit(2)
q1.h(0)
q1.cx(0, 1)
q1.save_statevector() # Save state after CNOT (also a final state)
backend=Aer.get_backend('aer_simulator')
q1 = transpile(q1, backend)
result = backend.run(q1).result()
statevector = result.get_statevector()
which will return your statevector here as:
array([0.70710678+0.j, 0. +0.j, 0. +0.j, 0.70710678+0.j])
If you have more than one place in the circuit that you want to save the statevector of, by using multiple save_statevector()
methods in the circuit, then what you can do is copy the circuit at each of these step to another circuit. At the end, you can execute the simulation for each of these copied circuit independently and extract out your statevector through get_statevector()
method.
For example: Using your original problem, we can do something like
from qiskit import transpile
import copy
main_qc = QuantumCircuit(2)
q1 = copy.deepcopy(main_qc)
q1.save_statevector() # Save initial state
main_qc.h(0)
q2 = copy.deepcopy(main_qc)
q2.save_statevector() # Save state after Hadamard
main_qc.cx(0, 1)
q3 = copy.deepcopy(main_qc)
q3.save_statevector() # Save state after CNOT (also a final state)
backend=Aer.get_backend('aer_simulator')
statevectors_circuits = [ q1, q2, q3]
transpiled_circuits = [transpile(circuit, backend) for circuit in circuits]
results =[ backend.run(transpile_circuit).result() for transpile_circuit in transpiled_circuits]
statevectors = [results[i].get_statevector(circuits[i]) for i in range(len(statevectors_circuits)) ]
Now, if you print out the statevectors, you will see:
[array([1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j]),
array([0.70710678+0.j, 0.70710678+0.j, 0. +0.j, 0. +0.j]),
array([0.70710678+0.j, 0. +0.j, 0. +0.j, 0.70710678+0.j])]
These are the 3 states that you were trying to save.
Simulation failed and returned the following error message: ERROR: Failed to load qobj: Duplicate key "statevector" in save instruction.
$\endgroup$