Korean
언어
English
Bengali
French
German
Japanese
Korean
Portuguese
Spanish
Tamil

참고

이 페이지는 tutorials/circuits_advanced/03_advanced_circuit_visualization.ipynb 로부터 생성되었다.

양자 회로를 시각화 하기

[1]:
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister

양자 회로 그리기

양자 회로를 작성할 때 종종 그 회로를 그려보는 것이 도움이 된다. 이 기능은 QuantumCircuit 객체에서 기본적으로 지원된다. 회로를 그리려면 회로에 print() 를 사용하거나 객체에서 draw() 매서드를 불러오는 방법이 있다. 이렇게 하면 회로 다이어그램이 ASCII art 버전 으로 그려진다.

[2]:
# Build a quantum circuit
circuit = QuantumCircuit(3, 3)

circuit.x(1)
circuit.h(range(3))
circuit.cx(0, 1)
circuit.measure(range(3), range(3));
[3]:
print(circuit)
     ┌───┐          ┌─┐
q_0: ┤ H ├───────■──┤M├───
     ├───┤┌───┐┌─┴─┐└╥┘┌─┐
q_1: ┤ X ├┤ H ├┤ X ├─╫─┤M├
     ├───┤└┬─┬┘└───┘ ║ └╥┘
q_2: ┤ H ├─┤M├───────╫──╫─
     └───┘ └╥┘       ║  ║
c_0: ═══════╬════════╩══╬═
            ║           ║
c_1: ═══════╬═══════════╩═
            ║
c_2: ═══════╩═════════════

[4]:
circuit.draw()
[4]:
     ┌───┐          ┌─┐
q_0: ┤ H ├───────■──┤M├───
     ├───┤┌───┐┌─┴─┐└╥┘┌─┐
q_1: ┤ X ├┤ H ├┤ X ├─╫─┤M├
     ├───┤└┬─┬┘└───┘ ║ └╥┘
q_2: ┤ H ├─┤M├───────╫──╫─
     └───┘ └╥┘       ║  ║
c_0: ═══════╬════════╩══╬═
            ║           ║
c_1: ═══════╬═══════════╩═
            ║
c_2: ═══════╩═════════════
                          

회로 시각화 대체 방법들 (Renderers)

A text output is useful for quickly seeing the output while developing a circuit, but it doesn’t provide the most flexibility in its output. There are two alternative output renderers for the quantum circuit. One uses matplotlib, and the other uses LaTeX, which leverages the qcircuit package. These can be specified by using mpl and latex values for the output kwarg on the draw() method.

[5]:
# Matplotlib Drawing
circuit.draw(output='mpl')
[5]:
../../_images/tutorials_circuits_advanced_03_advanced_circuit_visualization_7_0.png

circuit.draw()의 출력값 설정하기

By default, the draw() method returns the rendered image as an object and does not output anything. The exact class returned depends on the output specified: 'text' (the default) returns a TextDrawer object, 'mpl' returns a matplotlib.Figure object, and latex returns a PIL.Image object. Having the return types enables modifying or directly interacting with the rendered output from the drawers. Jupyter notebooks understand these return types and render them for us in this tutorial, but when running outside of Jupyter, you do not have this feature automatically. However, the draw() method has optional arguments to display or save the output. When specified, the filename kwarg takes a path to which it saves the rendered output. Alternatively, if you’re using the mpl or latex outputs, you can leverage the interactive kwarg to open the image in a new window (this will not always work from within a notebook but will be demonstrated anyway).

출력을 맞춤 하기

결과에 따라 회로 다이어그램을 맞춤 해 주는 옵션들이 준비되어 있다.

장벽 (Barriers) 그림 금지와 비트 순서 뒤집기

처음 두 개의 옵션은 세 개의 백엔드(Renderer) 전부 공유한다. 이를 통해 비트 순서와 장벽을 그릴지에 대한 여부를 둘 다 설정할 수 있다. 이들은 reverse_bits 키워드와 plot_barriers 키워드에 의해 각각 설정될 수 있다. 아래 예제는 어떤 출력 백엔드와도 작동할 것이며 여기에선 간결성을 위해 mpl 이 사용된다.

[8]:
# Draw a new circuit with barriers and more registers

q_a = QuantumRegister(3, name='qa')
q_b = QuantumRegister(5, name='qb')
c_a = ClassicalRegister(3)
c_b = ClassicalRegister(5)

circuit = QuantumCircuit(q_a, q_b, c_a, c_b)

