https://fr.answacode.com/quantumcomputing/20894/enregistrement-du-vecteur-detat-sur-plusieurs-emplacements-dans-un-circuit-quant
The above is a rare reference document about save_density_matrix, but it failed when I ported the code to my own project, and an error occurred. Can you provide a complete case of this function. My idea is to randomly sample 3 of the 20 qubits for visualization.
1 Answer
you can do it like this, for the error, you might have have duplicate name in save instruction. you probably have two instruction output the same label name 'final_rho'
####import needed function####
from qiskit import QuantumCircuit, Aer,execute
from qiskit.visualization import plot_state_city
from qiskit.providers.aer.library import SaveDensityMatrix
from random import seed,randint,sample
seed(1)
####example circuit#####
qc = QuantumCircuit(4)
qc.h(0)
for i in range(qc.num_qubits-1):
qc.cx(i, i+1)
display(qc.draw())
####example of your idea####
#sample selected number
sample_selected = sample([i for i in range(qc.num_qubits)],3) # selected random separate qubit
#print(sample_selected)
#random group of number
seleted_num = randint(0,qc.num_qubits-3) # random seleted group of qubit
select_group = [seleted_num+i for i in range(3)]
#print(select_group)
#qc.save_density_matrix(sample_selected,label=f'final_rho')# old way
qc.append(SaveDensityMatrix(3, label=f'final_rho'),sample_selected)# new way
####run####
aer_sim = Aer.get_backend('aer_simulator')
result = aer_sim.run(qc,shots=1024).result()
####Extract density matrix snapshot from result ####
density_matrix = result.data()['final_rho']# extract label
#print(density_matrix)
####visualize it####
plot_state_city(density_matrix, color=['midnightblue', 'midnightblue'],
title="New State City")
```
-
$\begingroup$ I tried your code and it works. As a newcomer to QISKIT, I can ask you further, what parameters can be changed to use your template? $\endgroup$– R-X ZhaoJun 18 at 2:16
-
$\begingroup$ @R-XZhao you can try to understand each step, so you know what is the thing you need, and modify. $\endgroup$– poigJun 18 at 2:23
-
-
$\begingroup$ I read the official 0.36.2 documentation, unfortunately there are too few reference codes $\endgroup$– R-X ZhaoJun 18 at 2:42
-
$\begingroup$ @R-XZhao you need to learn how to look at it, and test it out but you can search example on tutorial, google or github. $\endgroup$– poigJun 18 at 2:47