Nota
Esta página foi gerada a partir do link tutorials/circuits/2_plotting_data_in_qiskit.ipynb.
Visualizações no Qiskit¶
[1]:
from qiskit import *
from qiskit.visualization import plot_histogram
Plot Histogram¶
Para visualizar os dados que um circuito quântico executa em um dispositivo real ou no qasm_simulator
, fizemos uma função simples
plot_histogram(data)
Como um exemplo, fazemos um estado de Bell de 2 qubits
[2]:
# quantum circuit to make a Bell state
bell = QuantumCircuit(2, 2)
bell.h(0)
bell.cx(0, 1)
meas = QuantumCircuit(2, 2)
meas.measure([0,1], [0,1])
# execute the quantum circuit
backend = BasicAer.get_backend('qasm_simulator') # the device to run on
circ = bell.compose(meas)
result = backend.run(transpile(circ, backend), shots=1000).result()
counts = result.get_counts(circ)
print(counts)
{'11': 504, '00': 496}
[3]:
plot_histogram(counts)
[3]:

Opções quando desenhamos um histograma¶
The plot_histogram()
has a few options to adjust the output graph. The first option is the legend
kwarg. This is used to provide a label for the executions. It takes a list of strings use to label each execution’s results. This is mostly useful when plotting multiple execution results in the same histogram. The sort
kwarg is used to adjust the order the bars in the histogram are rendered. It can be set to either ascending order with asc
or descending order with desc
. The
number_to_keep
kwarg takes an integer for the number of terms to show, the rest are grouped together in a single bar called rest. You can adjust the color of the bars with the color
kwarg which either takes a string or a list of strings for the colors to use for the bars for each execution. You can adjust whether labels are printed above the bars or not with the bar_labels
kwarg. The last option available is the figsize
kwarg which takes a tuple of the size in inches to make the
output figure.
[4]:
# Execute 2-qubit Bell state again
second_result = backend.run(transpile(circ, backend), shots=1000).result()
second_counts = second_result.get_counts(circ)
# Plot results with legend
legend = ['First execution', 'Second execution']
plot_histogram([counts, second_counts], legend=legend)
[4]:

[5]:
plot_histogram([counts, second_counts], legend=legend, sort='desc', figsize=(15,12),
color=['orange', 'black'], bar_labels=False)
[5]:

Usando a saída da função plot_histogram()¶
When using the plot_histogram() function it returns a matplotlib.Figure
for the rendered visualization. Jupyter notebooks understand this return type and render it for us in this tutorial, but when running outside of Jupyter you do not have this feature automatically. However, the matplotlib.Figure
class natively has methods to both display and save the visualization. You can call .show()
on the returned object from plot_histogram()
to open the image in a new window (assuming
your configured matplotlib backend is interactive). Or alternatively you can call .savefig('out.png')
to save the figure to out.png
. The savefig()
method takes a path so you can adjust the location and filename where you’re saving the output.
Visualizando o Estado¶
Em muitas situações, você quer ver o estado de um computador quântico. Isto pode ser para depuração. Aqui, assumimos que você tem este estado (seja da simulação ou da tomografia do estado) e o objetivo é visualizar o estado quântico. Isto requer recursos exponenciais, então, aconselhamos a ver apenas o estado de sistemas quânticos pequenos. Existem várias funções para gerar diferentes tipos de visualização de um estado quântico
plot_state_city(quantum_state)
plot_state_qsphere(quantum_state)
plot_state_paulivec(quantum_state)
plot_state_hinton(quantum_state)
plot_bloch_multivector(quantum_state)
Um estado quântico é uma matriz \(\rho\) (matriz Hermitiana) ou um vetor de estado \(├\psi\rangle\) (vetor complexo). A matriz densidade está relacionada ao vetor de estado por
e é mais geral, pois pode representar estados mistos (soma positiva de vetores de estado)
As visualizações geradas pelas funções são:
'plot_state_city'
: A visão padrão para os estado quânticos, onde as partes reais e imaginárias (imag) da matriz de estado são exibidas como uma cidade.'plot_state_qsphere'
: Visualização única do Qiskit de um estado quântico na qual a amplitude e fase do vetor de estado são traçados em uma bola esférica. A amplitude é a espessura da seta e a fase é a cor. Para estados mistos, mostrará diferentes'qsphere'
para cada componente.'plot_state_paulivec'
: Representação da matriz de estados usando os operadores de Pauli como base \(\rho=\sum_{q=0}^{d^2-1}p_jP_d\).'plot_state_hinton'
: Idêntico a'city'
com a diferença de que o tamanho do elemento representa o valor do elemento da matriz.'plot_bloch_multivector'
: Projeção do estado quântico no espaço de um único qubit e traçando em um bloco da esfera.
[6]:
from qiskit.visualization import plot_state_city, plot_bloch_multivector
from qiskit.visualization import plot_state_paulivec, plot_state_hinton
from qiskit.visualization import plot_state_qsphere
[7]:
# execute the quantum circuit
backend = BasicAer.get_backend('statevector_simulator') # the device to run on
result = backend.run(transpile(bell, backend)).result()
psi = result.get_statevector(bell)
[8]:
plot_state_city(psi)
[8]:

