I have a 26 bit output, but I only want to get 8 bit statevector in 26 bit. If I use
backend = Aer.get_backend('statevector_simulator') statevector = execute(qc, backend=backend).result().get_statevector(qc)
,
the output is $2^{26}$ outputs, and I want to get $2^8$ output.
How can I do in qiskit?
2 Answers
In general, you can't get the state vector for a subset of circuit qubits because they can be entangled with the other qubits. However, you can always use density matrices to represent the state of the qubits (entangled with other qubits or not).
An easy way to get the density matrix for some qubits is to use save_density_matrix
method. And if the density matrix represents a pure state, you can use DensityMatrix.to_statevector()
method to get the state vector.
As an example, let's create a 5-qubit circuit and get the density matrix of the first two qubits:
circ = QuantumCircuit(5)
circ.h(range(5))
circ.save_density_matrix(qubits=[0, 1]) # <== here
circ.measure_all()
simulator = AerSimulator()
circ = transpile(circ, backend=simulator)
job = simulator.run(circ)
state = job.result().data()['density_matrix']
To display the density matrix:
state.draw('latex')
To get the state vector:
# Check state purity:
if math.isclose(state.purity().real, 1):
# Get the state vector
sv = state.to_statevector()
And to display it:
sv.draw('latex')
-
$\begingroup$ you help me a lot but i can't understand what's mean about math.isclose(state.purity().real, 1),why check 1 rather others,my results not close 1 $\endgroup$ Mar 27 at 13:24
-
$\begingroup$ i really want to ask how can i get the state vector from the density_matrix,thank you $\endgroup$ Mar 27 at 13:33
-
$\begingroup$
math.isclose
is used to avoid the approximation errors. If you take a look at the code ofto_statevector()
here you will find similar checks. $\endgroup$ Mar 27 at 15:00 -
$\begingroup$ i understand it after look to_statevector(), but my Density matrix is not a pure state, beacuse len(nonzero_evals) != 1 , maybe I make mistake before measure , it really gives me a headache , but thanks your advice $\endgroup$ Mar 28 at 13:40
I think you have to look at this question (and at the 2nd answer in particular): Get state vector of a single qubit in a circuit in Qiskit