circuit.x(q_a[1])
circuit.x(q_b[1])
circuit.x(q_b[2])
circuit.x(q_b[4])
circuit.barrier()
circuit.h(q_a)
circuit.barrier(q_a)
circuit.h(q_b)
circuit.cswap(q_b[0], q_b[1], q_b[2])
circuit.cswap(q_b[2], q_b[3], q_b[4])
circuit.cswap(q_b[3], q_b[4], q_b[0])
circuit.barrier(q_b)
circuit.measure(q_a, c_a)
circuit.measure(q_b, c_b);
[9]:
# Draw the circuit
circuit.draw(output='mpl')
[9]:
../../_images/tutorials_circuits_advanced_03_advanced_circuit_visualization_11_0.png
[10]:
# Draw the circuit with reversed bit order
circuit.draw(output='mpl', reverse_bits=True)
[10]:
../../_images/tutorials_circuits_advanced_03_advanced_circuit_visualization_12_0.png
[11]:
# Draw the circuit without barriers
circuit.draw(output='mpl', plot_barriers=False)
[11]:
../../_images/tutorials_circuits_advanced_03_advanced_circuit_visualization_13_0.png
[12]:
# Draw the circuit without barriers and reverse bit order
circuit.draw(output='mpl', plot_barriers=False, reverse_bits=True)
[12]:
../../_images/tutorials_circuits_advanced_03_advanced_circuit_visualization_14_0.png

백엔드 특정 맞춤

사용 가능한 일부 사용자 지정 옵션은 백엔드에 따라 다르다. text 백엔드에 대한 line_length kwarg를 사용하여 출력의 최대 너비를 설정할 수 있다. 다이어그램이 최대값보다 넓으면 아래 다이어그래을 래핑(wrapping) 한다. mpl 백엔드에는 사용자에 따라 출력을 맞춤 지정하는 데 사용되는 style kwarg가 있다. scale 옵션은 mpllatex 백엔드에서 곱셈 조정 계수(multiplicative adjustment factor) 를 이용하여 출력 이미지의 크기를 조정하는 데 사용된다. style kwarg는 여러 옵션이 있는 dict 를 가져와서 색상 변경, 다양한 유형의 게이트, 다양한 선 스타일 등에 대하여 렌더링된 텍스트를 변경하는 데 높은 수준의 유연성을 제공한다. 사용 가능한 옵션은 다음과 같다:

  • textcolor (str): 텍스트에 사용할 색상 코드 기본설정은 '#000000' 이다.

  • subtextcolor (str): 서브텍스트에 사용할 색상코드 기본설정은 '#000000' 이다.

  • linecolor (str): 선들에 사용할 색상 코드 기본설정은 '#000000' 이다.

  • creglinecolor (str): 고전 레지스트에 사용할 색상코드는 '#778899' 이다.

  • gatetextcolor (str): 게이트 텍스트에 사용할 색상코드는 '#000000' 이다.

  • gatefacecolor (str): 게이트에 사용할 색상코드 기본설정은 '#ffffff' 이다.

  • barrierfacecolor (str): 배리어(Barriers) 에 사용할 색상코드 기본설정은 '#bdbdbd' 이다.

  • backgroundcolor (str): 배경에 사용할 색상코드 기본설정은 '#ffffff' 이다.

  • fontsize (int): 텍스트의 글씨 크기 기본값은 13이다.

  • subfontsize (int): 서브텍스트의 글씨 크기 기본값은 8이다.

  • displaytext (dict): 출력 시각화의 각 요소 유형에 사용할 딕셔너리. 기본값들은 다음과 같다.

    'id': 'id',
    'u0': 'U_0',
    'u1': 'U_1',
    'u2': 'U_2',
    'u3': 'U_3',
    'x': 'X',
    'y': 'Y',
    'z': 'Z',
    'h': 'H',
    's': 'S',
    'sdg': 'S^\\dagger',
    't': 'T',
    'tdg': 'T^\\dagger',
    'rx': 'R_x',
    'ry': 'R_y',
    'rz': 'R_z',
    'reset': '\\left|0\\right\\rangle'
    

    이를 사용하게 될 경우, 요구되는 모든 값을 명시해야 한다. 불완전한 딕셔너리를 넘겨받았을 경우에 대한 규칙은 존재하지 않는다.

  • displaycolor (dict): 각 회로 요소에 사용할 색상 코드. 기본적으로 모든 값은 gatefacecolor 의 값을 사용하며, 키는 displaytext 에 해당한다. 또한, displaytext 와 동일하게, 불완전한 딕셔너리가 넘겨졌을 경우에 대한 규칙은 존재하지 않는다.

  • latexdrawerstyle (bool): 참일때 LaTeX 모드로 전환하여 게이트를 latex output 모드로 그려준다.

  • usepiformat (bool): 참이면 출력에 라디안을 사용한다.

  • fold (int): 회로를 접게 되는 회로요소들의 개수 기본값은 20이다.

  • cregbundle (bool): 참(True) 이면 고전 레지스터를 묶는다.

  • showindex (bool): 참(True) 이면 인덱스를 그린다.

  • Compress (bool): 참(True) 이면 압축된 회로를 그린다.

  • figwidth (int): 출력되는 그림의 최대 너비(인치 단위).

  • dpi (int): 이미지의 DPI 설정 기본값은 150이다.

  • creglinestyle (str): 고전 레지스터에 사용할 선의 디자인 스타일. 옵션 중에는 'solid', 'doublet', 또는 다른 유효한 matplotlib의 linestyle kwarg 값을 넣을 수 있다. 기본값은 doublet 이다.