[9]:
plot_state_hinton(psi)
[9]:

[10]:
plot_state_qsphere(psi)
[10]:

[11]:
plot_state_paulivec(psi)
[11]:

[12]:
plot_bloch_multivector(psi)
[12]:

Neste caso, verificamos que não há qualquer informação sobre o estado quântico no espaço de um único qubit, uma vez que todos os vetores são zero.
Opções quando usando funções de visualização do estado¶
As várias funções para a visualização de estados quânticos fornecem uma série de opções para ajustar a forma como os gráficos são renderizados. Quais opções estão disponíveis depende da função sendo usada.
Opções da função plot_state_city()
title (str): uma string que representa o título do gráfico
figsize (tupla): tamanho da figura em polegadas (largura, altura).
color (lista): uma lista de len=2 dando cores para os componentes reais e imaginárias dos elementos da matriz.
[13]:
plot_state_city(psi, title="My City", color=['black', 'orange'])
[13]:

Opções da função plot_state_hinton()
title (str): uma string que representa o título do gráfico
figsize (tupla): tamanho da figura em polegadas (largura, altura).
[14]:
plot_state_hinton(psi, title="My Hinton")
[14]:

Opções da função plot_state_paulivec()
title (str): uma string que representa o título do gráfico
figsize (tupla): tamanho da figura em polegadas (largura, altura).
color (lista ou str): cor esperada das barras dos valores.
[15]:
plot_state_paulivec(psi, title="My Paulivec", color=['purple', 'orange', 'green'])
[15]:

Opções da função plot_state_qsphere()
figsize (tupla): tamanho da figura em polegadas (largura, altura).
Opções da função plot_bloch_multivector()
title (str): uma string que representa o título do gráfico
figsize (tupla): tamanho da figura em polegadas (largura, altura).
[16]:
plot_bloch_multivector(psi, title="My Bloch Spheres")
[16]:

Usando a saída de funções de visualização de estado¶
When using any of the state plotting functions it returns a matplotlib.Figure
for the rendered visualization. Jupyter notebooks understand this return type and render it for us in this tutorial, but when running outside of Jupyter you do not have this feature automatically. However, the matplotlib.Figure
class natively has methods to both display and save the visualization. You can call .show()
on the returned object to open the image in a new window (assuming your configured
matplotlib backend is interactive). Or alternatively you can call .savefig('out.png')
to save the figure to out.png
in the current working directory. The savefig()
method takes a path so you can adjust the location and filename where you’re saving the output.
Visualizando vetores Bloch¶
Uma maneira padrão de visualizar um sistema quântico é usando um vetor de Bloch. Isto só funciona para um único qubit e recebe como entrada o vetor de Bloch.
O vetor de Bloch é definido como \([x = \mathrm{Tr}[X \rho], y = \mathrm{Tr}[Y \rho], z = \mathrm{Tr}[Z \rho]]\), onde \(X\), \(Y\), e \(Z\) são os operadores de Pauli para um único qubit e \(\rho\) é a matriz `de estado.
[17]:
from qiskit.visualization import plot_bloch_vector
[18]:
plot_bloch_vector([0,1,0])
[18]:

Opções para a função plot_bloch_vector()¶
title (str): uma string que representa o título do gráfico
figsize (tupla): tamanho da figura em polegadas (largura, altura).
[19]:
plot_bloch_vector([0,1,0], title='My Bloch Sphere')
[19]:

Ajustando a saída da função plot_bloch_vector()¶
When using the plot_bloch_vector
function it returns a matplotlib.Figure
for the rendered visualization. Jupyter notebooks understand this return type and render it for us in this tutorial, but when running outside of Jupyter you do not have this feature automatically. However, the matplotlib.Figure
class natively has methods to both display and save the visualization. You can call .show()
on the returned object to open the image in a new window (assuming your configured
matplotlib backend is interactive). Or alternatively you can call .savefig('out.png')
to save the figure to out.png
in the current working directory. The savefig()
method takes a path so you can adjust the location and filename where you’re saving the output.
[20]:
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
Version Information
Qiskit Software | Version |
---|---|
qiskit-terra | 0.22.2 |
qiskit-aer | 0.11.1 |
qiskit-ibmq-provider | 0.19.2 |
qiskit | 0.39.2 |
System information | |
Python version | 3.10.6 |
Python compiler | GCC 11.2.0 |
Python build | main, Oct 24 2022 16:07:47 |
OS | Linux |
CPUs | 10 |
Memory (Gb) | 7.676124572753906 |
Fri Nov 11 04:47:42 2022 JST |
This code is a part of Qiskit
© Copyright IBM 2017, 2022.
This code is licensed under the Apache License, Version 2.0. You may
obtain a copy of this license in the LICENSE.txt file in the root directory
of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
Any modifications or derivative works of this code must retain this
copyright notice, and modified files need to carry a notice indicating
that they have been altered from the originals.