[13]:
# Set line length to 80 for above circuit
circuit.draw(output='text')
[13]:
            ░ ┌───┐ ░    ┌─┐
qa_0: ──────░─┤ H ├─░────┤M├───────────────────────────
      ┌───┐ ░ ├───┤ ░    └╥┘┌─┐
qa_1: ┤ X ├─░─┤ H ├─░─────╫─┤M├────────────────────────
      └───┘ ░ ├───┤ ░     ║ └╥┘┌─┐
qa_2: ──────░─┤ H ├─░─────╫──╫─┤M├─────────────────────
            ░ ├───┤ ░     ║  ║ └╥┘    ░ ┌─┐
qb_0: ──────░─┤ H ├─■─────╫──╫──╫──X──░─┤M├────────────
      ┌───┐ ░ ├───┤ │     ║  ║  ║  │  ░ └╥┘┌─┐
qb_1: ┤ X ├─░─┤ H ├─X─────╫──╫──╫──┼──░──╫─┤M├─────────
      ├───┤ ░ ├───┤ │     ║  ║  ║  │  ░  ║ └╥┘┌─┐
qb_2: ┤ X ├─░─┤ H ├─X──■──╫──╫──╫──┼──░──╫──╫─┤M├──────
      └───┘ ░ ├───┤    │  ║  ║  ║  │  ░  ║  ║ └╥┘┌─┐
qb_3: ──────░─┤ H ├────X──╫──╫──╫──■──░──╫──╫──╫─┤M├───
      ┌───┐ ░ ├───┤    │  ║  ║  ║  │  ░  ║  ║  ║ └╥┘┌─┐
qb_4: ┤ X ├─░─┤ H ├────X──╫──╫──╫──X──░──╫──╫──╫──╫─┤M├
      └───┘ ░ └───┘       ║  ║  ║     ░  ║  ║  ║  ║ └╥┘
c0_0: ════════════════════╩══╬══╬════════╬══╬══╬══╬══╬═
                             ║  ║        ║  ║  ║  ║  ║
c0_1: ═══════════════════════╩══╬════════╬══╬══╬══╬══╬═
                                ║        ║  ║  ║  ║  ║
c0_2: ══════════════════════════╩════════╬══╬══╬══╬══╬═
                                         ║  ║  ║  ║  ║
c1_0: ═══════════════════════════════════╩══╬══╬══╬══╬═
                                            ║  ║  ║  ║
c1_1: ══════════════════════════════════════╩══╬══╬══╬═
                                               ║  ║  ║
c1_2: ═════════════════════════════════════════╩══╬══╬═
                                                  ║  ║
c1_3: ════════════════════════════════════════════╩══╬═
                                                     ║
c1_4: ═══════════════════════════════════════════════╩═
                                                       
[14]:
# Change the background color in mpl

style = {'backgroundcolor': 'lightgreen'}

circuit.draw(output='mpl', style=style)
[14]:
../../_images/tutorials_circuits_advanced_03_advanced_circuit_visualization_17_0.png
[15]:
# Scale the mpl output to 1/2 the normal size
circuit.draw(output='mpl', scale=0.5)
[15]:
../../_images/tutorials_circuits_advanced_03_advanced_circuit_visualization_18_0.png

함수로서의 circuit_drawer()

회로 객체의 메소드가 아니라 자체 포함 함수로 회로를 그리는 것을 선호하는 애플리케이션이 있는 경우에는 qiskit.tools.visualization 에서 public stable 인터페이스의 일부인 circuit_drawer() 기능을 직접 사용할 수 있다. 이 함수는 요구되는 인자로서 회로 객체를 취하는 것을 제외하고는 circuit.draw() 함수와 동일하게 동작한다.

참고: Qiskit Terra <= 0.7에서, circuit_drawer() 함수는 기본적으로 LaTeX 출력 백엔드를 사용한다. 그리고 0.6.x 버전 라인업에서는 LaTeX이 어떤 이유로 작동 실패할 경우 mpl(matplotlib)으로 자동 전환된다. 릴리즈 > 0.7 부터, 기본값은 텍스트 출력으로 변경된다.

[17]:
from qiskit.tools.visualization import circuit_drawer
[18]:
circuit_drawer(circuit, output='mpl', plot_barriers=False)
[18]:
../../_images/tutorials_circuits_advanced_03_advanced_circuit_visualization_21_0.png
[19]:
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright

Version Information

Qiskit SoftwareVersion
QiskitNone
Terra0.15.0
Aer0.5.1
IgnisNone
AquaNone
IBM Q Provider0.7.0
System information
Python3.8.2 (default, Mar 26 2020, 10:43:30) [Clang 4.0.1 (tags/RELEASE_401/final)]
OSDarwin
CPUs4
Memory (Gb)16.0
Fri May 08 08:43:36 2020 EDT

This code is a part of Qiskit

© Copyright IBM 2017, 2020.

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.

[ ]: