Instruction
stringlengths 13
145k
| input_code
stringlengths 35
390k
| output_code
stringlengths 35
390k
|
|---|---|---|
Loading Qiskit with no internet results in a ConnectionError
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### What is the current behavior?
Loading Qiskit with no Internet results in a `ConnectionError`.
### Steps to reproduce the problem
Run Qiskit without Internet connection.
### What is the expected behavior?
Qiskit prompt no error at all.
|
qiskit/_util.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=too-many-ancestors
"""Common utilities for QISKit."""
import logging
import re
import sys
import warnings
from collections import UserDict
API_NAME = 'IBMQuantumExperience'
logger = logging.getLogger(__name__)
FIRST_CAP_RE = re.compile('(.)([A-Z][a-z]+)')
ALL_CAP_RE = re.compile('([a-z0-9])([A-Z])')
def _check_python_version():
"""Check for Python version 3.5+
"""
if sys.version_info < (3, 5):
raise Exception('QISKit requires Python version 3.5 or greater.')
def _check_ibmqx_version():
"""Check if the available IBMQuantumExperience version is the required one.
Check that the installed "IBMQuantumExperience" package version matches the
version required by the package, emitting a warning if it is not present.
Note:
The check is only performed when `qiskit` is installed via `pip`
(available under `pkg_resources.working_set`). For other configurations
(such as local development, etc), the check is skipped silently.
"""
try:
# Use a local import, as in very specific environments setuptools
# might not be available or updated (conda with specific setup).
import pkg_resources
working_set = pkg_resources.working_set
qiskit_pkg = working_set.by_key['qiskit']
except (ImportError, KeyError):
# If 'qiskit' was not found among the installed packages, silently
# return.
return
# Find the IBMQuantumExperience version specified in this release of qiskit
# based on pkg_resources (in turn, based on setup.py::install_requires).
ibmqx_require = next(r for r in qiskit_pkg.requires() if
r.name == API_NAME)
# Finally, compare the versions.
try:
# First try to use IBMQuantumExperience.__version__ directly.
from IBMQuantumExperience import __version__ as ibmqx_version
if ibmqx_version in ibmqx_require:
return
except ImportError:
# __version__ was not available, so try to compare using the
# working_set. This assumes IBMQuantumExperience is installed as a
# library (using pip, etc).
try:
working_set.require(str(ibmqx_require))
return
except pkg_resources.DistributionNotFound:
# IBMQuantumExperience was not found among the installed libraries.
# The warning is not printed, assuming the user is using a local
# version and takes responsibility of handling the versions.
return
except pkg_resources.VersionConflict:
pass
logger.warning('The installed IBMQuantumExperience package does '
'not match the required version - some features might '
'not work as intended. Please install %s.',
str(ibmqx_require))
def _enable_deprecation_warnings():
"""
Force the `DeprecationWarning` warnings to be displayed for the qiskit
module, overriding the system configuration as they are ignored by default
[1] for end-users.
TODO: on Python 3.7, this might not be needed due to PEP-0565 [2].
[1] https://docs.python.org/3/library/warnings.html#default-warning-filters
[2] https://www.python.org/dev/peps/pep-0565/
"""
# pylint: disable=invalid-name
deprecation_filter = ('always', None, DeprecationWarning,
re.compile(r'^qiskit\.*', re.UNICODE), 0)
# Instead of using warnings.simple_filter() directly, the internal
# _add_filter() function is used for being able to match against the
# module.
try:
warnings._add_filter(*deprecation_filter, append=False)
except AttributeError:
# ._add_filter is internal and not available in some Python versions.
pass
def _camel_case_to_snake_case(identifier):
"""Return a `snake_case` string from a `camelCase` string.
Args:
identifier (str): a `camelCase` string.
Returns:
str: a `snake_case` string.
"""
string_1 = FIRST_CAP_RE.sub(r'\1_\2', identifier)
return ALL_CAP_RE.sub(r'\1_\2', string_1).lower()
_check_python_version()
_check_ibmqx_version()
_enable_deprecation_warnings()
class AvailableToOperationalDict(UserDict):
"""
TEMPORARY class for transitioning from `status['available']` to
`status['operational']`.
FIXME: Remove this class as soon as the API is updated, please.
"""
def __getitem__(self, key):
if key == 'available':
warnings.warn(
"status['available'] has been renamed to status['operational'] "
" since 0.5.5. Please use status['operational'] accordingly.",
DeprecationWarning)
return super(AvailableToOperationalDict, self).__getitem__(key)
def _parse_ibmq_credentials(url, hub=None, group=None, project=None):
"""Converts old Q network credentials to new url only
format, if needed.
"""
if any([hub, group, project]):
url = "https://q-console-api.mybluemix.net/api/" + \
"Hubs/{hub}/Groups/{group}/Projects/{project}"
url = url.format(hub=hub, group=group, project=project)
warnings.warn(
"Passing hub/group/project as parameters is deprecated in qiskit "
"0.6+. Please use the new URL format provided in the q-console.",
DeprecationWarning)
return url
<|code_end|>
qiskit/tools/visualization/__init__.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Main QISKit visualization methods."""
import sys
from ._circuit_visualization import circuit_drawer, plot_circuit, generate_latex_source,\
latex_circuit_drawer, matplotlib_circuit_drawer, qx_color_scheme
from ._error import VisualizationError
from ._state_visualization import plot_bloch_vector
if ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
import requests
if requests.get(
'https://qvisualization.mybluemix.net/').status_code == 200:
from .interactive._iplot_state import iplot_state as plot_state
from .interactive._iplot_histogram import iplot_histogram as \
plot_histogram
else:
from ._state_visualization import plot_state
from ._counts_visualization import plot_histogram
else:
from ._state_visualization import plot_state
from ._counts_visualization import plot_histogram
<|code_end|>
|
qiskit/_util.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=too-many-ancestors
"""Common utilities for QISKit."""
import logging
import re
import sys
import warnings
import socket
from collections import UserDict
API_NAME = 'IBMQuantumExperience'
logger = logging.getLogger(__name__)
FIRST_CAP_RE = re.compile('(.)([A-Z][a-z]+)')
ALL_CAP_RE = re.compile('([a-z0-9])([A-Z])')
def _check_python_version():
"""Check for Python version 3.5+
"""
if sys.version_info < (3, 5):
raise Exception('QISKit requires Python version 3.5 or greater.')
def _check_ibmqx_version():
"""Check if the available IBMQuantumExperience version is the required one.
Check that the installed "IBMQuantumExperience" package version matches the
version required by the package, emitting a warning if it is not present.
Note:
The check is only performed when `qiskit` is installed via `pip`
(available under `pkg_resources.working_set`). For other configurations
(such as local development, etc), the check is skipped silently.
"""
try:
# Use a local import, as in very specific environments setuptools
# might not be available or updated (conda with specific setup).
import pkg_resources
working_set = pkg_resources.working_set
qiskit_pkg = working_set.by_key['qiskit']
except (ImportError, KeyError):
# If 'qiskit' was not found among the installed packages, silently
# return.
return
# Find the IBMQuantumExperience version specified in this release of qiskit
# based on pkg_resources (in turn, based on setup.py::install_requires).
ibmqx_require = next(r for r in qiskit_pkg.requires() if
r.name == API_NAME)
# Finally, compare the versions.
try:
# First try to use IBMQuantumExperience.__version__ directly.
from IBMQuantumExperience import __version__ as ibmqx_version
if ibmqx_version in ibmqx_require:
return
except ImportError:
# __version__ was not available, so try to compare using the
# working_set. This assumes IBMQuantumExperience is installed as a
# library (using pip, etc).
try:
working_set.require(str(ibmqx_require))
return
except pkg_resources.DistributionNotFound:
# IBMQuantumExperience was not found among the installed libraries.
# The warning is not printed, assuming the user is using a local
# version and takes responsibility of handling the versions.
return
except pkg_resources.VersionConflict:
pass
logger.warning('The installed IBMQuantumExperience package does '
'not match the required version - some features might '
'not work as intended. Please install %s.',
str(ibmqx_require))
def _enable_deprecation_warnings():
"""
Force the `DeprecationWarning` warnings to be displayed for the qiskit
module, overriding the system configuration as they are ignored by default
[1] for end-users.
TODO: on Python 3.7, this might not be needed due to PEP-0565 [2].
[1] https://docs.python.org/3/library/warnings.html#default-warning-filters
[2] https://www.python.org/dev/peps/pep-0565/
"""
# pylint: disable=invalid-name
deprecation_filter = ('always', None, DeprecationWarning,
re.compile(r'^qiskit\.*', re.UNICODE), 0)
# Instead of using warnings.simple_filter() directly, the internal
# _add_filter() function is used for being able to match against the
# module.
try:
warnings._add_filter(*deprecation_filter, append=False)
except AttributeError:
# ._add_filter is internal and not available in some Python versions.
pass
def _camel_case_to_snake_case(identifier):
"""Return a `snake_case` string from a `camelCase` string.
Args:
identifier (str): a `camelCase` string.
Returns:
str: a `snake_case` string.
"""
string_1 = FIRST_CAP_RE.sub(r'\1_\2', identifier)
return ALL_CAP_RE.sub(r'\1_\2', string_1).lower()
_check_python_version()
_check_ibmqx_version()
_enable_deprecation_warnings()
class AvailableToOperationalDict(UserDict):
"""
TEMPORARY class for transitioning from `status['available']` to
`status['operational']`.
FIXME: Remove this class as soon as the API is updated, please.
"""
def __getitem__(self, key):
if key == 'available':
warnings.warn(
"status['available'] has been renamed to status['operational'] "
" since 0.5.5. Please use status['operational'] accordingly.",
DeprecationWarning)
return super(AvailableToOperationalDict, self).__getitem__(key)
def _parse_ibmq_credentials(url, hub=None, group=None, project=None):
"""Converts old Q network credentials to new url only
format, if needed.
"""
if any([hub, group, project]):
url = "https://q-console-api.mybluemix.net/api/" + \
"Hubs/{hub}/Groups/{group}/Projects/{project}"
url = url.format(hub=hub, group=group, project=project)
warnings.warn(
"Passing hub/group/project as parameters is deprecated in qiskit "
"0.6+. Please use the new URL format provided in the q-console.",
DeprecationWarning)
return url
def _has_connection(hostname, port):
"""Checks to see if internet connection exists to host
via specified port
Args:
hostname (str): Hostname to connect to.
port (int): Port to connect to
Returns:
bool: Has connection or not
Raises:
gaierror: No connection established.
"""
try:
host = socket.gethostbyname(hostname)
socket.create_connection((host, port), 2)
return True
except socket.gaierror:
pass
return False
<|code_end|>
qiskit/tools/visualization/__init__.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Main QISKit visualization methods."""
import sys
from qiskit._util import _has_connection
from ._circuit_visualization import circuit_drawer, plot_circuit, generate_latex_source,\
latex_circuit_drawer, matplotlib_circuit_drawer, qx_color_scheme
from ._error import VisualizationError
from ._state_visualization import plot_bloch_vector
if ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
if _has_connection('https://qvisualization.mybluemix.net/', 443):
from .interactive._iplot_state import iplot_state as plot_state
from .interactive._iplot_histogram import iplot_histogram as \
plot_histogram
else:
from ._state_visualization import plot_state
from ._counts_visualization import plot_histogram
else:
from ._state_visualization import plot_state
from ._counts_visualization import plot_histogram
<|code_end|>
|
Speedup python local_unitary_simulator
@chriseclectic noted in #893
### What is the expected enhancement?
An important speedup by using Einstein summation for enlarging one and two qubit operations.
An example of runtime for a random circuit of 100 gates on my laptop (Macbook pro 3.1 GHz i7, 16 GB Ram):
Timing results for new implementation are:
```
2 qubit circuit, 100 gates, time taken: 0.073 s
3 qubit circuit, 100 gates, time taken: 0.072 s
4 qubit circuit, 100 gates, time taken: 0.071 s
5 qubit circuit, 100 gates, time taken: 0.075 s
6 qubit circuit, 100 gates, time taken: 0.087 s
7 qubit circuit, 100 gates, time taken: 0.08 s
8 qubit circuit, 100 gates, time taken: 0.11 s
9 qubit circuit, 100 gates, time taken: 0.352 s
10 qubit circuit, 100 gates, time taken: 1.346 s
11 qubit circuit, 100 gates, time taken: 4.931 s
12 qubit circuit, 100 gates, time taken: 28.891 s
```
Timing results for old implementation are
```
2 qubit circuit, 100 gates, time taken: 0.24 s
3 qubit circuit, 100 gates, time taken: 0.123 s
4 qubit circuit, 100 gates, time taken: 0.178 s
5 qubit circuit, 100 gates, time taken: 0.114 s
6 qubit circuit, 100 gates, time taken: 0.138 s
7 qubit circuit, 100 gates, time taken: 0.238 s
8 qubit circuit, 100 gates, time taken: 0.486 s
9 qubit circuit, 100 gates, time taken: 2.835 s
10 qubit circuit, 100 gates, time taken: 15.714 s
11 qubit circuit, 100 gates, time taken: 115.502 s
12 qubit circuit, 100 gates, time taken: ?
```
(I wasn't patient enough for the 12 qubit circuit)
The python file used for printing benchmarks was:
```python
# Simple benchmark
import numpy as np
import time
import qiskit
# Create a test circuit
for num_qubits in range(2, 13):
# Create random test circuit
num_gates = 100
qr = qiskit.QuantumRegister(num_qubits)
circ = qiskit.QuantumCircuit(qr)
for j in range(num_gates):
q = np.random.randint(0, num_qubits)
r = np.random.randint(0, 4)
if r == 0:
circ.cx(qr[q], qr[(q + 1) % num_qubits])
elif r == 1:
circ.h(qr[q])
elif r == 2:
circ.s(qr[q])
elif r == 3:
circ.t(qr[q])
# Execute with timer
start = time.time()
result = qiskit.execute(circ, 'local_unitary_simulator').result()
stop = time.time()
print("{} qubit circuit, {} gates, time taken: {} s".format(num_qubits, num_gates, np.round(stop-start,3)))
```
|
qiskit/backends/local/_simulatortools.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""Contains functions used by the simulators.
Functions
index2 -- Takes a bitstring k and inserts bits b1 as the i1th bit
and b2 as the i2th bit
enlarge_single_opt(opt, qubit, number_of_qubits) -- takes a single qubit
operator opt to a opterator on n qubits
enlarge_two_opt(opt, q0, q1, number_of_qubits) -- takes a two-qubit
operator opt to a opterator on n qubits
"""
import numpy as np
from sympy import Matrix, pi, E, I, cos, sin, N, sympify
from qiskit import QISKitError
def index1(b, i, k):
"""Magic index1 function.
Takes a bitstring k and inserts bit b as the ith bit,
shifting bits >= i over to make room.
"""
retval = k
lowbits = k & ((1 << i) - 1) # get the low i bits
retval >>= i
retval <<= 1
retval |= b
retval <<= i
retval |= lowbits
return retval
def index2(b1, i1, b2, i2, k):
"""Magic index1 function.
Takes a bitstring k and inserts bits b1 as the i1th bit
and b2 as the i2th bit
"""
assert i1 != i2
if i1 > i2:
# insert as (i1-1)th bit, will be shifted left 1 by next line
retval = index1(b1, i1-1, k)
retval = index1(b2, i2, retval)
else: # i2>i1
# insert as (i2-1)th bit, will be shifted left 1 by next line
retval = index1(b2, i2-1, k)
retval = index1(b1, i1, retval)
return retval
def enlarge_single_opt(opt, qubit, number_of_qubits):
"""Enlarge single operator to n qubits.
It is exponential in the number of qubits.
Args:
opt (array): the single-qubit opt.
qubit (int): the qubit to apply it on counts from 0 and order
is q_{n-1} ... otimes q_1 otimes q_0.
number_of_qubits (int): the number of qubits in the system.
Returns:
array: enlarge single operator to n qubits
"""
temp_1 = np.identity(2**(number_of_qubits-qubit-1), dtype=complex)
temp_2 = np.identity(2**qubit, dtype=complex)
enlarge_opt = np.kron(temp_1, np.kron(opt, temp_2))
return enlarge_opt
def enlarge_two_opt(opt, q0, q1, num):
"""Enlarge two-qubit operator to n qubits.
It is exponential in the number of qubits.
opt is the two-qubit gate
q0 is the first qubit (control) counts from 0
q1 is the second qubit (target)
returns a complex numpy array
number_of_qubits is the number of qubits in the system.
"""
enlarge_opt = np.zeros([1 << (num), 1 << (num)])
for i in range(1 << (num-2)):
for j in range(2):
for k in range(2):
for jj in range(2):
for kk in range(2):
enlarge_opt[index2(j, q0, k, q1, i),
index2(jj, q0, kk, q1, i)] = opt[j+2*k,
jj+2*kk]
return enlarge_opt
def single_gate_params(gate, params=None):
"""Apply a single qubit gate to the qubit.
Args:
gate(str): the single qubit gate name
params(list): the operation parameters op['params']
Returns:
tuple: a tuple of U gate parameters (theta, phi, lam)
Raises:
QISKitError: if the gate name is not valid
"""
if gate == 'U' or gate == 'u3':
return params[0], params[1], params[2]
elif gate == 'u2':
return np.pi/2, params[0], params[1]
elif gate == 'u1':
return 0, 0, params[0]
elif gate == 'id':
return 0, 0, 0
raise QISKitError('Gate is not among the valid types: %s' % gate)
def single_gate_matrix(gate, params=None):
"""Get the matrix for a single qubit.
Args:
gate(str): the single qubit gate name
params(list): the operation parameters op['params']
Returns:
array: A numpy array representing the matrix
"""
# Converting sym to floats improves the performance of the simulator 10x.
# This a is a probable a FIXME since it might show bugs in the simulator.
(theta, phi, lam) = map(float, single_gate_params(gate, params))
return np.array([[np.cos(theta/2),
-np.exp(1j*lam)*np.sin(theta/2)],
[np.exp(1j*phi)*np.sin(theta/2),
np.exp(1j*phi+1j*lam)*np.cos(theta/2)]])
# Functions used by the sympy simulators.
def regulate(theta):
"""
Return the regulated symbolic representation of `theta`::
* if it has a representation close enough to `pi` transformations,
return that representation (for example, `3.14` -> `sympy.pi`).
* otherwise, return a sympified representation of theta (for example,
`1.23` -> `sympy.Float(1.23)`).
See also `UGateGeneric`.
Args:
theta (float or sympy.Basic): the float value (e.g., 3.14) or the
symbolic value (e.g., pi)
Returns:
sympy.Basic: the sympy-regulated representation of `theta`
"""
error_margin = 0.01
targets = [pi, pi/2, pi * 2, pi / 4]
for t in targets:
if abs(N(theta - t)) < error_margin:
return t
return sympify(theta)
def compute_ugate_matrix(parameters):
"""Compute the matrix associated with a parameterized U gate.
Args:
parameters (list[float]): parameters carried by the U gate
Returns:
sympy.Matrix: the matrix associated with a parameterized U gate
"""
theta = regulate(parameters[0])
phi = regulate(parameters[1])
lamb = regulate(parameters[2])
left_up = cos(theta/2)
right_up = (-E**(I*lamb)) * sin(theta/2)
left_down = (E**(I*phi)) * sin(theta/2)
right_down = (E**(I*(phi + lamb))) * cos(theta/2)
return Matrix([[left_up, right_up], [left_down, right_down]])
<|code_end|>
qiskit/backends/local/unitary_simulator_py.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Contains a (slow) Python simulator that returns the unitary of the circuit.
It simulates a unitary of a quantum circuit that has been compiled to run on
the simulator. It is exponential in the number of qubits.
The input is the circuit object and the output is the same circuit object with
a result field added results['data']['unitary'] where the unitary is
a 2**n x 2**n complex numpy array representing the unitary matrix.
The input is
compiled_circuit object
and the output is the results object
The simulator is run using
UnitarySimulatorPy(compiled_circuit).run().
In the qasm, key operations with type 'measure' and 'reset' are dropped.
Internal circuit_object::
compiled_circuit =
{
"header": {
"number_of_qubits": 2, // int
"number_of_clbits": 2, // int
"qubit_labels": [["q", 0], ["v", 0]], // list[list[string, int]]
"clbit_labels": [["c", 2]], // list[list[string, int]]
}
"operations": // list[map]
[
{
"name": , // required -- string
"params": , // optional -- list[double]
"qubits": , // required -- list[int]
"clbits": , //optional -- list[int]
"conditional": // optional -- map
{
"type": , // string
"mask": , // hex string
"val": , // bhex string
}
},
]
}
returned results object::
result =
{
'data':
{
'unitary': np.array([[ 0.70710678 +0.00000000e+00j
0.70710678 -8.65956056e-17j
0.00000000 +0.00000000e+00j
0.00000000 +0.00000000e+00j]
[ 0.00000000 +0.00000000e+00j
0.00000000 +0.00000000e+00j
0.70710678 +0.00000000e+00j
-0.70710678 +8.65956056e-17j]
[ 0.00000000 +0.00000000e+00j
0.00000000 +0.00000000e+00j
0.70710678 +0.00000000e+00j
0.70710678 -8.65956056e-17j]
[ 0.70710678 +0.00000000e+00j
-0.70710678 +8.65956056e-17j
0.00000000 +0.00000000e+00j
0.00000000 +0.00000000e+00j]
}
'state': 'DONE'
}
"""
import logging
import uuid
import time
import numpy as np
from qiskit.result._utils import copy_qasm_from_qobj_into_result, result_from_old_style_dict
from qiskit.backends import BaseBackend
from qiskit.backends.local.localjob import LocalJob
from ._simulatortools import enlarge_single_opt, enlarge_two_opt, single_gate_matrix
logger = logging.getLogger(__name__)
# TODO add ["status"] = 'DONE', 'ERROR' especitally for empty circuit error
# does not show up
class UnitarySimulatorPy(BaseBackend):
"""Python implementation of a unitary simulator."""
DEFAULT_CONFIGURATION = {
'name': 'local_unitary_simulator_py',
'url': 'https://github.com/QISKit/qiskit-terra',
'simulator': True,
'local': True,
'description': 'A python simulator for unitary matrix',
'coupling_map': 'all-to-all',
'basis_gates': 'u1,u2,u3,cx,id'
}
def __init__(self, configuration=None):
"""Initialize the UnitarySimulatorPy object.
"""
super().__init__(configuration or self.DEFAULT_CONFIGURATION.copy())
# Define attributes inside __init__.
self._unitary_state = None
self._number_of_qubits = 0
def _add_unitary_single(self, gate, qubit):
"""Apply the single-qubit gate.
gate is the single-qubit gate.
qubit is the qubit to apply it on counts from 0 and order
is q_{n-1} ... otimes q_1 otimes q_0.
number_of_qubits is the number of qubits in the system.
"""
unitary_add = enlarge_single_opt(gate, qubit, self._number_of_qubits)
self._unitary_state = np.dot(unitary_add, self._unitary_state)
def _add_unitary_two(self, gate, q_0, q_1):
"""Apply the two-qubit gate.
gate is the two-qubit gate
q0 is the first qubit (control) counts from 0
q1 is the second qubit (target)
returns a complex numpy array
"""
unitaty_add = enlarge_two_opt(gate, q_0, q_1, self._number_of_qubits)
self._unitary_state = np.dot(unitaty_add, self._unitary_state)
def run(self, qobj):
"""Run qobj asynchronously.
Args:
qobj (dict): job description
Returns:
LocalJob: derived from BaseJob
"""
local_job = LocalJob(self._run_job, qobj)
local_job.submit()
return local_job
def _run_job(self, qobj):
"""Run qobj. This is a blocking call.
Args:
qobj (Qobj): job description
Returns:
Result: Result object
"""
result_list = []
start = time.time()
for circuit in qobj.experiments:
result_list.append(self.run_circuit(circuit))
end = time.time()
job_id = str(uuid.uuid4())
result = {'backend': self._configuration['name'],
'id': qobj.qobj_id,
'job_id': job_id,
'result': result_list,
'status': 'COMPLETED',
'success': True,
'time_taken': (end - start)}
copy_qasm_from_qobj_into_result(qobj, result)
return result_from_old_style_dict(
result, [circuit.header.name for circuit in qobj.experiments])
def run_circuit(self, circuit):
"""Apply the single-qubit gate.
Args:
circuit (QobjExperiment): experiment from qobj experiments list
Returns:
dict: A dictionary of results.
"""
self._number_of_qubits = circuit.header.number_of_qubits
result = {
'data': {},
'name': circuit.header.name
}
self._unitary_state = np.identity(2 ** self._number_of_qubits,
dtype=complex)
for operation in circuit.instructions:
if operation.name in ('U', 'u1', 'u2', 'u3'):
params = getattr(operation, 'params', None)
qubit = operation.qubits[0]
gate = single_gate_matrix(operation.name, params)
self._add_unitary_single(gate, qubit)
elif operation.name in ('id', 'u0'):
pass
elif operation.name in ('CX', 'cx'):
qubit0 = operation.qubits[0]
qubit1 = operation.qubits[1]
gate = np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0],
[0, 1, 0, 0]])
self._add_unitary_two(gate, qubit0, qubit1)
elif operation.name == 'measure':
logger.info('Warning have dropped measure from unitary '
'simulator')
elif operation.name == 'reset':
logger.info('Warning have dropped reset from unitary '
'simulator')
elif operation.name == 'barrier':
pass
else:
result['status'] = 'ERROR'
return result
result['data']['unitary'] = self._unitary_state
result['status'] = 'DONE'
result['success'] = True
result['shots'] = 1
return result
<|code_end|>
|
qiskit/backends/local/_simulatortools.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""Contains functions used by the simulators.
Functions
index2 -- Takes a bitstring k and inserts bits b1 as the i1th bit
and b2 as the i2th bit
"""
from string import ascii_uppercase, ascii_lowercase
import numpy as np
from sympy import Matrix, pi, E, I, cos, sin, N, sympify
from qiskit import QISKitError
def index1(b, i, k):
"""Magic index1 function.
Takes a bitstring k and inserts bit b as the ith bit,
shifting bits >= i over to make room.
"""
retval = k
lowbits = k & ((1 << i) - 1) # get the low i bits
retval >>= i
retval <<= 1
retval |= b
retval <<= i
retval |= lowbits
return retval
def index2(b1, i1, b2, i2, k):
"""Magic index1 function.
Takes a bitstring k and inserts bits b1 as the i1th bit
and b2 as the i2th bit
"""
assert i1 != i2
if i1 > i2:
# insert as (i1-1)th bit, will be shifted left 1 by next line
retval = index1(b1, i1-1, k)
retval = index1(b2, i2, retval)
else: # i2>i1
# insert as (i2-1)th bit, will be shifted left 1 by next line
retval = index1(b2, i2-1, k)
retval = index1(b1, i1, retval)
return retval
def single_gate_params(gate, params=None):
"""Apply a single qubit gate to the qubit.
Args:
gate(str): the single qubit gate name
params(list): the operation parameters op['params']
Returns:
tuple: a tuple of U gate parameters (theta, phi, lam)
Raises:
QISKitError: if the gate name is not valid
"""
if gate == 'U' or gate == 'u3':
return params[0], params[1], params[2]
elif gate == 'u2':
return np.pi/2, params[0], params[1]
elif gate == 'u1':
return 0, 0, params[0]
elif gate == 'id':
return 0, 0, 0
raise QISKitError('Gate is not among the valid types: %s' % gate)
def single_gate_matrix(gate, params=None):
"""Get the matrix for a single qubit.
Args:
gate(str): the single qubit gate name
params(list): the operation parameters op['params']
Returns:
array: A numpy array representing the matrix
"""
# Converting sym to floats improves the performance of the simulator 10x.
# This a is a probable a FIXME since it might show bugs in the simulator.
(theta, phi, lam) = map(float, single_gate_params(gate, params))
return np.array([[np.cos(theta/2),
-np.exp(1j*lam)*np.sin(theta/2)],
[np.exp(1j*phi)*np.sin(theta/2),
np.exp(1j*phi+1j*lam)*np.cos(theta/2)]])
def einsum_matmul_index(gate_indices, number_of_qubits):
"""Return the index string for Numpy.eignsum matrix multiplication.
The returned indices are to perform a matrix multiplication A.B where
the matrix A is an M-qubit matrix, matrix B is an N-qubit matrix, and
M <= N, and identity matrices are implied on the subsystems where A has no
support on B.
Args:
gate_indices (list[int]): the indices of the right matrix subsystems
to contract with the left matrix.
number_of_qubits (int): the total number of qubits for the right matrix.
Returns:
str: An indices string for the Numpy.einsum function.
Raises:
QISKitError: if the total number of qubits plus the number of
contracted indices is greater than 26.
"""
# Since we use ASCII alphabet for einsum index labels we are limited
# to 26 total free left (lowercase) and 26 right (uppercase) indexes.
# The rank of the contracted tensor reduces this as we need to use that
# many characters for the contracted indices
if len(gate_indices) + number_of_qubits > 26:
raise QISKitError("Total number of free indexes limited to 26")
# Right indices for the N-qubit input and output tensor
idx_right = ascii_uppercase[:number_of_qubits]
# Left ndicies for N-qubit input tensor
idx_left_in = ascii_lowercase[:number_of_qubits]
# Left indices for the N-qubit output tensor
idx_left_out = list(idx_left_in)
# Left and right indices for the M-qubit multiplying tensor
mat_left = ""
mat_right = ""
# Update left indices for mat and output
for pos, idx in enumerate(reversed(gate_indices)):
mat_left += ascii_lowercase[-1 - pos]
mat_right += idx_left_in[-1 - idx]
idx_left_out[-1 - idx] = ascii_lowercase[-1 - pos]
idx_left_out = "".join(idx_left_out)
# Combine indices into matrix multiplication string format
# for numpy.einsum function
return "{mat_l}{mat_r}, ".format(mat_l=mat_left, mat_r=mat_right) + \
"{tens_lin}{tens_r}->{tens_lout}{tens_r}".format(tens_lin=idx_left_in,
tens_lout=idx_left_out,
tens_r=idx_right)
# Functions used by the sympy simulators.
def regulate(theta):
"""
Return the regulated symbolic representation of `theta`::
* if it has a representation close enough to `pi` transformations,
return that representation (for example, `3.14` -> `sympy.pi`).
* otherwise, return a sympified representation of theta (for example,
`1.23` -> `sympy.Float(1.23)`).
See also `UGateGeneric`.
Args:
theta (float or sympy.Basic): the float value (e.g., 3.14) or the
symbolic value (e.g., pi)
Returns:
sympy.Basic: the sympy-regulated representation of `theta`
"""
error_margin = 0.01
targets = [pi, pi/2, pi * 2, pi / 4]
for t in targets:
if abs(N(theta - t)) < error_margin:
return t
return sympify(theta)
def compute_ugate_matrix(parameters):
"""Compute the matrix associated with a parameterized U gate.
Args:
parameters (list[float]): parameters carried by the U gate
Returns:
sympy.Matrix: the matrix associated with a parameterized U gate
"""
theta = regulate(parameters[0])
phi = regulate(parameters[1])
lamb = regulate(parameters[2])
left_up = cos(theta/2)
right_up = (-E**(I*lamb)) * sin(theta/2)
left_down = (E**(I*phi)) * sin(theta/2)
right_down = (E**(I*(phi + lamb))) * cos(theta/2)
return Matrix([[left_up, right_up], [left_down, right_down]])
<|code_end|>
qiskit/backends/local/unitary_simulator_py.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Contains a Python simulator that returns the unitary of the circuit.
It simulates a unitary of a quantum circuit that has been compiled to run on
the simulator. It is exponential in the number of qubits.
The input is the circuit object and the output is the same circuit object with
a result field added results['data']['unitary'] where the unitary is
a 2**n x 2**n complex numpy array representing the unitary matrix.
The input is
compiled_circuit object
and the output is the results object
The simulator is run using
UnitarySimulatorPy(compiled_circuit).run().
In the qasm, key operations with type 'measure' and 'reset' are dropped.
Internal circuit_object::
compiled_circuit =
{
"header": {
"number_of_qubits": 2, // int
"number_of_clbits": 2, // int
"qubit_labels": [["q", 0], ["v", 0]], // list[list[string, int]]
"clbit_labels": [["c", 2]], // list[list[string, int]]
}
"operations": // list[map]
[
{
"name": , // required -- string
"params": , // optional -- list[double]
"qubits": , // required -- list[int]
"clbits": , //optional -- list[int]
"conditional": // optional -- map
{
"type": , // string
"mask": , // hex string
"val": , // bhex string
}
},
]
}
returned results object::
result =
{
'data':
{
'unitary': np.array([[ 0.70710678 +0.00000000e+00j
0.70710678 -8.65956056e-17j
0.00000000 +0.00000000e+00j
0.00000000 +0.00000000e+00j]
[ 0.00000000 +0.00000000e+00j
0.00000000 +0.00000000e+00j
0.70710678 +0.00000000e+00j
-0.70710678 +8.65956056e-17j]
[ 0.00000000 +0.00000000e+00j
0.00000000 +0.00000000e+00j
0.70710678 +0.00000000e+00j
0.70710678 -8.65956056e-17j]
[ 0.70710678 +0.00000000e+00j
-0.70710678 +8.65956056e-17j
0.00000000 +0.00000000e+00j
0.00000000 +0.00000000e+00j]
}
'state': 'DONE'
}
"""
import logging
import uuid
import time
import numpy as np
from qiskit.result._utils import copy_qasm_from_qobj_into_result, result_from_old_style_dict
from qiskit.backends import BaseBackend
from qiskit.backends.local.localjob import LocalJob
from qiskit import QISKitError
from ._simulatortools import single_gate_matrix, einsum_matmul_index
logger = logging.getLogger(__name__)
# TODO add ["status"] = 'DONE', 'ERROR' especitally for empty circuit error
# does not show up
class UnitarySimulatorPy(BaseBackend):
"""Python implementation of a unitary simulator."""
DEFAULT_CONFIGURATION = {
'name': 'local_unitary_simulator_py',
'url': 'https://github.com/QISKit/qiskit-terra',
'simulator': True,
'local': True,
'description': 'A python simulator for unitary matrix',
'coupling_map': 'all-to-all',
'basis_gates': 'u1,u2,u3,cx,id'
}
def __init__(self, configuration=None):
"""Initialize the UnitarySimulatorPy object.
"""
super().__init__(configuration or self.DEFAULT_CONFIGURATION.copy())
# Define attributes inside __init__.
self._unitary_state = None
self._number_of_qubits = 0
def _add_unitary_single(self, gate, qubit):
"""Apply the single-qubit gate.
gate is the single-qubit gate.
qubit is the qubit to apply it on counts from 0 and order
is q_{n-1} ... otimes q_1 otimes q_0.
number_of_qubits is the number of qubits in the system.
"""
# Convert to complex rank-2 tensor
gate_tensor = np.array(gate, dtype=complex)
# Compute einsum index string for 1-qubit matrix multiplication
indexes = einsum_matmul_index([qubit], self._number_of_qubits)
# Apply matrix multiplication
self._unitary_state = np.einsum(indexes,
gate_tensor,
self._unitary_state,
dtype=complex,
casting='no')
def _add_unitary_two(self, gate, qubit0, qubit1):
"""Apply the two-qubit gate.
gate is the two-qubit gate
qubit0 is the first qubit (control) counts from 0
qubit1 is the second qubit (target)
returns a complex numpy array
"""
# Convert to complex rank-4 tensor
gate_tensor = np.reshape(np.array(gate, dtype=complex), 4 * [2])
# Compute einsum index string for 2-qubit matrix multiplication
indexes = einsum_matmul_index([qubit0, qubit1], self._number_of_qubits)
# Apply matrix multiplication
self._unitary_state = np.einsum(indexes,
gate_tensor,
self._unitary_state,
dtype=complex,
casting='no')
def run(self, qobj):
"""Run qobj asynchronously.
Args:
qobj (dict): job description
Returns:
LocalJob: derived from BaseJob
"""
local_job = LocalJob(self._run_job, qobj)
local_job.submit()
return local_job
def _run_job(self, qobj):
"""Run qobj. This is a blocking call.
Args:
qobj (Qobj): job description
Returns:
Result: Result object
"""
result_list = []
start = time.time()
for circuit in qobj.experiments:
result_list.append(self.run_circuit(circuit))
end = time.time()
job_id = str(uuid.uuid4())
result = {'backend': self._configuration['name'],
'id': qobj.qobj_id,
'job_id': job_id,
'result': result_list,
'status': 'COMPLETED',
'success': True,
'time_taken': (end - start)}
copy_qasm_from_qobj_into_result(qobj, result)
return result_from_old_style_dict(
result, [circuit.header.name for circuit in qobj.experiments])
def run_circuit(self, circuit):
"""Apply the single-qubit gate.
Args:
circuit (QobjExperiment): experiment from qobj experiments list
Returns:
dict: A dictionary of results.
Raises:
QISKitError: if the number of qubits in the circuit is greater than 24.
Note that the practical qubit limit is much lower than 24.
"""
self._number_of_qubits = circuit.header.number_of_qubits
if self._number_of_qubits > 24:
raise QISKitError("np.einsum implementation limits local_unitary_simulator" +
" to 24 qubit circuits.")
result = {
'data': {},
'name': circuit.header.name
}
# Initilize unitary as rank 2*N tensor
self._unitary_state = np.reshape(np.eye(2 ** self._number_of_qubits,
dtype=complex),
self._number_of_qubits * [2, 2])
for operation in circuit.instructions:
if operation.name in ('U', 'u1', 'u2', 'u3'):
params = getattr(operation, 'params', None)
qubit = operation.qubits[0]
gate = single_gate_matrix(operation.name, params)
self._add_unitary_single(gate, qubit)
elif operation.name in ('id', 'u0'):
pass
elif operation.name in ('CX', 'cx'):
qubit0 = operation.qubits[0]
qubit1 = operation.qubits[1]
gate = np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0],
[0, 1, 0, 0]])
self._add_unitary_two(gate, qubit0, qubit1)
elif operation.name == 'measure':
logger.info('Warning have dropped measure from unitary '
'simulator')
elif operation.name == 'reset':
logger.info('Warning have dropped reset from unitary '
'simulator')
elif operation.name == 'barrier':
pass
else:
result['status'] = 'ERROR'
return result
# Reshape unitary rank-2n tensor back to a matrix
result['data']['unitary'] = np.reshape(self._unitary_state,
2 * [2 ** self._number_of_qubits])
result['status'] = 'DONE'
result['success'] = True
result['shots'] = 1
return result
<|code_end|>
|
Aqua GUI interface crashes for default OSX matplotlib backend.
@nonhermitian noted in #903:
### What is the current behavior?
Aqua GUI interface crashes for default OSX matplotlib backend.
|
qiskit/__init__.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=wrong-import-order
# pylint: disable=redefined-builtin
"""Main QISKit public functionality."""
import os
import pkgutil
# First, check for required Python and API version
from . import _util
from ._qiskiterror import QISKitError
from ._classicalregister import ClassicalRegister
from ._quantumregister import QuantumRegister
from ._quantumcircuit import QuantumCircuit
from ._gate import Gate
from ._compositegate import CompositeGate
from ._instruction import Instruction
from ._instructionset import InstructionSet
from ._reset import Reset
from ._measure import Measure
from .result import Result
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions.standard
import qiskit.extensions.quantum_initializer
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code.
__path__ = pkgutil.extend_path(__path__, __name__)
from .wrapper._wrapper import (
available_backends, local_backends, remote_backends,
get_backend, compile, execute, register, unregister,
registered_providers, load_qasm_string, load_qasm_file, least_busy,
store_credentials)
# Import circuit drawing methods by default
# This is wrapped in a try because the Travis tests fail due to non-framework
# Python build since using pyenv
try:
from qiskit.tools.visualization import (circuit_drawer, plot_histogram)
except (ImportError, RuntimeError) as expt:
print("Error: {0}".format(expt))
# Import the wrapper, to make it available when doing "import qiskit".
from . import wrapper
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(ROOT_DIR, "VERSION.txt"), "r") as version_file:
__version__ = version_file.read().strip()
<|code_end|>
|
qiskit/__init__.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=wrong-import-order
# pylint: disable=redefined-builtin
"""Main QISKit public functionality."""
import os
import pkgutil
# First, check for required Python and API version
from . import _util
from ._qiskiterror import QISKitError
from ._classicalregister import ClassicalRegister
from ._quantumregister import QuantumRegister
from ._quantumcircuit import QuantumCircuit
from ._gate import Gate
from ._compositegate import CompositeGate
from ._instruction import Instruction
from ._instructionset import InstructionSet
from ._reset import Reset
from ._measure import Measure
from .result import Result
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions.standard
import qiskit.extensions.quantum_initializer
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code.
__path__ = pkgutil.extend_path(__path__, __name__)
from .wrapper._wrapper import (
available_backends, local_backends, remote_backends,
get_backend, compile, execute, register, unregister,
registered_providers, load_qasm_string, load_qasm_file, least_busy,
store_credentials)
# Import the wrapper, to make it available when doing "import qiskit".
from . import wrapper
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(ROOT_DIR, "VERSION.txt"), "r") as version_file:
__version__ = version_file.read().strip()
<|code_end|>
|
Make plot_state automatically convert state vectors to density matrices
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
When calling the `plot_state` visualization function the input must be a density matrix, however the statevector simulator returns a state vector that must be manually converted to a density matrix. This should be done automatically when a user calls `plot_state(statevector)`:
Expected use:
```python
import qiskit
from qiskit.tools.visualization import plot_state
qr = qiskit.QuantumRegister(2)
circ = qiskit.QuantumCircuit(qr)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
result = qiskit.execute(circ, 'local_statevector_simulator).result()
state = result.get_statevector(circ)
fig = plot_state(state)
fig.show()
```
|
qiskit/tools/visualization/_state_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string
"""
Visualization functions for quantum states.
"""
from functools import reduce
from scipy import linalg
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
import numpy as np
from qiskit.tools.qi.pauli import pauli_group, pauli_singles
from qiskit.tools.visualization.bloch import Bloch
class Arrow3D(FancyArrowPatch):
"""Standard 3D arrow."""
def __init__(self, xs, ys, zs, *args, **kwargs):
"""Create arrow."""
FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
self._verts3d = xs, ys, zs
def draw(self, renderer):
"""Draw the arrow."""
xs3d, ys3d, zs3d = self._verts3d
xs, ys, _ = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
FancyArrowPatch.draw(self, renderer)
def plot_bloch_vector(bloch, title=""):
"""Plot the Bloch sphere.
Plot a sphere, axes, the Bloch vector, and its projections onto each axis.
Args:
bloch (list[double]): array of three elements where [<x>, <y>,<z>]
title (str): a string that represents the plot title
"""
B = Bloch()
B.add_vectors(bloch)
B.show(title=title)
def plot_state_city(rho, title=""):
"""Plot the cityscape of quantum state.
Plot two 3d bargraphs (two dimenstional) of the mixed state rho
Args:
rho (np.array[[complex]]): array of dimensions 2**n x 2**nn complex
numbers
title (str): a string that represents the plot title
"""
num = int(np.log2(len(rho)))
# get the real and imag parts of rho
datareal = np.real(rho)
dataimag = np.imag(rho)
# get the labels
column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
row_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
lx = len(datareal[0]) # Work out matrix dimensions
ly = len(datareal[:, 0])
xpos = np.arange(0, lx, 1) # Set up a mesh of positions
ypos = np.arange(0, ly, 1)
xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25)
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(lx*ly)
dx = 0.5 * np.ones_like(zpos) # width of bars
dy = dx.copy()
dzr = datareal.flatten()
dzi = dataimag.flatten()
fig = plt.figure(figsize=(8, 8))
ax1 = fig.add_subplot(2, 1, 1, projection='3d')
ax1.bar3d(xpos, ypos, zpos, dx, dy, dzr, color="g", alpha=0.5)
ax2 = fig.add_subplot(2, 1, 2, projection='3d')
ax2.bar3d(xpos, ypos, zpos, dx, dy, dzi, color="g", alpha=0.5)
ax1.set_xticks(np.arange(0.5, lx+0.5, 1))
ax1.set_yticks(np.arange(0.5, ly+0.5, 1))
ax1.axes.set_zlim3d(-1.0, 1.0001)
ax1.set_zticks(np.arange(-1, 1, 0.5))
ax1.w_xaxis.set_ticklabels(row_names, fontsize=12, rotation=45)
ax1.w_yaxis.set_ticklabels(column_names, fontsize=12, rotation=-22.5)
# ax1.set_xlabel('basis state', fontsize=12)
# ax1.set_ylabel('basis state', fontsize=12)
ax1.set_zlabel("Real[rho]")
ax2.set_xticks(np.arange(0.5, lx+0.5, 1))
ax2.set_yticks(np.arange(0.5, ly+0.5, 1))
ax2.axes.set_zlim3d(-1.0, 1.0001)
ax2.set_zticks(np.arange(-1, 1, 0.5))
ax2.w_xaxis.set_ticklabels(row_names, fontsize=12, rotation=45)
ax2.w_yaxis.set_ticklabels(column_names, fontsize=12, rotation=-22.5)
# ax2.set_xlabel('basis state', fontsize=12)
# ax2.set_ylabel('basis state', fontsize=12)
ax2.set_zlabel("Imag[rho]")
plt.title(title)
plt.show()
def plot_state_paulivec(rho, title=""):
"""Plot the paulivec representation of a quantum state.
Plot a bargraph of the mixed state rho over the pauli matricies
Args:
rho (np.array[[complex]]): array of dimensions 2**n x 2**nn complex
numbers
title (str): a string that represents the plot title
"""
num = int(np.log2(len(rho)))
labels = list(map(lambda x: x.to_label(), pauli_group(num)))
values = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_group(num)))
numelem = len(values)
ind = np.arange(numelem) # the x locations for the groups
width = 0.5 # the width of the bars
_, ax = plt.subplots()
ax.grid(zorder=0)
ax.bar(ind, values, width, color='seagreen')
# add some text for labels, title, and axes ticks
ax.set_ylabel('Expectation value', fontsize=12)
ax.set_xticks(ind)
ax.set_yticks([-1, -0.5, 0, 0.5, 1])
ax.set_xticklabels(labels, fontsize=12, rotation=70)
ax.set_xlabel('Pauli', fontsize=12)
ax.set_ylim([-1, 1])
plt.title(title)
plt.show()
def n_choose_k(n, k):
"""Return the number of combinations for n choose k.
Args:
n (int): the total number of options .
k (int): The number of elements.
Returns:
int: returns the binomial coefficient
"""
if n == 0:
return 0
return reduce(lambda x, y: x * y[0] / y[1],
zip(range(n - k + 1, n + 1),
range(1, k + 1)), 1)
def lex_index(n, k, lst):
"""Return the lex index of a combination..
Args:
n (int): the total number of options .
k (int): The number of elements.
lst (list): list
Returns:
int: returns int index for lex order
"""
assert len(lst) == k, "list should have length k"
comb = list(map(lambda x: n - 1 - x, lst))
dualm = sum([n_choose_k(comb[k - 1 - i], i + 1) for i in range(k)])
return int(dualm)
def bit_string_index(s):
"""Return the index of a string of 0s and 1s."""
n = len(s)
k = s.count("1")
assert s.count("0") == n - k, "s must be a string of 0 and 1"
ones = [pos for pos, char in enumerate(s) if char == "1"]
return lex_index(n, k, ones)
def phase_to_color_wheel(complex_number):
"""Map a phase of a complexnumber to a color in (r,g,b).
complex_number is phase is first mapped to angle in the range
[0, 2pi] and then to a color wheel with blue at zero phase.
"""
angles = np.angle(complex_number)
angle_round = int(((angles + 2 * np.pi) % (2 * np.pi))/np.pi*6)
color_map = {
0: (0, 0, 1), # blue,
1: (0.5, 0, 1), # blue-violet
2: (1, 0, 1), # violet
3: (1, 0, 0.5), # red-violet,
4: (1, 0, 0), # red
5: (1, 0.5, 0), # red-oranage,
6: (1, 1, 0), # orange
7: (0.5, 1, 0), # orange-yellow
8: (0, 1, 0), # yellow,
9: (0, 1, 0.5), # yellow-green,
10: (0, 1, 1), # green,
11: (0, 0.5, 1) # green-blue,
}
return color_map[angle_round]
def plot_state_qsphere(rho):
"""Plot the qsphere representation of a quantum state."""
num = int(np.log2(len(rho)))
# get the eigenvectors and egivenvalues
we, stateall = linalg.eigh(rho)
for k in range(2**num):
# start with the max
probmix = we.max()
prob_location = we.argmax()
if probmix > 0.001:
print("The " + str(k) + "th eigenvalue = " + str(probmix))
# get the max eigenvalue
state = stateall[:, prob_location]
loc = np.absolute(state).argmax()
# get the element location closes to lowest bin representation.
for j in range(2**num):
test = np.absolute(np.absolute(state[j]) -
np.absolute(state[loc]))
if test < 0.001:
loc = j
break
# remove the global phase
angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi)
angleset = np.exp(-1j*angles)
# print(state)
# print(angles)
state = angleset*state
# print(state)
state.flatten()
# start the plotting
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')
ax.axes.set_xlim3d(-1.0, 1.0)
ax.axes.set_ylim3d(-1.0, 1.0)
ax.axes.set_zlim3d(-1.0, 1.0)
ax.set_aspect("equal")
ax.axes.grid(False)
# Plot semi-transparent sphere
u = np.linspace(0, 2 * np.pi, 25)
v = np.linspace(0, np.pi, 25)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(x, y, z, rstride=1, cstride=1, color='k',
alpha=0.05, linewidth=0)
# wireframe
# Get rid of the panes
ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the spines
ax.w_xaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.w_yaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.w_zaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
d = num
for i in range(2**num):
# get x,y,z points
element = bin(i)[2:].zfill(num)
weight = element.count("1")
zvalue = -2 * weight / d + 1
number_of_divisions = n_choose_k(d, weight)
weight_order = bit_string_index(element)
# if weight_order >= number_of_divisions / 2:
# com_key = compliment(element)
# weight_order_temp = bit_string_index(com_key)
# weight_order = np.floor(
# number_of_divisions / 2) + weight_order_temp + 1
angle = weight_order * 2 * np.pi / number_of_divisions
xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle)
yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle)
ax.plot([xvalue], [yvalue], [zvalue],
markerfacecolor=(.5, .5, .5),
markeredgecolor=(.5, .5, .5),
marker='o', markersize=10, alpha=1)
# get prob and angle - prob will be shade and angle color
prob = np.real(np.dot(state[i], state[i].conj()))
colorstate = phase_to_color_wheel(state[i])
a = Arrow3D([0, xvalue], [0, yvalue], [0, zvalue],
mutation_scale=20, alpha=prob, arrowstyle="-",
color=colorstate, lw=10)
ax.add_artist(a)
# add weight lines
for weight in range(d + 1):
theta = np.linspace(-2 * np.pi, 2 * np.pi, 100)
z = -2 * weight / d + 1
r = np.sqrt(1 - z**2)
x = r * np.cos(theta)
y = r * np.sin(theta)
ax.plot(x, y, z, color=(.5, .5, .5))
# add center point
ax.plot([0], [0], [0], markerfacecolor=(.5, .5, .5),
markeredgecolor=(.5, .5, .5), marker='o', markersize=10,
alpha=1)
plt.show()
we[prob_location] = 0
else:
break
def plot_state(rho, method='city'):
"""Plot the quantum state.
Args:
rho (ndarray): Density matrix representation
of a quantum state vector or mized state.
method (str): Plotting method to use.
Note:
If input is a state vector, you must first
convert to density matrix via `qiskit.tools.qi.qi.outer`.
"""
num = int(np.log2(len(rho)))
# Need updating to check its a matrix
if method == 'city':
plot_state_city(rho)
elif method == "paulivec":
plot_state_paulivec(rho)
elif method == "qsphere":
plot_state_qsphere(rho)
elif method == "bloch":
for i in range(num):
bloch_state = list(
map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_singles(i, num)))
plot_bloch_vector(bloch_state, "qubit " + str(i))
elif method == "wigner":
plot_wigner_function(rho)
###############################################################
# Plotting Wigner functions
###############################################################
def plot_wigner_function(state, res=100):
"""Plot the equal angle slice spin Wigner function of an arbitrary
quantum state.
Args:
state (np.matrix[[complex]]):
- Matrix of 2**n x 2**n complex numbers
- State Vector of 2**n x 1 complex numbers
res (int) : number of theta and phi values in meshgrid
on sphere (creates a res x res grid of points)
References:
[1] T. Tilma, M. J. Everitt, J. H. Samson, W. J. Munro,
and K. Nemoto, Phys. Rev. Lett. 117, 180401 (2016).
[2] R. P. Rundle, P. W. Mills, T. Tilma, J. H. Samson, and
M. J. Everitt, Phys. Rev. A 96, 022117 (2017).
"""
state = np.array(state)
if state.ndim == 1:
state = np.outer(state,
state) # turns state vector to a density matrix
state = np.matrix(state)
num = int(np.log2(len(state))) # number of qubits
phi_vals = np.linspace(0, np.pi, num=res,
dtype=np.complex_)
theta_vals = np.linspace(0, 0.5*np.pi, num=res,
dtype=np.complex_) # phi and theta values for WF
w = np.empty([res, res])
harr = np.sqrt(3)
delta_su2 = np.zeros((2, 2), dtype=np.complex_)
# create the spin Wigner function
for theta in range(res):
costheta = harr*np.cos(2*theta_vals[theta])
sintheta = harr*np.sin(2*theta_vals[theta])
for phi in range(res):
delta_su2[0, 0] = 0.5*(1+costheta)
delta_su2[0, 1] = -0.5*(np.exp(2j*phi_vals[phi])*sintheta)
delta_su2[1, 0] = -0.5*(np.exp(-2j*phi_vals[phi])*sintheta)
delta_su2[1, 1] = 0.5*(1-costheta)
kernel = 1
for _ in range(num):
kernel = np.kron(kernel,
delta_su2) # creates phase point kernel
w[phi, theta] = np.real(np.trace(state*kernel)) # Wigner function
# Plot a sphere (x,y,z) with Wigner function facecolor data stored in Wc
fig = plt.figure(figsize=(11, 9))
ax = fig.gca(projection='3d')
w_max = np.amax(w)
# Color data for plotting
w_c = cm.seismic_r((w+w_max)/(2*w_max)) # color data for sphere
w_c2 = cm.seismic_r((w[0:res, int(res/2):res]+w_max)/(2*w_max)) # bottom
w_c3 = cm.seismic_r((w[int(res/4):int(3*res/4), 0:res]+w_max) /
(2*w_max)) # side
w_c4 = cm.seismic_r((w[int(res/2):res, 0:res]+w_max)/(2*w_max)) # back
u = np.linspace(0, 2 * np.pi, res)
v = np.linspace(0, np.pi, res)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones(np.size(u)), np.cos(v)) # creates a sphere mesh
ax.plot_surface(x, y, z, facecolors=w_c,
vmin=-w_max, vmax=w_max,
rcount=res, ccount=res,
linewidth=0, zorder=0.5,
antialiased=False) # plots Wigner Bloch sphere
ax.plot_surface(x[0:res, int(res/2):res],
y[0:res, int(res/2):res],
-1.5*np.ones((res, int(res/2))),
facecolors=w_c2,
vmin=-w_max, vmax=w_max,
rcount=res/2, ccount=res/2,
linewidth=0, zorder=0.5,
antialiased=False) # plots bottom reflection
ax.plot_surface(-1.5*np.ones((int(res/2), res)),
y[int(res/4):int(3*res/4), 0:res],
z[int(res/4):int(3*res/4), 0:res],
facecolors=w_c3,
vmin=-w_max, vmax=w_max,
rcount=res/2, ccount=res/2,
linewidth=0, zorder=0.5,
antialiased=False) # plots side reflection
ax.plot_surface(x[int(res/2):res, 0:res],
1.5*np.ones((int(res/2), res)),
z[int(res/2):res, 0:res],
facecolors=w_c4,
vmin=-w_max, vmax=w_max,
rcount=res/2, ccount=res/2,
linewidth=0, zorder=0.5,
antialiased=False) # plots back reflection
ax.w_xaxis.set_pane_color((0.4, 0.4, 0.4, 1.0))
ax.w_yaxis.set_pane_color((0.4, 0.4, 0.4, 1.0))
ax.w_zaxis.set_pane_color((0.4, 0.4, 0.4, 1.0))
ax.set_xticks([], [])
ax.set_yticks([], [])
ax.set_zticks([], [])
ax.grid(False)
ax.xaxis.pane.set_edgecolor('black')
ax.yaxis.pane.set_edgecolor('black')
ax.zaxis.pane.set_edgecolor('black')
ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_zlim(-1.5, 1.5)
m = cm.ScalarMappable(cmap=cm.seismic_r)
m.set_array([-w_max, w_max])
plt.colorbar(m, shrink=0.5, aspect=10)
plt.show()
def plot_wigner_curve(wigner_data, xaxis=None):
"""Plots a curve for points in phase space of the spin Wigner function.
Args:
wigner_data(np.array): an array of points to plot as a 2d curve
xaxis (np.array): the range of the x axis
"""
if not xaxis:
xaxis = np.linspace(0, len(wigner_data)-1, num=len(wigner_data))
plt.plot(xaxis, wigner_data)
plt.show()
def plot_wigner_plaquette(wigner_data, max_wigner='local'):
"""Plots plaquette of wigner function data, the plaquette will
consist of cicles each colored to match the value of the Wigner
function at the given point in phase space.
Args:
wigner_data (matrix): array of Wigner function data where the
rows are plotted along the x axis and the
columns are plotted along the y axis
max_wigner (str or float):
- 'local' puts the maximum value to maximum of the points
- 'unit' sets maximum to 1
- float for a custom maximum.
"""
wigner_data = np.matrix(wigner_data)
dim = wigner_data.shape
if max_wigner == 'local':
w_max = np.amax(wigner_data)
elif max_wigner == 'unit':
w_max = 1
else:
w_max = max_wigner # For a float input
w_max = float(w_max)
cmap = plt.cm.get_cmap('seismic_r')
xax = dim[1]-0.5
yax = dim[0]-0.5
norm = np.amax(dim)
fig = plt.figure(figsize=((xax+0.5)*6/norm, (yax+0.5)*6/norm))
ax = fig.gca()
for x in range(int(dim[1])):
for y in range(int(dim[0])):
circle = plt.Circle(
(x, y), 0.49, color=cmap((wigner_data[y, x]+w_max)/(2*w_max)))
ax.add_artist(circle)
ax.set_xlim(-1, xax+0.5)
ax.set_ylim(-1, yax+0.5)
ax.set_xticks([], [])
ax.set_yticks([], [])
m = cm.ScalarMappable(cmap=cm.seismic_r)
m.set_array([-w_max, w_max])
plt.colorbar(m, shrink=0.5, aspect=10)
plt.show()
def plot_wigner_data(wigner_data, phis=None, method=None):
"""Plots Wigner results in appropriate format.
Args:
wigner_data (numpy.array): Output returned from the wigner_data
function
phis (numpy.array): Values of phi
method (str or None): how the data is to be plotted, methods are:
point: a single point in phase space
curve: a two dimensional curve
plaquette: points plotted as circles
"""
if not method:
wig_dim = len(np.shape(wigner_data))
if wig_dim == 1:
if np.shape(wigner_data) == 1:
method = 'point'
else:
method = 'curve'
elif wig_dim == 2:
method = 'plaquette'
if method == 'curve':
plot_wigner_curve(wigner_data, xaxis=phis)
elif method == 'plaquette':
plot_wigner_plaquette(wigner_data)
elif method == 'state':
plot_wigner_function(wigner_data)
elif method == 'point':
plot_wigner_plaquette(wigner_data)
print('point in phase space is '+str(wigner_data))
else:
print("No method given")
<|code_end|>
qiskit/tools/visualization/interactive/_iplot_state.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
QISKit visualization library.
"""
from ._iplot_blochsphere import iplot_blochsphere
from ._iplot_cities import iplot_cities
from ._iplot_hinton import iplot_hinton
from ._iplot_paulivec import iplot_paulivec
from ._iplot_qsphere import iplot_qsphere
def iplot_state(rho, method='city', options=None):
"""Plot the quantum state.
Args:
rho (ndarray): Density matrix representation
of a quantum state vector or mized state.
method (str): Plotting method to use.
options (dict): Plotting settings.
Note:
If input is a state vector, you must first
convert to density matrix via `qiskit.tools.qi.qi.outer`.
"""
# Need updating to check its a matrix
if method == "city":
iplot_cities(rho, options)
elif method == "paulivec":
iplot_paulivec(rho, options)
elif method == "qsphere":
iplot_qsphere(rho, options)
elif method == "bloch":
iplot_blochsphere(rho, options)
elif method == "hinton":
iplot_hinton(rho, options)
else:
print("Unknown method '" + method + "'.")
<|code_end|>
|
qiskit/tools/visualization/_state_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string
"""
Visualization functions for quantum states.
"""
from functools import reduce
from scipy import linalg
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
import numpy as np
from qiskit.tools.qi.pauli import pauli_group, pauli_singles
from qiskit.tools.visualization import VisualizationError
from qiskit.tools.visualization.bloch import Bloch
class Arrow3D(FancyArrowPatch):
"""Standard 3D arrow."""
def __init__(self, xs, ys, zs, *args, **kwargs):
"""Create arrow."""
FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
self._verts3d = xs, ys, zs
def draw(self, renderer):
"""Draw the arrow."""
xs3d, ys3d, zs3d = self._verts3d
xs, ys, _ = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
FancyArrowPatch.draw(self, renderer)
def plot_bloch_vector(bloch, title=""):
"""Plot the Bloch sphere.
Plot a sphere, axes, the Bloch vector, and its projections onto each axis.
Args:
bloch (list[double]): array of three elements where [<x>, <y>,<z>]
title (str): a string that represents the plot title
"""
B = Bloch()
B.add_vectors(bloch)
B.show(title=title)
def plot_state_city(rho, title=""):
"""Plot the cityscape of quantum state.
Plot two 3d bargraphs (two dimenstional) of the mixed state rho
Args:
rho (np.array[[complex]]): array of dimensions 2**n x 2**nn complex
numbers
title (str): a string that represents the plot title
"""
num = int(np.log2(len(rho)))
# get the real and imag parts of rho
datareal = np.real(rho)
dataimag = np.imag(rho)
# get the labels
column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
row_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
lx = len(datareal[0]) # Work out matrix dimensions
ly = len(datareal[:, 0])
xpos = np.arange(0, lx, 1) # Set up a mesh of positions
ypos = np.arange(0, ly, 1)
xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25)
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(lx*ly)
dx = 0.5 * np.ones_like(zpos) # width of bars
dy = dx.copy()
dzr = datareal.flatten()
dzi = dataimag.flatten()
fig = plt.figure(figsize=(8, 8))
ax1 = fig.add_subplot(2, 1, 1, projection='3d')
ax1.bar3d(xpos, ypos, zpos, dx, dy, dzr, color="g", alpha=0.5)
ax2 = fig.add_subplot(2, 1, 2, projection='3d')
ax2.bar3d(xpos, ypos, zpos, dx, dy, dzi, color="g", alpha=0.5)
ax1.set_xticks(np.arange(0.5, lx+0.5, 1))
ax1.set_yticks(np.arange(0.5, ly+0.5, 1))
ax1.axes.set_zlim3d(-1.0, 1.0001)
ax1.set_zticks(np.arange(-1, 1, 0.5))
ax1.w_xaxis.set_ticklabels(row_names, fontsize=12, rotation=45)
ax1.w_yaxis.set_ticklabels(column_names, fontsize=12, rotation=-22.5)
# ax1.set_xlabel('basis state', fontsize=12)
# ax1.set_ylabel('basis state', fontsize=12)
ax1.set_zlabel("Real[rho]")
ax2.set_xticks(np.arange(0.5, lx+0.5, 1))
ax2.set_yticks(np.arange(0.5, ly+0.5, 1))
ax2.axes.set_zlim3d(-1.0, 1.0001)
ax2.set_zticks(np.arange(-1, 1, 0.5))
ax2.w_xaxis.set_ticklabels(row_names, fontsize=12, rotation=45)
ax2.w_yaxis.set_ticklabels(column_names, fontsize=12, rotation=-22.5)
# ax2.set_xlabel('basis state', fontsize=12)
# ax2.set_ylabel('basis state', fontsize=12)
ax2.set_zlabel("Imag[rho]")
plt.title(title)
plt.show()
def plot_state_paulivec(rho, title=""):
"""Plot the paulivec representation of a quantum state.
Plot a bargraph of the mixed state rho over the pauli matricies
Args:
rho (np.array[[complex]]): array of dimensions 2**n x 2**nn complex
numbers
title (str): a string that represents the plot title
"""
num = int(np.log2(len(rho)))
labels = list(map(lambda x: x.to_label(), pauli_group(num)))
values = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_group(num)))
numelem = len(values)
ind = np.arange(numelem) # the x locations for the groups
width = 0.5 # the width of the bars
_, ax = plt.subplots()
ax.grid(zorder=0)
ax.bar(ind, values, width, color='seagreen')
# add some text for labels, title, and axes ticks
ax.set_ylabel('Expectation value', fontsize=12)
ax.set_xticks(ind)
ax.set_yticks([-1, -0.5, 0, 0.5, 1])
ax.set_xticklabels(labels, fontsize=12, rotation=70)
ax.set_xlabel('Pauli', fontsize=12)
ax.set_ylim([-1, 1])
plt.title(title)
plt.show()
def n_choose_k(n, k):
"""Return the number of combinations for n choose k.
Args:
n (int): the total number of options .
k (int): The number of elements.
Returns:
int: returns the binomial coefficient
"""
if n == 0:
return 0
return reduce(lambda x, y: x * y[0] / y[1],
zip(range(n - k + 1, n + 1),
range(1, k + 1)), 1)
def lex_index(n, k, lst):
"""Return the lex index of a combination..
Args:
n (int): the total number of options .
k (int): The number of elements.
lst (list): list
Returns:
int: returns int index for lex order
"""
assert len(lst) == k, "list should have length k"
comb = list(map(lambda x: n - 1 - x, lst))
dualm = sum([n_choose_k(comb[k - 1 - i], i + 1) for i in range(k)])
return int(dualm)
def bit_string_index(s):
"""Return the index of a string of 0s and 1s."""
n = len(s)
k = s.count("1")
assert s.count("0") == n - k, "s must be a string of 0 and 1"
ones = [pos for pos, char in enumerate(s) if char == "1"]
return lex_index(n, k, ones)
def phase_to_color_wheel(complex_number):
"""Map a phase of a complexnumber to a color in (r,g,b).
complex_number is phase is first mapped to angle in the range
[0, 2pi] and then to a color wheel with blue at zero phase.
"""
angles = np.angle(complex_number)
angle_round = int(((angles + 2 * np.pi) % (2 * np.pi))/np.pi*6)
color_map = {
0: (0, 0, 1), # blue,
1: (0.5, 0, 1), # blue-violet
2: (1, 0, 1), # violet
3: (1, 0, 0.5), # red-violet,
4: (1, 0, 0), # red
5: (1, 0.5, 0), # red-oranage,
6: (1, 1, 0), # orange
7: (0.5, 1, 0), # orange-yellow
8: (0, 1, 0), # yellow,
9: (0, 1, 0.5), # yellow-green,
10: (0, 1, 1), # green,
11: (0, 0.5, 1) # green-blue,
}
return color_map[angle_round]
def plot_state_qsphere(rho):
"""Plot the qsphere representation of a quantum state."""
num = int(np.log2(len(rho)))
# get the eigenvectors and egivenvalues
we, stateall = linalg.eigh(rho)
for k in range(2**num):
# start with the max
probmix = we.max()
prob_location = we.argmax()
if probmix > 0.001:
print("The " + str(k) + "th eigenvalue = " + str(probmix))
# get the max eigenvalue
state = stateall[:, prob_location]
loc = np.absolute(state).argmax()
# get the element location closes to lowest bin representation.
for j in range(2**num):
test = np.absolute(np.absolute(state[j]) -
np.absolute(state[loc]))
if test < 0.001:
loc = j
break
# remove the global phase
angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi)
angleset = np.exp(-1j*angles)
# print(state)
# print(angles)
state = angleset*state
# print(state)
state.flatten()
# start the plotting
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')
ax.axes.set_xlim3d(-1.0, 1.0)
ax.axes.set_ylim3d(-1.0, 1.0)
ax.axes.set_zlim3d(-1.0, 1.0)
ax.set_aspect("equal")
ax.axes.grid(False)
# Plot semi-transparent sphere
u = np.linspace(0, 2 * np.pi, 25)
v = np.linspace(0, np.pi, 25)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(x, y, z, rstride=1, cstride=1, color='k',
alpha=0.05, linewidth=0)
# wireframe
# Get rid of the panes
ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the spines
ax.w_xaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.w_yaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.w_zaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
d = num
for i in range(2**num):
# get x,y,z points
element = bin(i)[2:].zfill(num)
weight = element.count("1")
zvalue = -2 * weight / d + 1
number_of_divisions = n_choose_k(d, weight)
weight_order = bit_string_index(element)
# if weight_order >= number_of_divisions / 2:
# com_key = compliment(element)
# weight_order_temp = bit_string_index(com_key)
# weight_order = np.floor(
# number_of_divisions / 2) + weight_order_temp + 1
angle = weight_order * 2 * np.pi / number_of_divisions
xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle)
yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle)
ax.plot([xvalue], [yvalue], [zvalue],
markerfacecolor=(.5, .5, .5),
markeredgecolor=(.5, .5, .5),
marker='o', markersize=10, alpha=1)
# get prob and angle - prob will be shade and angle color
prob = np.real(np.dot(state[i], state[i].conj()))
colorstate = phase_to_color_wheel(state[i])
a = Arrow3D([0, xvalue], [0, yvalue], [0, zvalue],
mutation_scale=20, alpha=prob, arrowstyle="-",
color=colorstate, lw=10)
ax.add_artist(a)
# add weight lines
for weight in range(d + 1):
theta = np.linspace(-2 * np.pi, 2 * np.pi, 100)
z = -2 * weight / d + 1
r = np.sqrt(1 - z**2)
x = r * np.cos(theta)
y = r * np.sin(theta)
ax.plot(x, y, z, color=(.5, .5, .5))
# add center point
ax.plot([0], [0], [0], markerfacecolor=(.5, .5, .5),
markeredgecolor=(.5, .5, .5), marker='o', markersize=10,
alpha=1)
plt.show()
we[prob_location] = 0
else:
break
def plot_state(quantum_state, method='city'):
"""Plot the quantum state.
Args:
quantum_state (ndarray): statevector or density matrix
representation of a quantum state.
method (str): Plotting method to use.
Raises:
VisualizationError: if the input is not a statevector or density
matrix, or if the state is not an multi-qubit quantum state.
"""
# Check if input is a statevector, and convert to density matrix
rho = np.array(quantum_state)
if rho.ndim == 1:
rho = np.outer(rho, np.conj(rho))
# Check the shape of the input is a square matrix
shape = np.shape(rho)
if len(shape) != 2 or shape[0] != shape[1]:
raise VisualizationError("Input is not a valid quantum state.")
# Check state is an n-qubit state
num = int(np.log2(len(rho)))
if 2 ** num != len(rho):
raise VisualizationError("Input is not a multi-qubit quantum state.")
if method == 'city':
plot_state_city(rho)
elif method == "paulivec":
plot_state_paulivec(rho)
elif method == "qsphere":
plot_state_qsphere(rho)
elif method == "bloch":
for i in range(num):
bloch_state = list(
map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_singles(i, num)))
plot_bloch_vector(bloch_state, "qubit " + str(i))
elif method == "wigner":
plot_wigner_function(rho)
###############################################################
# Plotting Wigner functions
###############################################################
def plot_wigner_function(state, res=100):
"""Plot the equal angle slice spin Wigner function of an arbitrary
quantum state.
Args:
state (np.matrix[[complex]]):
- Matrix of 2**n x 2**n complex numbers
- State Vector of 2**n x 1 complex numbers
res (int) : number of theta and phi values in meshgrid
on sphere (creates a res x res grid of points)
References:
[1] T. Tilma, M. J. Everitt, J. H. Samson, W. J. Munro,
and K. Nemoto, Phys. Rev. Lett. 117, 180401 (2016).
[2] R. P. Rundle, P. W. Mills, T. Tilma, J. H. Samson, and
M. J. Everitt, Phys. Rev. A 96, 022117 (2017).
"""
state = np.array(state)
if state.ndim == 1:
state = np.outer(state,
state) # turns state vector to a density matrix
state = np.matrix(state)
num = int(np.log2(len(state))) # number of qubits
phi_vals = np.linspace(0, np.pi, num=res,
dtype=np.complex_)
theta_vals = np.linspace(0, 0.5*np.pi, num=res,
dtype=np.complex_) # phi and theta values for WF
w = np.empty([res, res])
harr = np.sqrt(3)
delta_su2 = np.zeros((2, 2), dtype=np.complex_)
# create the spin Wigner function
for theta in range(res):
costheta = harr*np.cos(2*theta_vals[theta])
sintheta = harr*np.sin(2*theta_vals[theta])
for phi in range(res):
delta_su2[0, 0] = 0.5*(1+costheta)
delta_su2[0, 1] = -0.5*(np.exp(2j*phi_vals[phi])*sintheta)
delta_su2[1, 0] = -0.5*(np.exp(-2j*phi_vals[phi])*sintheta)
delta_su2[1, 1] = 0.5*(1-costheta)
kernel = 1
for _ in range(num):
kernel = np.kron(kernel,
delta_su2) # creates phase point kernel
w[phi, theta] = np.real(np.trace(state*kernel)) # Wigner function
# Plot a sphere (x,y,z) with Wigner function facecolor data stored in Wc
fig = plt.figure(figsize=(11, 9))
ax = fig.gca(projection='3d')
w_max = np.amax(w)
# Color data for plotting
w_c = cm.seismic_r((w+w_max)/(2*w_max)) # color data for sphere
w_c2 = cm.seismic_r((w[0:res, int(res/2):res]+w_max)/(2*w_max)) # bottom
w_c3 = cm.seismic_r((w[int(res/4):int(3*res/4), 0:res]+w_max) /
(2*w_max)) # side
w_c4 = cm.seismic_r((w[int(res/2):res, 0:res]+w_max)/(2*w_max)) # back
u = np.linspace(0, 2 * np.pi, res)
v = np.linspace(0, np.pi, res)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones(np.size(u)), np.cos(v)) # creates a sphere mesh
ax.plot_surface(x, y, z, facecolors=w_c,
vmin=-w_max, vmax=w_max,
rcount=res, ccount=res,
linewidth=0, zorder=0.5,
antialiased=False) # plots Wigner Bloch sphere
ax.plot_surface(x[0:res, int(res/2):res],
y[0:res, int(res/2):res],
-1.5*np.ones((res, int(res/2))),
facecolors=w_c2,
vmin=-w_max, vmax=w_max,
rcount=res/2, ccount=res/2,
linewidth=0, zorder=0.5,
antialiased=False) # plots bottom reflection
ax.plot_surface(-1.5*np.ones((int(res/2), res)),
y[int(res/4):int(3*res/4), 0:res],
z[int(res/4):int(3*res/4), 0:res],
facecolors=w_c3,
vmin=-w_max, vmax=w_max,
rcount=res/2, ccount=res/2,
linewidth=0, zorder=0.5,
antialiased=False) # plots side reflection
ax.plot_surface(x[int(res/2):res, 0:res],
1.5*np.ones((int(res/2), res)),
z[int(res/2):res, 0:res],
facecolors=w_c4,
vmin=-w_max, vmax=w_max,
rcount=res/2, ccount=res/2,
linewidth=0, zorder=0.5,
antialiased=False) # plots back reflection
ax.w_xaxis.set_pane_color((0.4, 0.4, 0.4, 1.0))
ax.w_yaxis.set_pane_color((0.4, 0.4, 0.4, 1.0))
ax.w_zaxis.set_pane_color((0.4, 0.4, 0.4, 1.0))
ax.set_xticks([], [])
ax.set_yticks([], [])
ax.set_zticks([], [])
ax.grid(False)
ax.xaxis.pane.set_edgecolor('black')
ax.yaxis.pane.set_edgecolor('black')
ax.zaxis.pane.set_edgecolor('black')
ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_zlim(-1.5, 1.5)
m = cm.ScalarMappable(cmap=cm.seismic_r)
m.set_array([-w_max, w_max])
plt.colorbar(m, shrink=0.5, aspect=10)
plt.show()
def plot_wigner_curve(wigner_data, xaxis=None):
"""Plots a curve for points in phase space of the spin Wigner function.
Args:
wigner_data(np.array): an array of points to plot as a 2d curve
xaxis (np.array): the range of the x axis
"""
if not xaxis:
xaxis = np.linspace(0, len(wigner_data)-1, num=len(wigner_data))
plt.plot(xaxis, wigner_data)
plt.show()
def plot_wigner_plaquette(wigner_data, max_wigner='local'):
"""Plots plaquette of wigner function data, the plaquette will
consist of cicles each colored to match the value of the Wigner
function at the given point in phase space.
Args:
wigner_data (matrix): array of Wigner function data where the
rows are plotted along the x axis and the
columns are plotted along the y axis
max_wigner (str or float):
- 'local' puts the maximum value to maximum of the points
- 'unit' sets maximum to 1
- float for a custom maximum.
"""
wigner_data = np.matrix(wigner_data)
dim = wigner_data.shape
if max_wigner == 'local':
w_max = np.amax(wigner_data)
elif max_wigner == 'unit':
w_max = 1
else:
w_max = max_wigner # For a float input
w_max = float(w_max)
cmap = plt.cm.get_cmap('seismic_r')
xax = dim[1]-0.5
yax = dim[0]-0.5
norm = np.amax(dim)
fig = plt.figure(figsize=((xax+0.5)*6/norm, (yax+0.5)*6/norm))
ax = fig.gca()
for x in range(int(dim[1])):
for y in range(int(dim[0])):
circle = plt.Circle(
(x, y), 0.49, color=cmap((wigner_data[y, x]+w_max)/(2*w_max)))
ax.add_artist(circle)
ax.set_xlim(-1, xax+0.5)
ax.set_ylim(-1, yax+0.5)
ax.set_xticks([], [])
ax.set_yticks([], [])
m = cm.ScalarMappable(cmap=cm.seismic_r)
m.set_array([-w_max, w_max])
plt.colorbar(m, shrink=0.5, aspect=10)
plt.show()
def plot_wigner_data(wigner_data, phis=None, method=None):
"""Plots Wigner results in appropriate format.
Args:
wigner_data (numpy.array): Output returned from the wigner_data
function
phis (numpy.array): Values of phi
method (str or None): how the data is to be plotted, methods are:
point: a single point in phase space
curve: a two dimensional curve
plaquette: points plotted as circles
"""
if not method:
wig_dim = len(np.shape(wigner_data))
if wig_dim == 1:
if np.shape(wigner_data) == 1:
method = 'point'
else:
method = 'curve'
elif wig_dim == 2:
method = 'plaquette'
if method == 'curve':
plot_wigner_curve(wigner_data, xaxis=phis)
elif method == 'plaquette':
plot_wigner_plaquette(wigner_data)
elif method == 'state':
plot_wigner_function(wigner_data)
elif method == 'point':
plot_wigner_plaquette(wigner_data)
print('point in phase space is '+str(wigner_data))
else:
print("No method given")
<|code_end|>
qiskit/tools/visualization/interactive/_iplot_state.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
QISKit visualization library.
"""
import numpy as np
from qiskit.tools.visualization import VisualizationError
from ._iplot_blochsphere import iplot_blochsphere
from ._iplot_cities import iplot_cities
from ._iplot_hinton import iplot_hinton
from ._iplot_paulivec import iplot_paulivec
from ._iplot_qsphere import iplot_qsphere
def iplot_state(quantum_state, method='city', options=None):
"""Plot the quantum state.
Args:
quantum_state (ndarray): statevector or density matrix
representation of a quantum state.
method (str): Plotting method to use.
options (dict): Plotting settings.
Raises:
VisualizationError: if the input is not a statevector or density
matrix, or if the state is not an multi-qubit quantum state.
"""
# Check if input is a statevector, and convert to density matrix
rho = np.array(quantum_state)
if rho.ndim == 1:
rho = np.outer(rho, np.conj(rho))
# Check the shape of the input is a square matrix
shape = np.shape(rho)
if len(shape) != 2 or shape[0] != shape[1]:
raise VisualizationError("Input is not a valid quantum state.")
# Check state is an n-qubit state
num = int(np.log2(len(rho)))
if 2 ** num != len(rho):
raise VisualizationError("Input is not a multi-qubit quantum state.")
if method == "city":
iplot_cities(rho, options)
elif method == "paulivec":
iplot_paulivec(rho, options)
elif method == "qsphere":
iplot_qsphere(rho, options)
elif method == "bloch":
iplot_blochsphere(rho, options)
elif method == "hinton":
iplot_hinton(rho, options)
else:
print("Unknown method '" + method + "'.")
<|code_end|>
|
Reverse bit order in latex_circuit_drawer with conditional
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### What is the current behavior?
I found a bug in `latex_circuit_drawer` when conditional gate is drawn with `reversebits` option.
Index of registers is not correctly handled in `latex_circuit_drawer` when bit order is reversed.
### Steps to reproduce the problem
```
q1 = QuantumRegister(3, 'q1')
c1 = ClassicalRegister(3, 'c1')
qc = QuantumCircuit(q1, c1)
qc.x(q1[0]).c_if(c1, 2)
circuit_drawer(qc, style={"reversebits": True})
```
The results:
```
...
~/testbench/qiskit/tools/visualization/_circuit_visualization.py in _get_image_depth(self, aliases)
611 for i in range(pos_1, pos_2 + self.cregs[if_reg]):
612 if is_occupied[i] is False:
--> 613 is_occupied[i] = True
614 else:
615 columns += 1
IndexError: list index out of range
```
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
1. LaTeX
2. Matplotlib
"""
import json
import logging
import operator
import os
import re
import subprocess
import tempfile
from collections import namedtuple, OrderedDict
from fractions import Fraction
from io import StringIO
from itertools import groupby, zip_longest
from math import fmod, isclose, ceil
import numpy as np
from PIL import Image, ImageChops
from matplotlib import get_backend as get_matplotlib_backend, \
patches as patches, pyplot as plt
from qiskit._qiskiterror import QISKitError
from qiskit._quantumcircuit import QuantumCircuit
from qiskit.wrapper import load_qasm_file
from qiskit.dagcircuit import DAGCircuit
from qiskit.transpiler import transpile
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit, via 2 methods (try 1st, if unsuccessful, 2nd):
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
try:
return latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError):
return matplotlib_circuit_drawer(circuit, basis, scale, filename, style)
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
class QCStyle:
def __init__(self):
self.tc = '#000000'
self.sc = '#000000'
self.lc = '#000000'
self.cc = '#778899'
self.gc = '#ffffff'
self.gt = '#000000'
self.bc = '#bdbdbd'
self.bg = '#ffffff'
self.fs = 13
self.sfs = 8
self.disptex = {
'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'
}
self.dispcol = {
'id': '#ffffff',
'u0': '#ffffff',
'u1': '#ffffff',
'u2': '#ffffff',
'u3': '#ffffff',
'x': '#ffffff',
'y': '#ffffff',
'z': '#ffffff',
'h': '#ffffff',
's': '#ffffff',
'sdg': '#ffffff',
't': '#ffffff',
'tdg': '#ffffff',
'rx': '#ffffff',
'ry': '#ffffff',
'rz': '#ffffff',
'reset': '#ffffff',
'target': '#ffffff',
'meas': '#ffffff'
}
self.latexmode = True
self.pimode = False
self.fold = 20
self.bundle = False
self.barrier = False
self.index = False
self.compress = True
self.figwidth = -1
self.dpi = 150
self.margin = [2.0, 0.0, 0.0, 0.3]
self.cline = 'doublet'
self.reverse = False
def set_style(self, dic):
self.tc = dic.get('textcolor', self.tc)
self.sc = dic.get('subtextcolor', self.sc)
self.lc = dic.get('linecolor', self.lc)
self.cc = dic.get('creglinecolor', self.cc)
self.gt = dic.get('gatetextcolor', self.tc)
self.gc = dic.get('gatefacecolor', self.gc)
self.bc = dic.get('barrierfacecolor', self.bc)
self.bg = dic.get('backgroundcolor', self.bg)
self.fs = dic.get('fontsize', self.fs)
self.sfs = dic.get('subfontsize', self.sfs)
self.disptex = dic.get('displaytext', self.disptex)
for key in self.dispcol.keys():
self.dispcol[key] = self.gc
self.dispcol = dic.get('displaycolor', self.dispcol)
self.latexmode = dic.get('latexdrawerstyle', self.latexmode)
self.pimode = dic.get('usepiformat', self.pimode)
self.fold = dic.get('fold', self.fold)
if self.fold < 2:
self.fold = -1
self.bundle = dic.get('cregbundle', self.bundle)
self.barrier = dic.get('plotbarrier', self.barrier)
self.index = dic.get('showindex', self.index)
self.compress = dic.get('compress', self.compress)
self.figwidth = dic.get('figwidth', self.figwidth)
self.dpi = dic.get('dpi', self.dpi)
self.margin = dic.get('margin', self.margin)
self.cline = dic.get('creglinestyle', self.cline)
self.reverse = dic.get('reversebits', self.reverse)
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": False,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to complile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def _trim(im):
"""Trim image and remove white space
"""
bg = Image.new(im.mode, im.size, im.getpixel((0, 0)))
diff = ImageChops.difference(im, bg)
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
im = im.crop(bbox)
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
qcimg = QCircuitImage(json_circuit, scale, style=style)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, circuit, scale, style=None):
"""
Args:
circuit (dict): compiled_circuit from qobj
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
"""
# style sheet
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.circuit = circuit
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
#################################
self.header = self.circuit['header']
self.qregs = OrderedDict(_get_register_specs(
self.header['qubit_labels']))
self.qubit_list = []
for qr in self.qregs:
for i in range(self.qregs[qr]):
self.qubit_list.append((qr, i))
self.cregs = OrderedDict()
if 'clbit_labels' in self.header:
for item in self.header['clbit_labels']:
self.cregs[item[0]] = item[1]
self.clbit_list = []
for cr in self.cregs:
for i in range(self.cregs[cr]):
self.clbit_list.append((cr, i))
self.ordered_regs = [(item[0], item[1]) for
item in self.header['qubit_labels']]
if self._style.reverse:
reg_size = []
reg_labels = []
new_ordered_regs = []
for regs in self.ordered_regs:
if regs[0] in reg_labels:
continue
reg_labels.append(regs[0])
reg_size.append(len(
[x for x in self.ordered_regs if x[0] == regs[0]]))
index = 0
for size in reg_size:
new_index = index + size
for i in range(new_index - 1, index - 1, -1):
new_ordered_regs.append(self.ordered_regs[i])
index = new_index
self.ordered_regs = new_ordered_regs
if 'clbit_labels' in self.header:
for clabel in self.header['clbit_labels']:
if self._style.reverse:
for cind in reversed(range(clabel[1])):
self.ordered_regs.append((clabel[0], cind))
else:
for cind in range(clabel[1]):
self.ordered_regs.append((clabel[0], cind))
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\'+'\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
QISKitError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.circuit['instructions']:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's', 'sdg',
't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy', 'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['texparams']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, arg)
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
assert len(op['clbits']) == 1 and len(op['qubits']) == 1
if 'conditional' in op:
raise QISKitError('conditional measures currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise QISKitError('conditional reset currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
assert False, "bad node data"
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns+1, ceil(sum_column_widths)+4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above example,
index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.circuit['instructions']):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier']:
nm = op['name']
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] =\
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
elif nm == "reset":
self._latex[pos_1][columns] = \
"\\push{\\rule{.6em}{0em}\\ket{0}\\rule{.2em}{0em}} \\qw"
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
assert len(op['clbits']) == 1 and \
len(op['qubits']) == 1 and \
'params' not in op, "bad operation record"
if 'conditional' in op:
assert False, "If controlled measures currently not supported."
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_entry = self._latex[pos_1][columns - 1]
if 'barrier' in prev_entry:
self._latex[pos_1][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise QISKitError('Error during Latex building: %s' %
str(e))
elif op['name'] == "barrier":
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qubits']) - 1
self._latex[start][columns] += " \\barrier{" + str(span) + "}"
else:
assert False, "bad node data"
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
return (mask & (-mask)).bit_length() - 1
def _get_register_specs(bit_labels):
"""
Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = MatplotlibDrawer(basis=basis, scale=scale, style=style)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
Register = namedtuple('Register', 'name index')
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=1.0, style=None):
self._ast = None
self._basis = basis
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = OrderedDict()
self._creg_dict = OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom='off', labeltop='off', labelleft='off', labelright='off')
def load_qasm_file(self, filename):
circuit = load_qasm_file(filename, name='draw', basis_gates=self._basis)
self.parse_circuit(circuit)
def parse_circuit(self, circuit: QuantumCircuit):
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
self._ast = transpile(dag_circuit, basis_gates=self._basis, format='json')
self._registers()
self._ops = self._ast['instructions']
def _registers(self):
# NOTE: formats of clbit and qubit are different!
header = self._ast['header']
self._creg = []
for e in header['clbit_labels']:
for i in range(e[1]):
self._creg.append(Register(name=e[0], index=i))
assert len(self._creg) == header['number_of_clbits']
self._qreg = []
for e in header['qubit_labels']:
self._qreg.append(Register(name=e[0], index=e[1]))
assert len(self._qreg) == header['number_of_qubits']
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.sc,
clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7, height=HIG * 0.7,
theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID], [qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy+0.35*WID], lc=self._style.cc, ls=self._style.cline)
arrowhead = patches.Polygon(((cx-0.20*WID, cy+0.35*WID),
(cx+0.20*WID, cy+0.35*WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'], ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if get_matplotlib_backend() == 'module://ipykernel.pylab.backend_inline':
# returns None when matplotlib is inline mode to prevent Jupyter
# with matplotlib inlining enabled to draw the diagram twice.
im = None
else:
# when matplotlib is not inline mode,
# self.figure.savefig is called twice because...
# ... this is needed to get the in-memory representation
with tempfile.TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, 'circuit.png')
self.figure.savefig(tmpfile, dpi=self._style.dpi,
bbox_inches='tight')
im = Image.open(tmpfile)
_trim(im)
os.remove(tmpfile)
# ... and this is needed to delegate in matplotlib the generation of
# the proper format.
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
return im
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index, 'group': reg.name}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(zip_longest(self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
self._cond['n_lines'] += 1
idx += 1
# reverse bit order
if self._style.reverse:
self._reverse_bits(self._qreg_dict)
self._reverse_bits(self._creg_dict)
def _reverse_bits(self, target_dict):
coord = {}
# grouping
for dict_ in target_dict.values():
if dict_['group'] not in coord:
coord[dict_['group']] = [dict_['y']]
else:
coord[dict_['group']].insert(0, dict_['y'])
# reverse bit order
for key in target_dict.keys():
target_dict[key]['y'] = coord[target_dict[key]['group']].pop(0)
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc, ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qubits' in op.keys():
q_idxs = op['qubits']
else:
q_idxs = []
# get creg index
if 'clbits' in op.keys():
c_idxs = op['clbits']
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied), max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] == 'barrier' and not self._style.barrier:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg corrdinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc, ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] == 'barrier':
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self._style.barrier:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise QISKitError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if isclose(fmod(abs_val, 1.0), 0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
elif 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return Fraction(i, j)
return None
<|code_end|>
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
1. LaTeX
2. Matplotlib
"""
import json
import logging
import operator
import os
import re
import subprocess
import tempfile
from collections import namedtuple, OrderedDict
from fractions import Fraction
from io import StringIO
from itertools import groupby, zip_longest
from math import fmod, isclose, ceil
import numpy as np
from PIL import Image, ImageChops
from matplotlib import get_backend as get_matplotlib_backend, \
patches as patches, pyplot as plt
from qiskit._qiskiterror import QISKitError
from qiskit._quantumcircuit import QuantumCircuit
from qiskit.wrapper import load_qasm_file
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization._error import VisualizationError
from qiskit.transpiler import transpile
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit, via 2 methods (try 1st, if unsuccessful, 2nd):
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
try:
return latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError):
return matplotlib_circuit_drawer(circuit, basis, scale, filename, style)
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
class QCStyle:
def __init__(self):
self.tc = '#000000'
self.sc = '#000000'
self.lc = '#000000'
self.cc = '#778899'
self.gc = '#ffffff'
self.gt = '#000000'
self.bc = '#bdbdbd'
self.bg = '#ffffff'
self.fs = 13
self.sfs = 8
self.disptex = {
'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'
}
self.dispcol = {
'id': '#ffffff',
'u0': '#ffffff',
'u1': '#ffffff',
'u2': '#ffffff',
'u3': '#ffffff',
'x': '#ffffff',
'y': '#ffffff',
'z': '#ffffff',
'h': '#ffffff',
's': '#ffffff',
'sdg': '#ffffff',
't': '#ffffff',
'tdg': '#ffffff',
'rx': '#ffffff',
'ry': '#ffffff',
'rz': '#ffffff',
'reset': '#ffffff',
'target': '#ffffff',
'meas': '#ffffff'
}
self.latexmode = True
self.pimode = False
self.fold = 20
self.bundle = False
self.barrier = False
self.index = False
self.compress = True
self.figwidth = -1
self.dpi = 150
self.margin = [2.0, 0.0, 0.0, 0.3]
self.cline = 'doublet'
self.reverse = False
def set_style(self, dic):
self.tc = dic.get('textcolor', self.tc)
self.sc = dic.get('subtextcolor', self.sc)
self.lc = dic.get('linecolor', self.lc)
self.cc = dic.get('creglinecolor', self.cc)
self.gt = dic.get('gatetextcolor', self.tc)
self.gc = dic.get('gatefacecolor', self.gc)
self.bc = dic.get('barrierfacecolor', self.bc)
self.bg = dic.get('backgroundcolor', self.bg)
self.fs = dic.get('fontsize', self.fs)
self.sfs = dic.get('subfontsize', self.sfs)
self.disptex = dic.get('displaytext', self.disptex)
for key in self.dispcol.keys():
self.dispcol[key] = self.gc
self.dispcol = dic.get('displaycolor', self.dispcol)
self.latexmode = dic.get('latexdrawerstyle', self.latexmode)
self.pimode = dic.get('usepiformat', self.pimode)
self.fold = dic.get('fold', self.fold)
if self.fold < 2:
self.fold = -1
self.bundle = dic.get('cregbundle', self.bundle)
self.barrier = dic.get('plotbarrier', self.barrier)
self.index = dic.get('showindex', self.index)
self.compress = dic.get('compress', self.compress)
self.figwidth = dic.get('figwidth', self.figwidth)
self.dpi = dic.get('dpi', self.dpi)
self.margin = dic.get('margin', self.margin)
self.cline = dic.get('creglinestyle', self.cline)
self.reverse = dic.get('reversebits', self.reverse)
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": False,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to complile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def _trim(im):
"""Trim image and remove white space
"""
bg = Image.new(im.mode, im.size, im.getpixel((0, 0)))
diff = ImageChops.difference(im, bg)
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
im = im.crop(bbox)
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
qcimg = QCircuitImage(json_circuit, scale, style=style)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, circuit, scale, style=None):
"""
Args:
circuit (dict): compiled_circuit from qobj
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
"""
# style sheet
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.circuit = circuit
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
#################################
self.header = self.circuit['header']
self.qregs = OrderedDict(_get_register_specs(
self.header['qubit_labels']))
self.qubit_list = []
for qr in self.qregs:
for i in range(self.qregs[qr]):
self.qubit_list.append((qr, i))
self.cregs = OrderedDict()
if 'clbit_labels' in self.header:
for item in self.header['clbit_labels']:
self.cregs[item[0]] = item[1]
self.clbit_list = []
cregs = self.cregs
if self._style.reverse:
self.orig_cregs = self.cregs
cregs = reversed(self.cregs)
for cr in cregs:
for i in range(self.cregs[cr]):
self.clbit_list.append((cr, i))
self.ordered_regs = [(item[0], item[1]) for
item in self.header['qubit_labels']]
if self._style.reverse:
reg_size = []
reg_labels = []
new_ordered_regs = []
for regs in self.ordered_regs:
if regs[0] in reg_labels:
continue
reg_labels.append(regs[0])
reg_size.append(len(
[x for x in self.ordered_regs if x[0] == regs[0]]))
index = 0
for size in reg_size:
new_index = index + size
for i in range(new_index - 1, index - 1, -1):
new_ordered_regs.append(self.ordered_regs[i])
index = new_index
self.ordered_regs = new_ordered_regs
if 'clbit_labels' in self.header:
for clabel in self.header['clbit_labels']:
if self._style.reverse:
for cind in reversed(range(clabel[1])):
self.ordered_regs.append((clabel[0], cind))
else:
for cind in range(clabel[1]):
self.ordered_regs.append((clabel[0], cind))
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\'+'\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
QISKitError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.circuit['instructions']:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's', 'sdg',
't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy', 'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['texparams']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, arg)
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
assert len(op['clbits']) == 1 and len(op['qubits']) == 1
if 'conditional' in op:
raise QISKitError('conditional measures currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise QISKitError('conditional reset currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
assert False, "bad node data"
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns+1, ceil(sum_column_widths)+4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above example,
index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _convert_mask(self, mask):
orig_clbit_list = []
for cr in self.orig_cregs:
for i in range(self.orig_cregs[cr]):
orig_clbit_list.append((cr, i))
bit_list = [(mask >> bit) & 1 for bit in range(
len(orig_clbit_list) - 1, -1, -1)]
converted_mask_list = [None] * len(bit_list)
converted_mask = 0
for pos, bit in enumerate(reversed(bit_list)):
new_pos = self.clbit_list.index(orig_clbit_list[pos])
converted_mask_list[new_pos] = bit
if None in converted_mask_list:
raise VisualizationError('Reverse mask creation failed')
converted_mask_list = list(reversed(converted_mask_list))
for bit in converted_mask_list:
converted_mask = (converted_mask << 1) | bit
return converted_mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.circuit['instructions']):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier']:
nm = op['name']
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] =\
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
elif nm == "reset":
self._latex[pos_1][columns] = \
"\\push{\\rule{.6em}{0em}\\ket{0}\\rule{.2em}{0em}} \\qw"
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
assert len(op['clbits']) == 1 and \
len(op['qubits']) == 1 and \
'params' not in op, "bad operation record"
if 'conditional' in op:
assert False, "If controlled measures currently not supported."
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_entry = self._latex[pos_1][columns - 1]
if 'barrier' in prev_entry:
self._latex[pos_1][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise QISKitError('Error during Latex building: %s' %
str(e))
elif op['name'] == "barrier":
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qubits']) - 1
self._latex[start][columns] += " \\barrier{" + str(span) + "}"
else:
assert False, "bad node data"
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
if self._style.reverse:
return origin + 1
return origin - 1
def _get_register_specs(bit_labels):
"""
Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = MatplotlibDrawer(basis=basis, scale=scale, style=style)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
Register = namedtuple('Register', 'name index')
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=1.0, style=None):
self._ast = None
self._basis = basis
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = OrderedDict()
self._creg_dict = OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom='off', labeltop='off', labelleft='off', labelright='off')
def load_qasm_file(self, filename):
circuit = load_qasm_file(filename, name='draw', basis_gates=self._basis)
self.parse_circuit(circuit)
def parse_circuit(self, circuit: QuantumCircuit):
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
self._ast = transpile(dag_circuit, basis_gates=self._basis, format='json')
self._registers()
self._ops = self._ast['instructions']
def _registers(self):
# NOTE: formats of clbit and qubit are different!
header = self._ast['header']
self._creg = []
for e in header['clbit_labels']:
for i in range(e[1]):
self._creg.append(Register(name=e[0], index=i))
assert len(self._creg) == header['number_of_clbits']
self._qreg = []
for e in header['qubit_labels']:
self._qreg.append(Register(name=e[0], index=e[1]))
assert len(self._qreg) == header['number_of_qubits']
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.sc,
clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7, height=HIG * 0.7,
theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID], [qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy+0.35*WID], lc=self._style.cc, ls=self._style.cline)
arrowhead = patches.Polygon(((cx-0.20*WID, cy+0.35*WID),
(cx+0.20*WID, cy+0.35*WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'], ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if get_matplotlib_backend() == 'module://ipykernel.pylab.backend_inline':
# returns None when matplotlib is inline mode to prevent Jupyter
# with matplotlib inlining enabled to draw the diagram twice.
im = None
else:
# when matplotlib is not inline mode,
# self.figure.savefig is called twice because...
# ... this is needed to get the in-memory representation
with tempfile.TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, 'circuit.png')
self.figure.savefig(tmpfile, dpi=self._style.dpi,
bbox_inches='tight')
im = Image.open(tmpfile)
_trim(im)
os.remove(tmpfile)
# ... and this is needed to delegate in matplotlib the generation of
# the proper format.
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
return im
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index, 'group': reg.name}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(zip_longest(self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
self._cond['n_lines'] += 1
idx += 1
# reverse bit order
if self._style.reverse:
self._reverse_bits(self._qreg_dict)
self._reverse_bits(self._creg_dict)
def _reverse_bits(self, target_dict):
coord = {}
# grouping
for dict_ in target_dict.values():
if dict_['group'] not in coord:
coord[dict_['group']] = [dict_['y']]
else:
coord[dict_['group']].insert(0, dict_['y'])
# reverse bit order
for key in target_dict.keys():
target_dict[key]['y'] = coord[target_dict[key]['group']].pop(0)
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc, ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qubits' in op.keys():
q_idxs = op['qubits']
else:
q_idxs = []
# get creg index
if 'clbits' in op.keys():
c_idxs = op['clbits']
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied), max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] == 'barrier' and not self._style.barrier:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg corrdinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc, ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] == 'barrier':
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self._style.barrier:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise QISKitError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if isclose(fmod(abs_val, 1.0), 0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
elif 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return Fraction(i, j)
return None
<|code_end|>
|
Latex circuit drawer fails when barrier is present.
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: latest master
- **Python version**: 3.7
- **Operating system**: OSX
### What is the current behavior?
Using `circuit_drawer` on a circuit with a barrier fails:
```python
q = QuantumRegister(2, "q")
qc = QuantumCircuit(q)
qc.cx(q[0],q[1])
qc.barrier(q)
circuit_drawer(qc)
```
giving the following log report:
```
<xymatrix
! Undefined control sequence.
<recently read> \barrier
```
### Steps to reproduce the problem
### What is the expected behavior?
### Suggested solutions
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
1. LaTeX
2. Matplotlib
"""
import json
import logging
import operator
import os
import re
import subprocess
import tempfile
from collections import namedtuple, OrderedDict
from fractions import Fraction
from io import StringIO
from itertools import groupby, zip_longest
from math import fmod, isclose, ceil
import numpy as np
from PIL import Image, ImageChops
from matplotlib import get_backend as get_matplotlib_backend, \
patches as patches, pyplot as plt
from qiskit._qiskiterror import QISKitError
from qiskit._quantumcircuit import QuantumCircuit
from qiskit.wrapper import load_qasm_file
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization._error import VisualizationError
from qiskit.transpiler import transpile
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit, via 2 methods (try 1st, if unsuccessful, 2nd):
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
try:
return latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError):
return matplotlib_circuit_drawer(circuit, basis, scale, filename, style)
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
class QCStyle:
def __init__(self):
self.tc = '#000000'
self.sc = '#000000'
self.lc = '#000000'
self.cc = '#778899'
self.gc = '#ffffff'
self.gt = '#000000'
self.bc = '#bdbdbd'
self.bg = '#ffffff'
self.fs = 13
self.sfs = 8
self.disptex = {
'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'
}
self.dispcol = {
'id': '#ffffff',
'u0': '#ffffff',
'u1': '#ffffff',
'u2': '#ffffff',
'u3': '#ffffff',
'x': '#ffffff',
'y': '#ffffff',
'z': '#ffffff',
'h': '#ffffff',
's': '#ffffff',
'sdg': '#ffffff',
't': '#ffffff',
'tdg': '#ffffff',
'rx': '#ffffff',
'ry': '#ffffff',
'rz': '#ffffff',
'reset': '#ffffff',
'target': '#ffffff',
'meas': '#ffffff'
}
self.latexmode = True
self.pimode = False
self.fold = 20
self.bundle = False
self.barrier = False
self.index = False
self.compress = True
self.figwidth = -1
self.dpi = 150
self.margin = [2.0, 0.0, 0.0, 0.3]
self.cline = 'doublet'
self.reverse = False
def set_style(self, dic):
self.tc = dic.get('textcolor', self.tc)
self.sc = dic.get('subtextcolor', self.sc)
self.lc = dic.get('linecolor', self.lc)
self.cc = dic.get('creglinecolor', self.cc)
self.gt = dic.get('gatetextcolor', self.tc)
self.gc = dic.get('gatefacecolor', self.gc)
self.bc = dic.get('barrierfacecolor', self.bc)
self.bg = dic.get('backgroundcolor', self.bg)
self.fs = dic.get('fontsize', self.fs)
self.sfs = dic.get('subfontsize', self.sfs)
self.disptex = dic.get('displaytext', self.disptex)
for key in self.dispcol.keys():
self.dispcol[key] = self.gc
self.dispcol = dic.get('displaycolor', self.dispcol)
self.latexmode = dic.get('latexdrawerstyle', self.latexmode)
self.pimode = dic.get('usepiformat', self.pimode)
self.fold = dic.get('fold', self.fold)
if self.fold < 2:
self.fold = -1
self.bundle = dic.get('cregbundle', self.bundle)
self.barrier = dic.get('plotbarrier', self.barrier)
self.index = dic.get('showindex', self.index)
self.compress = dic.get('compress', self.compress)
self.figwidth = dic.get('figwidth', self.figwidth)
self.dpi = dic.get('dpi', self.dpi)
self.margin = dic.get('margin', self.margin)
self.cline = dic.get('creglinestyle', self.cline)
self.reverse = dic.get('reversebits', self.reverse)
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": False,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to complile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def _trim(im):
"""Trim image and remove white space
"""
bg = Image.new(im.mode, im.size, im.getpixel((0, 0)))
diff = ImageChops.difference(im, bg)
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
im = im.crop(bbox)
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
qcimg = QCircuitImage(json_circuit, scale, style=style)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, circuit, scale, style=None):
"""
Args:
circuit (dict): compiled_circuit from qobj
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
"""
# style sheet
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.circuit = circuit
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
#################################
self.header = self.circuit['header']
self.qregs = OrderedDict(_get_register_specs(
self.header['qubit_labels']))
self.qubit_list = []
for qr in self.qregs:
for i in range(self.qregs[qr]):
self.qubit_list.append((qr, i))
self.cregs = OrderedDict()
if 'clbit_labels' in self.header:
for item in self.header['clbit_labels']:
self.cregs[item[0]] = item[1]
self.clbit_list = []
cregs = self.cregs
if self._style.reverse:
self.orig_cregs = self.cregs
cregs = reversed(self.cregs)
for cr in cregs:
for i in range(self.cregs[cr]):
self.clbit_list.append((cr, i))
self.ordered_regs = [(item[0], item[1]) for
item in self.header['qubit_labels']]
if self._style.reverse:
reg_size = []
reg_labels = []
new_ordered_regs = []
for regs in self.ordered_regs:
if regs[0] in reg_labels:
continue
reg_labels.append(regs[0])
reg_size.append(len(
[x for x in self.ordered_regs if x[0] == regs[0]]))
index = 0
for size in reg_size:
new_index = index + size
for i in range(new_index - 1, index - 1, -1):
new_ordered_regs.append(self.ordered_regs[i])
index = new_index
self.ordered_regs = new_ordered_regs
if 'clbit_labels' in self.header:
for clabel in self.header['clbit_labels']:
if self._style.reverse:
for cind in reversed(range(clabel[1])):
self.ordered_regs.append((clabel[0], cind))
else:
for cind in range(clabel[1]):
self.ordered_regs.append((clabel[0], cind))
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\'+'\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
QISKitError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.circuit['instructions']:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's', 'sdg',
't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy', 'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['texparams']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, arg)
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
assert len(op['clbits']) == 1 and len(op['qubits']) == 1
if 'conditional' in op:
raise QISKitError('conditional measures currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise QISKitError('conditional reset currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
assert False, "bad node data"
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns+1, ceil(sum_column_widths)+4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above example,
index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _convert_mask(self, mask):
orig_clbit_list = []
for cr in self.orig_cregs:
for i in range(self.orig_cregs[cr]):
orig_clbit_list.append((cr, i))
bit_list = [(mask >> bit) & 1 for bit in range(
len(orig_clbit_list) - 1, -1, -1)]
converted_mask_list = [None] * len(bit_list)
converted_mask = 0
for pos, bit in enumerate(reversed(bit_list)):
new_pos = self.clbit_list.index(orig_clbit_list[pos])
converted_mask_list[new_pos] = bit
if None in converted_mask_list:
raise VisualizationError('Reverse mask creation failed')
converted_mask_list = list(reversed(converted_mask_list))
for bit in converted_mask_list:
converted_mask = (converted_mask << 1) | bit
return converted_mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.circuit['instructions']):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier']:
nm = op['name']
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] =\
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
elif nm == "reset":
self._latex[pos_1][columns] = \
"\\push{\\rule{.6em}{0em}\\ket{0}\\rule{.2em}{0em}} \\qw"
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
assert len(op['clbits']) == 1 and \
len(op['qubits']) == 1 and \
'params' not in op, "bad operation record"
if 'conditional' in op:
assert False, "If controlled measures currently not supported."
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise QISKitError('Error during Latex building: %s' %
str(e))
elif op['name'] == "barrier":
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qubits']) - 1
self._latex[start][columns] += " \\barrier{" + str(span) + "}"
else:
assert False, "bad node data"
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
if self._style.reverse:
return origin + 1
return origin - 1
def _get_register_specs(bit_labels):
"""
Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = MatplotlibDrawer(basis=basis, scale=scale, style=style)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
Register = namedtuple('Register', 'name index')
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=1.0, style=None):
self._ast = None
self._basis = basis
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = OrderedDict()
self._creg_dict = OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False, labelleft=False, labelright=False)
def load_qasm_file(self, filename):
circuit = load_qasm_file(filename, name='draw', basis_gates=self._basis)
self.parse_circuit(circuit)
def parse_circuit(self, circuit: QuantumCircuit):
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
self._ast = transpile(dag_circuit, basis_gates=self._basis, format='json')
self._registers()
self._ops = self._ast['instructions']
def _registers(self):
# NOTE: formats of clbit and qubit are different!
header = self._ast['header']
self._creg = []
for e in header['clbit_labels']:
for i in range(e[1]):
self._creg.append(Register(name=e[0], index=i))
assert len(self._creg) == header['number_of_clbits']
self._qreg = []
for e in header['qubit_labels']:
self._qreg.append(Register(name=e[0], index=e[1]))
assert len(self._qreg) == header['number_of_qubits']
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.sc,
clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7, height=HIG * 0.7,
theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID], [qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy+0.35*WID], lc=self._style.cc, ls=self._style.cline)
arrowhead = patches.Polygon(((cx-0.20*WID, cy+0.35*WID),
(cx+0.20*WID, cy+0.35*WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'], ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if get_matplotlib_backend() == 'module://ipykernel.pylab.backend_inline':
# returns None when matplotlib is inline mode to prevent Jupyter
# with matplotlib inlining enabled to draw the diagram twice.
im = None
else:
# when matplotlib is not inline mode,
# self.figure.savefig is called twice because...
# ... this is needed to get the in-memory representation
with tempfile.TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, 'circuit.png')
self.figure.savefig(tmpfile, dpi=self._style.dpi,
bbox_inches='tight')
im = Image.open(tmpfile)
_trim(im)
os.remove(tmpfile)
# ... and this is needed to delegate in matplotlib the generation of
# the proper format.
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
return im
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index, 'group': reg.name}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(zip_longest(self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
self._cond['n_lines'] += 1
idx += 1
# reverse bit order
if self._style.reverse:
self._reverse_bits(self._qreg_dict)
self._reverse_bits(self._creg_dict)
def _reverse_bits(self, target_dict):
coord = {}
# grouping
for dict_ in target_dict.values():
if dict_['group'] not in coord:
coord[dict_['group']] = [dict_['y']]
else:
coord[dict_['group']].insert(0, dict_['y'])
# reverse bit order
for key in target_dict.keys():
target_dict[key]['y'] = coord[target_dict[key]['group']].pop(0)
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc, ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qubits' in op.keys():
q_idxs = op['qubits']
else:
q_idxs = []
# get creg index
if 'clbits' in op.keys():
c_idxs = op['clbits']
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied), max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] == 'barrier' and not self._style.barrier:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg corrdinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc, ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] == 'barrier':
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self._style.barrier:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise QISKitError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if isclose(fmod(abs_val, 1.0), 0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
elif 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return Fraction(i, j)
return None
<|code_end|>
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
1. LaTeX
2. Matplotlib
"""
import json
import logging
import operator
import os
import re
import subprocess
import tempfile
from collections import namedtuple, OrderedDict
from fractions import Fraction
from io import StringIO
from itertools import groupby, zip_longest
from math import fmod, isclose, ceil
import numpy as np
from PIL import Image, ImageChops
from matplotlib import get_backend as get_matplotlib_backend, \
patches as patches, pyplot as plt
from qiskit._qiskiterror import QISKitError
from qiskit._quantumcircuit import QuantumCircuit
from qiskit.wrapper import load_qasm_file
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization._error import VisualizationError
from qiskit.transpiler import transpile
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit, via 2 methods (try 1st, if unsuccessful, 2nd):
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
try:
return latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError):
return matplotlib_circuit_drawer(circuit, basis, scale, filename, style)
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
class QCStyle:
def __init__(self):
self.tc = '#000000'
self.sc = '#000000'
self.lc = '#000000'
self.cc = '#778899'
self.gc = '#ffffff'
self.gt = '#000000'
self.bc = '#bdbdbd'
self.bg = '#ffffff'
self.fs = 13
self.sfs = 8
self.disptex = {
'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'
}
self.dispcol = {
'id': '#ffffff',
'u0': '#ffffff',
'u1': '#ffffff',
'u2': '#ffffff',
'u3': '#ffffff',
'x': '#ffffff',
'y': '#ffffff',
'z': '#ffffff',
'h': '#ffffff',
's': '#ffffff',
'sdg': '#ffffff',
't': '#ffffff',
'tdg': '#ffffff',
'rx': '#ffffff',
'ry': '#ffffff',
'rz': '#ffffff',
'reset': '#ffffff',
'target': '#ffffff',
'meas': '#ffffff'
}
self.latexmode = True
self.pimode = False
self.fold = 20
self.bundle = False
self.barrier = False
self.index = False
self.compress = True
self.figwidth = -1
self.dpi = 150
self.margin = [2.0, 0.0, 0.0, 0.3]
self.cline = 'doublet'
self.reverse = False
def set_style(self, dic):
self.tc = dic.get('textcolor', self.tc)
self.sc = dic.get('subtextcolor', self.sc)
self.lc = dic.get('linecolor', self.lc)
self.cc = dic.get('creglinecolor', self.cc)
self.gt = dic.get('gatetextcolor', self.tc)
self.gc = dic.get('gatefacecolor', self.gc)
self.bc = dic.get('barrierfacecolor', self.bc)
self.bg = dic.get('backgroundcolor', self.bg)
self.fs = dic.get('fontsize', self.fs)
self.sfs = dic.get('subfontsize', self.sfs)
self.disptex = dic.get('displaytext', self.disptex)
for key in self.dispcol.keys():
self.dispcol[key] = self.gc
self.dispcol = dic.get('displaycolor', self.dispcol)
self.latexmode = dic.get('latexdrawerstyle', self.latexmode)
self.pimode = dic.get('usepiformat', self.pimode)
self.fold = dic.get('fold', self.fold)
if self.fold < 2:
self.fold = -1
self.bundle = dic.get('cregbundle', self.bundle)
self.barrier = dic.get('plotbarrier', self.barrier)
self.index = dic.get('showindex', self.index)
self.compress = dic.get('compress', self.compress)
self.figwidth = dic.get('figwidth', self.figwidth)
self.dpi = dic.get('dpi', self.dpi)
self.margin = dic.get('margin', self.margin)
self.cline = dic.get('creglinestyle', self.cline)
self.reverse = dic.get('reversebits', self.reverse)
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": False,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to complile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def _trim(im):
"""Trim image and remove white space
"""
bg = Image.new(im.mode, im.size, im.getpixel((0, 0)))
diff = ImageChops.difference(im, bg)
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
im = im.crop(bbox)
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
qcimg = QCircuitImage(json_circuit, scale, style=style)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, circuit, scale, style=None):
"""
Args:
circuit (dict): compiled_circuit from qobj
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
"""
# style sheet
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.circuit = circuit
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
#################################
self.header = self.circuit['header']
self.qregs = OrderedDict(_get_register_specs(
self.header['qubit_labels']))
self.qubit_list = []
for qr in self.qregs:
for i in range(self.qregs[qr]):
self.qubit_list.append((qr, i))
self.cregs = OrderedDict()
if 'clbit_labels' in self.header:
for item in self.header['clbit_labels']:
self.cregs[item[0]] = item[1]
self.clbit_list = []
cregs = self.cregs
if self._style.reverse:
self.orig_cregs = self.cregs
cregs = reversed(self.cregs)
for cr in cregs:
for i in range(self.cregs[cr]):
self.clbit_list.append((cr, i))
self.ordered_regs = [(item[0], item[1]) for
item in self.header['qubit_labels']]
if self._style.reverse:
reg_size = []
reg_labels = []
new_ordered_regs = []
for regs in self.ordered_regs:
if regs[0] in reg_labels:
continue
reg_labels.append(regs[0])
reg_size.append(len(
[x for x in self.ordered_regs if x[0] == regs[0]]))
index = 0
for size in reg_size:
new_index = index + size
for i in range(new_index - 1, index - 1, -1):
new_ordered_regs.append(self.ordered_regs[i])
index = new_index
self.ordered_regs = new_ordered_regs
if 'clbit_labels' in self.header:
for clabel in self.header['clbit_labels']:
if self._style.reverse:
for cind in reversed(range(clabel[1])):
self.ordered_regs.append((clabel[0], cind))
else:
for cind in range(clabel[1]):
self.ordered_regs.append((clabel[0], cind))
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\'+'\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
QISKitError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.circuit['instructions']:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's', 'sdg',
't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy', 'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['texparams']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, arg)
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
assert len(op['clbits']) == 1 and len(op['qubits']) == 1
if 'conditional' in op:
raise QISKitError('conditional measures currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise QISKitError('conditional reset currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
assert False, "bad node data"
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns+1, ceil(sum_column_widths)+4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above example,
index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _convert_mask(self, mask):
orig_clbit_list = []
for cr in self.orig_cregs:
for i in range(self.orig_cregs[cr]):
orig_clbit_list.append((cr, i))
bit_list = [(mask >> bit) & 1 for bit in range(
len(orig_clbit_list) - 1, -1, -1)]
converted_mask_list = [None] * len(bit_list)
converted_mask = 0
for pos, bit in enumerate(reversed(bit_list)):
new_pos = self.clbit_list.index(orig_clbit_list[pos])
converted_mask_list[new_pos] = bit
if None in converted_mask_list:
raise VisualizationError('Reverse mask creation failed')
converted_mask_list = list(reversed(converted_mask_list))
for bit in converted_mask_list:
converted_mask = (converted_mask << 1) | bit
return converted_mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.circuit['instructions']):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier']:
nm = op['name']
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] =\
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
elif nm == "reset":
self._latex[pos_1][columns] = \
"\\push{\\rule{.6em}{0em}\\ket{0}\\rule{.2em}{0em}} \\qw"
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
assert len(op['clbits']) == 1 and \
len(op['qubits']) == 1 and \
'params' not in op, "bad operation record"
if 'conditional' in op:
assert False, "If controlled measures currently not supported."
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise QISKitError('Error during Latex building: %s' %
str(e))
elif op['name'] == "barrier":
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qubits']) - 1
self._latex[start][columns] += " \\barrier{" + str(span) + "}"
else:
assert False, "bad node data"
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
if self._style.reverse:
return origin + 1
return origin - 1
def _get_register_specs(bit_labels):
"""
Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = MatplotlibDrawer(basis=basis, scale=scale, style=style)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
Register = namedtuple('Register', 'name index')
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=1.0, style=None):
self._ast = None
self._basis = basis
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = OrderedDict()
self._creg_dict = OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False, labelleft=False, labelright=False)
def load_qasm_file(self, filename):
circuit = load_qasm_file(filename, name='draw', basis_gates=self._basis)
self.parse_circuit(circuit)
def parse_circuit(self, circuit: QuantumCircuit):
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
self._ast = transpile(dag_circuit, basis_gates=self._basis, format='json')
self._registers()
self._ops = self._ast['instructions']
def _registers(self):
# NOTE: formats of clbit and qubit are different!
header = self._ast['header']
self._creg = []
for e in header['clbit_labels']:
for i in range(e[1]):
self._creg.append(Register(name=e[0], index=i))
assert len(self._creg) == header['number_of_clbits']
self._qreg = []
for e in header['qubit_labels']:
self._qreg.append(Register(name=e[0], index=e[1]))
assert len(self._qreg) == header['number_of_qubits']
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.sc,
clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7, height=HIG * 0.7,
theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID], [qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy+0.35*WID], lc=self._style.cc, ls=self._style.cline)
arrowhead = patches.Polygon(((cx-0.20*WID, cy+0.35*WID),
(cx+0.20*WID, cy+0.35*WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'], ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if get_matplotlib_backend() == 'module://ipykernel.pylab.backend_inline':
# returns None when matplotlib is inline mode to prevent Jupyter
# with matplotlib inlining enabled to draw the diagram twice.
im = None
else:
# when matplotlib is not inline mode,
# self.figure.savefig is called twice because...
# ... this is needed to get the in-memory representation
with tempfile.TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, 'circuit.png')
self.figure.savefig(tmpfile, dpi=self._style.dpi,
bbox_inches='tight')
im = Image.open(tmpfile)
_trim(im)
os.remove(tmpfile)
# ... and this is needed to delegate in matplotlib the generation of
# the proper format.
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
return im
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index, 'group': reg.name}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(zip_longest(self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
self._cond['n_lines'] += 1
idx += 1
# reverse bit order
if self._style.reverse:
self._reverse_bits(self._qreg_dict)
self._reverse_bits(self._creg_dict)
def _reverse_bits(self, target_dict):
coord = {}
# grouping
for dict_ in target_dict.values():
if dict_['group'] not in coord:
coord[dict_['group']] = [dict_['y']]
else:
coord[dict_['group']].insert(0, dict_['y'])
# reverse bit order
for key in target_dict.keys():
target_dict[key]['y'] = coord[target_dict[key]['group']].pop(0)
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc, ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qubits' in op.keys():
q_idxs = op['qubits']
else:
q_idxs = []
# get creg index
if 'clbits' in op.keys():
c_idxs = op['clbits']
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied), max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] == 'barrier' and not self._style.barrier:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg corrdinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc, ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] == 'barrier':
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self._style.barrier:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise QISKitError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if isclose(fmod(abs_val, 1.0), 0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
elif 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return Fraction(i, j)
return None
<|code_end|>
|
LaTeX Barriers are not centered between gates and measures on all columns
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: latest master
- **Python version**: 3.7
- **Operating system**: linux
### What is the current behavior?
@nonhermitian example in issue #938 shows a circuit with a barrier being drawn with a measure after a gate but the barrier is not centered for the gate and measure on q0_15:

The barrier is being drawn from q0_0 (because the \barrier command in latex draws the barrier line down from the topmost bit) and the default horizontal offset is used because there is no measure immediately after the gate on that bit. This ends up being incorrect on q0_15 because because there is a measure immediately after the gate on that bit which moves the center line between those 2 boxes to the left.
### Steps to reproduce the problem
Draw a circuit with a measure right after a gate on a bit covered by the barrier, but is not the bit where \barrier will be written in the latex.
### What is the expected behavior?
The barrier line should centered between gates and measures on all bits covered by a barrier, not just the topmost bit (where the \barrier call is made from in the latex)
### Suggested solutions
We need to adjust the check in the latex circuit drawer that looks for a measure directly after a gate on a bit to check all bits being covered by the barrier, not just the bit
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
1. LaTeX
2. Matplotlib
"""
import json
import logging
import operator
import os
import re
import subprocess
import tempfile
from collections import namedtuple, OrderedDict
from fractions import Fraction
from io import StringIO
from itertools import groupby, zip_longest
from math import fmod, isclose, ceil
import numpy as np
from PIL import Image, ImageChops
from matplotlib import get_backend as get_matplotlib_backend, \
patches as patches, pyplot as plt
from qiskit._qiskiterror import QISKitError
from qiskit._quantumcircuit import QuantumCircuit
from qiskit.wrapper import load_qasm_file
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization._error import VisualizationError
from qiskit.transpiler import transpile
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit, via 2 methods (try 1st, if unsuccessful, 2nd):
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
try:
return latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError):
return matplotlib_circuit_drawer(circuit, basis, scale, filename, style)
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
class QCStyle:
def __init__(self):
self.tc = '#000000'
self.sc = '#000000'
self.lc = '#000000'
self.cc = '#778899'
self.gc = '#ffffff'
self.gt = '#000000'
self.bc = '#bdbdbd'
self.bg = '#ffffff'
self.fs = 13
self.sfs = 8
self.disptex = {
'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'
}
self.dispcol = {
'id': '#ffffff',
'u0': '#ffffff',
'u1': '#ffffff',
'u2': '#ffffff',
'u3': '#ffffff',
'x': '#ffffff',
'y': '#ffffff',
'z': '#ffffff',
'h': '#ffffff',
's': '#ffffff',
'sdg': '#ffffff',
't': '#ffffff',
'tdg': '#ffffff',
'rx': '#ffffff',
'ry': '#ffffff',
'rz': '#ffffff',
'reset': '#ffffff',
'target': '#ffffff',
'meas': '#ffffff'
}
self.latexmode = True
self.pimode = False
self.fold = 20
self.bundle = False
self.barrier = False
self.index = False
self.compress = True
self.figwidth = -1
self.dpi = 150
self.margin = [2.0, 0.0, 0.0, 0.3]
self.cline = 'doublet'
self.reverse = False
def set_style(self, dic):
self.tc = dic.get('textcolor', self.tc)
self.sc = dic.get('subtextcolor', self.sc)
self.lc = dic.get('linecolor', self.lc)
self.cc = dic.get('creglinecolor', self.cc)
self.gt = dic.get('gatetextcolor', self.tc)
self.gc = dic.get('gatefacecolor', self.gc)
self.bc = dic.get('barrierfacecolor', self.bc)
self.bg = dic.get('backgroundcolor', self.bg)
self.fs = dic.get('fontsize', self.fs)
self.sfs = dic.get('subfontsize', self.sfs)
self.disptex = dic.get('displaytext', self.disptex)
for key in self.dispcol.keys():
self.dispcol[key] = self.gc
self.dispcol = dic.get('displaycolor', self.dispcol)
self.latexmode = dic.get('latexdrawerstyle', self.latexmode)
self.pimode = dic.get('usepiformat', self.pimode)
self.fold = dic.get('fold', self.fold)
if self.fold < 2:
self.fold = -1
self.bundle = dic.get('cregbundle', self.bundle)
self.barrier = dic.get('plotbarrier', self.barrier)
self.index = dic.get('showindex', self.index)
self.compress = dic.get('compress', self.compress)
self.figwidth = dic.get('figwidth', self.figwidth)
self.dpi = dic.get('dpi', self.dpi)
self.margin = dic.get('margin', self.margin)
self.cline = dic.get('creglinestyle', self.cline)
self.reverse = dic.get('reversebits', self.reverse)
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": False,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to complile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def _trim(im):
"""Trim image and remove white space
"""
bg = Image.new(im.mode, im.size, im.getpixel((0, 0)))
diff = ImageChops.difference(im, bg)
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
im = im.crop(bbox)
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
qcimg = QCircuitImage(json_circuit, scale, style=style)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, circuit, scale, style=None):
"""
Args:
circuit (dict): compiled_circuit from qobj
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
"""
# style sheet
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.circuit = circuit
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
#################################
self.header = self.circuit['header']
self.qregs = OrderedDict(_get_register_specs(
self.header['qubit_labels']))
self.qubit_list = []
for qr in self.qregs:
for i in range(self.qregs[qr]):
self.qubit_list.append((qr, i))
self.cregs = OrderedDict()
if 'clbit_labels' in self.header:
for item in self.header['clbit_labels']:
self.cregs[item[0]] = item[1]
self.clbit_list = []
cregs = self.cregs
if self._style.reverse:
self.orig_cregs = self.cregs
cregs = reversed(self.cregs)
for cr in cregs:
for i in range(self.cregs[cr]):
self.clbit_list.append((cr, i))
self.ordered_regs = [(item[0], item[1]) for
item in self.header['qubit_labels']]
if self._style.reverse:
reg_size = []
reg_labels = []
new_ordered_regs = []
for regs in self.ordered_regs:
if regs[0] in reg_labels:
continue
reg_labels.append(regs[0])
reg_size.append(len(
[x for x in self.ordered_regs if x[0] == regs[0]]))
index = 0
for size in reg_size:
new_index = index + size
for i in range(new_index - 1, index - 1, -1):
new_ordered_regs.append(self.ordered_regs[i])
index = new_index
self.ordered_regs = new_ordered_regs
if 'clbit_labels' in self.header:
for clabel in self.header['clbit_labels']:
if self._style.reverse:
for cind in reversed(range(clabel[1])):
self.ordered_regs.append((clabel[0], cind))
else:
for cind in range(clabel[1]):
self.ordered_regs.append((clabel[0], cind))
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\'+'\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
QISKitError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.circuit['instructions']:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's', 'sdg',
't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy', 'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['texparams']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, arg)
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
assert len(op['clbits']) == 1 and len(op['qubits']) == 1
if 'conditional' in op:
raise QISKitError('conditional measures currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise QISKitError('conditional reset currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
assert False, "bad node data"
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns+1, ceil(sum_column_widths)+4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above example,
index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _convert_mask(self, mask):
orig_clbit_list = []
for cr in self.orig_cregs:
for i in range(self.orig_cregs[cr]):
orig_clbit_list.append((cr, i))
bit_list = [(mask >> bit) & 1 for bit in range(
len(orig_clbit_list) - 1, -1, -1)]
converted_mask_list = [None] * len(bit_list)
converted_mask = 0
for pos, bit in enumerate(reversed(bit_list)):
new_pos = self.clbit_list.index(orig_clbit_list[pos])
converted_mask_list[new_pos] = bit
if None in converted_mask_list:
raise VisualizationError('Reverse mask creation failed')
converted_mask_list = list(reversed(converted_mask_list))
for bit in converted_mask_list:
converted_mask = (converted_mask << 1) | bit
return converted_mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.circuit['instructions']):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier']:
nm = op['name']
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] =\
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
elif nm == "reset":
self._latex[pos_1][columns] = \
"\\push{\\rule{.6em}{0em}\\ket{0}\\rule{.2em}{0em}} \\qw"
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
assert len(op['clbits']) == 1 and \
len(op['qubits']) == 1 and \
'params' not in op, "bad operation record"
if 'conditional' in op:
assert False, "If controlled measures currently not supported."
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_entry = self._latex[pos_1][columns - 1]
if 'barrier' in prev_entry:
self._latex[pos_1][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise QISKitError('Error during Latex building: %s' %
str(e))
elif op['name'] == "barrier":
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qubits']) - 1
self._latex[start][columns] += " \\barrier{" + str(span) + "}"
else:
assert False, "bad node data"
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
if self._style.reverse:
return origin + 1
return origin - 1
def _get_register_specs(bit_labels):
"""
Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = MatplotlibDrawer(basis=basis, scale=scale, style=style)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
Register = namedtuple('Register', 'name index')
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=1.0, style=None):
self._ast = None
self._basis = basis
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = OrderedDict()
self._creg_dict = OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False, labelleft=False, labelright=False)
def load_qasm_file(self, filename):
circuit = load_qasm_file(filename, name='draw', basis_gates=self._basis)
self.parse_circuit(circuit)
def parse_circuit(self, circuit: QuantumCircuit):
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
self._ast = transpile(dag_circuit, basis_gates=self._basis, format='json')
self._registers()
self._ops = self._ast['instructions']
def _registers(self):
# NOTE: formats of clbit and qubit are different!
header = self._ast['header']
self._creg = []
for e in header['clbit_labels']:
for i in range(e[1]):
self._creg.append(Register(name=e[0], index=i))
assert len(self._creg) == header['number_of_clbits']
self._qreg = []
for e in header['qubit_labels']:
self._qreg.append(Register(name=e[0], index=e[1]))
assert len(self._qreg) == header['number_of_qubits']
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.sc,
clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7, height=HIG * 0.7,
theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID], [qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy+0.35*WID], lc=self._style.cc, ls=self._style.cline)
arrowhead = patches.Polygon(((cx-0.20*WID, cy+0.35*WID),
(cx+0.20*WID, cy+0.35*WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'], ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if get_matplotlib_backend() == 'module://ipykernel.pylab.backend_inline':
# returns None when matplotlib is inline mode to prevent Jupyter
# with matplotlib inlining enabled to draw the diagram twice.
im = None
else:
# when matplotlib is not inline mode,
# self.figure.savefig is called twice because...
# ... this is needed to get the in-memory representation
with tempfile.TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, 'circuit.png')
self.figure.savefig(tmpfile, dpi=self._style.dpi,
bbox_inches='tight')
im = Image.open(tmpfile)
_trim(im)
os.remove(tmpfile)
# ... and this is needed to delegate in matplotlib the generation of
# the proper format.
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
return im
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index, 'group': reg.name}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(zip_longest(self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
self._cond['n_lines'] += 1
idx += 1
# reverse bit order
if self._style.reverse:
self._reverse_bits(self._qreg_dict)
self._reverse_bits(self._creg_dict)
def _reverse_bits(self, target_dict):
coord = {}
# grouping
for dict_ in target_dict.values():
if dict_['group'] not in coord:
coord[dict_['group']] = [dict_['y']]
else:
coord[dict_['group']].insert(0, dict_['y'])
# reverse bit order
for key in target_dict.keys():
target_dict[key]['y'] = coord[target_dict[key]['group']].pop(0)
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc, ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qubits' in op.keys():
q_idxs = op['qubits']
else:
q_idxs = []
# get creg index
if 'clbits' in op.keys():
c_idxs = op['clbits']
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied), max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] == 'barrier' and not self._style.barrier:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg corrdinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc, ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] == 'barrier':
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self._style.barrier:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise QISKitError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if isclose(fmod(abs_val, 1.0), 0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
elif 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return Fraction(i, j)
return None
<|code_end|>
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
1. LaTeX
2. Matplotlib
"""
import json
import logging
import operator
import os
import re
import subprocess
import tempfile
from collections import namedtuple, OrderedDict
from fractions import Fraction
from io import StringIO
from itertools import groupby, zip_longest
from math import fmod, isclose, ceil
import numpy as np
from PIL import Image, ImageChops
from matplotlib import get_backend as get_matplotlib_backend, \
patches as patches, pyplot as plt
from qiskit._qiskiterror import QISKitError
from qiskit._quantumcircuit import QuantumCircuit
from qiskit.wrapper import load_qasm_file
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization._error import VisualizationError
from qiskit.transpiler import transpile
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit, via 2 methods (try 1st, if unsuccessful, 2nd):
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
try:
return latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError):
return matplotlib_circuit_drawer(circuit, basis, scale, filename, style)
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
class QCStyle:
def __init__(self):
self.tc = '#000000'
self.sc = '#000000'
self.lc = '#000000'
self.cc = '#778899'
self.gc = '#ffffff'
self.gt = '#000000'
self.bc = '#bdbdbd'
self.bg = '#ffffff'
self.fs = 13
self.sfs = 8
self.disptex = {
'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'
}
self.dispcol = {
'id': '#ffffff',
'u0': '#ffffff',
'u1': '#ffffff',
'u2': '#ffffff',
'u3': '#ffffff',
'x': '#ffffff',
'y': '#ffffff',
'z': '#ffffff',
'h': '#ffffff',
's': '#ffffff',
'sdg': '#ffffff',
't': '#ffffff',
'tdg': '#ffffff',
'rx': '#ffffff',
'ry': '#ffffff',
'rz': '#ffffff',
'reset': '#ffffff',
'target': '#ffffff',
'meas': '#ffffff'
}
self.latexmode = True
self.pimode = False
self.fold = 20
self.bundle = False
self.barrier = False
self.index = False
self.compress = True
self.figwidth = -1
self.dpi = 150
self.margin = [2.0, 0.0, 0.0, 0.3]
self.cline = 'doublet'
self.reverse = False
def set_style(self, dic):
self.tc = dic.get('textcolor', self.tc)
self.sc = dic.get('subtextcolor', self.sc)
self.lc = dic.get('linecolor', self.lc)
self.cc = dic.get('creglinecolor', self.cc)
self.gt = dic.get('gatetextcolor', self.tc)
self.gc = dic.get('gatefacecolor', self.gc)
self.bc = dic.get('barrierfacecolor', self.bc)
self.bg = dic.get('backgroundcolor', self.bg)
self.fs = dic.get('fontsize', self.fs)
self.sfs = dic.get('subfontsize', self.sfs)
self.disptex = dic.get('displaytext', self.disptex)
for key in self.dispcol.keys():
self.dispcol[key] = self.gc
self.dispcol = dic.get('displaycolor', self.dispcol)
self.latexmode = dic.get('latexdrawerstyle', self.latexmode)
self.pimode = dic.get('usepiformat', self.pimode)
self.fold = dic.get('fold', self.fold)
if self.fold < 2:
self.fold = -1
self.bundle = dic.get('cregbundle', self.bundle)
self.barrier = dic.get('plotbarrier', self.barrier)
self.index = dic.get('showindex', self.index)
self.compress = dic.get('compress', self.compress)
self.figwidth = dic.get('figwidth', self.figwidth)
self.dpi = dic.get('dpi', self.dpi)
self.margin = dic.get('margin', self.margin)
self.cline = dic.get('creglinestyle', self.cline)
self.reverse = dic.get('reversebits', self.reverse)
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": False,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to complile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def _trim(im):
"""Trim image and remove white space
"""
bg = Image.new(im.mode, im.size, im.getpixel((0, 0)))
diff = ImageChops.difference(im, bg)
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
im = im.crop(bbox)
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
qcimg = QCircuitImage(json_circuit, scale, style=style)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, circuit, scale, style=None):
"""
Args:
circuit (dict): compiled_circuit from qobj
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
"""
# style sheet
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.circuit = circuit
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
#################################
self.header = self.circuit['header']
self.qregs = OrderedDict(_get_register_specs(
self.header['qubit_labels']))
self.qubit_list = []
for qr in self.qregs:
for i in range(self.qregs[qr]):
self.qubit_list.append((qr, i))
self.cregs = OrderedDict()
if 'clbit_labels' in self.header:
for item in self.header['clbit_labels']:
self.cregs[item[0]] = item[1]
self.clbit_list = []
cregs = self.cregs
if self._style.reverse:
self.orig_cregs = self.cregs
cregs = reversed(self.cregs)
for cr in cregs:
for i in range(self.cregs[cr]):
self.clbit_list.append((cr, i))
self.ordered_regs = [(item[0], item[1]) for
item in self.header['qubit_labels']]
if self._style.reverse:
reg_size = []
reg_labels = []
new_ordered_regs = []
for regs in self.ordered_regs:
if regs[0] in reg_labels:
continue
reg_labels.append(regs[0])
reg_size.append(len(
[x for x in self.ordered_regs if x[0] == regs[0]]))
index = 0
for size in reg_size:
new_index = index + size
for i in range(new_index - 1, index - 1, -1):
new_ordered_regs.append(self.ordered_regs[i])
index = new_index
self.ordered_regs = new_ordered_regs
if 'clbit_labels' in self.header:
for clabel in self.header['clbit_labels']:
if self._style.reverse:
for cind in reversed(range(clabel[1])):
self.ordered_regs.append((clabel[0], cind))
else:
for cind in range(clabel[1]):
self.ordered_regs.append((clabel[0], cind))
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\'+'\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
QISKitError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.circuit['instructions']:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's', 'sdg',
't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy', 'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['texparams']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, arg)
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
assert len(op['clbits']) == 1 and len(op['qubits']) == 1
if 'conditional' in op:
raise QISKitError('conditional measures currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise QISKitError('conditional reset currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
assert False, "bad node data"
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns+1, ceil(sum_column_widths)+4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above example,
index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _convert_mask(self, mask):
orig_clbit_list = []
for cr in self.orig_cregs:
for i in range(self.orig_cregs[cr]):
orig_clbit_list.append((cr, i))
bit_list = [(mask >> bit) & 1 for bit in range(
len(orig_clbit_list) - 1, -1, -1)]
converted_mask_list = [None] * len(bit_list)
converted_mask = 0
for pos, bit in enumerate(reversed(bit_list)):
new_pos = self.clbit_list.index(orig_clbit_list[pos])
converted_mask_list[new_pos] = bit
if None in converted_mask_list:
raise VisualizationError('Reverse mask creation failed')
converted_mask_list = list(reversed(converted_mask_list))
for bit in converted_mask_list:
converted_mask = (converted_mask << 1) | bit
return converted_mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.circuit['instructions']):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier']:
nm = op['name']
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] =\
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
elif nm == "reset":
self._latex[pos_1][columns] = \
"\\push{\\rule{.6em}{0em}\\ket{0}\\rule{.2em}{0em}} \\qw"
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
assert len(op['clbits']) == 1 and \
len(op['qubits']) == 1 and \
'params' not in op, "bad operation record"
if 'conditional' in op:
assert False, "If controlled measures currently not supported."
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise QISKitError('Error during Latex building: %s' %
str(e))
elif op['name'] == "barrier":
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qubits']) - 1
self._latex[start][columns] += " \\barrier{" + str(span) + "}"
else:
assert False, "bad node data"
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
if self._style.reverse:
return origin + 1
return origin - 1
def _get_register_specs(bit_labels):
"""
Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = MatplotlibDrawer(basis=basis, scale=scale, style=style)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
Register = namedtuple('Register', 'name index')
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=1.0, style=None):
self._ast = None
self._basis = basis
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = OrderedDict()
self._creg_dict = OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False, labelleft=False, labelright=False)
def load_qasm_file(self, filename):
circuit = load_qasm_file(filename, name='draw', basis_gates=self._basis)
self.parse_circuit(circuit)
def parse_circuit(self, circuit: QuantumCircuit):
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
self._ast = transpile(dag_circuit, basis_gates=self._basis, format='json')
self._registers()
self._ops = self._ast['instructions']
def _registers(self):
# NOTE: formats of clbit and qubit are different!
header = self._ast['header']
self._creg = []
for e in header['clbit_labels']:
for i in range(e[1]):
self._creg.append(Register(name=e[0], index=i))
assert len(self._creg) == header['number_of_clbits']
self._qreg = []
for e in header['qubit_labels']:
self._qreg.append(Register(name=e[0], index=e[1]))
assert len(self._qreg) == header['number_of_qubits']
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.sc,
clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7, height=HIG * 0.7,
theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID], [qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy+0.35*WID], lc=self._style.cc, ls=self._style.cline)
arrowhead = patches.Polygon(((cx-0.20*WID, cy+0.35*WID),
(cx+0.20*WID, cy+0.35*WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'], ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if get_matplotlib_backend() == 'module://ipykernel.pylab.backend_inline':
# returns None when matplotlib is inline mode to prevent Jupyter
# with matplotlib inlining enabled to draw the diagram twice.
im = None
else:
# when matplotlib is not inline mode,
# self.figure.savefig is called twice because...
# ... this is needed to get the in-memory representation
with tempfile.TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, 'circuit.png')
self.figure.savefig(tmpfile, dpi=self._style.dpi,
bbox_inches='tight')
im = Image.open(tmpfile)
_trim(im)
os.remove(tmpfile)
# ... and this is needed to delegate in matplotlib the generation of
# the proper format.
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
return im
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index, 'group': reg.name}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(zip_longest(self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
self._cond['n_lines'] += 1
idx += 1
# reverse bit order
if self._style.reverse:
self._reverse_bits(self._qreg_dict)
self._reverse_bits(self._creg_dict)
def _reverse_bits(self, target_dict):
coord = {}
# grouping
for dict_ in target_dict.values():
if dict_['group'] not in coord:
coord[dict_['group']] = [dict_['y']]
else:
coord[dict_['group']].insert(0, dict_['y'])
# reverse bit order
for key in target_dict.keys():
target_dict[key]['y'] = coord[target_dict[key]['group']].pop(0)
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc, ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qubits' in op.keys():
q_idxs = op['qubits']
else:
q_idxs = []
# get creg index
if 'clbits' in op.keys():
c_idxs = op['clbits']
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied), max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] == 'barrier' and not self._style.barrier:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg corrdinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc, ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] == 'barrier':
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self._style.barrier:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise QISKitError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if isclose(fmod(abs_val, 1.0), 0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
elif 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return Fraction(i, j)
return None
<|code_end|>
|
Need a dag visualizer
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected behavior?
A dag visualizer is important for developing transpiler passes. It should be easy to use like the circuit visualizer.
|
qiskit/tools/visualization/__init__.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Main QISKit visualization methods."""
import sys
from qiskit._util import _has_connection
from ._circuit_visualization import circuit_drawer, plot_circuit, generate_latex_source,\
latex_circuit_drawer, matplotlib_circuit_drawer, qx_color_scheme
from ._error import VisualizationError
from ._state_visualization import plot_bloch_vector
if ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
if _has_connection('https://qvisualization.mybluemix.net/', 443):
from .interactive._iplot_state import iplot_state as plot_state
from .interactive._iplot_histogram import iplot_histogram as \
plot_histogram
else:
from ._state_visualization import plot_state
from ._counts_visualization import plot_histogram
else:
from ._state_visualization import plot_state
from ._counts_visualization import plot_histogram
<|code_end|>
qiskit/tools/visualization/_dag_visualization.py
<|code_start|><|code_end|>
|
qiskit/tools/visualization/__init__.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Main Qiskit visualization methods."""
import sys
from qiskit._util import _has_connection
from ._circuit_visualization import circuit_drawer, plot_circuit, generate_latex_source,\
latex_circuit_drawer, matplotlib_circuit_drawer, qx_color_scheme
from ._error import VisualizationError
from ._state_visualization import plot_bloch_vector
from ._dag_visualization import dag_drawer
if ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
if _has_connection('https://qvisualization.mybluemix.net/', 443):
from .interactive._iplot_state import iplot_state as plot_state
from .interactive._iplot_histogram import iplot_histogram as \
plot_histogram
else:
from ._state_visualization import plot_state
from ._counts_visualization import plot_histogram
else:
from ._state_visualization import plot_state
from ._counts_visualization import plot_histogram
<|code_end|>
qiskit/tools/visualization/_dag_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""
Visualization function for DAG circuit representation.
"""
import sys
import copy
import nxpd
from ._error import VisualizationError
def dag_drawer(dag, scale=0.7, filename=None, style='color'):
"""Plot the directed acyclic graph (dag) to represent operation dependencies
in a quantum circuit.
Args:
dag (DAGCircuit): The dag to draw.
scale (float): scaling factor
filename (str): file path to save image to (format inferred from name)
style (str): 'plain': B&W graph
'color' (default): color input/output/op nodes
Returns:
Ipython.display.Image: if in Jupyter notebook and not saving to file,
otherwise None.
Raises:
VisualizationError: when style is not recognized.
"""
G = copy.deepcopy(dag.multi_graph) # don't modify the original graph attributes
G.graph['dpi'] = 100 * scale
if style == 'plain':
pass
elif style == 'color':
for n in G.nodes:
G.nodes[n]['label'] = str(G.nodes[n]['name'])
if G.nodes[n]['type'] == 'op':
G.nodes[n]['color'] = 'blue'
G.nodes[n]['style'] = 'filled'
G.nodes[n]['fillcolor'] = 'lightblue'
if G.nodes[n]['type'] == 'in':
G.nodes[n]['color'] = 'black'
G.nodes[n]['style'] = 'filled'
G.nodes[n]['fillcolor'] = 'green'
if G.nodes[n]['type'] == 'out':
G.nodes[n]['color'] = 'black'
G.nodes[n]['style'] = 'filled'
G.nodes[n]['fillcolor'] = 'red'
else:
raise VisualizationError("Unrecognized style for the dag_drawer.")
show = nxpd.nxpdParams['show']
if filename:
show = False
elif ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
show = 'ipynb'
else:
show = True
return nxpd.draw(G, filename=filename, show=show)
<|code_end|>
|
follow up from #948 add a remove_all_accounts() command
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
removed many accounts are annoying we need a remove_all command
|
qiskit/backends/ibmq/ibmqprovider.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Provider for remote IBMQ backends with admin features."""
from collections import OrderedDict
from qiskit.backends import BaseProvider
from .credentials._configrc import remove_credentials
from .credentials import (Credentials,
read_credentials_from_qiskitrc, store_credentials, discover_credentials)
from .ibmqaccounterror import IBMQAccountError
from .ibmqsingleprovider import IBMQSingleProvider
QE_URL = 'https://quantumexperience.ng.bluemix.net/api'
class IBMQProvider(BaseProvider):
"""Provider for remote IBMQ backends with admin features.
This class is the entry point for handling backends from IBMQ, allowing
using different accounts.
"""
def __init__(self):
super().__init__()
# dict[credentials_unique_id: IBMQSingleProvider]
# This attribute stores a reference to the different accounts. The
# keys are tuples (hub, group, project), as the convention is that
# that tuple uniquely identifies a set of credentials.
self._accounts = OrderedDict()
def backends(self, name=None, filters=None, **kwargs):
# pylint: disable=arguments-differ
def _match_all(obj, criteria):
"""Return True if all items in criteria matches items in obj."""
return all(getattr(obj, key_, None) == value_ for
key_, value_ in criteria.items())
# Special handling of the credentials filters.
credentials_filter = {}
for key in ['token', 'url', 'hub', 'group', 'project']:
if key in kwargs:
credentials_filter[key] = kwargs.pop(key)
providers = [provider for provider in self._accounts.values() if
_match_all(provider.credentials, credentials_filter)]
# Special handling of the `name` parameter, to support alias resolution.
if name:
aliases = self.aliased_backend_names()
aliases.update(self.deprecated_backend_names())
name = aliases.get(name, name)
# Aggregate the list of filtered backends.
backends = []
for provider in providers:
backends = backends + provider.backends(
name=name, filters=filters, **kwargs)
return backends
@staticmethod
def deprecated_backend_names():
"""Returns deprecated backend names."""
return {
'ibmqx_qasm_simulator': 'ibmq_qasm_simulator',
'ibmqx_hpc_qasm_simulator': 'ibmq_qasm_simulator',
'real': 'ibmqx1'
}
@staticmethod
def aliased_backend_names():
"""Returns aliased backend names."""
return {
'ibmq_5_yorktown': 'ibmqx2',
'ibmq_5_tenerife': 'ibmqx4',
'ibmq_16_rueschlikon': 'ibmqx5',
'ibmq_20_austin': 'QS1_1'
}
def add_account(self, token, url=QE_URL, **kwargs):
"""Authenticate against IBMQ and store the account for future use.
Login into Quantum Experience or IBMQ using the provided credentials,
adding the account to the current session. The account is stored in
disk for future use.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
Raises:
IBMQAccountError: if the credentials are already in use.
"""
credentials = Credentials(token, url, **kwargs)
# Check if duplicated credentials are already stored. By convention,
# we assume (hub, group, project) is always unique.
stored_credentials = read_credentials_from_qiskitrc()
if credentials.unique_id() in stored_credentials.keys():
raise IBMQAccountError('Credentials are already stored')
self._append_account(credentials)
# Store the credentials back to disk.
store_credentials(credentials)
def remove_account(self, token, url=QE_URL, **kwargs):
"""Remove an account from the session and from disk.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
Raises:
IBMQAccountError: if the credentials could not be removed.
"""
removed = False
credentials = Credentials(token, url, **kwargs)
# Check if the credentials are already stored in session or disk. By
# convention, we assume (hub, group, project) is always unique.
stored_credentials = read_credentials_from_qiskitrc()
# Try to remove from session.
if credentials.unique_id() in self._accounts.keys():
del self._accounts[credentials.unique_id()]
removed = True
# Try to remove from disk.
if credentials.unique_id() in stored_credentials.keys():
remove_credentials(credentials)
removed = True
if not removed:
raise IBMQAccountError('Unable to find credentials')
def use_account(self, token, url=QE_URL, **kwargs):
"""Authenticate against IBMQ during this session.
Login into Quantum Experience or IBMQ using the provided credentials,
adding the account to the current session. The account is not stored
in disk.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
"""
credentials = Credentials(token, url, **kwargs)
self._append_account(credentials)
def list_accounts(self):
"""List all accounts currently stored in the session.
Returns:
list[dict]: a list with information about the accounts currently
in the session.
"""
information = []
for provider in self._accounts.values():
information.append({
'token': provider.credentials.token,
'url': provider.credentials.url,
})
return information
def load_accounts(self):
"""Load all accounts found in the system.
Automatically load all the accounts found in the system. This method
looks for credentials in the following locations, in order, and
returning as soon as credentials are found::
1. in the `Qconfig.py` file in the current working directory.
2. in the environment variables.
3. in the `qiskitrc` configuration file
Raises:
IBMQAccountError: if there already loaded accounts in the session, or
no credentials could be found.
"""
if self._accounts:
raise IBMQAccountError('The account list is not empty')
for credentials in discover_credentials().values():
self._append_account(credentials)
if not self._accounts:
raise IBMQAccountError('No IBMQ credentials found')
def _append_account(self, credentials):
"""Append an account with the specified credentials to the session.
Args:
credentials (Credentials): set of credentials.
Returns:
IBMQSingleProvider: new single-account provider.
Raises:
IBMQAccountError: if the provider could not be appended.
"""
# Check if duplicated credentials are already in use. By convention,
# we assume (hub, group, project) is always unique.
if credentials.unique_id() in self._accounts.keys():
raise IBMQAccountError('Credentials are already in use')
single_provider = IBMQSingleProvider(credentials, self)
self._accounts[credentials.unique_id()] = single_provider
return single_provider
<|code_end|>
|
qiskit/backends/ibmq/ibmqprovider.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Provider for remote IBMQ backends with admin features."""
from collections import OrderedDict
from qiskit.backends import BaseProvider
from .credentials._configrc import remove_credentials
from .credentials import (Credentials,
read_credentials_from_qiskitrc, store_credentials, discover_credentials)
from .ibmqaccounterror import IBMQAccountError
from .ibmqsingleprovider import IBMQSingleProvider
QE_URL = 'https://quantumexperience.ng.bluemix.net/api'
class IBMQProvider(BaseProvider):
"""Provider for remote IBMQ backends with admin features.
This class is the entry point for handling backends from IBMQ, allowing
using different accounts.
"""
def __init__(self):
super().__init__()
# dict[credentials_unique_id: IBMQSingleProvider]
# This attribute stores a reference to the different accounts. The
# keys are tuples (hub, group, project), as the convention is that
# that tuple uniquely identifies a set of credentials.
self._accounts = OrderedDict()
def backends(self, name=None, filters=None, **kwargs):
# pylint: disable=arguments-differ
def _match_all(obj, criteria):
"""Return True if all items in criteria matches items in obj."""
return all(getattr(obj, key_, None) == value_ for
key_, value_ in criteria.items())
# Special handling of the credentials filters.
credentials_filter = {}
for key in ['token', 'url', 'hub', 'group', 'project']:
if key in kwargs:
credentials_filter[key] = kwargs.pop(key)
providers = [provider for provider in self._accounts.values() if
_match_all(provider.credentials, credentials_filter)]
# Special handling of the `name` parameter, to support alias resolution.
if name:
aliases = self.aliased_backend_names()
aliases.update(self.deprecated_backend_names())
name = aliases.get(name, name)
# Aggregate the list of filtered backends.
backends = []
for provider in providers:
backends = backends + provider.backends(
name=name, filters=filters, **kwargs)
return backends
@staticmethod
def deprecated_backend_names():
"""Returns deprecated backend names."""
return {
'ibmqx_qasm_simulator': 'ibmq_qasm_simulator',
'ibmqx_hpc_qasm_simulator': 'ibmq_qasm_simulator',
'real': 'ibmqx1'
}
@staticmethod
def aliased_backend_names():
"""Returns aliased backend names."""
return {
'ibmq_5_yorktown': 'ibmqx2',
'ibmq_5_tenerife': 'ibmqx4',
'ibmq_16_rueschlikon': 'ibmqx5',
'ibmq_20_austin': 'QS1_1'
}
def add_account(self, token, url=QE_URL, **kwargs):
"""Authenticate against IBMQ and store the account for future use.
Login into Quantum Experience or IBMQ using the provided credentials,
adding the account to the current session. The account is stored in
disk for future use.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
Raises:
IBMQAccountError: if the credentials are already in use.
"""
credentials = Credentials(token, url, **kwargs)
# Check if duplicated credentials are already stored. By convention,
# we assume (hub, group, project) is always unique.
stored_credentials = read_credentials_from_qiskitrc()
if credentials.unique_id() in stored_credentials.keys():
raise IBMQAccountError('Credentials are already stored')
self._append_account(credentials)
# Store the credentials back to disk.
store_credentials(credentials)
def remove_account(self, token, url=QE_URL, **kwargs):
"""Remove an account from the session and from disk.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
Raises:
IBMQAccountError: if the credentials could not be removed.
"""
removed = False
credentials = Credentials(token, url, **kwargs)
# Check if the credentials are already stored in session or disk. By
# convention, we assume (hub, group, project) is always unique.
stored_credentials = read_credentials_from_qiskitrc()
# Try to remove from session.
if credentials.unique_id() in self._accounts.keys():
del self._accounts[credentials.unique_id()]
removed = True
# Try to remove from disk.
if credentials.unique_id() in stored_credentials.keys():
remove_credentials(credentials)
removed = True
if not removed:
raise IBMQAccountError('Unable to find credentials')
def remove_accounts(self):
"""Remove all accounts from this session and optionally from disk."""
current_creds = self._accounts.copy()
for creds in current_creds:
self.remove_account(current_creds[creds].credentials.token,
current_creds[creds].credentials.url)
def use_account(self, token, url=QE_URL, **kwargs):
"""Authenticate against IBMQ during this session.
Login into Quantum Experience or IBMQ using the provided credentials,
adding the account to the current session. The account is not stored
in disk.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
"""
credentials = Credentials(token, url, **kwargs)
self._append_account(credentials)
def list_accounts(self):
"""List all accounts currently stored in the session.
Returns:
list[dict]: a list with information about the accounts currently
in the session.
"""
information = []
for provider in self._accounts.values():
information.append({
'token': provider.credentials.token,
'url': provider.credentials.url,
})
return information
def load_accounts(self):
"""Load all accounts found in the system.
Automatically load all the accounts found in the system. This method
looks for credentials in the following locations, in order, and
returning as soon as credentials are found::
1. in the `Qconfig.py` file in the current working directory.
2. in the environment variables.
3. in the `qiskitrc` configuration file
Raises:
IBMQAccountError: if there already loaded accounts in the session, or
no credentials could be found.
"""
if self._accounts:
raise IBMQAccountError('The account list is not empty')
for credentials in discover_credentials().values():
self._append_account(credentials)
if not self._accounts:
raise IBMQAccountError('No IBMQ credentials found')
def _append_account(self, credentials):
"""Append an account with the specified credentials to the session.
Args:
credentials (Credentials): set of credentials.
Returns:
IBMQSingleProvider: new single-account provider.
Raises:
IBMQAccountError: if the provider could not be appended.
"""
# Check if duplicated credentials are already in use. By convention,
# we assume (hub, group, project) is always unique.
if credentials.unique_id() in self._accounts.keys():
raise IBMQAccountError('Credentials are already in use')
single_provider = IBMQSingleProvider(credentials, self)
self._accounts[credentials.unique_id()] = single_provider
return single_provider
<|code_end|>
|
Calling IBMQ.load_accounts() twice should give warning, not exception
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: latest master
- **Python version**: 3.7
- **Operating system**: OSX
### What is the current behavior?
Calling `IBMQ.load_accounts()` twice gives an Exception. However, in notebooks, it is common to just run multiple cells (or whole notebooks) repeatedly. Raising an exception breaks this convenient workflow. A similar issue, #673 , was raised and corrected, previously.
### Steps to reproduce the problem
### What is the expected behavior?
### Suggested solutions
Make repeated calls to `IBMQ.load_accounts()` give a warning instead.
|
qiskit/backends/ibmq/ibmqprovider.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Provider for remote IBMQ backends with admin features."""
from collections import OrderedDict
from qiskit.backends import BaseProvider
from .credentials._configrc import remove_credentials
from .credentials import (Credentials,
read_credentials_from_qiskitrc, store_credentials, discover_credentials)
from .ibmqaccounterror import IBMQAccountError
from .ibmqsingleprovider import IBMQSingleProvider
QE_URL = 'https://quantumexperience.ng.bluemix.net/api'
class IBMQProvider(BaseProvider):
"""Provider for remote IBMQ backends with admin features.
This class is the entry point for handling backends from IBMQ, allowing
using different accounts.
"""
def __init__(self):
super().__init__()
# dict[credentials_unique_id: IBMQSingleProvider]
# This attribute stores a reference to the different accounts. The
# keys are tuples (hub, group, project), as the convention is that
# that tuple uniquely identifies a set of credentials.
self._accounts = OrderedDict()
def backends(self, name=None, filters=None, **kwargs):
# pylint: disable=arguments-differ
def _match_all(obj, criteria):
"""Return True if all items in criteria matches items in obj."""
return all(getattr(obj, key_, None) == value_ for
key_, value_ in criteria.items())
# Special handling of the credentials filters.
credentials_filter = {}
for key in ['token', 'url', 'hub', 'group', 'project']:
if key in kwargs:
credentials_filter[key] = kwargs.pop(key)
providers = [provider for provider in self._accounts.values() if
_match_all(provider.credentials, credentials_filter)]
# Special handling of the `name` parameter, to support alias resolution.
if name:
aliases = self.aliased_backend_names()
aliases.update(self.deprecated_backend_names())
name = aliases.get(name, name)
# Aggregate the list of filtered backends.
backends = []
for provider in providers:
backends = backends + provider.backends(
name=name, filters=filters, **kwargs)
return backends
@staticmethod
def deprecated_backend_names():
"""Returns deprecated backend names."""
return {
'ibmqx_qasm_simulator': 'ibmq_qasm_simulator',
'ibmqx_hpc_qasm_simulator': 'ibmq_qasm_simulator',
'real': 'ibmqx1'
}
@staticmethod
def aliased_backend_names():
"""Returns aliased backend names."""
return {
'ibmq_5_yorktown': 'ibmqx2',
'ibmq_5_tenerife': 'ibmqx4',
'ibmq_16_rueschlikon': 'ibmqx5',
'ibmq_20_austin': 'QS1_1'
}
def add_account(self, token, url=QE_URL, **kwargs):
"""Authenticate against IBMQ and store the account for future use.
Login into Quantum Experience or IBMQ using the provided credentials,
adding the account to the current session. The account is stored in
disk for future use.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
Raises:
IBMQAccountError: if the credentials are already in use.
"""
credentials = Credentials(token, url, **kwargs)
# Check if duplicated credentials are already stored. By convention,
# we assume (hub, group, project) is always unique.
stored_credentials = read_credentials_from_qiskitrc()
if credentials.unique_id() in stored_credentials.keys():
raise IBMQAccountError('Credentials are already stored')
self._append_account(credentials)
# Store the credentials back to disk.
store_credentials(credentials)
def remove_account(self, token, url=QE_URL, **kwargs):
"""Remove an account from the session and from disk.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
Raises:
IBMQAccountError: if the credentials could not be removed.
"""
removed = False
credentials = Credentials(token, url, **kwargs)
# Check if the credentials are already stored in session or disk. By
# convention, we assume (hub, group, project) is always unique.
stored_credentials = read_credentials_from_qiskitrc()
# Try to remove from session.
if credentials.unique_id() in self._accounts.keys():
del self._accounts[credentials.unique_id()]
removed = True
# Try to remove from disk.
if credentials.unique_id() in stored_credentials.keys():
remove_credentials(credentials)
removed = True
if not removed:
raise IBMQAccountError('Unable to find credentials')
def remove_accounts(self):
"""Remove all accounts from this session and optionally from disk."""
current_creds = self._accounts.copy()
for creds in current_creds:
self.remove_account(current_creds[creds].credentials.token,
current_creds[creds].credentials.url)
def use_account(self, token, url=QE_URL, **kwargs):
"""Authenticate against IBMQ during this session.
Login into Quantum Experience or IBMQ using the provided credentials,
adding the account to the current session. The account is not stored
in disk.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
"""
credentials = Credentials(token, url, **kwargs)
self._append_account(credentials)
def list_accounts(self):
"""List all accounts currently stored in the session.
Returns:
list[dict]: a list with information about the accounts currently
in the session.
"""
information = []
for provider in self._accounts.values():
information.append({
'token': provider.credentials.token,
'url': provider.credentials.url,
})
return information
def load_accounts(self):
"""Load all accounts found in the system.
Automatically load all the accounts found in the system. This method
looks for credentials in the following locations, in order, and
returning as soon as credentials are found::
1. in the `Qconfig.py` file in the current working directory.
2. in the environment variables.
3. in the `qiskitrc` configuration file
Raises:
IBMQAccountError: if there already loaded accounts in the session, or
no credentials could be found.
"""
if self._accounts:
raise IBMQAccountError('The account list is not empty')
for credentials in discover_credentials().values():
self._append_account(credentials)
if not self._accounts:
raise IBMQAccountError('No IBMQ credentials found')
def _append_account(self, credentials):
"""Append an account with the specified credentials to the session.
Args:
credentials (Credentials): set of credentials.
Returns:
IBMQSingleProvider: new single-account provider.
Raises:
IBMQAccountError: if the provider could not be appended.
"""
# Check if duplicated credentials are already in use. By convention,
# we assume (hub, group, project) is always unique.
if credentials.unique_id() in self._accounts.keys():
raise IBMQAccountError('Credentials are already in use')
single_provider = IBMQSingleProvider(credentials, self)
self._accounts[credentials.unique_id()] = single_provider
return single_provider
<|code_end|>
|
qiskit/backends/ibmq/ibmqprovider.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Provider for remote IBMQ backends with admin features."""
from collections import OrderedDict
from qiskit.backends import BaseProvider
from .credentials._configrc import remove_credentials
from .credentials import (Credentials,
read_credentials_from_qiskitrc, store_credentials, discover_credentials)
from .ibmqaccounterror import IBMQAccountError
from .ibmqsingleprovider import IBMQSingleProvider
QE_URL = 'https://quantumexperience.ng.bluemix.net/api'
class IBMQProvider(BaseProvider):
"""Provider for remote IBMQ backends with admin features.
This class is the entry point for handling backends from IBMQ, allowing
using different accounts.
"""
def __init__(self):
super().__init__()
# dict[credentials_unique_id: IBMQSingleProvider]
# This attribute stores a reference to the different accounts. The
# keys are tuples (hub, group, project), as the convention is that
# that tuple uniquely identifies a set of credentials.
self._accounts = OrderedDict()
def backends(self, name=None, filters=None, **kwargs):
# pylint: disable=arguments-differ
# Special handling of the credentials filters.
credentials_filter = {}
for key in ['token', 'url', 'hub', 'group', 'project']:
if key in kwargs:
credentials_filter[key] = kwargs.pop(key)
providers = [provider for provider in self._accounts.values() if
self._match_all(provider.credentials, credentials_filter)]
# Special handling of the `name` parameter, to support alias resolution.
if name:
aliases = self.aliased_backend_names()
aliases.update(self.deprecated_backend_names())
name = aliases.get(name, name)
# Aggregate the list of filtered backends.
backends = []
for provider in providers:
backends = backends + provider.backends(
name=name, filters=filters, **kwargs)
return backends
@staticmethod
def deprecated_backend_names():
"""Returns deprecated backend names."""
return {
'ibmqx_qasm_simulator': 'ibmq_qasm_simulator',
'ibmqx_hpc_qasm_simulator': 'ibmq_qasm_simulator',
'real': 'ibmqx1'
}
@staticmethod
def aliased_backend_names():
"""Returns aliased backend names."""
return {
'ibmq_5_yorktown': 'ibmqx2',
'ibmq_5_tenerife': 'ibmqx4',
'ibmq_16_rueschlikon': 'ibmqx5',
'ibmq_20_austin': 'QS1_1'
}
def add_account(self, token, url=QE_URL, **kwargs):
"""Authenticate against IBMQ and store the account for future use.
Login into Quantum Experience or IBMQ using the provided credentials,
adding the account to the current session. The account is stored in
disk for future use.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
Raises:
IBMQAccountError: if the credentials are already in use.
"""
credentials = Credentials(token, url, **kwargs)
# Check if duplicated credentials are already stored. By convention,
# we assume (hub, group, project) is always unique.
stored_credentials = read_credentials_from_qiskitrc()
if credentials.unique_id() in stored_credentials.keys():
raise IBMQAccountError('Credentials are already stored')
self._append_account(credentials)
# Store the credentials back to disk.
store_credentials(credentials)
def remove_account(self, token, url=QE_URL, **kwargs):
"""Remove an account from the session and from disk.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
Raises:
IBMQAccountError: if the credentials could not be removed.
"""
removed = False
credentials = Credentials(token, url, **kwargs)
# Check if the credentials are already stored in session or disk. By
# convention, we assume (hub, group, project) is always unique.
stored_credentials = read_credentials_from_qiskitrc()
# Try to remove from session.
if credentials.unique_id() in self._accounts.keys():
del self._accounts[credentials.unique_id()]
removed = True
# Try to remove from disk.
if credentials.unique_id() in stored_credentials.keys():
remove_credentials(credentials)
removed = True
if not removed:
raise IBMQAccountError('Unable to find credentials')
def remove_accounts(self):
"""Remove all accounts from this session and optionally from disk."""
current_creds = self._accounts.copy()
for creds in current_creds:
self.remove_account(current_creds[creds].credentials.token,
current_creds[creds].credentials.url)
def use_account(self, token, url=QE_URL, **kwargs):
"""Authenticate against IBMQ during this session.
Login into Quantum Experience or IBMQ using the provided credentials,
adding the account to the current session. The account is not stored
in disk.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
"""
credentials = Credentials(token, url, **kwargs)
self._append_account(credentials)
def list_accounts(self):
"""List all accounts currently stored in the session.
Returns:
list[dict]: a list with information about the accounts currently
in the session.
"""
information = []
for provider in self._accounts.values():
information.append({
'token': provider.credentials.token,
'url': provider.credentials.url,
})
return information
def load_accounts(self, **kwargs):
"""Load IBMQ accounts found in the system, subject to optional filtering.
Automatically load the accounts found in the system. This method
looks for credentials in the following locations, in order, and
returns as soon as credentials are found:
1. in the `Qconfig.py` file in the current working directory.
2. in the environment variables.
3. in the `qiskitrc` configuration file
Raises:
IBMQAccountError: if attempting to load previously loaded accounts,
or if no credentials can be found.
"""
# Special handling of the credentials filters.
credentials_filter = {}
for key in ['token', 'url', 'hub', 'group', 'project']:
if key in kwargs:
credentials_filter[key] = kwargs.pop(key)
for credentials in discover_credentials().values():
if self._match_all(credentials, credentials_filter):
self._append_account(credentials)
if not self._accounts:
raise IBMQAccountError('No IBMQ credentials found.')
def _append_account(self, credentials):
"""Append an account with the specified credentials to the session.
Args:
credentials (Credentials): set of credentials.
Returns:
IBMQSingleProvider: new single-account provider.
Raises:
IBMQAccountError: if the provider could not be appended.
"""
# Check if duplicated credentials are already in use. By convention,
# we assume (hub, group, project) is always unique.
if credentials.unique_id() in self._accounts.keys():
raise IBMQAccountError('Credentials are already in use')
single_provider = IBMQSingleProvider(credentials, self)
self._accounts[credentials.unique_id()] = single_provider
return single_provider
def _match_all(self, obj, criteria):
"""Return True if all items in criteria matches items in obj."""
return all(getattr(obj, key_, None) == value_ for
key_, value_ in criteria.items())
<|code_end|>
|
Calling IBMQ.load_accounts() twice should give warning, not exception
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: latest master
- **Python version**: 3.7
- **Operating system**: OSX
### What is the current behavior?
Calling `IBMQ.load_accounts()` twice gives an Exception. However, in notebooks, it is common to just run multiple cells (or whole notebooks) repeatedly. Raising an exception breaks this convenient workflow. A similar issue, #673 , was raised and corrected, previously.
### Steps to reproduce the problem
### What is the expected behavior?
### Suggested solutions
Make repeated calls to `IBMQ.load_accounts()` give a warning instead.
|
qiskit/backends/ibmq/ibmqprovider.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Provider for remote IBMQ backends with admin features."""
from collections import OrderedDict
from qiskit.backends import BaseProvider
from .credentials._configrc import remove_credentials
from .credentials import (Credentials,
read_credentials_from_qiskitrc, store_credentials, discover_credentials)
from .ibmqaccounterror import IBMQAccountError
from .ibmqsingleprovider import IBMQSingleProvider
QE_URL = 'https://quantumexperience.ng.bluemix.net/api'
class IBMQProvider(BaseProvider):
"""Provider for remote IBMQ backends with admin features.
This class is the entry point for handling backends from IBMQ, allowing
using different accounts.
"""
def __init__(self):
super().__init__()
# dict[credentials_unique_id: IBMQSingleProvider]
# This attribute stores a reference to the different accounts. The
# keys are tuples (hub, group, project), as the convention is that
# that tuple uniquely identifies a set of credentials.
self._accounts = OrderedDict()
def backends(self, name=None, filters=None, **kwargs):
# pylint: disable=arguments-differ
# Special handling of the credentials filters.
credentials_filter = {}
for key in ['token', 'url', 'hub', 'group', 'project']:
if key in kwargs:
credentials_filter[key] = kwargs.pop(key)
providers = [provider for provider in self._accounts.values() if
self._match_all(provider.credentials, credentials_filter)]
# Special handling of the `name` parameter, to support alias resolution.
if name:
aliases = self.aliased_backend_names()
aliases.update(self.deprecated_backend_names())
name = aliases.get(name, name)
# Aggregate the list of filtered backends.
backends = []
for provider in providers:
backends = backends + provider.backends(
name=name, filters=filters, **kwargs)
return backends
@staticmethod
def deprecated_backend_names():
"""Returns deprecated backend names."""
return {
'ibmqx_qasm_simulator': 'ibmq_qasm_simulator',
'ibmqx_hpc_qasm_simulator': 'ibmq_qasm_simulator',
'real': 'ibmqx1'
}
@staticmethod
def aliased_backend_names():
"""Returns aliased backend names."""
return {
'ibmq_5_yorktown': 'ibmqx2',
'ibmq_5_tenerife': 'ibmqx4',
'ibmq_16_rueschlikon': 'ibmqx5',
'ibmq_20_austin': 'QS1_1'
}
def add_account(self, token, url=QE_URL, **kwargs):
"""Authenticate against IBMQ and store the account for future use.
Login into Quantum Experience or IBMQ using the provided credentials,
adding the account to the current session. The account is stored in
disk for future use.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
Raises:
IBMQAccountError: if the credentials are already in use.
"""
credentials = Credentials(token, url, **kwargs)
# Check if duplicated credentials are already stored. By convention,
# we assume (hub, group, project) is always unique.
stored_credentials = read_credentials_from_qiskitrc()
if credentials.unique_id() in stored_credentials.keys():
raise IBMQAccountError('Credentials are already stored')
self._append_account(credentials)
# Store the credentials back to disk.
store_credentials(credentials)
def remove_account(self, token, url=QE_URL, **kwargs):
"""Remove an account from the session and from disk.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
Raises:
IBMQAccountError: if the credentials could not be removed.
"""
removed = False
credentials = Credentials(token, url, **kwargs)
# Check if the credentials are already stored in session or disk. By
# convention, we assume (hub, group, project) is always unique.
stored_credentials = read_credentials_from_qiskitrc()
# Try to remove from session.
if credentials.unique_id() in self._accounts.keys():
del self._accounts[credentials.unique_id()]
removed = True
# Try to remove from disk.
if credentials.unique_id() in stored_credentials.keys():
remove_credentials(credentials)
removed = True
if not removed:
raise IBMQAccountError('Unable to find credentials')
def remove_accounts(self):
"""Remove all accounts from this session and optionally from disk."""
current_creds = self._accounts.copy()
for creds in current_creds:
self.remove_account(current_creds[creds].credentials.token,
current_creds[creds].credentials.url)
def use_account(self, token, url=QE_URL, **kwargs):
"""Authenticate against IBMQ during this session.
Login into Quantum Experience or IBMQ using the provided credentials,
adding the account to the current session. The account is not stored
in disk.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
"""
credentials = Credentials(token, url, **kwargs)
self._append_account(credentials)
def list_accounts(self):
"""List all accounts currently stored in the session.
Returns:
list[dict]: a list with information about the accounts currently
in the session.
"""
information = []
for provider in self._accounts.values():
information.append({
'token': provider.credentials.token,
'url': provider.credentials.url,
})
return information
def load_accounts(self, **kwargs):
"""Load IBMQ accounts found in the system, subject to optional filtering.
Automatically load the accounts found in the system. This method
looks for credentials in the following locations, in order, and
returns as soon as credentials are found:
1. in the `Qconfig.py` file in the current working directory.
2. in the environment variables.
3. in the `qiskitrc` configuration file
Raises:
IBMQAccountError: if attempting to load previously loaded accounts,
or if no credentials can be found.
"""
# Special handling of the credentials filters.
credentials_filter = {}
for key in ['token', 'url', 'hub', 'group', 'project']:
if key in kwargs:
credentials_filter[key] = kwargs.pop(key)
for credentials in discover_credentials().values():
if self._match_all(credentials, credentials_filter):
self._append_account(credentials)
if not self._accounts:
raise IBMQAccountError('No IBMQ credentials found.')
def _append_account(self, credentials):
"""Append an account with the specified credentials to the session.
Args:
credentials (Credentials): set of credentials.
Returns:
IBMQSingleProvider: new single-account provider.
Raises:
IBMQAccountError: if the provider could not be appended.
"""
# Check if duplicated credentials are already in use. By convention,
# we assume (hub, group, project) is always unique.
if credentials.unique_id() in self._accounts.keys():
raise IBMQAccountError('Credentials are already in use')
single_provider = IBMQSingleProvider(credentials, self)
self._accounts[credentials.unique_id()] = single_provider
return single_provider
def _match_all(self, obj, criteria):
"""Return True if all items in criteria matches items in obj."""
return all(getattr(obj, key_, None) == value_ for
key_, value_ in criteria.items())
<|code_end|>
|
qiskit/backends/ibmq/ibmqprovider.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Provider for remote IBMQ backends with admin features."""
import warnings
from collections import OrderedDict
from qiskit.backends import BaseProvider
from .credentials._configrc import remove_credentials
from .credentials import (Credentials,
read_credentials_from_qiskitrc, store_credentials, discover_credentials)
from .ibmqaccounterror import IBMQAccountError
from .ibmqsingleprovider import IBMQSingleProvider
QE_URL = 'https://quantumexperience.ng.bluemix.net/api'
class IBMQProvider(BaseProvider):
"""Provider for remote IBMQ backends with admin features.
This class is the entry point for handling backends from IBMQ, allowing
using different accounts.
"""
def __init__(self):
super().__init__()
# dict[credentials_unique_id: IBMQSingleProvider]
# This attribute stores a reference to the different accounts. The
# keys are tuples (hub, group, project), as the convention is that
# that tuple uniquely identifies a set of credentials.
self._accounts = OrderedDict()
def backends(self, name=None, filters=None, **kwargs):
# pylint: disable=arguments-differ
# Special handling of the credentials filters.
credentials_filter = {}
for key in ['token', 'url', 'hub', 'group', 'project']:
if key in kwargs:
credentials_filter[key] = kwargs.pop(key)
providers = [provider for provider in self._accounts.values() if
self._match_all(provider.credentials, credentials_filter)]
# Special handling of the `name` parameter, to support alias resolution.
if name:
aliases = self.aliased_backend_names()
aliases.update(self.deprecated_backend_names())
name = aliases.get(name, name)
# Aggregate the list of filtered backends.
backends = []
for provider in providers:
backends = backends + provider.backends(
name=name, filters=filters, **kwargs)
return backends
@staticmethod
def deprecated_backend_names():
"""Returns deprecated backend names."""
return {
'ibmqx_qasm_simulator': 'ibmq_qasm_simulator',
'ibmqx_hpc_qasm_simulator': 'ibmq_qasm_simulator',
'real': 'ibmqx1'
}
@staticmethod
def aliased_backend_names():
"""Returns aliased backend names."""
return {
'ibmq_5_yorktown': 'ibmqx2',
'ibmq_5_tenerife': 'ibmqx4',
'ibmq_16_rueschlikon': 'ibmqx5',
'ibmq_20_austin': 'QS1_1'
}
def add_account(self, token, url=QE_URL, **kwargs):
"""Authenticate against IBMQ and store the account for future use.
Login into Quantum Experience or IBMQ using the provided credentials,
adding the account to the current session. The account is stored in
disk for future use.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
"""
credentials = Credentials(token, url, **kwargs)
# Check if duplicated credentials are already stored. By convention,
# we assume (hub, group, project) is always unique.
stored_credentials = read_credentials_from_qiskitrc()
if credentials.unique_id() in stored_credentials.keys():
warnings.warn('Credentials are already stored')
else:
self._append_account(credentials)
# Store the credentials back to disk.
store_credentials(credentials)
def remove_account(self, token, url=QE_URL, **kwargs):
"""Remove an account from the session and from disk.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
Raises:
IBMQAccountError: if the credentials could not be removed.
"""
removed = False
credentials = Credentials(token, url, **kwargs)
# Check if the credentials are already stored in session or disk. By
# convention, we assume (hub, group, project) is always unique.
stored_credentials = read_credentials_from_qiskitrc()
# Try to remove from session.
if credentials.unique_id() in self._accounts.keys():
del self._accounts[credentials.unique_id()]
removed = True
# Try to remove from disk.
if credentials.unique_id() in stored_credentials.keys():
remove_credentials(credentials)
removed = True
if not removed:
raise IBMQAccountError('Unable to find credentials')
def remove_accounts(self):
"""Remove all accounts from this session and optionally from disk."""
current_creds = self._accounts.copy()
for creds in current_creds:
self.remove_account(current_creds[creds].credentials.token,
current_creds[creds].credentials.url)
def use_account(self, token, url=QE_URL, **kwargs):
"""Authenticate against IBMQ during this session.
Login into Quantum Experience or IBMQ using the provided credentials,
adding the account to the current session. The account is not stored
in disk.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
"""
credentials = Credentials(token, url, **kwargs)
self._append_account(credentials)
def list_accounts(self):
"""List all accounts currently stored in the session.
Returns:
list[dict]: a list with information about the accounts currently
in the session.
"""
information = []
for provider in self._accounts.values():
information.append({
'token': provider.credentials.token,
'url': provider.credentials.url,
})
return information
def load_accounts(self, **kwargs):
"""Load IBMQ accounts found in the system, subject to optional filtering.
Automatically load the accounts found in the system. This method
looks for credentials in the following locations, in order, and
returns as soon as credentials are found:
1. in the `Qconfig.py` file in the current working directory.
2. in the environment variables.
3. in the `qiskitrc` configuration file
Raises:
IBMQAccountError: if no credentials are found.
"""
# Special handling of the credentials filters.
credentials_filter = {}
for key in ['token', 'url', 'hub', 'group', 'project']:
if key in kwargs:
credentials_filter[key] = kwargs.pop(key)
for credentials in discover_credentials().values():
if self._match_all(credentials, credentials_filter):
self._append_account(credentials)
if not self._accounts:
raise IBMQAccountError('No IBMQ credentials found.')
def _append_account(self, credentials):
"""Append an account with the specified credentials to the session.
Args:
credentials (Credentials): set of credentials.
Returns:
IBMQSingleProvider: new single-account provider.
"""
# Check if duplicated credentials are already in use. By convention,
# we assume (hub, group, project) is always unique.
if credentials.unique_id() in self._accounts.keys():
warnings.warn('Credentials are already in use.')
single_provider = IBMQSingleProvider(credentials, self)
self._accounts[credentials.unique_id()] = single_provider
return single_provider
def _match_all(self, obj, criteria):
"""Return True if all items in criteria matches items in obj."""
return all(getattr(obj, key_, None) == value_ for
key_, value_ in criteria.items())
<|code_end|>
|
Changing style in matplotlib circuit_drawer changes the circuit layout
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: current master
- **Python version**: 3.7
- **Operating system**: OSX
### What is the current behavior?
The output from the Matplotlib circuit drawer changes when the `style` kwarg is modified
### Steps to reproduce the problem
`circuit_drawer(circ)` vs `circuit_drawer(circ,style=qx_color_scheme())`: (Here I show only the first pane of the circuit)
<img width="964" alt="screen shot 2018-09-25 at 5 44 48 am" src="https://user-images.githubusercontent.com/1249193/46006709-298c2080-c086-11e8-9c62-f05c5a91153e.png">
<img width="965" alt="screen shot 2018-09-25 at 5 45 33 am" src="https://user-images.githubusercontent.com/1249193/46006778-4de7fd00-c086-11e8-897d-433f48219b98.png">
### What is the expected behavior?
I would assume that the style does not change the circuit layout in the figure.
### Suggested solutions
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
1. LaTeX
2. Matplotlib
"""
import json
import logging
import operator
import os
import re
import subprocess
import tempfile
from collections import namedtuple, OrderedDict
from fractions import Fraction
from io import StringIO
from itertools import groupby, zip_longest
from math import fmod, isclose, ceil
import numpy as np
from PIL import Image, ImageChops
from matplotlib import get_backend as get_matplotlib_backend, \
patches as patches, pyplot as plt
from qiskit._qiskiterror import QISKitError
from qiskit._quantumcircuit import QuantumCircuit
from qiskit.wrapper import load_qasm_file
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization._error import VisualizationError
from qiskit.transpiler import transpile
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit, via 2 methods (try 1st, if unsuccessful, 2nd):
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
try:
return latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError):
return matplotlib_circuit_drawer(circuit, basis, scale, filename, style)
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
class QCStyle:
def __init__(self):
self.tc = '#000000'
self.sc = '#000000'
self.lc = '#000000'
self.cc = '#778899'
self.gc = '#ffffff'
self.gt = '#000000'
self.bc = '#bdbdbd'
self.bg = '#ffffff'
self.fs = 13
self.sfs = 8
self.disptex = {
'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'
}
self.dispcol = {
'id': '#ffffff',
'u0': '#ffffff',
'u1': '#ffffff',
'u2': '#ffffff',
'u3': '#ffffff',
'x': '#ffffff',
'y': '#ffffff',
'z': '#ffffff',
'h': '#ffffff',
's': '#ffffff',
'sdg': '#ffffff',
't': '#ffffff',
'tdg': '#ffffff',
'rx': '#ffffff',
'ry': '#ffffff',
'rz': '#ffffff',
'reset': '#ffffff',
'target': '#ffffff',
'meas': '#ffffff'
}
self.latexmode = True
self.pimode = False
self.fold = 20
self.bundle = False
self.barrier = False
self.index = False
self.compress = True
self.figwidth = -1
self.dpi = 150
self.margin = [2.0, 0.0, 0.0, 0.3]
self.cline = 'doublet'
self.reverse = False
def set_style(self, dic):
self.tc = dic.get('textcolor', self.tc)
self.sc = dic.get('subtextcolor', self.sc)
self.lc = dic.get('linecolor', self.lc)
self.cc = dic.get('creglinecolor', self.cc)
self.gt = dic.get('gatetextcolor', self.tc)
self.gc = dic.get('gatefacecolor', self.gc)
self.bc = dic.get('barrierfacecolor', self.bc)
self.bg = dic.get('backgroundcolor', self.bg)
self.fs = dic.get('fontsize', self.fs)
self.sfs = dic.get('subfontsize', self.sfs)
self.disptex = dic.get('displaytext', self.disptex)
for key in self.dispcol.keys():
self.dispcol[key] = self.gc
self.dispcol = dic.get('displaycolor', self.dispcol)
self.latexmode = dic.get('latexdrawerstyle', self.latexmode)
self.pimode = dic.get('usepiformat', self.pimode)
self.fold = dic.get('fold', self.fold)
if self.fold < 2:
self.fold = -1
self.bundle = dic.get('cregbundle', self.bundle)
self.barrier = dic.get('plotbarrier', self.barrier)
self.index = dic.get('showindex', self.index)
self.compress = dic.get('compress', self.compress)
self.figwidth = dic.get('figwidth', self.figwidth)
self.dpi = dic.get('dpi', self.dpi)
self.margin = dic.get('margin', self.margin)
self.cline = dic.get('creglinestyle', self.cline)
self.reverse = dic.get('reversebits', self.reverse)
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": False,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to complile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def _trim(im):
"""Trim image and remove white space
"""
bg = Image.new(im.mode, im.size, im.getpixel((0, 0)))
diff = ImageChops.difference(im, bg)
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
im = im.crop(bbox)
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
qcimg = QCircuitImage(json_circuit, scale, style=style)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, circuit, scale, style=None):
"""
Args:
circuit (dict): compiled_circuit from qobj
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
"""
# style sheet
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.circuit = circuit
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
#################################
self.header = self.circuit['header']
self.qregs = OrderedDict(_get_register_specs(
self.header['qubit_labels']))
self.qubit_list = []
for qr in self.qregs:
for i in range(self.qregs[qr]):
self.qubit_list.append((qr, i))
self.cregs = OrderedDict()
if 'clbit_labels' in self.header:
for item in self.header['clbit_labels']:
self.cregs[item[0]] = item[1]
self.clbit_list = []
cregs = self.cregs
if self._style.reverse:
self.orig_cregs = self.cregs
cregs = reversed(self.cregs)
for cr in cregs:
for i in range(self.cregs[cr]):
self.clbit_list.append((cr, i))
self.ordered_regs = [(item[0], item[1]) for
item in self.header['qubit_labels']]
if self._style.reverse:
reg_size = []
reg_labels = []
new_ordered_regs = []
for regs in self.ordered_regs:
if regs[0] in reg_labels:
continue
reg_labels.append(regs[0])
reg_size.append(len(
[x for x in self.ordered_regs if x[0] == regs[0]]))
index = 0
for size in reg_size:
new_index = index + size
for i in range(new_index - 1, index - 1, -1):
new_ordered_regs.append(self.ordered_regs[i])
index = new_index
self.ordered_regs = new_ordered_regs
if 'clbit_labels' in self.header:
for clabel in self.header['clbit_labels']:
if self._style.reverse:
for cind in reversed(range(clabel[1])):
self.ordered_regs.append((clabel[0], cind))
else:
for cind in range(clabel[1]):
self.ordered_regs.append((clabel[0], cind))
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\'+'\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
QISKitError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.circuit['instructions']:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's', 'sdg',
't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy', 'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['texparams']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, arg)
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
assert len(op['clbits']) == 1 and len(op['qubits']) == 1
if 'conditional' in op:
raise QISKitError('conditional measures currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise QISKitError('conditional reset currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
assert False, "bad node data"
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns+1, ceil(sum_column_widths)+4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above example,
index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _convert_mask(self, mask):
orig_clbit_list = []
for cr in self.orig_cregs:
for i in range(self.orig_cregs[cr]):
orig_clbit_list.append((cr, i))
bit_list = [(mask >> bit) & 1 for bit in range(
len(orig_clbit_list) - 1, -1, -1)]
converted_mask_list = [None] * len(bit_list)
converted_mask = 0
for pos, bit in enumerate(reversed(bit_list)):
new_pos = self.clbit_list.index(orig_clbit_list[pos])
converted_mask_list[new_pos] = bit
if None in converted_mask_list:
raise VisualizationError('Reverse mask creation failed')
converted_mask_list = list(reversed(converted_mask_list))
for bit in converted_mask_list:
converted_mask = (converted_mask << 1) | bit
return converted_mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.circuit['instructions']):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier']:
nm = op['name']
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] =\
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
elif nm == "reset":
self._latex[pos_1][columns] = \
"\\push{\\rule{.6em}{0em}\\ket{0}\\rule{.2em}{0em}} \\qw"
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
assert len(op['clbits']) == 1 and \
len(op['qubits']) == 1 and \
'params' not in op, "bad operation record"
if 'conditional' in op:
assert False, "If controlled measures currently not supported."
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise QISKitError('Error during Latex building: %s' %
str(e))
elif op['name'] == "barrier":
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qubits']) - 1
self._latex[start][columns] += " \\barrier{" + str(span) + "}"
else:
assert False, "bad node data"
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
if self._style.reverse:
return origin + 1
return origin - 1
def _get_register_specs(bit_labels):
"""
Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = MatplotlibDrawer(basis=basis, scale=scale, style=style)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
Register = namedtuple('Register', 'name index')
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=1.0, style=None):
self._ast = None
self._basis = basis
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = OrderedDict()
self._creg_dict = OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False, labelleft=False, labelright=False)
def load_qasm_file(self, filename):
circuit = load_qasm_file(filename, name='draw', basis_gates=self._basis)
self.parse_circuit(circuit)
def parse_circuit(self, circuit: QuantumCircuit):
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
self._ast = transpile(dag_circuit, basis_gates=self._basis, format='json')
self._registers()
self._ops = self._ast['instructions']
def _registers(self):
# NOTE: formats of clbit and qubit are different!
header = self._ast['header']
self._creg = []
for e in header['clbit_labels']:
for i in range(e[1]):
self._creg.append(Register(name=e[0], index=i))
assert len(self._creg) == header['number_of_clbits']
self._qreg = []
for e in header['qubit_labels']:
self._qreg.append(Register(name=e[0], index=e[1]))
assert len(self._qreg) == header['number_of_qubits']
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.sc,
clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7, height=HIG * 0.7,
theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID], [qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy+0.35*WID], lc=self._style.cc, ls=self._style.cline)
arrowhead = patches.Polygon(((cx-0.20*WID, cy+0.35*WID),
(cx+0.20*WID, cy+0.35*WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'], ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if get_matplotlib_backend() == 'module://ipykernel.pylab.backend_inline':
# returns None when matplotlib is inline mode to prevent Jupyter
# with matplotlib inlining enabled to draw the diagram twice.
im = None
else:
# when matplotlib is not inline mode,
# self.figure.savefig is called twice because...
# ... this is needed to get the in-memory representation
with tempfile.TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, 'circuit.png')
self.figure.savefig(tmpfile, dpi=self._style.dpi,
bbox_inches='tight')
im = Image.open(tmpfile)
_trim(im)
os.remove(tmpfile)
# ... and this is needed to delegate in matplotlib the generation of
# the proper format.
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
return im
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index, 'group': reg.name}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(zip_longest(self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
self._cond['n_lines'] += 1
idx += 1
# reverse bit order
if self._style.reverse:
self._reverse_bits(self._qreg_dict)
self._reverse_bits(self._creg_dict)
def _reverse_bits(self, target_dict):
coord = {}
# grouping
for dict_ in target_dict.values():
if dict_['group'] not in coord:
coord[dict_['group']] = [dict_['y']]
else:
coord[dict_['group']].insert(0, dict_['y'])
# reverse bit order
for key in target_dict.keys():
target_dict[key]['y'] = coord[target_dict[key]['group']].pop(0)
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc, ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qubits' in op.keys():
q_idxs = op['qubits']
else:
q_idxs = []
# get creg index
if 'clbits' in op.keys():
c_idxs = op['clbits']
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied), max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] == 'barrier' and not self._style.barrier:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg corrdinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc, ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] == 'barrier':
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self._style.barrier:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise QISKitError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if isclose(fmod(abs_val, 1.0), 0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
elif 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return Fraction(i, j)
return None
<|code_end|>
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
1. LaTeX
2. Matplotlib
"""
import json
import logging
import operator
import os
import re
import subprocess
import tempfile
from collections import namedtuple, OrderedDict
from fractions import Fraction
from io import StringIO
from itertools import groupby, zip_longest
from math import fmod, isclose, ceil
import numpy as np
from PIL import Image, ImageChops
from matplotlib import get_backend as get_matplotlib_backend, \
patches as patches, pyplot as plt
from qiskit._qiskiterror import QISKitError
from qiskit.wrapper import load_qasm_file
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization._error import VisualizationError
from qiskit.transpiler import transpile
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit, via 2 methods (try 1st, if unsuccessful, 2nd):
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
try:
return latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError):
return matplotlib_circuit_drawer(circuit, basis, scale, filename, style)
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
class QCStyle:
def __init__(self):
self.tc = '#000000'
self.sc = '#000000'
self.lc = '#000000'
self.cc = '#778899'
self.gc = '#ffffff'
self.gt = '#000000'
self.bc = '#bdbdbd'
self.bg = '#ffffff'
self.fs = 13
self.sfs = 8
self.disptex = {
'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'
}
self.dispcol = {
'id': '#ffffff',
'u0': '#ffffff',
'u1': '#ffffff',
'u2': '#ffffff',
'u3': '#ffffff',
'x': '#ffffff',
'y': '#ffffff',
'z': '#ffffff',
'h': '#ffffff',
's': '#ffffff',
'sdg': '#ffffff',
't': '#ffffff',
'tdg': '#ffffff',
'rx': '#ffffff',
'ry': '#ffffff',
'rz': '#ffffff',
'reset': '#ffffff',
'target': '#ffffff',
'meas': '#ffffff'
}
self.latexmode = True
self.pimode = False
self.fold = 20
self.bundle = False
self.barrier = False
self.index = False
self.compress = True
self.figwidth = -1
self.dpi = 150
self.margin = [2.0, 0.0, 0.0, 0.3]
self.cline = 'doublet'
self.reverse = False
def set_style(self, dic):
self.tc = dic.get('textcolor', self.tc)
self.sc = dic.get('subtextcolor', self.sc)
self.lc = dic.get('linecolor', self.lc)
self.cc = dic.get('creglinecolor', self.cc)
self.gt = dic.get('gatetextcolor', self.tc)
self.gc = dic.get('gatefacecolor', self.gc)
self.bc = dic.get('barrierfacecolor', self.bc)
self.bg = dic.get('backgroundcolor', self.bg)
self.fs = dic.get('fontsize', self.fs)
self.sfs = dic.get('subfontsize', self.sfs)
self.disptex = dic.get('displaytext', self.disptex)
for key in self.dispcol.keys():
self.dispcol[key] = self.gc
self.dispcol = dic.get('displaycolor', self.dispcol)
self.latexmode = dic.get('latexdrawerstyle', self.latexmode)
self.pimode = dic.get('usepiformat', self.pimode)
self.fold = dic.get('fold', self.fold)
if self.fold < 2:
self.fold = -1
self.bundle = dic.get('cregbundle', self.bundle)
self.barrier = dic.get('plotbarrier', self.barrier)
self.index = dic.get('showindex', self.index)
self.compress = dic.get('compress', self.compress)
self.figwidth = dic.get('figwidth', self.figwidth)
self.dpi = dic.get('dpi', self.dpi)
self.margin = dic.get('margin', self.margin)
self.cline = dic.get('creglinestyle', self.cline)
self.reverse = dic.get('reversebits', self.reverse)
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to complile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def _trim(im):
"""Trim image and remove white space
"""
bg = Image.new(im.mode, im.size, im.getpixel((0, 0)))
diff = ImageChops.difference(im, bg)
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
im = im.crop(bbox)
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
qcimg = QCircuitImage(json_circuit, scale, style=style)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, circuit, scale, style=None):
"""
Args:
circuit (dict): compiled_circuit from qobj
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
"""
# style sheet
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.circuit = circuit
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
#################################
self.header = self.circuit['header']
self.qregs = OrderedDict(_get_register_specs(
self.header['qubit_labels']))
self.qubit_list = []
for qr in self.qregs:
for i in range(self.qregs[qr]):
self.qubit_list.append((qr, i))
self.cregs = OrderedDict()
if 'clbit_labels' in self.header:
for item in self.header['clbit_labels']:
self.cregs[item[0]] = item[1]
self.clbit_list = []
cregs = self.cregs
if self._style.reverse:
self.orig_cregs = self.cregs
cregs = reversed(self.cregs)
for cr in cregs:
for i in range(self.cregs[cr]):
self.clbit_list.append((cr, i))
self.ordered_regs = [(item[0], item[1]) for
item in self.header['qubit_labels']]
if self._style.reverse:
reg_size = []
reg_labels = []
new_ordered_regs = []
for regs in self.ordered_regs:
if regs[0] in reg_labels:
continue
reg_labels.append(regs[0])
reg_size.append(len(
[x for x in self.ordered_regs if x[0] == regs[0]]))
index = 0
for size in reg_size:
new_index = index + size
for i in range(new_index - 1, index - 1, -1):
new_ordered_regs.append(self.ordered_regs[i])
index = new_index
self.ordered_regs = new_ordered_regs
if 'clbit_labels' in self.header:
for clabel in self.header['clbit_labels']:
if self._style.reverse:
for cind in reversed(range(clabel[1])):
self.ordered_regs.append((clabel[0], cind))
else:
for cind in range(clabel[1]):
self.ordered_regs.append((clabel[0], cind))
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\'+'\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
QISKitError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.circuit['instructions']:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's', 'sdg',
't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy', 'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['texparams']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, arg)
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
assert len(op['clbits']) == 1 and len(op['qubits']) == 1
if 'conditional' in op:
raise QISKitError('conditional measures currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise QISKitError('conditional reset currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
assert False, "bad node data"
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns+1, ceil(sum_column_widths)+4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above example,
index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _convert_mask(self, mask):
orig_clbit_list = []
for cr in self.orig_cregs:
for i in range(self.orig_cregs[cr]):
orig_clbit_list.append((cr, i))
bit_list = [(mask >> bit) & 1 for bit in range(
len(orig_clbit_list) - 1, -1, -1)]
converted_mask_list = [None] * len(bit_list)
converted_mask = 0
for pos, bit in enumerate(reversed(bit_list)):
new_pos = self.clbit_list.index(orig_clbit_list[pos])
converted_mask_list[new_pos] = bit
if None in converted_mask_list:
raise VisualizationError('Reverse mask creation failed')
converted_mask_list = list(reversed(converted_mask_list))
for bit in converted_mask_list:
converted_mask = (converted_mask << 1) | bit
return converted_mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.circuit['instructions']):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier']:
nm = op['name']
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] =\
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
elif nm == "reset":
self._latex[pos_1][columns] = \
"\\push{\\rule{.6em}{0em}\\ket{0}\\rule{.2em}{0em}} \\qw"
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
assert len(op['clbits']) == 1 and \
len(op['qubits']) == 1 and \
'params' not in op, "bad operation record"
if 'conditional' in op:
assert False, "If controlled measures currently not supported."
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise QISKitError('Error during Latex building: %s' %
str(e))
elif op['name'] == "barrier":
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qubits']) - 1
self._latex[start][columns] += " \\barrier{" + str(span) + "}"
else:
assert False, "bad node data"
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
if self._style.reverse:
return origin + 1
return origin - 1
def _get_register_specs(bit_labels):
"""
Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = MatplotlibDrawer(basis=basis, scale=scale, style=style)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
Register = namedtuple('Register', 'name index')
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=1.0, style=None):
self._ast = None
self._basis = basis
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = OrderedDict()
self._creg_dict = OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False, labelleft=False, labelright=False)
def load_qasm_file(self, filename):
circuit = load_qasm_file(filename, name='draw', basis_gates=self._basis)
self.parse_circuit(circuit)
def parse_circuit(self, circuit):
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
self._ast = transpile(dag_circuit, basis_gates=self._basis, format='json')
self._registers()
self._ops = self._ast['instructions']
def _registers(self):
# NOTE: formats of clbit and qubit are different!
header = self._ast['header']
self._creg = []
for e in header['clbit_labels']:
for i in range(e[1]):
self._creg.append(Register(name=e[0], index=i))
assert len(self._creg) == header['number_of_clbits']
self._qreg = []
for e in header['qubit_labels']:
self._qreg.append(Register(name=e[0], index=e[1]))
assert len(self._qreg) == header['number_of_qubits']
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.sc,
clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7, height=HIG * 0.7,
theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID], [qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy+0.35*WID], lc=self._style.cc, ls=self._style.cline)
arrowhead = patches.Polygon(((cx-0.20*WID, cy+0.35*WID),
(cx+0.20*WID, cy+0.35*WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'], ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if get_matplotlib_backend() == 'module://ipykernel.pylab.backend_inline':
# returns None when matplotlib is inline mode to prevent Jupyter
# with matplotlib inlining enabled to draw the diagram twice.
im = None
else:
# when matplotlib is not inline mode,
# self.figure.savefig is called twice because...
# ... this is needed to get the in-memory representation
with tempfile.TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, 'circuit.png')
self.figure.savefig(tmpfile, dpi=self._style.dpi,
bbox_inches='tight')
im = Image.open(tmpfile)
_trim(im)
os.remove(tmpfile)
# ... and this is needed to delegate in matplotlib the generation of
# the proper format.
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
return im
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index, 'group': reg.name}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(zip_longest(self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
self._cond['n_lines'] += 1
idx += 1
# reverse bit order
if self._style.reverse:
self._reverse_bits(self._qreg_dict)
self._reverse_bits(self._creg_dict)
def _reverse_bits(self, target_dict):
coord = {}
# grouping
for dict_ in target_dict.values():
if dict_['group'] not in coord:
coord[dict_['group']] = [dict_['y']]
else:
coord[dict_['group']].insert(0, dict_['y'])
# reverse bit order
for key in target_dict.keys():
target_dict[key]['y'] = coord[target_dict[key]['group']].pop(0)
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc, ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qubits' in op.keys():
q_idxs = op['qubits']
else:
q_idxs = []
# get creg index
if 'clbits' in op.keys():
c_idxs = op['clbits']
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied), max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] == 'barrier' and not self._style.barrier:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg corrdinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc, ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] == 'barrier':
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self._style.barrier:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise QISKitError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if isclose(fmod(abs_val, 1.0), 0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
elif 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return Fraction(i, j)
return None
<|code_end|>
|
Finalize changelog for 0.6 release
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
|
qiskit/_schema_validation.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Validation module for validation against JSON schemas."""
import json
import os
import logging
import jsonschema
from qiskit import QISKitError
from qiskit import __path__ as qiskit_path
logger = logging.getLogger(__name__)
_DEFAULT_SCHEMA_PATHS = {
'backend_configuration': 'schemas/backend_configuration_schema.json',
'backend_properties': 'schemas/backend_properties_schema.json',
'backend_status': 'schemas/backend_status_schema.json',
'default_pulse_configuration': 'schemas/default_pulse_configuration_schema.json',
'job_status': 'schemas/job_status_schema.json',
'qobj': 'schemas/qobj_schema.json',
'result': 'schemas/result_schema.json'}
# Schema and Validator storage
_SCHEMAS = {}
_VALIDATORS = {}
def _load_schema(file_path, name=None):
"""Loads the QObj schema for use in future validations. Caches schema in
_SCHEMAS module attribute.
Args:
file_path(str): Path to schema.
name(str): Given name for schema. Defaults to file_path filename
without schema.
Return:
schema(dict): Loaded schema.
"""
if name is None:
# filename without extension
name = os.path.splitext(os.path.basename(file_path))[0]
if name not in _SCHEMAS:
with open(file_path, 'r') as schema_file:
_SCHEMAS[name] = json.load(schema_file)
return _SCHEMAS[name]
def _get_validator(name, schema=None, check_schema=True,
validator_class=None, **validator_kwargs):
"""
Generate validator for JSON schema.
Args:
name (str): Name for validator. Will be validator key in
`_VALIDATORS` dict.
schema (dict): JSON schema `dict`. If not provided searches for schema
in `_SCHEMAS`.
check_schema (bool): Verify schema is valid.
validator_class (jsonschema.IValidator): jsonschema IValidator
instance. Default behavior is to determine this from the schema
`$schema` field.
**validator_kwargs: Additional keyword arguments for validator.
Return:
jsonschema.IValidator: Validator for JSON schema.
Raises:
SchemaValidationError: Raised if validation fails.
"""
if schema is None:
try:
schema = _SCHEMAS[name]
except KeyError:
raise SchemaValidationError("Valid schema name or schema must "
"be provided.")
if name not in _VALIDATORS:
# Resolve JSON spec from schema if needed
if validator_class is None:
validator_class = jsonschema.validators.validator_for(schema)
# Generate and store validator in _VALIDATORS
_VALIDATORS[name] = validator_class(schema, **validator_kwargs)
validator = _VALIDATORS[name]
if check_schema:
validator.check_schema(schema)
return validator
def _load_schemas_and_validators():
"""
Load all default schemas into `_SCHEMAS`.
"""
schema_base_path = qiskit_path[0]
for name, path in _DEFAULT_SCHEMA_PATHS.items():
_load_schema(os.path.join(schema_base_path, path), name)
_get_validator(name)
# Load all schemas on import
_load_schemas_and_validators()
def validate_json_against_schema(json_dict, schema,
err_msg=None):
"""
Validates JSON dict against a schema.
Args:
json_dict (dict): JSON to be validated.
schema (dict or str): JSON schema dictionary or the name of one of the
standards schemas in Qiskit to validate against it. The list of
standard schemas is: ``backend_configuration``,
``backend_properties``, ``backend_status``,
``default_pulse_configuration``, ``job_status``, ``qobj``,
``result``.
err_msg (str): Optional error message.
Raises:
SchemaValidationError: Raised if validation fails.
"""
try:
if isinstance(schema, str):
schema_name = schema
schema = _SCHEMAS[schema_name]
validator = _get_validator(schema_name)
validator.validate(json_dict)
else:
jsonschema.validate(json_dict, schema)
except jsonschema.ValidationError as err:
if err_msg is None:
err_msg = "JSON failed validation. Set Qiskit log level to DEBUG " \
"for further information."
newerr = SchemaValidationError(err_msg)
newerr.__cause__ = _SummaryValidationError(err)
logger.debug('%s', _format_causes(err))
raise newerr
def _format_causes(err, level=0):
"""Return a cascading explanation of the validation error in the form
of::
<validator> failed @ <subfield_path> because of:
<validator> failed @ <subfield_path> because of:
...
<validator> failed @ <subfield_path> because of:
...
...
For example::
'oneOf' failed @ '<root>' because of:
'required' failed @ '<root>.config' because of:
'meas_level' is a required property
Meaning the validator 'oneOf' failed while validating the whole object
because of the validator 'required' failing while validating the property
'config' because its 'meas_level' field is missing.
The cascade repeats the format "<validator> failed @ <path> because of"
until there are no deeper causes. In this case, the string representation
of the error is shown.
Args:
err (jsonschema.ValidationError): the instance to explain.
level (int): starting level of indentation for the cascade of
explanations.
Return:
str: a formatted string with the explanation of the error.
"""
lines = []
def _print(string, offset=0):
lines.append(_pad(string, offset=offset))
def _pad(string, offset=0):
padding = ' ' * (level + offset)
padded_lines = [padding + line for line in string.split('\n')]
return '\n'.join(padded_lines)
def _format_path(path):
def _format(item):
if isinstance(item, str):
return '.{}'.format(item)
return '[{}]'.format(item)
return ''.join(['<root>'] + list(map(_format, path)))
_print('\'{}\' failed @ \'{}\' because of:'.format(
err.validator, _format_path(err.absolute_path)))
if not err.context:
_print(str(err.message), offset=1)
else:
for suberr in err.context:
lines.append(_format_causes(suberr, level+1))
return '\n'.join(lines)
class SchemaValidationError(QISKitError):
"""Represents an error during JSON Schema validation."""
pass
class _SummaryValidationError(QISKitError):
"""Cut off the message of a jsonschema.ValidationError to avoid printing
noise in the standard output. The original validation error is in the
`validation_error` property.
Attributes:
validation_error (jsonschama.ValidationError): original validations
error.
"""
def __init__(self, validation_error):
super().__init__(self._shorten_message(str(validation_error)))
self.validation_error = validation_error
def _shorten_message(self, message):
if len(message) > 1000:
return 'Original message too long to be useful: {}[...]'\
''.format(message[:1000])
return message
<|code_end|>
qiskit/transpiler/_parallel.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# This file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names
# of its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################
"""Routines for running Python functions in parallel using process pools
from the multiprocessing library.
"""
import os
import platform
from multiprocessing import Pool
from qiskit._qiskiterror import QISKitError
from qiskit._util import local_hardware_info
from ._receiver import receiver as rec
from ._progressbar import BaseProgressBar
# Number of local physical cpus
CPU_COUNT = local_hardware_info()['cpus']
def parallel_map(task, values, task_args=tuple(), task_kwargs={}, # pylint: disable=W0102
num_processes=CPU_COUNT):
"""
Parallel execution of a mapping of `values` to the function `task`. This
is functionally equivalent to::
result = [task(value, *task_args, **task_kwargs) for value in values]
On Windows this function defaults to a serial implimentation to avoid the
overhead from spawning processes in Windows.
Parameters:
task (func): Function that is to be called for each value in ``task_vec``.
values (array_like): List or array of values for which the ``task``
function is to be evaluated.
task_args (list): Optional additional arguments to the ``task`` function.
task_kwargs (dict): Optional additional keyword argument to the ``task`` function.
num_processes (int): Number of processes to spawn.
Returns:
result: The result list contains the value of
``task(value, *task_args, **task_kwargs)`` for
each value in ``values``.
Raises:
QISKitError: If user interupts via keyboard.
"""
# len(values) == 1
if len(values) == 1:
return [task(values[0], *task_args, **task_kwargs)]
# Get last element of the receiver channels
if any(rec.channels):
progress_bar = None
for idx in rec.channels:
if rec.channels[idx].type == 'progressbar' and not rec.channels[idx].touched:
progress_bar = rec.channels[idx]
break
if progress_bar is None:
progress_bar = BaseProgressBar()
else:
progress_bar = BaseProgressBar()
progress_bar.start(len(values))
nfinished = [0]
def _callback(x): # pylint: disable=W0613
nfinished[0] += 1
progress_bar.update(nfinished[0])
# Run in parallel if not Win and not in parallel already
if platform.system() != 'Windows' and num_processes > 1 \
and os.getenv('QISKIT_IN_PARALLEL') == 'FALSE':
os.environ['QISKIT_IN_PARALLEL'] = 'TRUE'
try:
pool = Pool(processes=num_processes)
async_res = [pool.apply_async(task, (value,) + task_args, task_kwargs,
_callback) for value in values]
while not all([item.ready() for item in async_res]):
for item in async_res:
item.wait(timeout=0.1)
pool.terminate()
pool.join()
except KeyboardInterrupt:
pool.terminate()
pool.join()
progress_bar.finished()
raise QISKitError('Keyboard interrupt in parallel_map.')
progress_bar.finished()
os.environ['QISKIT_IN_PARALLEL'] = 'FALSE'
return [ar.get() for ar in async_res]
# Cannot do parallel on Windows , if another parallel_map is running in parallel,
# or len(values) == 1.
results = []
for _, value in enumerate(values):
result = task(value, *task_args, **task_kwargs)
results.append(result)
_callback(0)
progress_bar.finished()
return results
<|code_end|>
qiskit/wrapper/_wrapper.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Helper module for simplified QISKit usage."""
import logging
import warnings
from qiskit import IBMQ
from qiskit import Aer
from qiskit.backends import ibmq
from qiskit._qiskiterror import QISKitError
from qiskit import transpiler
from qiskit.transpiler._passmanager import PassManager
from ._circuittoolkit import circuit_from_qasm_file, circuit_from_qasm_string
logger = logging.getLogger(__name__)
def register(*args, provider_class=None, **kwargs):
"""
Authenticate against an online backend provider.
This is a factory method that returns the provider that gets registered.
Args:
args (tuple): positional arguments passed to provider class initialization
provider_class (BaseProvider): provider class
kwargs (dict): keyword arguments passed to provider class initialization.
For the IBMQSingleProvider default this can include things such as:
* token (str): The token used to register on the online backend such
as the quantum experience.
* url (str): The url used for online backend such as the quantum
experience.
* hub (str): The hub used for online backend.
* group (str): The group used for online backend.
* project (str): The project used for online backend.
* proxies (dict): Proxy configuration for the API, as a dict with
'urls' and credential keys.
* verify (bool): If False, ignores SSL certificates errors.
Returns:
BaseProvider: the provider instance that was just registered.
Raises:
QISKitError: if the provider could not be registered
.. deprecated:: 0.6+
After 0.6, this function is deprecated. Please use the methods in
`qiskit.IBMQ` instead (`enable_account()`) for using IBMQ
accounts. For custom `Provider`s, please instantiate them directly.
"""
if provider_class:
warnings.warn(
'The global registry of providers and register() is deprecated '
'since 0.6. Please instantiate "{}()" directly.'.format(provider_class),
DeprecationWarning)
return provider_class(*args, **kwargs)
else:
warnings.warn('register() will be deprecated after 0.6. Please use the '
'qiskit.IBMQ.enable_account() method instead.',
DeprecationWarning)
try:
provider = IBMQ.enable_account(*args, **kwargs)
except Exception as ex:
raise QISKitError("Couldn't instantiate provider! Error: {0}".format(ex))
return provider
def unregister(provider):
"""
Removes a provider from list of registered providers.
Note:
If backend names from provider1 and provider2 were clashing,
`unregister(provider1)` removes the clash and makes the backends
from provider2 available.
Args:
provider (BaseProvider): the provider instance to unregister
Raises:
QISKitError: if the provider instance is not registered
.. deprecated:: 0.6+
After 0.6, this function is deprecated. Please use the methods in
`qiskit.IBMQ` instead (`disable_account()`).
"""
# pylint: disable=unused-argument
warnings.warn('unregister() will be deprecated after 0.6. Please use the '
'qiskit.IBMQ.disable_account() method instead.',
DeprecationWarning)
def registered_providers():
"""Return the currently registered providers.
.. deprecated:: 0.6+
After 0.6, this function is deprecated. Please use the methods in
`qiskit.IBMQ` instead (`active_accounts()`).
"""
warnings.warn('registered_providers() will be deprecated after 0.6. Please '
'use the qiskit.IBMQ.active_accounts() method instead.',
DeprecationWarning)
return IBMQ.active_accounts()
# Functions for inspecting and retrieving backends.
def available_backends(filters=None, compact=True):
"""
Return names of backends that are available in the SDK, optionally filtering
them based on their capabilities.
Note:
In order for this function to return online backends, a connection with
an online backend provider needs to be established by calling the
`register()` function.
Note:
If two or more providers have backends with the same name, those names
will be shown only once. To disambiguate and choose a backend from a
specific provider, get the backend from that specific provider.
Example::
p1 = register(token1)
p2 = register(token2)
execute(circuit, p1.get_backend('ibmq_5_tenerife'))
execute(circuit, p2.get_backend('ibmq_5_tenerife'))
Args:
filters (dict or callable): filtering conditions.
compact (bool): group backend names based on compact group names.
Returns:
list[str]: the names of the available backends.
.. deprecated:: 0.6+
After 0.6, this function is deprecated. Please use the methods in
`qiskit.IBMQ` and `qiskit.backends.local.Aer` instead
(`backends()`).
"""
warnings.warn('available_backends() will be deprecated after 0.6. Please '
'use the qiskit.IBMQ.backends() and qiskit.Aer.backends() '
'method instead.',
DeprecationWarning)
if isinstance(filters, dict):
kwargs = filters
else:
kwargs = {'filters': filters}
ibmq_names = [backend.name() for backend in IBMQ.backends(**kwargs)]
aer_names = [backend.name() for backend in Aer.backends(**kwargs)]
if compact:
# Hack for backwards compatibility: reverse the groups for local.
aer_groups = Aer.grouped_backend_names()
reversed_aer_groups = {}
for group, items in aer_groups.items():
for alias in items:
reversed_aer_groups[alias] = group
aer_names = list(set(reversed_aer_groups[name] for name in aer_names))
return ibmq_names + aer_names
def least_busy(names):
"""
Return the least busy available backend for those that
have a `pending_jobs` in their `status`. Backends such as
local backends that do not have this are not considered.
Args:
names (list[str]): backend names to choose from
(e.g. output of ``available_backends()``)
Returns:
str: the name of the least busy backend
Raises:
QISKitError: if passing a list of backend names that is
either empty or none have attribute ``pending_jobs``
.. deprecated:: 0.6+
After 0.6, this function is deprecated. Please use the methods in
`qiskit.IBMQ` instead
(`backends()`).
"""
backends = [get_backend(name) for name in names]
warnings.warn('the global least_busy() will be deprecated after 0.6. Please '
'use least_busy() imported from qiskit.backends.ibmq',
DeprecationWarning)
return ibmq.least_busy(backends).name()
def get_backend(name):
"""
Return an instance of a `Backend` object from its name identifier.
Args:
name(str): unique name of the backend.
Returns:
BaseBackend: a Backend instance.
.. deprecated:: 0.6+
After 0.6, this function is deprecated. Please use the methods in
`qiskit.IBMQ` and `qiskit.Aer` instead
(`backends()`).
"""
warnings.warn('the global get_backend() will be deprecated after 0.6. Please '
'use the qiskit.IBMQ.backends() and qiskit.Aer.backends() '
'method instead with the "name" parameter.'
'(or qiskit.IBMQ.get_backend() and qiskit.Aer.get_backend())',
DeprecationWarning)
try:
return Aer.get_backend(name)
except KeyError:
return IBMQ.get_backend(name)
# Functions for compiling and executing.
def compile(circuits, backend,
config=None, basis_gates=None, coupling_map=None, initial_layout=None,
shots=1024, max_credits=10, seed=None, qobj_id=None, hpc=None,
skip_transpiler=False):
"""Compile a list of circuits into a qobj.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend or str): a backend to compile for
config (dict): dictionary of parameters (e.g. noise) used by runner
basis_gates (str): comma-separated basis gate set to compile to
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
shots (int): number of repetitions of each circuit, for sampling
max_credits (int): maximum credits to use
seed (int): random seed for simulators
qobj_id (int): identifier for the generated qobj
hpc (dict): HPC simulator parameters
skip_transpiler (bool): skip most of the compile steps and produce qobj directly
Returns:
Qobj: the qobj to be run on the backends
Raises:
TranspilerError: in case of bad compile options, e.g. the hpc options.
.. deprecated:: 0.6+
After 0.6, compile will only take a backend object.
"""
# pylint: disable=redefined-builtin
if isinstance(backend, str):
warnings.warn('compile() no longer takes backend string names.'
'Please pass backend objects, obtained via'
'IBMQ.get_backend() or Aer.get_backend().', DeprecationWarning)
try:
backend = Aer.get_backend(backend)
except KeyError:
backend = IBMQ.get_backend(backend)
pass_manager = None # default pass manager which executes predetermined passes
# TODO (jay) why do we need to pass skip and not pass manager directly
if skip_transpiler: # empty pass manager which does nothing
pass_manager = PassManager()
qobj_standard = transpiler.compile(circuits, backend, config, basis_gates, coupling_map,
initial_layout, shots, max_credits, seed, qobj_id, hpc,
pass_manager)
return qobj_standard
def execute(circuits, backend,
config=None, basis_gates=None, coupling_map=None, initial_layout=None,
shots=1024, max_credits=10, seed=None, qobj_id=None, hpc=None,
skip_transpiler=False):
"""Executes a set of circuits.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute
backend (BaseBackend or str): a backend to execute the circuits on
config (dict): dictionary of parameters (e.g. noise) used by runner
basis_gates (str): comma-separated basis gate set to compile to
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
shots (int): number of repetitions of each circuit, for sampling
max_credits (int): maximum credits to use
seed (int): random seed for simulators
qobj_id (int): identifier for the generated qobj
hpc (dict): HPC simulator parameters
skip_transpiler (bool): skip most of the compile steps and produce qobj directly
Returns:
BaseJob: returns job instance derived from BaseJob
.. deprecated:: 0.6+
After 0.6, execute will only take a backend object, not string.
"""
# pylint: disable=missing-param-doc, missing-type-doc
if isinstance(backend, str):
warnings.warn('execute() no longer takes backend string names. '
'Please pass backend objects, obtained via'
'IBMQ.get_backend() or Aer.get_backend().', DeprecationWarning)
try:
backend = Aer.get_backend(backend)
except KeyError:
backend = IBMQ.get_backend(backend)
qobj = compile(circuits, backend,
config, basis_gates, coupling_map, initial_layout,
shots, max_credits, seed, qobj_id, hpc,
skip_transpiler)
return backend.run(qobj)
# Functions for importing qasm
def load_qasm_string(qasm_string, name=None,
basis_gates="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap"):
"""Construct a quantum circuit from a qasm representation (string).
Args:
qasm_string (str): a string of qasm, or a filename containing qasm.
basis_gates (str): basis gates for the quantum circuit.
name (str or None): the name of the quantum circuit after loading qasm
text into it. If no name given, assign automatically.
Returns:
QuantumCircuit: circuit constructed from qasm.
Raises:
QISKitError: if the string is not valid QASM
"""
return circuit_from_qasm_string(qasm_string, name, basis_gates)
def load_qasm_file(qasm_file, name=None,
basis_gates="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap"):
"""Construct a quantum circuit from a qasm representation (file).
Args:
qasm_file (str): a string for the filename including its location.
name (str or None): the name of the quantum circuit after
loading qasm text into it. If no name is give the name is of
the text file.
basis_gates (str): basis gates for the quantum circuit.
Returns:
QuantumCircuit: circuit constructed from qasm.
Raises:
QISKitError: if the file cannot be read.
"""
return circuit_from_qasm_file(qasm_file, name, basis_gates)
def qobj_to_circuits(qobj):
"""Return a list of QuantumCircuit object(s) from a qobj
Args:
qobj (Qobj): The Qobj object to convert to QuantumCircuits
Returns:
list: A list of QuantumCircuit objects from the qobj
"""
if qobj.experiments:
circuits = []
for x in qobj.experiments:
if hasattr(x.header, 'compiled_circuit_qasm'):
circuits.append(
load_qasm_string(x.header.compiled_circuit_qasm))
return circuits
# TODO(mtreinish): add support for converting a qobj if the qasm isn't
# embedded in the header
return None
<|code_end|>
|
qiskit/_schema_validation.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Validation module for validation against JSON schemas."""
import json
import os
import logging
import jsonschema
from qiskit import QISKitError
from qiskit import __path__ as qiskit_path
logger = logging.getLogger(__name__)
_DEFAULT_SCHEMA_PATHS = {
'backend_configuration': 'schemas/backend_configuration_schema.json',
'backend_properties': 'schemas/backend_properties_schema.json',
'backend_status': 'schemas/backend_status_schema.json',
'default_pulse_configuration': 'schemas/default_pulse_configuration_schema.json',
'job_status': 'schemas/job_status_schema.json',
'qobj': 'schemas/qobj_schema.json',
'result': 'schemas/result_schema.json'}
# Schema and Validator storage
_SCHEMAS = {}
_VALIDATORS = {}
def _load_schema(file_path, name=None):
"""Loads the QObj schema for use in future validations.
Caches schema in _SCHEMAS module attribute.
Args:
file_path(str): Path to schema.
name(str): Given name for schema. Defaults to file_path filename
without schema.
Return:
schema(dict): Loaded schema.
"""
if name is None:
# filename without extension
name = os.path.splitext(os.path.basename(file_path))[0]
if name not in _SCHEMAS:
with open(file_path, 'r') as schema_file:
_SCHEMAS[name] = json.load(schema_file)
return _SCHEMAS[name]
def _get_validator(name, schema=None, check_schema=True,
validator_class=None, **validator_kwargs):
"""
Generate validator for JSON schema.
Args:
name (str): Name for validator. Will be validator key in
`_VALIDATORS` dict.
schema (dict): JSON schema `dict`. If not provided searches for schema
in `_SCHEMAS`.
check_schema (bool): Verify schema is valid.
validator_class (jsonschema.IValidator): jsonschema IValidator instance.
Default behavior is to determine this from the schema `$schema`
field.
**validator_kwargs (dict): Additional keyword arguments for validator.
Return:
jsonschema.IValidator: Validator for JSON schema.
Raises:
SchemaValidationError: Raised if validation fails.
"""
if schema is None:
try:
schema = _SCHEMAS[name]
except KeyError:
raise SchemaValidationError("Valid schema name or schema must "
"be provided.")
if name not in _VALIDATORS:
# Resolve JSON spec from schema if needed
if validator_class is None:
validator_class = jsonschema.validators.validator_for(schema)
# Generate and store validator in _VALIDATORS
_VALIDATORS[name] = validator_class(schema, **validator_kwargs)
validator = _VALIDATORS[name]
if check_schema:
validator.check_schema(schema)
return validator
def _load_schemas_and_validators():
"""Load all default schemas into `_SCHEMAS`."""
schema_base_path = qiskit_path[0]
for name, path in _DEFAULT_SCHEMA_PATHS.items():
_load_schema(os.path.join(schema_base_path, path), name)
_get_validator(name)
# Load all schemas on import
_load_schemas_and_validators()
def validate_json_against_schema(json_dict, schema,
err_msg=None):
"""Validates JSON dict against a schema.
Args:
json_dict (dict): JSON to be validated.
schema (dict or str): JSON schema dictionary or the name of one of the
standards schemas in Qiskit to validate against it. The list of
standard schemas is: ``backend_configuration``,
``backend_properties``, ``backend_status``,
``default_pulse_configuration``, ``job_status``, ``qobj``,
``result``.
err_msg (str): Optional error message.
Raises:
SchemaValidationError: Raised if validation fails.
"""
try:
if isinstance(schema, str):
schema_name = schema
schema = _SCHEMAS[schema_name]
validator = _get_validator(schema_name)
validator.validate(json_dict)
else:
jsonschema.validate(json_dict, schema)
except jsonschema.ValidationError as err:
if err_msg is None:
err_msg = "JSON failed validation. Set Qiskit log level to DEBUG " \
"for further information."
newerr = SchemaValidationError(err_msg)
newerr.__cause__ = _SummaryValidationError(err)
logger.debug('%s', _format_causes(err))
raise newerr
def _format_causes(err, level=0):
"""Return a cascading explanation of the validation error.
Returns a cascading explanation of the validation error in the form of::
<validator> failed @ <subfield_path> because of:
<validator> failed @ <subfield_path> because of:
...
<validator> failed @ <subfield_path> because of:
...
...
For example::
'oneOf' failed @ '<root>' because of:
'required' failed @ '<root>.config' because of:
'meas_level' is a required property
Meaning the validator 'oneOf' failed while validating the whole object
because of the validator 'required' failing while validating the property
'config' because its 'meas_level' field is missing.
The cascade repeats the format "<validator> failed @ <path> because of"
until there are no deeper causes. In this case, the string representation
of the error is shown.
Args:
err (jsonschema.ValidationError): the instance to explain.
level (int): starting level of indentation for the cascade of
explanations.
Return:
str: a formatted string with the explanation of the error.
"""
lines = []
def _print(string, offset=0):
lines.append(_pad(string, offset=offset))
def _pad(string, offset=0):
padding = ' ' * (level + offset)
padded_lines = [padding + line for line in string.split('\n')]
return '\n'.join(padded_lines)
def _format_path(path):
def _format(item):
if isinstance(item, str):
return '.{}'.format(item)
return '[{}]'.format(item)
return ''.join(['<root>'] + list(map(_format, path)))
_print('\'{}\' failed @ \'{}\' because of:'.format(
err.validator, _format_path(err.absolute_path)))
if not err.context:
_print(str(err.message), offset=1)
else:
for suberr in err.context:
lines.append(_format_causes(suberr, level+1))
return '\n'.join(lines)
class SchemaValidationError(QISKitError):
"""Represents an error during JSON Schema validation."""
pass
class _SummaryValidationError(QISKitError):
"""Cut off the message of a jsonschema.ValidationError for compactness.
Cut off the message of a jsonschema.ValidationError to avoid printing
noise in the standard output. The original validation error is in the
`validation_error` property.
Attributes:
validation_error (jsonschama.ValidationError): original validations
error.
"""
def __init__(self, validation_error):
super().__init__(self._shorten_message(str(validation_error)))
self.validation_error = validation_error
def _shorten_message(self, message):
if len(message) > 1000:
return 'Original message too long to be useful: {}[...]'\
''.format(message[:1000])
return message
<|code_end|>
qiskit/transpiler/_parallel.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# This file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names
# of its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################
"""
Routines for running Python functions in parallel using process pools
from the multiprocessing library.
"""
import os
import platform
from multiprocessing import Pool
from qiskit._qiskiterror import QISKitError
from qiskit._util import local_hardware_info
from ._receiver import receiver as rec
from ._progressbar import BaseProgressBar
# Number of local physical cpus
CPU_COUNT = local_hardware_info()['cpus']
def parallel_map(task, values, task_args=tuple(), task_kwargs={}, # pylint: disable=W0102
num_processes=CPU_COUNT):
"""
Parallel execution of a mapping of `values` to the function `task`. This
is functionally equivalent to::
result = [task(value, *task_args, **task_kwargs) for value in values]
On Windows this function defaults to a serial implimentation to avoid the
overhead from spawning processes in Windows.
Args:
task (func): Function that is to be called for each value in ``task_vec``.
values (array_like): List or array of values for which the ``task``
function is to be evaluated.
task_args (list): Optional additional arguments to the ``task`` function.
task_kwargs (dict): Optional additional keyword argument to the ``task`` function.
num_processes (int): Number of processes to spawn.
Returns:
result: The result list contains the value of
``task(value, *task_args, **task_kwargs)`` for
each value in ``values``.
Raises:
QISKitError: If user interupts via keyboard.
"""
# len(values) == 1
if len(values) == 1:
return [task(values[0], *task_args, **task_kwargs)]
# Get last element of the receiver channels
if any(rec.channels):
progress_bar = None
for idx in rec.channels:
if rec.channels[idx].type == 'progressbar' and not rec.channels[idx].touched:
progress_bar = rec.channels[idx]
break
if progress_bar is None:
progress_bar = BaseProgressBar()
else:
progress_bar = BaseProgressBar()
progress_bar.start(len(values))
nfinished = [0]
def _callback(x): # pylint: disable=W0613
nfinished[0] += 1
progress_bar.update(nfinished[0])
# Run in parallel if not Win and not in parallel already
if platform.system() != 'Windows' and num_processes > 1 \
and os.getenv('QISKIT_IN_PARALLEL') == 'FALSE':
os.environ['QISKIT_IN_PARALLEL'] = 'TRUE'
try:
pool = Pool(processes=num_processes)
async_res = [pool.apply_async(task, (value,) + task_args, task_kwargs,
_callback) for value in values]
while not all([item.ready() for item in async_res]):
for item in async_res:
item.wait(timeout=0.1)
pool.terminate()
pool.join()
except KeyboardInterrupt:
pool.terminate()
pool.join()
progress_bar.finished()
raise QISKitError('Keyboard interrupt in parallel_map.')
progress_bar.finished()
os.environ['QISKIT_IN_PARALLEL'] = 'FALSE'
return [ar.get() for ar in async_res]
# Cannot do parallel on Windows , if another parallel_map is running in parallel,
# or len(values) == 1.
results = []
for _, value in enumerate(values):
result = task(value, *task_args, **task_kwargs)
results.append(result)
_callback(0)
progress_bar.finished()
return results
<|code_end|>
qiskit/wrapper/_wrapper.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Helper module for simplified QISKit usage."""
import logging
import warnings
from qiskit import IBMQ
from qiskit import Aer
from qiskit.backends import ibmq
from qiskit._qiskiterror import QISKitError
from qiskit import transpiler
from qiskit.transpiler._passmanager import PassManager
from ._circuittoolkit import circuit_from_qasm_file, circuit_from_qasm_string
logger = logging.getLogger(__name__)
def register(*args, provider_class=None, **kwargs):
"""
Authenticate against an online backend provider.
This is a factory method that returns the provider that gets registered.
Args:
args (tuple): positional arguments passed to provider class initialization
provider_class (BaseProvider): provider class
kwargs (dict): keyword arguments passed to provider class initialization.
For the IBMQSingleProvider default this can include things such as:
* token (str): The token used to register on the online backend such
as the quantum experience.
* url (str): The url used for online backend such as the quantum
experience.
* hub (str): The hub used for online backend.
* group (str): The group used for online backend.
* project (str): The project used for online backend.
* proxies (dict): Proxy configuration for the API, as a dict with
'urls' and credential keys.
* verify (bool): If False, ignores SSL certificates errors.
Returns:
BaseProvider: the provider instance that was just registered.
Raises:
QISKitError: if the provider could not be registered
.. deprecated:: 0.6+
After 0.6, this function is deprecated. Please use the methods in
`qiskit.IBMQ` instead (`enable_account()`) for using IBMQ
accounts. For custom `Providers`, please instantiate them directly.
"""
if provider_class:
warnings.warn(
'The global registry of providers and register() is deprecated '
'since 0.6. Please instantiate "{}()" directly.'.format(provider_class),
DeprecationWarning)
return provider_class(*args, **kwargs)
else:
warnings.warn('register() will be deprecated after 0.6. Please use the '
'qiskit.IBMQ.enable_account() method instead.',
DeprecationWarning)
try:
provider = IBMQ.enable_account(*args, **kwargs)
except Exception as ex:
raise QISKitError("Couldn't instantiate provider! Error: {0}".format(ex))
return provider
def unregister(provider):
"""
Removes a provider from list of registered providers.
Note:
If backend names from provider1 and provider2 were clashing,
`unregister(provider1)` removes the clash and makes the backends
from provider2 available.
Args:
provider (BaseProvider): the provider instance to unregister
Raises:
QISKitError: if the provider instance is not registered
.. deprecated:: 0.6+
After 0.6, this function is deprecated. Please use the methods in
`qiskit.IBMQ` instead (`disable_account()`).
"""
# pylint: disable=unused-argument
warnings.warn('unregister() will be deprecated after 0.6. Please use the '
'qiskit.IBMQ.disable_account() method instead.',
DeprecationWarning)
def registered_providers():
"""Return the currently registered providers.
.. deprecated:: 0.6+
After 0.6, this function is deprecated. Please use the methods in
`qiskit.IBMQ` instead (`active_accounts()`).
"""
warnings.warn('registered_providers() will be deprecated after 0.6. Please '
'use the qiskit.IBMQ.active_accounts() method instead.',
DeprecationWarning)
return IBMQ.active_accounts()
# Functions for inspecting and retrieving backends.
def available_backends(filters=None, compact=True):
"""
Return names of backends that are available in the SDK, optionally filtering
them based on their capabilities.
Note:
In order for this function to return online backends, a connection with
an online backend provider needs to be established by calling the
`register()` function.
Note:
If two or more providers have backends with the same name, those names
will be shown only once. To disambiguate and choose a backend from a
specific provider, get the backend from that specific provider.
Example::
p1 = register(token1)
p2 = register(token2)
execute(circuit, p1.get_backend('ibmq_5_tenerife'))
execute(circuit, p2.get_backend('ibmq_5_tenerife'))
Args:
filters (dict or callable): filtering conditions.
compact (bool): group backend names based on compact group names.
Returns:
list[str]: the names of the available backends.
.. deprecated:: 0.6+
After 0.6, this function is deprecated. Please use the methods in
`qiskit.IBMQ` and `qiskit.backends.local.Aer` instead
(`backends()`).
"""
warnings.warn('available_backends() will be deprecated after 0.6. Please '
'use the qiskit.IBMQ.backends() and qiskit.Aer.backends() '
'method instead.',
DeprecationWarning)
if isinstance(filters, dict):
kwargs = filters
else:
kwargs = {'filters': filters}
ibmq_names = [backend.name() for backend in IBMQ.backends(**kwargs)]
aer_names = [backend.name() for backend in Aer.backends(**kwargs)]
if compact:
# Hack for backwards compatibility: reverse the groups for local.
aer_groups = Aer.grouped_backend_names()
reversed_aer_groups = {}
for group, items in aer_groups.items():
for alias in items:
reversed_aer_groups[alias] = group
aer_names = list(set(reversed_aer_groups[name] for name in aer_names))
return ibmq_names + aer_names
def least_busy(names):
"""
Return the least busy available backend for those that
have a `pending_jobs` in their `status`. Backends such as
local backends that do not have this are not considered.
Args:
names (list[str]): backend names to choose from
(e.g. output of ``available_backends()``)
Returns:
str: the name of the least busy backend
Raises:
QISKitError: if passing a list of backend names that is
either empty or none have attribute ``pending_jobs``
.. deprecated:: 0.6+
After 0.6, this function is deprecated. Please use the methods in
`qiskit.IBMQ` instead
(`backends()`).
"""
backends = [get_backend(name) for name in names]
warnings.warn('the global least_busy() will be deprecated after 0.6. Please '
'use least_busy() imported from qiskit.backends.ibmq',
DeprecationWarning)
return ibmq.least_busy(backends).name()
def get_backend(name):
"""
Return an instance of a `Backend` object from its name identifier.
Args:
name(str): unique name of the backend.
Returns:
BaseBackend: a Backend instance.
.. deprecated:: 0.6+
After 0.6, this function is deprecated. Please use the methods in
`qiskit.IBMQ` and `qiskit.Aer` instead
(`backends()`).
"""
warnings.warn('the global get_backend() will be deprecated after 0.6. Please '
'use the qiskit.IBMQ.backends() and qiskit.Aer.backends() '
'method instead with the "name" parameter.'
'(or qiskit.IBMQ.get_backend() and qiskit.Aer.get_backend())',
DeprecationWarning)
try:
return Aer.get_backend(name)
except KeyError:
return IBMQ.get_backend(name)
# Functions for compiling and executing.
def compile(circuits, backend,
config=None, basis_gates=None, coupling_map=None, initial_layout=None,
shots=1024, max_credits=10, seed=None, qobj_id=None, hpc=None,
skip_transpiler=False):
"""Compile a list of circuits into a qobj.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend or str): a backend to compile for
config (dict): dictionary of parameters (e.g. noise) used by runner
basis_gates (str): comma-separated basis gate set to compile to
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
shots (int): number of repetitions of each circuit, for sampling
max_credits (int): maximum credits to use
seed (int): random seed for simulators
qobj_id (int): identifier for the generated qobj
hpc (dict): HPC simulator parameters
skip_transpiler (bool): skip most of the compile steps and produce qobj directly
Returns:
Qobj: the qobj to be run on the backends
Raises:
TranspilerError: in case of bad compile options, e.g. the hpc options.
.. deprecated:: 0.6+
After 0.6, compile will only take a backend object.
"""
# pylint: disable=redefined-builtin
if isinstance(backend, str):
warnings.warn('compile() no longer takes backend string names.'
'Please pass backend objects, obtained via'
'IBMQ.get_backend() or Aer.get_backend().', DeprecationWarning)
try:
backend = Aer.get_backend(backend)
except KeyError:
backend = IBMQ.get_backend(backend)
pass_manager = None # default pass manager which executes predetermined passes
# TODO (jay) why do we need to pass skip and not pass manager directly
if skip_transpiler: # empty pass manager which does nothing
pass_manager = PassManager()
qobj_standard = transpiler.compile(circuits, backend, config, basis_gates, coupling_map,
initial_layout, shots, max_credits, seed, qobj_id, hpc,
pass_manager)
return qobj_standard
def execute(circuits, backend,
config=None, basis_gates=None, coupling_map=None, initial_layout=None,
shots=1024, max_credits=10, seed=None, qobj_id=None, hpc=None,
skip_transpiler=False):
"""Executes a set of circuits.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute
backend (BaseBackend or str): a backend to execute the circuits on
config (dict): dictionary of parameters (e.g. noise) used by runner
basis_gates (str): comma-separated basis gate set to compile to
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
shots (int): number of repetitions of each circuit, for sampling
max_credits (int): maximum credits to use
seed (int): random seed for simulators
qobj_id (int): identifier for the generated qobj
hpc (dict): HPC simulator parameters
skip_transpiler (bool): skip most of the compile steps and produce qobj directly
Returns:
BaseJob: returns job instance derived from BaseJob
.. deprecated:: 0.6+
After 0.6, execute will only take a backend object, not string.
"""
# pylint: disable=missing-param-doc, missing-type-doc
if isinstance(backend, str):
warnings.warn('execute() no longer takes backend string names. '
'Please pass backend objects, obtained via'
'IBMQ.get_backend() or Aer.get_backend().', DeprecationWarning)
try:
backend = Aer.get_backend(backend)
except KeyError:
backend = IBMQ.get_backend(backend)
qobj = compile(circuits, backend,
config, basis_gates, coupling_map, initial_layout,
shots, max_credits, seed, qobj_id, hpc,
skip_transpiler)
return backend.run(qobj)
# Functions for importing qasm
def load_qasm_string(qasm_string, name=None,
basis_gates="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap"):
"""Construct a quantum circuit from a qasm representation (string).
Args:
qasm_string (str): a string of qasm, or a filename containing qasm.
basis_gates (str): basis gates for the quantum circuit.
name (str or None): the name of the quantum circuit after loading qasm
text into it. If no name given, assign automatically.
Returns:
QuantumCircuit: circuit constructed from qasm.
Raises:
QISKitError: if the string is not valid QASM
"""
return circuit_from_qasm_string(qasm_string, name, basis_gates)
def load_qasm_file(qasm_file, name=None,
basis_gates="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap"):
"""Construct a quantum circuit from a qasm representation (file).
Args:
qasm_file (str): a string for the filename including its location.
name (str or None): the name of the quantum circuit after
loading qasm text into it. If no name is give the name is of
the text file.
basis_gates (str): basis gates for the quantum circuit.
Returns:
QuantumCircuit: circuit constructed from qasm.
Raises:
QISKitError: if the file cannot be read.
"""
return circuit_from_qasm_file(qasm_file, name, basis_gates)
def qobj_to_circuits(qobj):
"""Return a list of QuantumCircuit object(s) from a qobj
Args:
qobj (Qobj): The Qobj object to convert to QuantumCircuits
Returns:
list: A list of QuantumCircuit objects from the qobj
"""
if qobj.experiments:
circuits = []
for x in qobj.experiments:
if hasattr(x.header, 'compiled_circuit_qasm'):
circuits.append(
load_qasm_string(x.header.compiled_circuit_qasm))
return circuits
# TODO(mtreinish): add support for converting a qobj if the qasm isn't
# embedded in the header
return None
<|code_end|>
|
Using simulator instructions crashes the latex drawer
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: latest master
- **Python version**: 3.7
- **Operating system**: linux
### What is the current behavior?
Attempting to use the latex drawer to render a circuit with simulator instructions stack traces in the dagunroller. For example:
```
Traceback (most recent call last):
File "test_qiskit.py", line 67, in <module>
visualization.generate_latex_source(qc, filename='out.tex')
File "/tmp/qiskit/qiskit-terra/qiskit/tools/visualization/_circuit_visualization.py", line 354, in generate_latex_source
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
File "/tmp/qiskit/qiskit-terra/qiskit/transpiler/_transpiler.py", line 346, in transpile
dag = dag_unroller.expand_gates()
File "/tmp/qiskit/qiskit-terra/qiskit/unroll/_dagunroller.py", line 86, in expand_gates
not self.dag_circuit.gates[current_node["name"]]["opaque"]:
KeyError: 'snapshot'
```
It looks like it's trying to treat the snapshot instruction as a gate (which it's not) and that's causing things to crash.
### Steps to reproduce the problem
I've been running:
```
import qiskit.extensions.simulator
from qiskit import *
from qiskit.tools import visualization
q = QuantumRegister(2)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.x(q[0])
qc.snapshot(slot=3)
qc.x(q[1])
qc.h(q[0])
qc.barrier()
qc.measure(q[0], c[0])
visualization.generate_latex_source(qc, filename='out.tex')
```
Also replacing snapshot() with save(), load(), and noise()
### What is the expected behavior?
This should draw a circuit (the barriers won't be drawn for the simulator instructions, that's what I was working on adding when I encountered this) and not stack trace.
### Suggested solutions
Fix the crash.
|
qiskit/unroll/_dagunroller.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
DAG Unroller
"""
import networkx as nx
from qiskit.unroll import Unroller
from qiskit.qasm._node import Real, Id, IdList, ExpressionList, Gate, \
PrimaryList, Int, IndexedId, Qreg, If, Creg, \
Program, CustomUnitary
from ._unrollererror import UnrollerError
from ._dagbackend import DAGBackend
class DagUnroller(object):
"""An Unroller that takes Dag circuits as the input."""
def __init__(self, dag_circuit, backend=None):
if dag_circuit is None:
raise UnrollerError('Invalid dag circuit!!')
self.dag_circuit = dag_circuit
self.backend = backend
def set_backend(self, backend):
"""Set the backend object."""
self.backend = backend
def execute(self):
"""Interpret OPENQASM and make appropriate backend calls."""
if self.backend is not None:
self._process()
return self.backend.get_output()
else:
raise UnrollerError("backend not attached")
# TODO This method should merge with .execute(), so the output will depend
# on the backend associated with this DagUnroller instance
def expand_gates(self, basis=None):
"""Expand all gate nodes to the given basis.
If basis is empty, each custom gate node is replaced by its
implementation over U and CX. If basis contains names, then
those custom gates are not expanded. For example, if "u3"
is in basis, then the gate "u3" will not be expanded wherever
it occurs.
This member function replicates the behavior of the unroller
module without using the OpenQASM parser.
"""
if basis is None:
basis = self.backend.basis
if not isinstance(self.backend, DAGBackend):
raise UnrollerError("expand_gates only accepts a DAGBackend!!")
# Build the Gate AST nodes for user-defined gates
gatedefs = []
for name, gate in self.dag_circuit.gates.items():
children = [Id(name, 0, "")]
if gate["n_args"] > 0:
children.append(ExpressionList(list(
map(lambda x: Id(x, 0, ""),
gate["args"])
)))
children.append(IdList(list(
map(lambda x: Id(x, 0, ""),
gate["bits"])
)))
children.append(gate["body"])
gatedefs.append(Gate(children))
# Walk through the DAG and examine each node
builtins = ["U", "CX", "measure", "reset", "barrier"]
topological_sorted_list = list(nx.topological_sort(self.dag_circuit.multi_graph))
for node in topological_sorted_list:
current_node = self.dag_circuit.multi_graph.node[node]
if current_node["type"] == "op" and \
current_node["name"] not in builtins + basis and \
not self.dag_circuit.gates[current_node["name"]]["opaque"]:
subcircuit, wires = self._build_subcircuit(gatedefs,
basis,
current_node["name"],
current_node["params"],
current_node["qargs"],
current_node["condition"])
self.dag_circuit.substitute_circuit_one(node, subcircuit, wires)
return self.dag_circuit
def _build_subcircuit(self, gatedefs, basis, gate_name, gate_params, gate_args,
gate_condition):
"""Build DAGCircuit for a given user-defined gate node.
gatedefs = dictionary of Gate AST nodes for user-defined gates
gate_name = name of gate to expand to target_basis (nd["name"])
gate_params = list of gate parameters (nd["params"])
gate_args = list of gate arguments (nd["qargs"])
gate_condition = None or tuple (string, int) (nd["condition"])
Returns (subcircuit, wires) where subcircuit is the DAGCircuit
corresponding to the user-defined gate node expanded to target_basis
and wires is the list of input wires to the subcircuit in order
corresponding to the gate's arguments.
"""
children = [Id(gate_name, 0, "")]
if gate_params:
children.append(
ExpressionList(list(map(Real, gate_params)))
)
new_wires = [("q", j) for j in range(len(gate_args))]
children.append(
PrimaryList(
list(map(lambda x: IndexedId(
[Id(x[0], 0, ""), Int(x[1])]
), new_wires))
)
)
gate_node = CustomUnitary(children)
id_int = [Id("q", 0, ""), Int(len(gate_args))]
# Make a list of register declaration nodes
reg_nodes = [
Qreg(
[
IndexedId(id_int)
]
)
]
# Add an If node when there is a condition present
if gate_condition:
gate_node = If([
Id(gate_condition[0], 0, ""),
Int(gate_condition[1]),
gate_node
])
new_wires += [(gate_condition[0], j)
for j in range(self.dag_circuit.cregs[gate_condition[0]])]
reg_nodes.append(
Creg([
IndexedId([
Id(gate_condition[0], 0, ""),
Int(self.dag_circuit.cregs[gate_condition[0]])
])
])
)
# Build the whole program's AST
sub_ast = Program(gatedefs + reg_nodes + [gate_node])
# Interpret the AST to give a new DAGCircuit over backend basis
sub_circuit = Unroller(sub_ast, DAGBackend(basis)).execute()
return sub_circuit, new_wires
def _process(self):
for name, width in self.dag_circuit.qregs.items():
self.backend.new_qreg(name, width)
for name, width in self.dag_circuit.cregs.items():
self.backend.new_creg(name, width)
for name, data in self.dag_circuit.gates.items():
self.backend.define_gate(name, data)
for n in nx.topological_sort(self.dag_circuit.multi_graph):
current_node = self.dag_circuit.multi_graph.node[n]
if current_node["type"] == "op":
params = map(Real, current_node["params"])
params = list(params)
if current_node["condition"] is not None:
self.backend.set_condition(current_node["condition"][0],
current_node["condition"][1])
if not current_node["cargs"]:
if current_node["name"] == "U":
self.backend.u(params, current_node["qargs"][0])
elif current_node["name"] == "CX":
self.backend.cx(current_node["qargs"][0], current_node["qargs"][1])
elif current_node["name"] == "barrier":
self.backend.barrier([current_node["qargs"]])
elif current_node["name"] == "reset":
self.backend.reset(current_node["qargs"][0])
# TODO: The schema of the snapshot gate is radically
# different to other QASM instructions. The current model
# of extensions does not support generating custom Qobj
# instructions (only custom QASM strings) and the default
# instruction generator is not enough to produce a valid
# snapshot instruction for the new Qobj format.
#
# This is a hack since there would be mechanisms for the
# extensions to provide their own Qobj instructions.
# Extensions should not be hardcoded in the DAGUnroller.
elif current_node["name"] == "snapshot":
self.backend.start_gate(
"snapshot", params, current_node["qargs"],
extra_fields={'type': 'MISSING', 'label': 'MISSING', 'texparams': []})
self.backend.end_gate("snapshot", params, current_node["qargs"])
else:
self.backend.start_gate(current_node["name"], params,
current_node["qargs"])
self.backend.end_gate(current_node["name"], params, current_node["qargs"])
else:
if current_node["name"] == "measure":
if len(current_node["cargs"]) != 1 or len(current_node["qargs"]) != 1 \
or current_node["params"]:
raise UnrollerError("Bad node data!!")
self.backend.measure(current_node["qargs"][0], current_node["cargs"][0])
else:
raise UnrollerError("Bad node data!")
self.backend.drop_condition()
return self.backend.get_output()
<|code_end|>
|
qiskit/unroll/_dagunroller.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
DAG Unroller
"""
import networkx as nx
from qiskit.unroll import Unroller
from qiskit.qasm._node import Real, Id, IdList, ExpressionList, Gate, \
PrimaryList, Int, IndexedId, Qreg, If, Creg, \
Program, CustomUnitary
from ._unrollererror import UnrollerError
from ._dagbackend import DAGBackend
class DagUnroller(object):
"""An Unroller that takes Dag circuits as the input."""
def __init__(self, dag_circuit, backend=None):
if dag_circuit is None:
raise UnrollerError('Invalid dag circuit!!')
self.dag_circuit = dag_circuit
self.backend = backend
def set_backend(self, backend):
"""Set the backend object."""
self.backend = backend
def execute(self):
"""Interpret OPENQASM and make appropriate backend calls."""
if self.backend is not None:
self._process()
return self.backend.get_output()
else:
raise UnrollerError("backend not attached")
# TODO This method should merge with .execute(), so the output will depend
# on the backend associated with this DagUnroller instance
def expand_gates(self, basis=None):
"""Expand all gate nodes to the given basis.
If basis is empty, each custom gate node is replaced by its
implementation over U and CX. If basis contains names, then
those custom gates are not expanded. For example, if "u3"
is in basis, then the gate "u3" will not be expanded wherever
it occurs.
This member function replicates the behavior of the unroller
module without using the OpenQASM parser.
"""
if basis is None:
basis = self.backend.basis
if not isinstance(self.backend, DAGBackend):
raise UnrollerError("expand_gates only accepts a DAGBackend!!")
# Build the Gate AST nodes for user-defined gates
gatedefs = []
for name, gate in self.dag_circuit.gates.items():
children = [Id(name, 0, "")]
if gate["n_args"] > 0:
children.append(ExpressionList(list(
map(lambda x: Id(x, 0, ""),
gate["args"])
)))
children.append(IdList(list(
map(lambda x: Id(x, 0, ""),
gate["bits"])
)))
children.append(gate["body"])
gatedefs.append(Gate(children))
# Walk through the DAG and examine each node
builtins = ["U", "CX", "measure", "reset", "barrier"]
simulator_builtins = ['snapshot', 'save', 'load', 'noise']
topological_sorted_list = list(nx.topological_sort(self.dag_circuit.multi_graph))
for node in topological_sorted_list:
current_node = self.dag_circuit.multi_graph.node[node]
if current_node["type"] == "op" and \
current_node["name"] not in builtins + basis + simulator_builtins and \
not self.dag_circuit.gates[current_node["name"]]["opaque"]:
subcircuit, wires = self._build_subcircuit(gatedefs,
basis,
current_node["name"],
current_node["params"],
current_node["qargs"],
current_node["condition"])
self.dag_circuit.substitute_circuit_one(node, subcircuit, wires)
return self.dag_circuit
def _build_subcircuit(self, gatedefs, basis, gate_name, gate_params, gate_args,
gate_condition):
"""Build DAGCircuit for a given user-defined gate node.
gatedefs = dictionary of Gate AST nodes for user-defined gates
gate_name = name of gate to expand to target_basis (nd["name"])
gate_params = list of gate parameters (nd["params"])
gate_args = list of gate arguments (nd["qargs"])
gate_condition = None or tuple (string, int) (nd["condition"])
Returns (subcircuit, wires) where subcircuit is the DAGCircuit
corresponding to the user-defined gate node expanded to target_basis
and wires is the list of input wires to the subcircuit in order
corresponding to the gate's arguments.
"""
children = [Id(gate_name, 0, "")]
if gate_params:
children.append(
ExpressionList(list(map(Real, gate_params)))
)
new_wires = [("q", j) for j in range(len(gate_args))]
children.append(
PrimaryList(
list(map(lambda x: IndexedId(
[Id(x[0], 0, ""), Int(x[1])]
), new_wires))
)
)
gate_node = CustomUnitary(children)
id_int = [Id("q", 0, ""), Int(len(gate_args))]
# Make a list of register declaration nodes
reg_nodes = [
Qreg(
[
IndexedId(id_int)
]
)
]
# Add an If node when there is a condition present
if gate_condition:
gate_node = If([
Id(gate_condition[0], 0, ""),
Int(gate_condition[1]),
gate_node
])
new_wires += [(gate_condition[0], j)
for j in range(self.dag_circuit.cregs[gate_condition[0]])]
reg_nodes.append(
Creg([
IndexedId([
Id(gate_condition[0], 0, ""),
Int(self.dag_circuit.cregs[gate_condition[0]])
])
])
)
# Build the whole program's AST
sub_ast = Program(gatedefs + reg_nodes + [gate_node])
# Interpret the AST to give a new DAGCircuit over backend basis
sub_circuit = Unroller(sub_ast, DAGBackend(basis)).execute()
return sub_circuit, new_wires
def _process(self):
for name, width in self.dag_circuit.qregs.items():
self.backend.new_qreg(name, width)
for name, width in self.dag_circuit.cregs.items():
self.backend.new_creg(name, width)
for name, data in self.dag_circuit.gates.items():
self.backend.define_gate(name, data)
for n in nx.topological_sort(self.dag_circuit.multi_graph):
current_node = self.dag_circuit.multi_graph.node[n]
if current_node["type"] == "op":
params = map(Real, current_node["params"])
params = list(params)
if current_node["condition"] is not None:
self.backend.set_condition(current_node["condition"][0],
current_node["condition"][1])
if not current_node["cargs"]:
if current_node["name"] == "U":
self.backend.u(params, current_node["qargs"][0])
elif current_node["name"] == "CX":
self.backend.cx(current_node["qargs"][0], current_node["qargs"][1])
elif current_node["name"] == "barrier":
self.backend.barrier([current_node["qargs"]])
elif current_node["name"] == "reset":
self.backend.reset(current_node["qargs"][0])
# TODO: The schema of the snapshot gate is radically
# different to other QASM instructions. The current model
# of extensions does not support generating custom Qobj
# instructions (only custom QASM strings) and the default
# instruction generator is not enough to produce a valid
# snapshot instruction for the new Qobj format.
#
# This is a hack since there would be mechanisms for the
# extensions to provide their own Qobj instructions.
# Extensions should not be hardcoded in the DAGUnroller.
elif current_node["name"] == "snapshot":
self.backend.start_gate(
"snapshot", params, current_node["qargs"],
extra_fields={'type': 'MISSING', 'label': 'MISSING', 'texparams': []})
self.backend.end_gate("snapshot", params, current_node["qargs"])
else:
self.backend.start_gate(current_node["name"], params,
current_node["qargs"])
self.backend.end_gate(current_node["name"], params, current_node["qargs"])
else:
if current_node["name"] == "measure":
if len(current_node["cargs"]) != 1 or len(current_node["qargs"]) != 1 \
or current_node["params"]:
raise UnrollerError("Bad node data!!")
self.backend.measure(current_node["qargs"][0], current_node["cargs"][0])
else:
raise UnrollerError("Bad node data!")
self.backend.drop_condition()
return self.backend.get_output()
<|code_end|>
|
_matches_coupling_map seems to check single qubit ops too and fails
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: 0.6.0
- **Python version**: 3.6
- **Operating system**: macos
### What is the current behavior?
Using _matches_coupling_map breaks and returns false at first single qubit op as single qubits are not in the coupling map
### Steps to reproduce the problem
Run the function on a dag
### What is the expected behavior?
Ignore single qubits ops
### Suggested solutions
Check no of qubits. Have fixed and pull request ready to go if ok. 👍
|
qiskit/transpiler/_transpiler.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Tools for compiling a batch of quantum circuits."""
from copy import deepcopy
import logging
import uuid
import numpy as np
import scipy.sparse as sp
import scipy.sparse.csgraph as cs
from qiskit.transpiler._transpilererror import TranspilerError
from qiskit._qiskiterror import QISKitError
from qiskit import QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.unroll import DagUnroller, DAGBackend, JsonBackend
from qiskit.mapper import (Coupling, optimize_1q_gates, coupling_list2dict, swap_mapper,
cx_cancellation, direction_mapper,
remove_last_measurements, return_last_measurements)
from qiskit.qobj import Qobj, QobjConfig, QobjExperiment, QobjItem, QobjHeader
from ._parallel import parallel_map
logger = logging.getLogger(__name__)
# pylint: disable=redefined-builtin
def compile(circuits, backend,
config=None, basis_gates=None, coupling_map=None, initial_layout=None,
shots=1024, max_credits=10, seed=None, qobj_id=None, hpc=None,
pass_manager=None):
"""Compile a list of circuits into a qobj.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend): a backend to compile for
config (dict): dictionary of parameters (e.g. noise) used by runner
basis_gates (str): comma-separated basis gate set to compile to
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
shots (int): number of repetitions of each circuit, for sampling
max_credits (int): maximum credits to use
seed (int): random seed for simulators
qobj_id (int): identifier for the generated qobj
hpc (dict): HPC simulator parameters
pass_manager (PassManager): a pass_manager for the transpiler stage
Returns:
QobjExperiment: Experiment to be wrapped in a Qobj.
Raises:
TranspilerError: in case of bad compile options, e.g. the hpc options.
"""
if isinstance(circuits, QuantumCircuit):
circuits = [circuits]
# FIXME: THIS NEEDS TO BE CLEANED UP -- some things to decide for list of circuits:
# 1. do all circuits have same coupling map?
# 2. do all circuit have the same basis set?
# 3. do they all have same registers etc?
backend_conf = backend.configuration()
backend_name = backend_conf['name']
# Check for valid parameters for the experiments.
if hpc is not None and \
not all(key in hpc for key in ('multi_shot_optimization', 'omp_num_threads')):
raise TranspilerError('Unknown HPC parameter format!')
basis_gates = basis_gates or backend_conf['basis_gates']
coupling_map = coupling_map or backend_conf['coupling_map']
# step 1: Making the list of dag circuits
dags = _circuits_2_dags(circuits)
# step 2: Transpile all the dags
# FIXME: Work-around for transpiling multiple circuits with different qreg names.
# Make compile take a list of initial_layouts.
_initial_layout = initial_layout
# Pick a good initial layout if coupling_map is not already satisfied
# otherwise keep it as q[i]->q[i].
# TODO: move this inside mapper pass.
initial_layouts = []
for dag in dags:
if (initial_layout is None and not backend.configuration()['simulator']
and not _matches_coupling_map(dag, coupling_map)):
_initial_layout = _pick_best_layout(dag, backend)
initial_layouts.append(_initial_layout)
dags = _transpile_dags(dags, basis_gates=basis_gates, coupling_map=coupling_map,
initial_layouts=initial_layouts, seed=seed,
pass_manager=pass_manager)
# step 3: Making a qobj
qobj = _dags_2_qobj(dags, backend_name=backend_name,
config=config, shots=shots, max_credits=max_credits,
qobj_id=qobj_id, basis_gates=basis_gates,
coupling_map=coupling_map, seed=seed)
return qobj
def _circuits_2_dags(circuits):
"""Convert a list of circuits into a list of dags.
Args:
circuits (list[QuantumCircuit]): circuit to compile
Returns:
list[DAGCircuit]: the dag representation of the circuits
to be used in the transpiler
"""
dags = parallel_map(DAGCircuit.fromQuantumCircuit, circuits)
return dags
def _transpile_dags(dags, basis_gates='u1,u2,u3,cx,id', coupling_map=None,
initial_layouts=None, seed=None, pass_manager=None):
"""Transform multiple dags through a sequence of passes.
Args:
dags (list[DAGCircuit]): dag circuits to transform
basis_gates (str): a comma seperated string for the target basis gates
coupling_map (list): A graph of coupling
initial_layouts (list[dict]): A mapping of qubit to qubit for each dag
seed (int): random seed for the swap mapper
pass_manager (PassManager): pass manager instance for the tranpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
list[DAGCircuit]: the dag circuits after going through transpilation
Raises:
TranspilerError: if the format is not valid.
"""
index = list(range(len(dags)))
final_dags = parallel_map(_transpile_dags_parallel, index,
task_args=(dags, initial_layouts),
task_kwargs={'basis_gates': basis_gates,
'coupling_map': coupling_map,
'seed': seed,
'pass_manager': pass_manager})
return final_dags
def _transpile_dags_parallel(idx, dags, initial_layouts, basis_gates='u1,u2,u3,cx,id',
coupling_map=None, seed=None, pass_manager=None):
"""Helper function for transpiling in parallel (if available).
Args:
idx (int): Index for dag of interest
dags (list): List of dags
initial_layouts (list): List of initial layouts
basis_gates (str): a comma seperated string for the target basis gates
coupling_map (list): A graph of coupling
seed (int): random seed for the swap mapper
pass_manager (PassManager): pass manager instance for the tranpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
DAGCircuit: DAG circuit after going through transpilation.
"""
dag = dags[idx]
initial_layout = initial_layouts[idx]
final_dag, final_layout = transpile(
dag,
basis_gates=basis_gates,
coupling_map=coupling_map,
initial_layout=initial_layout,
get_layout=True,
seed=seed,
pass_manager=pass_manager)
final_dag.layout = [[k, v]
for k, v in final_layout.items()] if final_layout else None
return final_dag
def _dags_2_qobj(dags, backend_name, config=None, shots=None,
max_credits=None, qobj_id=None, basis_gates=None, coupling_map=None,
seed=None):
"""Convert a list of dags into a qobj.
Args:
dags (list[DAGCircuit]): dags to compile
backend_name (str): name of runner backend
config (dict): dictionary of parameters (e.g. noise) used by runner
shots (int): number of repetitions of each circuit, for sampling
max_credits (int): maximum credits to use
qobj_id (int): identifier for the generated qobj
basis_gates (list[str])): basis gates for the experiment
coupling_map (list): coupling map (perhaps custom) to target in mapping
seed (int): random seed for simulators
Returns:
Qobj: the Qobj to be run on the backends
"""
# TODO: the following will be removed from qobj and thus removed here:
# `basis_gates`, `coupling_map`
# Step 1: create the Qobj, with empty experiments.
# Copy the configuration: the values in `config` have preference
qobj_config = deepcopy(config or {})
# TODO: "memory_slots" is required by the qobj schema in the top-level
# qobj.config, and is user-defined. At the moment is set to the maximum
# number of *register* slots for the circuits, in order to have `measure`
# behave properly until the transition is over; and each circuit stores
# its memory_slots in its configuration.
qobj_config.update({'shots': shots,
'max_credits': max_credits,
'memory_slots': 0})
qobj = Qobj(qobj_id=qobj_id or str(uuid.uuid4()),
config=QobjConfig(**qobj_config),
experiments=[],
header=QobjHeader(backend_name=backend_name))
if seed:
qobj.config.seed = seed
qobj.experiments = parallel_map(_dags_2_qobj_parallel, dags,
task_kwargs={'basis_gates': basis_gates,
'config': config,
'coupling_map': coupling_map})
# Update the `memory_slots` value.
# TODO: remove when `memory_slots` can be provided by the user.
qobj.config.memory_slots = max(experiment.config.memory_slots for
experiment in qobj.experiments)
# Update the `n_qubits` global value.
# TODO: num_qubits is not part of the qobj specification, but needed
# for the simulator.
qobj.config.n_qubits = max(experiment.config.n_qubits for
experiment in qobj.experiments)
return qobj
def _dags_2_qobj_parallel(dag, config=None, basis_gates=None,
coupling_map=None):
"""Helper function for dags to qobj in parallel (if available).
Args:
dag (DAGCircuit): DAG to compile
config (dict): dictionary of parameters (e.g. noise) used by runner
basis_gates (list[str])): basis gates for the experiment
coupling_map (list): coupling map (perhaps custom) to target in mapping
Returns:
Qobj: Qobj to be run on the backends
"""
json_circuit = DagUnroller(dag, JsonBackend(dag.basis)).execute()
# Step 3a: create the Experiment based on json_circuit
experiment = QobjExperiment.from_dict(json_circuit)
# Step 3b: populate the Experiment configuration and header
experiment.header.name = dag.name
# TODO: place in header or config?
experiment_config = deepcopy(config or {})
experiment_config.update({
'coupling_map': coupling_map,
'basis_gates': basis_gates,
'layout': dag.layout,
'memory_slots': sum(dag.cregs.values()),
# TODO: `n_qubits` is not part of the qobj spec, but needed for the simulator.
'n_qubits': sum(dag.qregs.values())})
experiment.config = QobjItem(**experiment_config)
# set eval_symbols=True to evaluate each symbolic expression
# TODO: after transition to qobj, we can drop this
experiment.header.compiled_circuit_qasm = dag.qasm(
qeflag=True, eval_symbols=True)
# Step 3c: add the Experiment to the Qobj
return experiment
def transpile(dag, basis_gates='u1,u2,u3,cx,id', coupling_map=None,
initial_layout=None, get_layout=False,
format='dag', seed=None, pass_manager=None):
"""Transform a dag circuit into another dag circuit (transpile), through
consecutive passes on the dag.
Args:
dag (DAGCircuit): dag circuit to transform via transpilation
basis_gates (str): a comma seperated string for the target basis gates
coupling_map (list): A graph of coupling::
[
[control0(int), target0(int)],
[control1(int), target1(int)],
]
eg. [[0, 2], [1, 2], [1, 3], [3, 4]}
initial_layout (dict): A mapping of qubit to qubit::
{
("q", start(int)): ("q", final(int)),
...
}
eg.
{
("q", 0): ("q", 0),
("q", 1): ("q", 1),
("q", 2): ("q", 2),
("q", 3): ("q", 3)
}
get_layout (bool): flag for returning the final layout after mapping
format (str): The target format of the compilation:
{'dag', 'json', 'qasm'}
seed (int): random seed for the swap mapper
pass_manager (PassManager): pass manager instance for the tranpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
DAGCircuit: transformed dag
DAGCircuit, dict: transformed dag along with the final layout on backend qubits
Raises:
TranspilerError: if the format is not valid.
"""
# TODO: `basis_gates` will be removed after we have the unroller pass.
# TODO: `coupling_map`, `initial_layout`, `get_layout`, `seed` removed after mapper pass.
# TODO: move this to the mapper pass
num_qubits = sum(dag.qregs.values())
if num_qubits == 1 or coupling_map == "all-to-all":
coupling_map = None
final_layout = None
if pass_manager:
# run the passes specified by the pass manager
for pass_ in pass_manager.passes():
pass_.run(dag)
else:
# default set of passes
# TODO: move each step here to a pass, and use a default passmanager below
basis = basis_gates.split(',') if basis_gates else []
dag_unroller = DagUnroller(dag, DAGBackend(basis))
dag = dag_unroller.expand_gates()
# if a coupling map is given compile to the map
if coupling_map:
logger.info("pre-mapping properties: %s",
dag.property_summary())
# Insert swap gates
coupling = Coupling(coupling_list2dict(coupling_map))
removed_meas = remove_last_measurements(dag)
logger.info("measurements moved: %s", removed_meas)
logger.info("initial layout: %s", initial_layout)
dag, final_layout, last_layout = swap_mapper(
dag, coupling, initial_layout, trials=20, seed=seed)
logger.info("final layout: %s", final_layout)
# Expand swaps
dag_unroller = DagUnroller(dag, DAGBackend(basis))
dag = dag_unroller.expand_gates()
# Change cx directions
dag = direction_mapper(dag, coupling)
# Simplify cx gates
cx_cancellation(dag)
# Simplify single qubit gates
dag = optimize_1q_gates(dag)
return_last_measurements(dag, removed_meas,
last_layout)
logger.info("post-mapping properties: %s",
dag.property_summary())
# choose output format
# TODO: do we need all of these formats, or just the dag?
if format == 'dag':
compiled_circuit = dag
elif format == 'json':
# FIXME: JsonBackend is wrongly taking an ordered dict as basis, not list
dag_unroller = DagUnroller(dag, JsonBackend(dag.basis))
compiled_circuit = dag_unroller.execute()
elif format == 'qasm':
compiled_circuit = dag.qasm()
else:
raise TranspilerError('unrecognized circuit format')
if get_layout:
return compiled_circuit, final_layout
return compiled_circuit
def _best_subset(backend, n_qubits):
"""Computes the qubit mapping with the best
connectivity.
Parameters:
backend (Qiskit.BaseBackend): A QISKit backend instance.
n_qubits (int): Number of subset qubits to consider.
Returns:
ndarray: Array of qubits to use for best
connectivity mapping.
Raises:
QISKitError: Wrong number of qubits given.
"""
if n_qubits == 1:
return np.array([0])
elif n_qubits <= 0:
raise QISKitError('Number of qubits <= 0.')
device_qubits = backend.configuration()['n_qubits']
if n_qubits > device_qubits:
raise QISKitError('Number of qubits greater than device.')
cmap = np.asarray(backend.configuration()['coupling_map'])
data = np.ones_like(cmap[:, 0])
sp_cmap = sp.coo_matrix((data, (cmap[:, 0], cmap[:, 1])),
shape=(device_qubits, device_qubits)).tocsr()
best = 0
best_map = None
# do bfs with each node as starting point
for k in range(sp_cmap.shape[0]):
bfs = cs.breadth_first_order(sp_cmap, i_start=k, directed=False,
return_predecessors=False)
connection_count = 0
for i in range(n_qubits):
node_idx = bfs[i]
for j in range(sp_cmap.indptr[node_idx],
sp_cmap.indptr[node_idx + 1]):
node = sp_cmap.indices[j]
for counter in range(n_qubits):
if node == bfs[counter]:
connection_count += 1
break
if connection_count > best:
best = connection_count
best_map = bfs[0:n_qubits]
return best_map
def _matches_coupling_map(dag, coupling_map):
"""Iterate over circuit gates to check if all multi-qubit couplings
match the qubit coupling graph in the backend.
Parameters:
dag (DAGCircuit): DAG representation of circuit.
coupling_map (list): Backend coupling map, represented as an adjacency list.
Returns:
bool: True if all gates readily fit the backend coupling graph.
False if there's at least one gate that uses multiple qubits
which does not match the backend couplings.
"""
match = True
for _, data in dag.multi_graph.nodes(data=True):
if data['type'] == 'op':
gate_map = [qr[1] for qr in data['qargs']]
if gate_map not in coupling_map:
match = False
break
return match
def _pick_best_layout(dag, backend):
"""Pick a convenient layout depending on the best matching qubit connectivity
Parameters:
dag (DAGCircuit): DAG representation of circuit.
backend (BaseBackend) : The backend with the coupling_map for searching
Returns:
dict: A special ordered initial_layout
"""
num_qubits = sum(dag.qregs.values())
best_sub = _best_subset(backend, num_qubits)
layout = {}
map_iter = 0
for key, value in dag.qregs.items():
for i in range(value):
layout[(key, i)] = ('q', best_sub[map_iter])
map_iter += 1
return layout
<|code_end|>
|
qiskit/transpiler/_transpiler.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Tools for compiling a batch of quantum circuits."""
from copy import deepcopy
import logging
import uuid
import numpy as np
import scipy.sparse as sp
import scipy.sparse.csgraph as cs
from qiskit.transpiler._transpilererror import TranspilerError
from qiskit._qiskiterror import QISKitError
from qiskit import QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.unroll import DagUnroller, DAGBackend, JsonBackend
from qiskit.mapper import (Coupling, optimize_1q_gates, coupling_list2dict, swap_mapper,
cx_cancellation, direction_mapper,
remove_last_measurements, return_last_measurements)
from qiskit.qobj import Qobj, QobjConfig, QobjExperiment, QobjItem, QobjHeader
from ._parallel import parallel_map
logger = logging.getLogger(__name__)
# pylint: disable=redefined-builtin
def compile(circuits, backend,
config=None, basis_gates=None, coupling_map=None, initial_layout=None,
shots=1024, max_credits=10, seed=None, qobj_id=None, hpc=None,
pass_manager=None):
"""Compile a list of circuits into a qobj.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend): a backend to compile for
config (dict): dictionary of parameters (e.g. noise) used by runner
basis_gates (str): comma-separated basis gate set to compile to
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
shots (int): number of repetitions of each circuit, for sampling
max_credits (int): maximum credits to use
seed (int): random seed for simulators
qobj_id (int): identifier for the generated qobj
hpc (dict): HPC simulator parameters
pass_manager (PassManager): a pass_manager for the transpiler stage
Returns:
QobjExperiment: Experiment to be wrapped in a Qobj.
Raises:
TranspilerError: in case of bad compile options, e.g. the hpc options.
"""
if isinstance(circuits, QuantumCircuit):
circuits = [circuits]
# FIXME: THIS NEEDS TO BE CLEANED UP -- some things to decide for list of circuits:
# 1. do all circuits have same coupling map?
# 2. do all circuit have the same basis set?
# 3. do they all have same registers etc?
backend_conf = backend.configuration()
backend_name = backend_conf['name']
# Check for valid parameters for the experiments.
if hpc is not None and \
not all(key in hpc for key in ('multi_shot_optimization', 'omp_num_threads')):
raise TranspilerError('Unknown HPC parameter format!')
basis_gates = basis_gates or backend_conf['basis_gates']
coupling_map = coupling_map or backend_conf['coupling_map']
# step 1: Making the list of dag circuits
dags = _circuits_2_dags(circuits)
# step 2: Transpile all the dags
# FIXME: Work-around for transpiling multiple circuits with different qreg names.
# Make compile take a list of initial_layouts.
_initial_layout = initial_layout
# Pick a good initial layout if coupling_map is not already satisfied
# otherwise keep it as q[i]->q[i].
# TODO: move this inside mapper pass.
initial_layouts = []
for dag in dags:
if (initial_layout is None and not backend.configuration()['simulator']
and not _matches_coupling_map(dag, coupling_map)):
_initial_layout = _pick_best_layout(dag, backend)
initial_layouts.append(_initial_layout)
dags = _transpile_dags(dags, basis_gates=basis_gates, coupling_map=coupling_map,
initial_layouts=initial_layouts, seed=seed,
pass_manager=pass_manager)
# step 3: Making a qobj
qobj = _dags_2_qobj(dags, backend_name=backend_name,
config=config, shots=shots, max_credits=max_credits,
qobj_id=qobj_id, basis_gates=basis_gates,
coupling_map=coupling_map, seed=seed)
return qobj
def _circuits_2_dags(circuits):
"""Convert a list of circuits into a list of dags.
Args:
circuits (list[QuantumCircuit]): circuit to compile
Returns:
list[DAGCircuit]: the dag representation of the circuits
to be used in the transpiler
"""
dags = parallel_map(DAGCircuit.fromQuantumCircuit, circuits)
return dags
def _transpile_dags(dags, basis_gates='u1,u2,u3,cx,id', coupling_map=None,
initial_layouts=None, seed=None, pass_manager=None):
"""Transform multiple dags through a sequence of passes.
Args:
dags (list[DAGCircuit]): dag circuits to transform
basis_gates (str): a comma seperated string for the target basis gates
coupling_map (list): A graph of coupling
initial_layouts (list[dict]): A mapping of qubit to qubit for each dag
seed (int): random seed for the swap mapper
pass_manager (PassManager): pass manager instance for the tranpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
list[DAGCircuit]: the dag circuits after going through transpilation
Raises:
TranspilerError: if the format is not valid.
"""
index = list(range(len(dags)))
final_dags = parallel_map(_transpile_dags_parallel, index,
task_args=(dags, initial_layouts),
task_kwargs={'basis_gates': basis_gates,
'coupling_map': coupling_map,
'seed': seed,
'pass_manager': pass_manager})
return final_dags
def _transpile_dags_parallel(idx, dags, initial_layouts, basis_gates='u1,u2,u3,cx,id',
coupling_map=None, seed=None, pass_manager=None):
"""Helper function for transpiling in parallel (if available).
Args:
idx (int): Index for dag of interest
dags (list): List of dags
initial_layouts (list): List of initial layouts
basis_gates (str): a comma seperated string for the target basis gates
coupling_map (list): A graph of coupling
seed (int): random seed for the swap mapper
pass_manager (PassManager): pass manager instance for the tranpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
DAGCircuit: DAG circuit after going through transpilation.
"""
dag = dags[idx]
initial_layout = initial_layouts[idx]
final_dag, final_layout = transpile(
dag,
basis_gates=basis_gates,
coupling_map=coupling_map,
initial_layout=initial_layout,
get_layout=True,
seed=seed,
pass_manager=pass_manager)
final_dag.layout = [[k, v]
for k, v in final_layout.items()] if final_layout else None
return final_dag
def _dags_2_qobj(dags, backend_name, config=None, shots=None,
max_credits=None, qobj_id=None, basis_gates=None, coupling_map=None,
seed=None):
"""Convert a list of dags into a qobj.
Args:
dags (list[DAGCircuit]): dags to compile
backend_name (str): name of runner backend
config (dict): dictionary of parameters (e.g. noise) used by runner
shots (int): number of repetitions of each circuit, for sampling
max_credits (int): maximum credits to use
qobj_id (int): identifier for the generated qobj
basis_gates (list[str])): basis gates for the experiment
coupling_map (list): coupling map (perhaps custom) to target in mapping
seed (int): random seed for simulators
Returns:
Qobj: the Qobj to be run on the backends
"""
# TODO: the following will be removed from qobj and thus removed here:
# `basis_gates`, `coupling_map`
# Step 1: create the Qobj, with empty experiments.
# Copy the configuration: the values in `config` have preference
qobj_config = deepcopy(config or {})
# TODO: "memory_slots" is required by the qobj schema in the top-level
# qobj.config, and is user-defined. At the moment is set to the maximum
# number of *register* slots for the circuits, in order to have `measure`
# behave properly until the transition is over; and each circuit stores
# its memory_slots in its configuration.
qobj_config.update({'shots': shots,
'max_credits': max_credits,
'memory_slots': 0})
qobj = Qobj(qobj_id=qobj_id or str(uuid.uuid4()),
config=QobjConfig(**qobj_config),
experiments=[],
header=QobjHeader(backend_name=backend_name))
if seed:
qobj.config.seed = seed
qobj.experiments = parallel_map(_dags_2_qobj_parallel, dags,
task_kwargs={'basis_gates': basis_gates,
'config': config,
'coupling_map': coupling_map})
# Update the `memory_slots` value.
# TODO: remove when `memory_slots` can be provided by the user.
qobj.config.memory_slots = max(experiment.config.memory_slots for
experiment in qobj.experiments)
# Update the `n_qubits` global value.
# TODO: num_qubits is not part of the qobj specification, but needed
# for the simulator.
qobj.config.n_qubits = max(experiment.config.n_qubits for
experiment in qobj.experiments)
return qobj
def _dags_2_qobj_parallel(dag, config=None, basis_gates=None,
coupling_map=None):
"""Helper function for dags to qobj in parallel (if available).
Args:
dag (DAGCircuit): DAG to compile
config (dict): dictionary of parameters (e.g. noise) used by runner
basis_gates (list[str])): basis gates for the experiment
coupling_map (list): coupling map (perhaps custom) to target in mapping
Returns:
Qobj: Qobj to be run on the backends
"""
json_circuit = DagUnroller(dag, JsonBackend(dag.basis)).execute()
# Step 3a: create the Experiment based on json_circuit
experiment = QobjExperiment.from_dict(json_circuit)
# Step 3b: populate the Experiment configuration and header
experiment.header.name = dag.name
# TODO: place in header or config?
experiment_config = deepcopy(config or {})
experiment_config.update({
'coupling_map': coupling_map,
'basis_gates': basis_gates,
'layout': dag.layout,
'memory_slots': sum(dag.cregs.values()),
# TODO: `n_qubits` is not part of the qobj spec, but needed for the simulator.
'n_qubits': sum(dag.qregs.values())})
experiment.config = QobjItem(**experiment_config)
# set eval_symbols=True to evaluate each symbolic expression
# TODO: after transition to qobj, we can drop this
experiment.header.compiled_circuit_qasm = dag.qasm(
qeflag=True, eval_symbols=True)
# Step 3c: add the Experiment to the Qobj
return experiment
def transpile(dag, basis_gates='u1,u2,u3,cx,id', coupling_map=None,
initial_layout=None, get_layout=False,
format='dag', seed=None, pass_manager=None):
"""Transform a dag circuit into another dag circuit (transpile), through
consecutive passes on the dag.
Args:
dag (DAGCircuit): dag circuit to transform via transpilation
basis_gates (str): a comma seperated string for the target basis gates
coupling_map (list): A graph of coupling::
[
[control0(int), target0(int)],
[control1(int), target1(int)],
]
eg. [[0, 2], [1, 2], [1, 3], [3, 4]}
initial_layout (dict): A mapping of qubit to qubit::
{
("q", start(int)): ("q", final(int)),
...
}
eg.
{
("q", 0): ("q", 0),
("q", 1): ("q", 1),
("q", 2): ("q", 2),
("q", 3): ("q", 3)
}
get_layout (bool): flag for returning the final layout after mapping
format (str): The target format of the compilation:
{'dag', 'json', 'qasm'}
seed (int): random seed for the swap mapper
pass_manager (PassManager): pass manager instance for the tranpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
DAGCircuit: transformed dag
DAGCircuit, dict: transformed dag along with the final layout on backend qubits
Raises:
TranspilerError: if the format is not valid.
"""
# TODO: `basis_gates` will be removed after we have the unroller pass.
# TODO: `coupling_map`, `initial_layout`, `get_layout`, `seed` removed after mapper pass.
# TODO: move this to the mapper pass
num_qubits = sum(dag.qregs.values())
if num_qubits == 1 or coupling_map == "all-to-all":
coupling_map = None
final_layout = None
if pass_manager:
# run the passes specified by the pass manager
for pass_ in pass_manager.passes():
pass_.run(dag)
else:
# default set of passes
# TODO: move each step here to a pass, and use a default passmanager below
basis = basis_gates.split(',') if basis_gates else []
dag_unroller = DagUnroller(dag, DAGBackend(basis))
dag = dag_unroller.expand_gates()
# if a coupling map is given compile to the map
if coupling_map:
logger.info("pre-mapping properties: %s",
dag.property_summary())
# Insert swap gates
coupling = Coupling(coupling_list2dict(coupling_map))
removed_meas = remove_last_measurements(dag)
logger.info("measurements moved: %s", removed_meas)
logger.info("initial layout: %s", initial_layout)
dag, final_layout, last_layout = swap_mapper(
dag, coupling, initial_layout, trials=20, seed=seed)
logger.info("final layout: %s", final_layout)
# Expand swaps
dag_unroller = DagUnroller(dag, DAGBackend(basis))
dag = dag_unroller.expand_gates()
# Change cx directions
dag = direction_mapper(dag, coupling)
# Simplify cx gates
cx_cancellation(dag)
# Simplify single qubit gates
dag = optimize_1q_gates(dag)
return_last_measurements(dag, removed_meas,
last_layout)
logger.info("post-mapping properties: %s",
dag.property_summary())
# choose output format
# TODO: do we need all of these formats, or just the dag?
if format == 'dag':
compiled_circuit = dag
elif format == 'json':
# FIXME: JsonBackend is wrongly taking an ordered dict as basis, not list
dag_unroller = DagUnroller(dag, JsonBackend(dag.basis))
compiled_circuit = dag_unroller.execute()
elif format == 'qasm':
compiled_circuit = dag.qasm()
else:
raise TranspilerError('unrecognized circuit format')
if get_layout:
return compiled_circuit, final_layout
return compiled_circuit
def _best_subset(backend, n_qubits):
"""Computes the qubit mapping with the best
connectivity.
Parameters:
backend (Qiskit.BaseBackend): A QISKit backend instance.
n_qubits (int): Number of subset qubits to consider.
Returns:
ndarray: Array of qubits to use for best
connectivity mapping.
Raises:
QISKitError: Wrong number of qubits given.
"""
if n_qubits == 1:
return np.array([0])
elif n_qubits <= 0:
raise QISKitError('Number of qubits <= 0.')
device_qubits = backend.configuration()['n_qubits']
if n_qubits > device_qubits:
raise QISKitError('Number of qubits greater than device.')
cmap = np.asarray(backend.configuration()['coupling_map'])
data = np.ones_like(cmap[:, 0])
sp_cmap = sp.coo_matrix((data, (cmap[:, 0], cmap[:, 1])),
shape=(device_qubits, device_qubits)).tocsr()
best = 0
best_map = None
# do bfs with each node as starting point
for k in range(sp_cmap.shape[0]):
bfs = cs.breadth_first_order(sp_cmap, i_start=k, directed=False,
return_predecessors=False)
connection_count = 0
for i in range(n_qubits):
node_idx = bfs[i]
for j in range(sp_cmap.indptr[node_idx],
sp_cmap.indptr[node_idx + 1]):
node = sp_cmap.indices[j]
for counter in range(n_qubits):
if node == bfs[counter]:
connection_count += 1
break
if connection_count > best:
best = connection_count
best_map = bfs[0:n_qubits]
return best_map
def _matches_coupling_map(dag, coupling_map):
"""Iterate over circuit gates to check if all multi-qubit couplings
match the qubit coupling graph in the backend.
Parameters:
dag (DAGCircuit): DAG representation of circuit.
coupling_map (list): Backend coupling map, represented as an adjacency list.
Returns:
bool: True if all gates readily fit the backend coupling graph.
False if there's at least one gate that uses multiple qubits
which does not match the backend couplings.
"""
match = True
for _, data in dag.multi_graph.nodes(data=True):
if data['type'] == 'op':
gate_map = [qr[1] for qr in data['qargs']]
if len(gate_map) > 1:
if gate_map not in coupling_map:
match = False
break
return match
def _pick_best_layout(dag, backend):
"""Pick a convenient layout depending on the best matching qubit connectivity
Parameters:
dag (DAGCircuit): DAG representation of circuit.
backend (BaseBackend) : The backend with the coupling_map for searching
Returns:
dict: A special ordered initial_layout
"""
num_qubits = sum(dag.qregs.values())
best_sub = _best_subset(backend, num_qubits)
layout = {}
map_iter = 0
for key, value in dag.qregs.items():
for i in range(value):
layout[(key, i)] = ('q', best_sub[map_iter])
map_iter += 1
return layout
<|code_end|>
|
IBMQ Provider Documentation is unclear/incorrect
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**:0.6.1
- **Python version**:
- **Operating system**:
### What is the current behavior?
- [enable_account documentation](https://qiskit.org/documentation/_autodoc/qiskit.backends.ibmq.ibmqprovider.html?highlight=enable_account#qiskit.backends.ibmq.ibmqprovider.IBMQProvider.enable_account) is unclear.
```
Authenticate and use one IBMQ account during this session.
Login into Quantum Experience or IBMQ using the provided credentials, adding the account to the current session. The account is not stored in disk.
```
The first and second sentence can be interpreted as contradictory.
- [save_account](https://qiskit.org/documentation/_autodoc/qiskit.backends.ibmq.ibmqprovider.html?highlight=save_account#qiskit.backends.ibmq.ibmqprovider.IBMQProvider.save_account) does not authenticate but claims to.
### Steps to reproduce the problem
### What is the expected behavior?
Clear, concise and correct descriptions of the methods.
### Suggested solutions
See (#1053).
|
qiskit/backends/ibmq/ibmqprovider.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Provider for remote IBMQ backends with admin features."""
import warnings
from collections import OrderedDict
from qiskit.backends import BaseProvider
from .credentials._configrc import remove_credentials
from .credentials import (Credentials,
read_credentials_from_qiskitrc, store_credentials, discover_credentials)
from .ibmqaccounterror import IBMQAccountError
from .ibmqsingleprovider import IBMQSingleProvider
QE_URL = 'https://quantumexperience.ng.bluemix.net/api'
class IBMQProvider(BaseProvider):
"""Provider for remote IBMQ backends with admin features.
This class is the entry point for handling backends from IBMQ, allowing
using different accounts.
"""
def __init__(self):
super().__init__()
# dict[credentials_unique_id: IBMQSingleProvider]
# This attribute stores a reference to the different accounts. The
# keys are tuples (hub, group, project), as the convention is that
# that tuple uniquely identifies a set of credentials.
self._accounts = OrderedDict()
def backends(self, name=None, filters=None, **kwargs):
"""Return all backends accessible via IBMQ provider, subject to optional filtering.
Args:
name (str): backend name to filter by
filters (callable): more complex filters, such as lambda functions
e.g. IBMQ.backends(filters=lambda b: b.congiguration['n_qubits'] > 5)
kwargs: simple filters specifying a true/false criteria in the
backend configuration or backend status or provider credentials
e.g. IBMQ.backends(n_qubits=5, operational=True, hub='internal')
Returns:
list[IBMQBackend]: list of backends available that match the filter
Raises:
IBMQAccountError: if no account matched the filter.
"""
# pylint: disable=arguments-differ
# Special handling of the credentials filters: match and prune from kwargs
credentials_filter = {}
for key in ['token', 'url', 'hub', 'group', 'project', 'proxies', 'verify']:
if key in kwargs:
credentials_filter[key] = kwargs.pop(key)
providers = [provider for provider in self._accounts.values() if
self._credentials_match_filter(provider.credentials,
credentials_filter)]
# Special handling of the `name` parameter, to support alias resolution.
if name:
aliases = self.aliased_backend_names()
aliases.update(self.deprecated_backend_names())
name = aliases.get(name, name)
# Aggregate the list of filtered backends.
backends = []
for provider in providers:
backends = backends + provider.backends(
name=name, filters=filters, **kwargs)
return backends
@staticmethod
def deprecated_backend_names():
"""Returns deprecated backend names."""
return {
'ibmqx_qasm_simulator': 'ibmq_qasm_simulator',
'ibmqx_hpc_qasm_simulator': 'ibmq_qasm_simulator',
'real': 'ibmqx1'
}
@staticmethod
def aliased_backend_names():
"""Returns aliased backend names."""
return {
'ibmq_5_yorktown': 'ibmqx2',
'ibmq_5_tenerife': 'ibmqx4',
'ibmq_16_rueschlikon': 'ibmqx5',
'ibmq_20_austin': 'QS1_1'
}
def enable_account(self, token, url=QE_URL, **kwargs):
"""Authenticate and use one IBMQ account during this session.
Login into Quantum Experience or IBMQ using the provided credentials,
adding the account to the current session. The account is not stored
in disk.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
"""
credentials = Credentials(token, url, **kwargs)
self._append_account(credentials)
def save_account(self, token, url=QE_URL, **kwargs):
"""Authenticate against IBMQ and save the account to disk for future use.
Login into Quantum Experience or IBMQ using the provided credentials,
adding the account to the current session. The account is stored in
disk for future use.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
"""
credentials = Credentials(token, url, **kwargs)
# Check if duplicated credentials are already stored. By convention,
# we assume (hub, group, project) is always unique.
stored_credentials = read_credentials_from_qiskitrc()
if credentials.unique_id() in stored_credentials.keys():
warnings.warn('Credentials are already stored.')
else:
store_credentials(credentials)
def active_accounts(self):
"""List all accounts currently in the session.
Returns:
list[dict]: a list with information about the accounts currently
in the session.
"""
information = []
for provider in self._accounts.values():
information.append({
'token': provider.credentials.token,
'url': provider.credentials.url,
})
return information
def stored_accounts(self):
"""List all accounts stored to disk.
Returns:
list[dict]: a list with information about the accounts stored
on disk.
"""
information = []
stored_creds = read_credentials_from_qiskitrc()
for creds in stored_creds:
information.append({
'token': stored_creds[creds].token,
'url': stored_creds[creds].url
})
return information
def load_accounts(self, **kwargs):
"""Load IBMQ accounts found in the system into current session,
subject to optional filtering.
Automatically load the accounts found in the system. This method
looks for credentials in the following locations, in order, and
returns as soon as credentials are found:
1. in the `Qconfig.py` file in the current working directory.
2. in the environment variables.
3. in the `qiskitrc` configuration file
Raises:
IBMQAccountError: if no credentials are found.
"""
for credentials in discover_credentials().values():
if self._credentials_match_filter(credentials, kwargs):
self._append_account(credentials)
if not self._accounts:
raise IBMQAccountError('No IBMQ credentials found on disk.')
def disable_accounts(self, **kwargs):
"""Disable accounts in the current session, subject to optional filtering.
The filter kwargs can be `token`, `url`, `hub`, `group`, `project`.
If no filter is passed, all accounts in the current session will be disabled.
Raises:
IBMQAccountError: if no account matched the filter.
"""
disabled = False
# Try to remove from session.
current_creds = self._accounts.copy()
for creds in current_creds:
credentials = Credentials(current_creds[creds].credentials.token,
current_creds[creds].credentials.url)
if self._credentials_match_filter(credentials, kwargs):
del self._accounts[credentials.unique_id()]
disabled = True
if not disabled:
raise IBMQAccountError('No matching account to disable in current session.')
def delete_accounts(self, **kwargs):
"""Delete saved accounts from disk, subject to optional filtering.
The filter kwargs can be `token`, `url`, `hub`, `group`, `project`.
If no filter is passed, all accounts will be deleted from disk.
Raises:
IBMQAccountError: if no account matched the filter.
"""
deleted = False
# Try to delete from disk.
stored_creds = read_credentials_from_qiskitrc()
for creds in stored_creds:
credentials = Credentials(stored_creds[creds].token,
stored_creds[creds].url)
if self._credentials_match_filter(credentials, kwargs):
remove_credentials(credentials)
deleted = True
if not deleted:
raise IBMQAccountError('No matching account to delete from disk.')
def _append_account(self, credentials):
"""Append an account with the specified credentials to the session.
Args:
credentials (Credentials): set of credentials.
Returns:
IBMQSingleProvider: new single-account provider.
"""
# Check if duplicated credentials are already in use. By convention,
# we assume (hub, group, project) is always unique.
if credentials.unique_id() in self._accounts.keys():
warnings.warn('Credentials are already in use.')
single_provider = IBMQSingleProvider(credentials, self)
self._accounts[credentials.unique_id()] = single_provider
return single_provider
def _credentials_match_filter(self, credentials, filter_dict):
"""Return True if the credentials match a filter.
These filters apply on properties of a Credentials object:
token, url, hub, group, project, proxies, verify
Any other filter has no effect.
Args:
credentials (Credentials): IBMQ credentials object
filter_dict (dict): dictionary of filter conditions
Returns:
bool: True if the credentials meet all the filter conditions
"""
return all(getattr(credentials, key_, None) == value_ for
key_, value_ in filter_dict.items())
<|code_end|>
|
qiskit/backends/ibmq/ibmqprovider.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Provider for remote IBMQ backends with admin features."""
import warnings
from collections import OrderedDict
from qiskit.backends import BaseProvider
from .credentials._configrc import remove_credentials
from .credentials import (Credentials,
read_credentials_from_qiskitrc, store_credentials, discover_credentials)
from .ibmqaccounterror import IBMQAccountError
from .ibmqsingleprovider import IBMQSingleProvider
QE_URL = 'https://quantumexperience.ng.bluemix.net/api'
class IBMQProvider(BaseProvider):
"""Provider for remote IBMQ backends with admin features.
This class is the entry point for handling backends from IBMQ, allowing
using different accounts.
"""
def __init__(self):
super().__init__()
# dict[credentials_unique_id: IBMQSingleProvider]
# This attribute stores a reference to the different accounts. The
# keys are tuples (hub, group, project), as the convention is that
# that tuple uniquely identifies a set of credentials.
self._accounts = OrderedDict()
def backends(self, name=None, filters=None, **kwargs):
"""Return all backends accessible via IBMQ provider, subject to optional filtering.
Args:
name (str): backend name to filter by
filters (callable): more complex filters, such as lambda functions
e.g. IBMQ.backends(filters=lambda b: b.congiguration['n_qubits'] > 5)
kwargs: simple filters specifying a true/false criteria in the
backend configuration or backend status or provider credentials
e.g. IBMQ.backends(n_qubits=5, operational=True, hub='internal')
Returns:
list[IBMQBackend]: list of backends available that match the filter
Raises:
IBMQAccountError: if no account matched the filter.
"""
# pylint: disable=arguments-differ
# Special handling of the credentials filters: match and prune from kwargs
credentials_filter = {}
for key in ['token', 'url', 'hub', 'group', 'project', 'proxies', 'verify']:
if key in kwargs:
credentials_filter[key] = kwargs.pop(key)
providers = [provider for provider in self._accounts.values() if
self._credentials_match_filter(provider.credentials,
credentials_filter)]
# Special handling of the `name` parameter, to support alias resolution.
if name:
aliases = self.aliased_backend_names()
aliases.update(self.deprecated_backend_names())
name = aliases.get(name, name)
# Aggregate the list of filtered backends.
backends = []
for provider in providers:
backends = backends + provider.backends(
name=name, filters=filters, **kwargs)
return backends
@staticmethod
def deprecated_backend_names():
"""Returns deprecated backend names."""
return {
'ibmqx_qasm_simulator': 'ibmq_qasm_simulator',
'ibmqx_hpc_qasm_simulator': 'ibmq_qasm_simulator',
'real': 'ibmqx1'
}
@staticmethod
def aliased_backend_names():
"""Returns aliased backend names."""
return {
'ibmq_5_yorktown': 'ibmqx2',
'ibmq_5_tenerife': 'ibmqx4',
'ibmq_16_rueschlikon': 'ibmqx5',
'ibmq_20_austin': 'QS1_1'
}
def enable_account(self, token, url=QE_URL, **kwargs):
"""Authenticate a new IBMQ account and add for use during this session.
Login into Quantum Experience or IBMQ using the provided credentials,
adding the account to the current session. The account is not stored
in disk.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
"""
credentials = Credentials(token, url, **kwargs)
self._append_account(credentials)
def save_account(self, token, url=QE_URL, **kwargs):
"""Save the account to disk for future use.
Login into Quantum Experience or IBMQ using the provided credentials,
adding the account to the current session. The account is stored in
disk for future use.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
"""
credentials = Credentials(token, url, **kwargs)
# Check if duplicated credentials are already stored. By convention,
# we assume (hub, group, project) is always unique.
stored_credentials = read_credentials_from_qiskitrc()
if credentials.unique_id() in stored_credentials.keys():
warnings.warn('Credentials are already stored.')
else:
store_credentials(credentials)
def active_accounts(self):
"""List all accounts currently in the session.
Returns:
list[dict]: a list with information about the accounts currently
in the session.
"""
information = []
for provider in self._accounts.values():
information.append({
'token': provider.credentials.token,
'url': provider.credentials.url,
})
return information
def stored_accounts(self):
"""List all accounts stored to disk.
Returns:
list[dict]: a list with information about the accounts stored
on disk.
"""
information = []
stored_creds = read_credentials_from_qiskitrc()
for creds in stored_creds:
information.append({
'token': stored_creds[creds].token,
'url': stored_creds[creds].url
})
return information
def load_accounts(self, **kwargs):
"""Load IBMQ accounts found in the system into current session,
subject to optional filtering.
Automatically load the accounts found in the system. This method
looks for credentials in the following locations, in order, and
returns as soon as credentials are found:
1. in the `Qconfig.py` file in the current working directory.
2. in the environment variables.
3. in the `qiskitrc` configuration file
Raises:
IBMQAccountError: if no credentials are found.
"""
for credentials in discover_credentials().values():
if self._credentials_match_filter(credentials, kwargs):
self._append_account(credentials)
if not self._accounts:
raise IBMQAccountError('No IBMQ credentials found on disk.')
def disable_accounts(self, **kwargs):
"""Disable accounts in the current session, subject to optional filtering.
The filter kwargs can be `token`, `url`, `hub`, `group`, `project`.
If no filter is passed, all accounts in the current session will be disabled.
Raises:
IBMQAccountError: if no account matched the filter.
"""
disabled = False
# Try to remove from session.
current_creds = self._accounts.copy()
for creds in current_creds:
credentials = Credentials(current_creds[creds].credentials.token,
current_creds[creds].credentials.url)
if self._credentials_match_filter(credentials, kwargs):
del self._accounts[credentials.unique_id()]
disabled = True
if not disabled:
raise IBMQAccountError('No matching account to disable in current session.')
def delete_accounts(self, **kwargs):
"""Delete saved accounts from disk, subject to optional filtering.
The filter kwargs can be `token`, `url`, `hub`, `group`, `project`.
If no filter is passed, all accounts will be deleted from disk.
Raises:
IBMQAccountError: if no account matched the filter.
"""
deleted = False
# Try to delete from disk.
stored_creds = read_credentials_from_qiskitrc()
for creds in stored_creds:
credentials = Credentials(stored_creds[creds].token,
stored_creds[creds].url)
if self._credentials_match_filter(credentials, kwargs):
remove_credentials(credentials)
deleted = True
if not deleted:
raise IBMQAccountError('No matching account to delete from disk.')
def _append_account(self, credentials):
"""Append an account with the specified credentials to the session.
Args:
credentials (Credentials): set of credentials.
Returns:
IBMQSingleProvider: new single-account provider.
"""
# Check if duplicated credentials are already in use. By convention,
# we assume (hub, group, project) is always unique.
if credentials.unique_id() in self._accounts.keys():
warnings.warn('Credentials are already in use.')
single_provider = IBMQSingleProvider(credentials, self)
self._accounts[credentials.unique_id()] = single_provider
return single_provider
def _credentials_match_filter(self, credentials, filter_dict):
"""Return True if the credentials match a filter.
These filters apply on properties of a Credentials object:
token, url, hub, group, project, proxies, verify
Any other filter has no effect.
Args:
credentials (Credentials): IBMQ credentials object
filter_dict (dict): dictionary of filter conditions
Returns:
bool: True if the credentials meet all the filter conditions
"""
return all(getattr(credentials, key_, None) == value_ for
key_, value_ in filter_dict.items())
<|code_end|>
|
Add an eASCII/Unicode drawer
### What is the expected behavior?
Something along these lines, with minimal or non dependencies.
```
┌───┐
q[0] ──┤ H ├──·───m
└───┘ │ ║
q[1] ─────────┼───╫──m
│ ║ ║
q[2] ────────(+)──╫──╫──m
║ ║ ║
c[0] ─────────────╨──╫──╫──
║ ║
c[1] ────────────────╨──╫──
║
c[2] ───────────────────╨──
```
|
qiskit/tools/visualization/__init__.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Main Qiskit visualization methods."""
import sys
from qiskit._util import _has_connection
from ._circuit_visualization import circuit_drawer, plot_circuit, generate_latex_source,\
latex_circuit_drawer, matplotlib_circuit_drawer, qx_color_scheme
from ._error import VisualizationError
from ._state_visualization import plot_bloch_vector
from ._dag_visualization import dag_drawer
if ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
if _has_connection('https://qvisualization.mybluemix.net/', 443):
from .interactive._iplot_state import iplot_state as plot_state
from .interactive._iplot_histogram import iplot_histogram as \
plot_histogram
else:
from ._state_visualization import plot_state
from ._counts_visualization import plot_histogram
else:
from ._state_visualization import plot_state
from ._counts_visualization import plot_histogram
<|code_end|>
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
1. LaTeX
2. Matplotlib
"""
import json
import logging
import operator
import os
import re
import subprocess
import tempfile
from collections import namedtuple, OrderedDict
from fractions import Fraction
from io import StringIO
from itertools import groupby, zip_longest
from math import fmod, isclose, ceil
import warnings
import numpy as np
from PIL import Image, ImageChops
from matplotlib import get_backend as get_matplotlib_backend, \
patches as patches, pyplot as plt
from qiskit._qiskiterror import QISKitError
from qiskit.wrapper import load_qasm_file
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization._error import VisualizationError
from qiskit.transpiler import transpile
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False):
"""Draw a quantum circuit, via 2 methods (try 1st, if unsuccessful, 2nd):
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
output (str): Select the output method to use for drawing the circuit.
Valid choices are `latex`, `latex_source`, `mpl`. Note if one is
not specified it will use latex and if that fails fallback to
mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
VisualizationError: when an invalid output method is selected
"""
im = None
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'mpl by default', DeprecationWarning)
try:
im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError):
im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
else:
if output not in ['latex', 'latex_source', 'mpl']:
raise VisualizationError(
'Invalid output type %s selected. The only valid choices are '
'latex, latex_source, and mpl' % output)
if output == 'latex':
im = _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
elif output == 'latex_source':
return _generate_latex_source(circuit, basis=basis,
filename=filename, scale=scale,
style=style)
elif output == 'mpl':
im = _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
if im and interactive:
im.show()
return im
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
class QCStyle:
def __init__(self):
self.tc = '#000000'
self.sc = '#000000'
self.lc = '#000000'
self.cc = '#778899'
self.gc = '#ffffff'
self.gt = '#000000'
self.bc = '#bdbdbd'
self.bg = '#ffffff'
self.fs = 13
self.sfs = 8
self.disptex = {
'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'
}
self.dispcol = {
'id': '#ffffff',
'u0': '#ffffff',
'u1': '#ffffff',
'u2': '#ffffff',
'u3': '#ffffff',
'x': '#ffffff',
'y': '#ffffff',
'z': '#ffffff',
'h': '#ffffff',
's': '#ffffff',
'sdg': '#ffffff',
't': '#ffffff',
'tdg': '#ffffff',
'rx': '#ffffff',
'ry': '#ffffff',
'rz': '#ffffff',
'reset': '#ffffff',
'target': '#ffffff',
'meas': '#ffffff'
}
self.latexmode = True
self.pimode = False
self.fold = 20
self.bundle = False
self.barrier = False
self.index = False
self.compress = True
self.figwidth = -1
self.dpi = 150
self.margin = [2.0, 0.0, 0.0, 0.3]
self.cline = 'doublet'
self.reverse = False
def set_style(self, dic):
self.tc = dic.get('textcolor', self.tc)
self.sc = dic.get('subtextcolor', self.sc)
self.lc = dic.get('linecolor', self.lc)
self.cc = dic.get('creglinecolor', self.cc)
self.gt = dic.get('gatetextcolor', self.tc)
self.gc = dic.get('gatefacecolor', self.gc)
self.bc = dic.get('barrierfacecolor', self.bc)
self.bg = dic.get('backgroundcolor', self.bg)
self.fs = dic.get('fontsize', self.fs)
self.sfs = dic.get('subfontsize', self.sfs)
self.disptex = dic.get('displaytext', self.disptex)
for key in self.dispcol.keys():
self.dispcol[key] = self.gc
self.dispcol = dic.get('displaycolor', self.dispcol)
self.latexmode = dic.get('latexdrawerstyle', self.latexmode)
self.pimode = dic.get('usepiformat', self.pimode)
self.fold = dic.get('fold', self.fold)
if self.fold < 2:
self.fold = -1
self.bundle = dic.get('cregbundle', self.bundle)
self.barrier = dic.get('plotbarrier', self.barrier)
self.index = dic.get('showindex', self.index)
self.compress = dic.get('compress', self.compress)
self.figwidth = dic.get('figwidth', self.figwidth)
self.dpi = dic.get('dpi', self.dpi)
self.margin = dic.get('margin', self.margin)
self.cline = dic.get('creglinestyle', self.cline)
self.reverse = dic.get('reversebits', self.reverse)
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to complile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def _trim(im):
"""Trim image and remove white space
"""
bg = Image.new(im.mode, im.size, im.getpixel((0, 0)))
diff = ImageChops.difference(im, bg)
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
im = im.crop(bbox)
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename, basis=basis,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
qcimg = QCircuitImage(json_circuit, scale, style=style)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, circuit, scale, style=None):
"""
Args:
circuit (dict): compiled_circuit from qobj
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
"""
# style sheet
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.circuit = circuit
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
#################################
self.header = self.circuit['header']
self.qregs = OrderedDict(_get_register_specs(
self.header['qubit_labels']))
self.qubit_list = []
for qr in self.qregs:
for i in range(self.qregs[qr]):
self.qubit_list.append((qr, i))
self.cregs = OrderedDict()
if 'clbit_labels' in self.header:
for item in self.header['clbit_labels']:
self.cregs[item[0]] = item[1]
self.clbit_list = []
cregs = self.cregs
if self._style.reverse:
self.orig_cregs = self.cregs
cregs = reversed(self.cregs)
for cr in cregs:
for i in range(self.cregs[cr]):
self.clbit_list.append((cr, i))
self.ordered_regs = [(item[0], item[1]) for
item in self.header['qubit_labels']]
if self._style.reverse:
reg_size = []
reg_labels = []
new_ordered_regs = []
for regs in self.ordered_regs:
if regs[0] in reg_labels:
continue
reg_labels.append(regs[0])
reg_size.append(len(
[x for x in self.ordered_regs if x[0] == regs[0]]))
index = 0
for size in reg_size:
new_index = index + size
for i in range(new_index - 1, index - 1, -1):
new_ordered_regs.append(self.ordered_regs[i])
index = new_index
self.ordered_regs = new_ordered_regs
if 'clbit_labels' in self.header:
for clabel in self.header['clbit_labels']:
if self._style.reverse:
for cind in reversed(range(clabel[1])):
self.ordered_regs.append((clabel[0], cind))
else:
for cind in range(clabel[1]):
self.ordered_regs.append((clabel[0], cind))
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\'+'\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
QISKitError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.circuit['instructions']:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's', 'sdg',
't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy', 'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['texparams']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, arg)
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
assert len(op['clbits']) == 1 and len(op['qubits']) == 1
if 'conditional' in op:
raise QISKitError('conditional measures currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise QISKitError('conditional reset currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
assert False, "bad node data"
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns+1, ceil(sum_column_widths)+4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above example,
index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _convert_mask(self, mask):
orig_clbit_list = []
for cr in self.orig_cregs:
for i in range(self.orig_cregs[cr]):
orig_clbit_list.append((cr, i))
bit_list = [(mask >> bit) & 1 for bit in range(
len(orig_clbit_list) - 1, -1, -1)]
converted_mask_list = [None] * len(bit_list)
converted_mask = 0
for pos, bit in enumerate(reversed(bit_list)):
new_pos = self.clbit_list.index(orig_clbit_list[pos])
converted_mask_list[new_pos] = bit
if None in converted_mask_list:
raise VisualizationError('Reverse mask creation failed')
converted_mask_list = list(reversed(converted_mask_list))
for bit in converted_mask_list:
converted_mask = (converted_mask << 1) | bit
return converted_mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.circuit['instructions']):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier']:
nm = op['name']
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] =\
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
elif nm == "reset":
self._latex[pos_1][columns] = \
"\\push{\\rule{.6em}{0em}\\ket{0}\\rule{.2em}{0em}} \\qw"
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-0.65em]{')
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-0.65em]{')
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
assert len(op['clbits']) == 1 and \
len(op['qubits']) == 1 and \
'params' not in op, "bad operation record"
if 'conditional' in op:
assert False, "If controlled measures currently not supported."
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise QISKitError('Error during Latex building: %s' %
str(e))
elif op['name'] == "barrier":
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qubits']) - 1
self._latex[start][columns] += " \\barrier{" + str(span) + "}"
else:
assert False, "bad node data"
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
if self._style.reverse:
return origin + 1
return origin - 1
def _get_register_specs(bit_labels):
"""
Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,'
'ry,rz,cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,'
'cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = MatplotlibDrawer(basis=basis, scale=scale, style=style)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
Register = namedtuple('Register', 'name index')
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=1.0, style=None):
self._ast = None
self._basis = basis
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = OrderedDict()
self._creg_dict = OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False, labelleft=False, labelright=False)
def load_qasm_file(self, filename):
circuit = load_qasm_file(filename, name='draw', basis_gates=self._basis)
self.parse_circuit(circuit)
def parse_circuit(self, circuit):
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
self._ast = transpile(dag_circuit, basis_gates=self._basis, format='json')
self._registers()
self._ops = self._ast['instructions']
def _registers(self):
# NOTE: formats of clbit and qubit are different!
header = self._ast['header']
self._creg = []
for e in header['clbit_labels']:
for i in range(e[1]):
self._creg.append(Register(name=e[0], index=i))
assert len(self._creg) == header['number_of_clbits']
self._qreg = []
for e in header['qubit_labels']:
self._qreg.append(Register(name=e[0], index=e[1]))
assert len(self._qreg) == header['number_of_qubits']
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.sc,
clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7, height=HIG * 0.7,
theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID], [qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy+0.35*WID], lc=self._style.cc, ls=self._style.cline)
arrowhead = patches.Polygon(((cx-0.20*WID, cy+0.35*WID),
(cx+0.20*WID, cy+0.35*WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'], ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if get_matplotlib_backend() == 'module://ipykernel.pylab.backend_inline':
# returns None when matplotlib is inline mode to prevent Jupyter
# with matplotlib inlining enabled to draw the diagram twice.
im = None
else:
# when matplotlib is not inline mode,
# self.figure.savefig is called twice because...
# ... this is needed to get the in-memory representation
with tempfile.TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, 'circuit.png')
self.figure.savefig(tmpfile, dpi=self._style.dpi,
bbox_inches='tight')
im = Image.open(tmpfile)
_trim(im)
os.remove(tmpfile)
# ... and this is needed to delegate in matplotlib the generation of
# the proper format.
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
return im
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index, 'group': reg.name}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(zip_longest(self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
self._cond['n_lines'] += 1
idx += 1
# reverse bit order
if self._style.reverse:
self._reverse_bits(self._qreg_dict)
self._reverse_bits(self._creg_dict)
def _reverse_bits(self, target_dict):
coord = {}
# grouping
for dict_ in target_dict.values():
if dict_['group'] not in coord:
coord[dict_['group']] = [dict_['y']]
else:
coord[dict_['group']].insert(0, dict_['y'])
# reverse bit order
for key in target_dict.keys():
target_dict[key]['y'] = coord[target_dict[key]['group']].pop(0)
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc, ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qubits' in op.keys():
q_idxs = op['qubits']
else:
q_idxs = []
# get creg index
if 'clbits' in op.keys():
c_idxs = op['clbits']
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied), max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] == 'barrier' and not self._style.barrier:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg corrdinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc, ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] == 'barrier':
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self._style.barrier:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise QISKitError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if isclose(fmod(abs_val, 1.0), 0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
elif 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return Fraction(i, j)
return None
<|code_end|>
qiskit/tools/visualization/text.py
<|code_start|><|code_end|>
|
qiskit/tools/visualization/__init__.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Main Qiskit visualization methods."""
import sys
from qiskit._util import _has_connection
from ._circuit_visualization import circuit_drawer, plot_circuit, generate_latex_source,\
latex_circuit_drawer, matplotlib_circuit_drawer, _text_circuit_drawer, qx_color_scheme
from ._error import VisualizationError
from ._state_visualization import plot_bloch_vector
from ._dag_visualization import dag_drawer
if ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
if _has_connection('https://qvisualization.mybluemix.net/', 443):
from .interactive._iplot_state import iplot_state as plot_state
from .interactive._iplot_histogram import iplot_histogram as \
plot_histogram
else:
from ._state_visualization import plot_state
from ._counts_visualization import plot_histogram
else:
from ._state_visualization import plot_state
from ._counts_visualization import plot_histogram
<|code_end|>
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import json
import logging
import operator
import os
import re
import subprocess
import tempfile
from collections import namedtuple, OrderedDict
from fractions import Fraction
from io import StringIO
from itertools import groupby, zip_longest
from math import fmod, isclose, ceil
import warnings
import numpy as np
from PIL import Image, ImageChops
from matplotlib import get_backend as get_matplotlib_backend, \
patches as patches, pyplot as plt
from qiskit._qiskiterror import QISKitError
from qiskit.wrapper import load_qasm_file
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization._error import VisualizationError
from qiskit.transpiler import transpile
from .text import TextDrawing
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art string
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
output (str): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if one
is not specified it will use latex and if that fails fallback to
mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect
line_length (int): sets the length of the lines generated by `text`
Returns:
PIL.Image: (outputs `latex` and `python`) an in-memory representation of
the circuit diagram.
String: (outputs `text` and `latex_source`). The ascii art or the LaTeX
source code.
Raises:
VisualizationError: when an invalid output method is selected
"""
im = None
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'"text" by default', DeprecationWarning)
try:
im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError, FileNotFoundError):
im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
else:
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename, basis=basis,
line_length=line_length)
elif output == 'latex':
im = _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
elif output == 'latex_source':
return _generate_latex_source(circuit, basis=basis,
filename=filename, scale=scale,
style=style)
elif output == 'mpl':
im = _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
else:
raise VisualizationError('Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if im and interactive:
im.show()
return im
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
class QCStyle:
def __init__(self):
self.tc = '#000000'
self.sc = '#000000'
self.lc = '#000000'
self.cc = '#778899'
self.gc = '#ffffff'
self.gt = '#000000'
self.bc = '#bdbdbd'
self.bg = '#ffffff'
self.fs = 13
self.sfs = 8
self.disptex = {
'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'
}
self.dispcol = {
'id': '#ffffff',
'u0': '#ffffff',
'u1': '#ffffff',
'u2': '#ffffff',
'u3': '#ffffff',
'x': '#ffffff',
'y': '#ffffff',
'z': '#ffffff',
'h': '#ffffff',
's': '#ffffff',
'sdg': '#ffffff',
't': '#ffffff',
'tdg': '#ffffff',
'rx': '#ffffff',
'ry': '#ffffff',
'rz': '#ffffff',
'reset': '#ffffff',
'target': '#ffffff',
'meas': '#ffffff'
}
self.latexmode = True
self.pimode = False
self.fold = 20
self.bundle = False
self.barrier = False
self.index = False
self.compress = True
self.figwidth = -1
self.dpi = 150
self.margin = [2.0, 0.0, 0.0, 0.3]
self.cline = 'doublet'
self.reverse = False
def set_style(self, dic):
self.tc = dic.get('textcolor', self.tc)
self.sc = dic.get('subtextcolor', self.sc)
self.lc = dic.get('linecolor', self.lc)
self.cc = dic.get('creglinecolor', self.cc)
self.gt = dic.get('gatetextcolor', self.tc)
self.gc = dic.get('gatefacecolor', self.gc)
self.bc = dic.get('barrierfacecolor', self.bc)
self.bg = dic.get('backgroundcolor', self.bg)
self.fs = dic.get('fontsize', self.fs)
self.sfs = dic.get('subfontsize', self.sfs)
self.disptex = dic.get('displaytext', self.disptex)
for key in self.dispcol.keys():
self.dispcol[key] = self.gc
self.dispcol = dic.get('displaycolor', self.dispcol)
self.latexmode = dic.get('latexdrawerstyle', self.latexmode)
self.pimode = dic.get('usepiformat', self.pimode)
self.fold = dic.get('fold', self.fold)
if self.fold < 2:
self.fold = -1
self.bundle = dic.get('cregbundle', self.bundle)
self.barrier = dic.get('plotbarrier', self.barrier)
self.index = dic.get('showindex', self.index)
self.compress = dic.get('compress', self.compress)
self.figwidth = dic.get('figwidth', self.figwidth)
self.dpi = dic.get('dpi', self.dpi)
self.margin = dic.get('margin', self.margin)
self.cline = dic.get('creglinestyle', self.cline)
self.reverse = dic.get('reversebits', self.reverse)
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap", line_length=None):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
basis (str): Optional. Comma-separated list of gate names
line_length (int): Optional. Sometimes, your console is too small of the drawing. Give me
you maximum line length your console supports.
Returns:
String: The drawing in a loooong string.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
text = "\n".join(TextDrawing(json_circuit).lines(line_length))
if filename:
with open(filename, mode='w', encoding="utf8") as text_file:
text_file.write(text)
return text
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to complile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def _trim(im):
"""Trim image and remove white space
"""
bg = Image.new(im.mode, im.size, im.getpixel((0, 0)))
diff = ImageChops.difference(im, bg)
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
im = im.crop(bbox)
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename, basis=basis,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
qcimg = QCircuitImage(json_circuit, scale, style=style)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, circuit, scale, style=None):
"""
Args:
circuit (dict): compiled_circuit from qobj
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
"""
# style sheet
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.circuit = circuit
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
#################################
self.header = self.circuit['header']
self.qregs = OrderedDict(_get_register_specs(
self.header['qubit_labels']))
self.qubit_list = []
for qr in self.qregs:
for i in range(self.qregs[qr]):
self.qubit_list.append((qr, i))
self.cregs = OrderedDict()
if 'clbit_labels' in self.header:
for item in self.header['clbit_labels']:
self.cregs[item[0]] = item[1]
self.clbit_list = []
cregs = self.cregs
if self._style.reverse:
self.orig_cregs = self.cregs
cregs = reversed(self.cregs)
for cr in cregs:
for i in range(self.cregs[cr]):
self.clbit_list.append((cr, i))
self.ordered_regs = [(item[0], item[1]) for
item in self.header['qubit_labels']]
if self._style.reverse:
reg_size = []
reg_labels = []
new_ordered_regs = []
for regs in self.ordered_regs:
if regs[0] in reg_labels:
continue
reg_labels.append(regs[0])
reg_size.append(len(
[x for x in self.ordered_regs if x[0] == regs[0]]))
index = 0
for size in reg_size:
new_index = index + size
for i in range(new_index - 1, index - 1, -1):
new_ordered_regs.append(self.ordered_regs[i])
index = new_index
self.ordered_regs = new_ordered_regs
if 'clbit_labels' in self.header:
for clabel in self.header['clbit_labels']:
if self._style.reverse:
for cind in reversed(range(clabel[1])):
self.ordered_regs.append((clabel[0], cind))
else:
for cind in range(clabel[1]):
self.ordered_regs.append((clabel[0], cind))
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\' + '\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
QISKitError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.circuit['instructions']:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's', 'sdg',
't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy', 'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['texparams']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, arg)
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
assert len(op['clbits']) == 1 and len(op['qubits']) == 1
if 'conditional' in op:
raise QISKitError('conditional measures currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise QISKitError('conditional reset currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
assert False, "bad node data"
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns + 1, ceil(sum_column_widths) + 4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above example,
index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _convert_mask(self, mask):
orig_clbit_list = []
for cr in self.orig_cregs:
for i in range(self.orig_cregs[cr]):
orig_clbit_list.append((cr, i))
bit_list = [(mask >> bit) & 1 for bit in range(
len(orig_clbit_list) - 1, -1, -1)]
converted_mask_list = [None] * len(bit_list)
converted_mask = 0
for pos, bit in enumerate(reversed(bit_list)):
new_pos = self.clbit_list.index(orig_clbit_list[pos])
converted_mask_list[new_pos] = bit
if None in converted_mask_list:
raise VisualizationError('Reverse mask creation failed')
converted_mask_list = list(reversed(converted_mask_list))
for bit in converted_mask_list:
converted_mask = (converted_mask << 1) | bit
return converted_mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.circuit['instructions']):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier']:
nm = op['name']
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1],
op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1],
op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
elif nm == "reset":
self._latex[pos_1][columns] = \
"\\push{\\rule{.6em}{0em}\\ket{0}\\rule{.2em}{0em}} \\qw"
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1],
op["texparams"][2])
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace('\\barrier{', '\\barrier[-0.65em]{')
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace('\\barrier{', '\\barrier[-0.65em]{')
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
assert len(op['clbits']) == 1 and \
len(op['qubits']) == 1 and \
'params' not in op, "bad operation record"
if 'conditional' in op:
assert False, "If controlled measures currently not supported."
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[item][columns - 1] = \
prev_entry.replace('\\barrier{', '\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise QISKitError('Error during Latex building: %s' %
str(e))
elif op['name'] == "barrier":
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qubits']) - 1
self._latex[start][columns] += " \\barrier{" + str(span) + "}"
else:
assert False, "bad node data"
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
if self._style.reverse:
return origin + 1
return origin - 1
def _get_register_specs(bit_labels):
"""
Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,'
'ry,rz,cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,'
'cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = MatplotlibDrawer(basis=basis, scale=scale, style=style)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
Register = namedtuple('Register', 'name index')
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=1.0, style=None):
self._ast = None
self._basis = basis
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = OrderedDict()
self._creg_dict = OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False, labelleft=False, labelright=False)
def load_qasm_file(self, filename):
circuit = load_qasm_file(filename, name='draw', basis_gates=self._basis)
self.parse_circuit(circuit)
def parse_circuit(self, circuit):
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
self._ast = transpile(dag_circuit, basis_gates=self._basis, format='json')
self._registers()
self._ops = self._ast['instructions']
def _registers(self):
# NOTE: formats of clbit and qubit are different!
header = self._ast['header']
self._creg = []
for e in header['clbit_labels']:
for i in range(e[1]):
self._creg.append(Register(name=e[0], index=i))
assert len(self._creg) == header['number_of_clbits']
self._qreg = []
for e in header['qubit_labels']:
self._qreg.append(Register(name=e[0], index=e[1]))
assert len(self._qreg) == header['number_of_qubits']
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.sc,
clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7, height=HIG * 0.7,
theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID], [qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy + 0.35 * WID], lc=self._style.cc, ls=self._style.cline)
arrowhead = patches.Polygon(((cx - 0.20 * WID, cy + 0.35 * WID),
(cx + 0.20 * WID, cy + 0.35 * WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'], ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if get_matplotlib_backend() == 'module://ipykernel.pylab.backend_inline':
# returns None when matplotlib is inline mode to prevent Jupyter
# with matplotlib inlining enabled to draw the diagram twice.
im = None
else:
# when matplotlib is not inline mode,
# self.figure.savefig is called twice because...
# ... this is needed to get the in-memory representation
with tempfile.TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, 'circuit.png')
self.figure.savefig(tmpfile, dpi=self._style.dpi,
bbox_inches='tight')
im = Image.open(tmpfile)
_trim(im)
os.remove(tmpfile)
# ... and this is needed to delegate in matplotlib the generation of
# the proper format.
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
return im
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index, 'group': reg.name}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(zip_longest(self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
self._cond['n_lines'] += 1
idx += 1
# reverse bit order
if self._style.reverse:
self._reverse_bits(self._qreg_dict)
self._reverse_bits(self._creg_dict)
def _reverse_bits(self, target_dict):
coord = {}
# grouping
for dict_ in target_dict.values():
if dict_['group'] not in coord:
coord[dict_['group']] = [dict_['y']]
else:
coord[dict_['group']].insert(0, dict_['y'])
# reverse bit order
for key in target_dict.keys():
target_dict[key]['y'] = coord[target_dict[key]['group']].pop(0)
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc, ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qubits' in op.keys():
q_idxs = op['qubits']
else:
q_idxs = []
# get creg index
if 'clbits' in op.keys():
c_idxs = op['clbits']
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied), max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] == 'barrier' and not self._style.barrier:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg corrdinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc, ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] == 'barrier':
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self._style.barrier:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise QISKitError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if isclose(fmod(abs_val, 1.0), 0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
elif 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return Fraction(i, j)
return None
<|code_end|>
qiskit/tools/visualization/text.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A module for drawing circuits in ascii art or some other text representation
"""
class DrawElement():
""" An element is an instruction or an operation that need to be drawn."""
def __init__(self, label=None):
self._width = None
self.label = self.mid_content = label
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = self.bot_connect = " "
self.top_pad = self._mid_padding = self.bot_pad = " "
self.bot_connector = {}
self.top_connector = {}
self.right_fill = self.left_fill = 0
@property
def top(self):
""" Constructs the top line of the element"""
ret = self.top_format % self.top_connect.center(
self.width - self.left_fill - self.right_fill, self.top_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.top_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.top_pad)
return ret
@property
def mid(self):
""" Constructs the middle line of the element"""
ret = self.mid_format % self.mid_content.center(
self.width - self.left_fill - self.right_fill, self._mid_padding)
if self.right_fill:
ret = ret.ljust(self.right_fill, self._mid_padding)
if self.left_fill:
ret = ret.rjust(self.left_fill, self._mid_padding)
return ret
@property
def bot(self):
""" Constructs the bottom line of the element"""
ret = self.bot_format % self.bot_connect.center(
self.width - self.left_fill - self.right_fill, self.bot_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.bot_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.bot_pad)
return ret
@property
def length(self):
""" Returns the length of the element, including the box around."""
return max(len(self.top), len(self.mid), len(self.bot))
@length.setter
def length(self, value):
""" Adjusts width so the length fits."""
self.width = value - max(
[len(getattr(self, i) % '') for i in ["bot_format", "mid_format", "top_format"]])
@property
def width(self):
""" Returns the width of the label, including padding"""
if self._width:
return self._width
return len(self.mid_content)
@width.setter
def width(self, value):
self._width = value
def connect(self, wire_char, where, label=None):
"""
Connects boxes and elements using wire_char and setting proper connectors.
Args:
wire_char (char): For example '║' or '│'.
where (list["top", "bot"]): Where the connector should be set.
label (string): Some connectors have a label (see cu1, for example).
"""
if 'top' in where:
self.top_connect = self.top_connector[
wire_char] if wire_char in self.top_connector else wire_char
if 'bot' in where:
self.bot_connect = self.bot_connector[
wire_char] if wire_char in self.bot_connector else wire_char
if label:
self.top_format = self.top_format[:-1] + (label if label else "")
class BoxOnClWire(DrawElement):
""" Draws a box on the classical wire
top: ┌───┐ ┌───────┐
mid: ╡ A ╞ ╡ A ╞
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "╡ %s ╞"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
class BoxOnQuWire(DrawElement):
""" Draws a box on the quantum wire
top: ┌───┐ ┌───────┐
mid: ┤ A ├ ┤ A ├
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "┤ %s ├"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
self.top_connector = {"│": '┴'}
self.bot_connector = {"│": '┬'}
class MeasureTo(DrawElement):
""" The element on the classic wire to which the measure is performed
top: ║ ║
mid: ═╩═ ═══╩═══
bot:
"""
def __init__(self):
super().__init__()
self.top_connect = " ║ "
self.mid_content = "═╩═"
self.bot_connect = " "
self._mid_padding = "═"
class MeasureFrom(BoxOnQuWire):
""" The element on the quantum wire in which the measure is performed
top: ┌─┐ ┌─┐
mid: ┤M├ ───┤M├───
bot: └╥┘ └╥┘
"""
def __init__(self):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = "┌─┐"
self.mid_content = "┤M├"
self.bot_connect = "└╥┘"
class MultiBox(DrawElement):
"""Elements that is draw on over multiple wires."""
def center_label(self, input_length, order):
"""
In multi-bit elements, the label is centered vertically.
Args:
input_length (int): Rhe amount of wires affected.
order (int): Which middle element is this one?
"""
location_in_the_box = '*'.center(input_length * 2 - 1).index('*') + 1
top_limit = (order - 1) * 2 + 2
bot_limit = top_limit + 2
if top_limit <= location_in_the_box < bot_limit:
if location_in_the_box == top_limit:
self.top_connect = self.label
elif location_in_the_box == top_limit + 1:
self.mid_content = self.label
else:
self.bot_connect = self.label
class BoxOnQuWireTop(MultiBox, BoxOnQuWire):
""" Draws the top part of a box that affects more than one quantum wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnQuWireMid(MultiBox, BoxOnQuWire):
""" Draws the middle part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.center_label(input_length, order)
class BoxOnQuWireBot(MultiBox, BoxOnQuWire):
""" Draws the bottom part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length):
super().__init__(label)
self.top_format = "│ %s │"
self.mid_content = self.bot_connect = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class BoxOnClWireTop(MultiBox, BoxOnClWire):
""" Draws the top part of a conditional box that affects more than one classical wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnClWireMid(MultiBox, BoxOnClWire):
""" Draws the middle part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.mid_content = label
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.top_pad = self.bot_pad = ' '
self.top_connect = self.bot_connect = self.mid_content = ''
self.center_label(input_length, order)
class BoxOnClWireBot(MultiBox, BoxOnClWire):
""" Draws the bottom part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, bot_connect='─'):
super().__init__(label)
self.top_format = "│ %s │"
self.top_pad = " "
self.bot_connect = bot_connect
self.mid_content = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class DirectOnQuWire(DrawElement):
"""
Element to the wire (without the box).
"""
def __init__(self, label=""):
super().__init__(label)
self.top_format = ' %s '
self.mid_format = '─%s─'
self.bot_format = ' %s '
self._mid_padding = '─'
class Barrier(DirectOnQuWire):
""" Draws a barrier.
top: ░ ░
mid: ─░─ ───░───
bot: ░ ░
"""
def __init__(self, label=""):
super().__init__("░")
self.top_connect = "░"
self.bot_connect = "░"
class Ex(DirectOnQuWire):
""" Draws an X (usually with a connector). E.g. the top part of a swap gate
top:
mid: ─X─ ───X───
bot: │ │
"""
def __init__(self, bot_connect=" ", top_connect=" "):
super().__init__("X")
self.bot_connect = bot_connect
self.top_connect = top_connect
class Reset(DirectOnQuWire):
""" Draws a reset gate"""
def __init__(self):
super().__init__("|0>")
class Bullet(DirectOnQuWire):
""" Draws a bullet (usuallly with a connector). E.g. the top part of a CX gate.
top:
mid: ─■─ ───■───
bot: │ │
"""
def __init__(self, top_connect=" ", bot_connect=" "):
super().__init__('■')
self.top_connect = top_connect
self.bot_connect = bot_connect
class EmptyWire(DrawElement):
""" This element is just the wire, with no instructions nor operations."""
def __init__(self, wire):
super().__init__(wire)
self._mid_padding = wire
@staticmethod
def fillup_layer(layer, first_clbit):
"""
Given a layer, replace the Nones in it with EmptyWire elements.
Args:
layer (list): The layer that contains Nones.
first_clbit (int): The first wire that is classic.
Returns:
list: The new layer, with no Nones.
"""
for nones in [i for i, x in enumerate(layer) if x is None]:
layer[nones] = EmptyWire('═') if nones >= first_clbit else EmptyWire('─')
return layer
class BreakWire(DrawElement):
""" This element is used to break the drawing in several pages."""
def __init__(self, arrow_char):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = arrow_char
self.mid_content = arrow_char
self.bot_connect = arrow_char
@staticmethod
def fillup_layer(layer_length, arrow_char):
"""
Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer.
"""
breakwire_layer = []
for _ in range(layer_length):
breakwire_layer.append(BreakWire(arrow_char))
return breakwire_layer
class InputWire(DrawElement):
""" This element is the label and the initial value of a wire."""
def __init__(self, label):
super().__init__(label)
@staticmethod
def fillup_layer(names): # pylint: disable=arguments-differ
"""
Creates a layer with InputWire elements.
Args:
names (list): List of names for the wires.
Returns:
list: The new layer
"""
longest = max([len(name) for name in names])
inputs_wires = []
for name in names:
inputs_wires.append(InputWire(name.rjust(longest)))
return inputs_wires
class TextDrawing():
""" The text drawing"""
def __init__(self, json_circuit):
self.json_circuit = json_circuit
def lines(self, line_length=None):
"""
Generates a list with lines. These lines form the text drawing.
Args:
line_length (int): Optional. When given, breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console.
Returns:
list: A list of lines with the text drawing.
"""
noqubits = self.json_circuit['header']['number_of_qubits']
layers = self.build_layers()
# TODO compress layers
# -| H |----------
# --------| H |---
# should be
# -| H |---
# -| H |---
layer_groups = [[]]
rest_of_the_line = line_length
for layerno, layer in enumerate(layers):
# Replace the Nones with EmptyWire
layers[layerno] = EmptyWire.fillup_layer(layer, noqubits)
TextDrawing.normalize_width(layer)
if line_length is None:
# does not page
layer_groups[-1].append(layer)
continue
# chop the layer to the line_length (pager)
layer_length = layers[layerno][0].length
if layer_length < rest_of_the_line:
layer_groups[-1].append(layer)
rest_of_the_line -= layer_length
else:
layer_groups[-1].append(BreakWire.fillup_layer(len(layer), '»'))
# New group
layer_groups.append([BreakWire.fillup_layer(len(layer), '«')])
rest_of_the_line = line_length - layer_groups[-1][-1][0].length
layer_groups[-1].append(
InputWire.fillup_layer(self.wire_names(with_initial_value=False)))
rest_of_the_line -= layer_groups[-1][-1][0].length
layer_groups[-1].append(layer)
rest_of_the_line -= layer_groups[-1][-1][0].length
lines = []
for layer_group in layer_groups:
wires = [i for i in zip(*layer_group)]
lines += TextDrawing.draw_wires(wires)
return lines
def wire_names(self, with_initial_value=True):
"""
Returns a list of names for each wire.
Args:
with_initial_value (bool): Optional (Default: True). If true, adds the initial value to
the name.
Returns:
List: The list of wire names.
"""
ret = []
if with_initial_value:
initial_value = {'qubit': '|0>', 'clbit': '0 '}
else:
initial_value = {'qubit': '', 'clbit': ''}
header = self.json_circuit['header']
for qubit in header['qubit_labels']:
ret.append("%s_%s: %s" % (qubit[0], qubit[1], initial_value['qubit']))
for creg in header['clbit_labels']:
for clbit in range(creg[1]):
ret.append("%s_%s: %s" % (creg[0], clbit, initial_value['clbit']))
return ret
@staticmethod
def draw_wires(wires):
"""
Given a list of wires, creates a list of lines with the text drawing.
Args:
wires (list): A list of wires with instructions.
Returns:
list: A list of lines with the text drawing.
"""
lines = []
bot_line = None
for wire in wires:
# TOP
top_line = ""
for instruction in wire:
top_line += instruction.top
if bot_line is None:
lines.append(top_line)
else:
lines.append(TextDrawing.merge_lines(lines.pop(), top_line))
# MID
mid_line = ""
for instruction in wire:
mid_line += instruction.mid
lines.append(TextDrawing.merge_lines(lines[-1], mid_line, icod="bot"))
# BOT
bot_line = ""
for instruction in wire:
bot_line += instruction.bot
lines.append(TextDrawing.merge_lines(lines[-1], bot_line, icod="bot"))
return lines
@staticmethod
def label_for_conditional(instruction):
""" Creates the label for a conditional instruction."""
return "%s %s" % ('=', instruction['conditional']['val'])
@staticmethod
def params_for_label(instruction):
"""Get the params and format them to add them to a label. None of there is no param."""
if 'params' in instruction and instruction['params']:
return ['%.5g' % i for i in instruction['params']]
return None
@staticmethod
def label_for_box(instruction):
""" Creates the label for a box."""
label = instruction['name'].capitalize()
params = TextDrawing.params_for_label(instruction)
if params:
label += "(%s)" % ','.join(params)
return label
@staticmethod
def merge_lines(top, bot, icod="top"):
"""
Merges two lines (top and bot) in the way that the overlapping make senses.
Args:
top (str): the top line
bot (str): the bottom line
icod (top or bot): in case of doubt, which line should have priority? Default: "top".
Returns:
str: The merge of both lines.
"""
ret = ""
for topc, botc in zip(top, bot):
if topc == botc:
ret += topc
elif topc in '┼╪' and botc == " ":
ret += "│"
elif topc == " ":
ret += botc
elif topc in '┬╥' and botc in " ║│":
ret += topc
elif topc in '┬│' and botc == "═":
ret += '╪'
elif topc in '┬│' and botc == "─":
ret += '┼'
elif topc in '└┘║│░' and botc == " ":
ret += topc
elif topc in '─═' and botc == " " and icod == "top":
ret += topc
elif topc in '─═' and botc == " " and icod == "bot":
ret += botc
elif topc in "║╥" and botc in "═":
ret += "╬"
elif topc in "║╥" and botc in "─":
ret += "╫"
elif topc in '╫╬' and botc in " ":
ret += "║"
elif topc == '└' and botc == "┌":
ret += "├"
elif topc == '┘' and botc == "┐":
ret += "┤"
else:
ret += botc
return ret
def clbit_index_from_mask(self, mask):
"""
Given a mask, returns a list of classical indexes affected by that mask.
Args:
mask (int): The mask.
Returns:
list: A list of indexes affected by the mask.
"""
clbit_len = self.json_circuit['header']['number_of_clbits']
bit_mask = [bool(mask & (1 << n)) for n in range(clbit_len)]
return [i for i, x in enumerate(bit_mask) if x]
@staticmethod
def normalize_width(layer):
"""
When the elements of the layer have different widths, sets the width to the max elements.
Args:
layer (list): A list of elements.
"""
instructions = [instruction for instruction in filter(lambda x: x is not None, layer)]
longest = max([instruction.length for instruction in instructions])
for instruction in instructions:
instruction.length = longest
def build_layers(self):
"""
Constructs layers.
Returns:
list: List of DrawElements.
Raises:
Exception: When the drawing is, for some reason, impossible to be drawn.
"""
layers = []
noqubits = self.json_circuit['header']['number_of_qubits']
noclbits = self.json_circuit['header']['number_of_clbits']
layers.append(InputWire.fillup_layer(self.wire_names(with_initial_value=True)))
for instruction in self.json_circuit['instructions']:
layer = Layer(noqubits, noclbits)
if instruction['name'] == 'measure':
layer.set_qubit(instruction['qubits'][0], MeasureFrom())
layer.set_clbit(instruction['clbits'][0], MeasureTo())
elif instruction['name'] == 'barrier':
# barrier
for qubit in instruction['qubits']:
layer.qubit_layer[qubit] = Barrier()
elif instruction['name'] == 'swap':
# swap
for qubit in instruction['qubits']:
layer.qubit_layer[qubit] = Ex()
layer.connect_with("│")
elif instruction['name'] == 'cswap':
# cswap
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Ex())
layer.set_qubit(instruction['qubits'][2], Ex())
layer.connect_with("│")
elif instruction['name'] == 'reset':
layer.set_qubit(instruction['qubits'][0], Reset())
elif 'conditional' in instruction:
# conditional
clbits = self.clbit_index_from_mask(int(instruction['conditional']['mask'], 16))
cllabel = TextDrawing.label_for_conditional(instruction)
qulabel = TextDrawing.label_for_box(instruction)
layer.set_cl_multibox(clbits, cllabel, top_connect='┴')
layer.set_qubit(instruction['qubits'][0], BoxOnQuWire(qulabel, bot_connect='┬'))
elif instruction['name'] in ['cx', 'CX', 'ccx']:
# cx/ccx
for qubit in [qubit for qubit in instruction['qubits'][:-1]]:
layer.set_qubit(qubit, Bullet())
layer.set_qubit(instruction['qubits'][-1], BoxOnQuWire('X'))
layer.connect_with("│")
elif instruction['name'] == 'cy':
# cy
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], BoxOnQuWire('Y'))
layer.connect_with("│")
elif instruction['name'] == 'cz':
# cz
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Bullet())
layer.connect_with("│")
elif instruction['name'] == 'ch':
# ch
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], BoxOnQuWire('H'))
layer.connect_with("│")
elif instruction['name'] == 'cu1':
# cu1
label = TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Bullet())
layer.connect_with("│", label)
elif instruction['name'] == 'cu3':
# cu3
params = TextDrawing.params_for_label(instruction)
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1],
BoxOnQuWire("U3(%s)" % ','.join(params)))
layer.connect_with("│")
elif instruction['name'] == 'crz':
# crz
label = "Rz(%s)" % TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1],
BoxOnQuWire(label))
layer.connect_with("│")
elif len(instruction['qubits']) == 1 and 'clbits' not in instruction:
# unitary gate
layer.set_qubit(instruction['qubits'][0],
BoxOnQuWire(TextDrawing.label_for_box(instruction)))
elif len(instruction['qubits']) >= 2 and 'clbits' not in instruction:
# multiple qubit gate
layer.set_qu_multibox(instruction['qubits'], TextDrawing.label_for_box(instruction))
else:
raise Exception("I don't know how to handle this instruction", instruction)
layers.append(layer.full_layer)
return layers
class Layer:
""" A layer is the "column" of the circuit. """
def __init__(self, noqubits, noclbits):
self.qubit_layer = [None] * noqubits
self.clbit_layer = [None] * noclbits
@property
def full_layer(self):
"""
Returns the composition of qubits and classic wires.
Returns:
String: self.qubit_layer + self.clbit_layer
"""
return self.qubit_layer + self.clbit_layer
def set_qubit(self, qubit, element):
"""
Sets the qubit to the element
Args:
qubit (int): Qubit index.
element (DrawElement): Element to set in the qubit
"""
self.qubit_layer[qubit] = element
def set_clbit(self, clbit, element):
"""
Sets the clbit to the element
Args:
clbit (int): Clbit index.
element (DrawElement): Element to set in the clbit
"""
self.clbit_layer[clbit] = element
def _set_multibox(self, wire_type, bits, label, top_connect=None):
# pylint: disable=invalid-name
bits = sorted(bits)
if wire_type == "cl":
set_bit = self.set_clbit
BoxOnWire = BoxOnClWire
BoxOnWireTop = BoxOnClWireTop
BoxOnWireMid = BoxOnClWireMid
BoxOnWireBot = BoxOnClWireBot
elif wire_type == "qu":
set_bit = self.set_qubit
BoxOnWire = BoxOnQuWire
BoxOnWireTop = BoxOnQuWireTop
BoxOnWireMid = BoxOnQuWireMid
BoxOnWireBot = BoxOnQuWireBot
# Checks if qubits are consecutive
if bits != [i for i in range(bits[0], bits[-1] + 1)]:
raise Exception("I don't know how to build a gate with multiple bits when"
"they are not adjacent to each other")
if len(bits) == 1:
set_bit(bits[0], BoxOnWire(label, top_connect=top_connect))
else:
set_bit(bits[0], BoxOnWireTop(label, top_connect=top_connect))
for order, bit in enumerate(bits[1:-1], 1):
set_bit(bit, BoxOnWireMid(label, len(bits), order))
set_bit(bits[-1], BoxOnWireBot(label, len(bits)))
def set_cl_multibox(self, bits, label, top_connect='┴'):
"""
Sets the multi clbit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi clbit box.
top_connect (char): The char to connect the box on the top.
"""
self._set_multibox("cl", bits, label, top_connect=top_connect)
def set_qu_multibox(self, bits, label):
"""
Sets the multi qubit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi qubit box.
"""
self._set_multibox("qu", bits, label)
def connect_with(self, wire_char, label=None):
"""
Connects the elements in the layer using wire_char.
Args:
wire_char (char): For example '║' or '│'.
label (string): Some connectors have a label (see cu1, for example).
"""
affected_bits = [bit for bit in self.full_layer if bit is not None]
affected_bits[0].connect(wire_char, ['bot'])
for affected_bit in affected_bits[1:-1]:
affected_bit.connect(wire_char, ['bot', 'top'])
affected_bits[-1].connect(wire_char, ['top'], label)
if label:
for affected_bit in affected_bits:
affected_bit.right_fill = len(label) + len(affected_bit.mid)
<|code_end|>
|
making latex_circuit_drawer and matplotlib_circuit_drawer hidden functions.
Why do we need these, can't we just give circuit_drawer and option for this with a default to latex.
```python
circuit_drawer(circuit, out_put = 'latex')
```
```python
circuit_drawer(circuit, out_put = 'python')
```
Also, why do we need `generate_latex_source` cant it be
```python
circuit_drawer(circuit, out_put = 'latex_source')
```
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
1. LaTeX
2. Matplotlib
"""
import json
import logging
import operator
import os
import re
import subprocess
import tempfile
from collections import namedtuple, OrderedDict
from fractions import Fraction
from io import StringIO
from itertools import groupby, zip_longest
from math import fmod, isclose, ceil
import numpy as np
from PIL import Image, ImageChops
from matplotlib import get_backend as get_matplotlib_backend, \
patches as patches, pyplot as plt
from qiskit._qiskiterror import QISKitError
from qiskit.wrapper import load_qasm_file
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization._error import VisualizationError
from qiskit.transpiler import transpile
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit, via 2 methods (try 1st, if unsuccessful, 2nd):
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
try:
return latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError):
return matplotlib_circuit_drawer(circuit, basis, scale, filename, style)
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
class QCStyle:
def __init__(self):
self.tc = '#000000'
self.sc = '#000000'
self.lc = '#000000'
self.cc = '#778899'
self.gc = '#ffffff'
self.gt = '#000000'
self.bc = '#bdbdbd'
self.bg = '#ffffff'
self.fs = 13
self.sfs = 8
self.disptex = {
'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'
}
self.dispcol = {
'id': '#ffffff',
'u0': '#ffffff',
'u1': '#ffffff',
'u2': '#ffffff',
'u3': '#ffffff',
'x': '#ffffff',
'y': '#ffffff',
'z': '#ffffff',
'h': '#ffffff',
's': '#ffffff',
'sdg': '#ffffff',
't': '#ffffff',
'tdg': '#ffffff',
'rx': '#ffffff',
'ry': '#ffffff',
'rz': '#ffffff',
'reset': '#ffffff',
'target': '#ffffff',
'meas': '#ffffff'
}
self.latexmode = True
self.pimode = False
self.fold = 20
self.bundle = False
self.barrier = False
self.index = False
self.compress = True
self.figwidth = -1
self.dpi = 150
self.margin = [2.0, 0.0, 0.0, 0.3]
self.cline = 'doublet'
self.reverse = False
def set_style(self, dic):
self.tc = dic.get('textcolor', self.tc)
self.sc = dic.get('subtextcolor', self.sc)
self.lc = dic.get('linecolor', self.lc)
self.cc = dic.get('creglinecolor', self.cc)
self.gt = dic.get('gatetextcolor', self.tc)
self.gc = dic.get('gatefacecolor', self.gc)
self.bc = dic.get('barrierfacecolor', self.bc)
self.bg = dic.get('backgroundcolor', self.bg)
self.fs = dic.get('fontsize', self.fs)
self.sfs = dic.get('subfontsize', self.sfs)
self.disptex = dic.get('displaytext', self.disptex)
for key in self.dispcol.keys():
self.dispcol[key] = self.gc
self.dispcol = dic.get('displaycolor', self.dispcol)
self.latexmode = dic.get('latexdrawerstyle', self.latexmode)
self.pimode = dic.get('usepiformat', self.pimode)
self.fold = dic.get('fold', self.fold)
if self.fold < 2:
self.fold = -1
self.bundle = dic.get('cregbundle', self.bundle)
self.barrier = dic.get('plotbarrier', self.barrier)
self.index = dic.get('showindex', self.index)
self.compress = dic.get('compress', self.compress)
self.figwidth = dic.get('figwidth', self.figwidth)
self.dpi = dic.get('dpi', self.dpi)
self.margin = dic.get('margin', self.margin)
self.cline = dic.get('creglinestyle', self.cline)
self.reverse = dic.get('reversebits', self.reverse)
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to complile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def _trim(im):
"""Trim image and remove white space
"""
bg = Image.new(im.mode, im.size, im.getpixel((0, 0)))
diff = ImageChops.difference(im, bg)
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
im = im.crop(bbox)
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
qcimg = QCircuitImage(json_circuit, scale, style=style)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, circuit, scale, style=None):
"""
Args:
circuit (dict): compiled_circuit from qobj
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
"""
# style sheet
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.circuit = circuit
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
#################################
self.header = self.circuit['header']
self.qregs = OrderedDict(_get_register_specs(
self.header['qubit_labels']))
self.qubit_list = []
for qr in self.qregs:
for i in range(self.qregs[qr]):
self.qubit_list.append((qr, i))
self.cregs = OrderedDict()
if 'clbit_labels' in self.header:
for item in self.header['clbit_labels']:
self.cregs[item[0]] = item[1]
self.clbit_list = []
cregs = self.cregs
if self._style.reverse:
self.orig_cregs = self.cregs
cregs = reversed(self.cregs)
for cr in cregs:
for i in range(self.cregs[cr]):
self.clbit_list.append((cr, i))
self.ordered_regs = [(item[0], item[1]) for
item in self.header['qubit_labels']]
if self._style.reverse:
reg_size = []
reg_labels = []
new_ordered_regs = []
for regs in self.ordered_regs:
if regs[0] in reg_labels:
continue
reg_labels.append(regs[0])
reg_size.append(len(
[x for x in self.ordered_regs if x[0] == regs[0]]))
index = 0
for size in reg_size:
new_index = index + size
for i in range(new_index - 1, index - 1, -1):
new_ordered_regs.append(self.ordered_regs[i])
index = new_index
self.ordered_regs = new_ordered_regs
if 'clbit_labels' in self.header:
for clabel in self.header['clbit_labels']:
if self._style.reverse:
for cind in reversed(range(clabel[1])):
self.ordered_regs.append((clabel[0], cind))
else:
for cind in range(clabel[1]):
self.ordered_regs.append((clabel[0], cind))
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\'+'\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
QISKitError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.circuit['instructions']:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's', 'sdg',
't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy', 'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['texparams']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, arg)
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
assert len(op['clbits']) == 1 and len(op['qubits']) == 1
if 'conditional' in op:
raise QISKitError('conditional measures currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise QISKitError('conditional reset currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
assert False, "bad node data"
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns+1, ceil(sum_column_widths)+4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above example,
index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _convert_mask(self, mask):
orig_clbit_list = []
for cr in self.orig_cregs:
for i in range(self.orig_cregs[cr]):
orig_clbit_list.append((cr, i))
bit_list = [(mask >> bit) & 1 for bit in range(
len(orig_clbit_list) - 1, -1, -1)]
converted_mask_list = [None] * len(bit_list)
converted_mask = 0
for pos, bit in enumerate(reversed(bit_list)):
new_pos = self.clbit_list.index(orig_clbit_list[pos])
converted_mask_list[new_pos] = bit
if None in converted_mask_list:
raise VisualizationError('Reverse mask creation failed')
converted_mask_list = list(reversed(converted_mask_list))
for bit in converted_mask_list:
converted_mask = (converted_mask << 1) | bit
return converted_mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.circuit['instructions']):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier']:
nm = op['name']
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] =\
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
elif nm == "reset":
self._latex[pos_1][columns] = \
"\\push{\\rule{.6em}{0em}\\ket{0}\\rule{.2em}{0em}} \\qw"
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-0.65em]{')
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-0.65em]{')
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
assert len(op['clbits']) == 1 and \
len(op['qubits']) == 1 and \
'params' not in op, "bad operation record"
if 'conditional' in op:
assert False, "If controlled measures currently not supported."
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise QISKitError('Error during Latex building: %s' %
str(e))
elif op['name'] == "barrier":
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qubits']) - 1
self._latex[start][columns] += " \\barrier{" + str(span) + "}"
else:
assert False, "bad node data"
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
if self._style.reverse:
return origin + 1
return origin - 1
def _get_register_specs(bit_labels):
"""
Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = MatplotlibDrawer(basis=basis, scale=scale, style=style)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
Register = namedtuple('Register', 'name index')
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=1.0, style=None):
self._ast = None
self._basis = basis
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = OrderedDict()
self._creg_dict = OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False, labelleft=False, labelright=False)
def load_qasm_file(self, filename):
circuit = load_qasm_file(filename, name='draw', basis_gates=self._basis)
self.parse_circuit(circuit)
def parse_circuit(self, circuit):
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
self._ast = transpile(dag_circuit, basis_gates=self._basis, format='json')
self._registers()
self._ops = self._ast['instructions']
def _registers(self):
# NOTE: formats of clbit and qubit are different!
header = self._ast['header']
self._creg = []
for e in header['clbit_labels']:
for i in range(e[1]):
self._creg.append(Register(name=e[0], index=i))
assert len(self._creg) == header['number_of_clbits']
self._qreg = []
for e in header['qubit_labels']:
self._qreg.append(Register(name=e[0], index=e[1]))
assert len(self._qreg) == header['number_of_qubits']
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.sc,
clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7, height=HIG * 0.7,
theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID], [qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy+0.35*WID], lc=self._style.cc, ls=self._style.cline)
arrowhead = patches.Polygon(((cx-0.20*WID, cy+0.35*WID),
(cx+0.20*WID, cy+0.35*WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'], ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if get_matplotlib_backend() == 'module://ipykernel.pylab.backend_inline':
# returns None when matplotlib is inline mode to prevent Jupyter
# with matplotlib inlining enabled to draw the diagram twice.
im = None
else:
# when matplotlib is not inline mode,
# self.figure.savefig is called twice because...
# ... this is needed to get the in-memory representation
with tempfile.TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, 'circuit.png')
self.figure.savefig(tmpfile, dpi=self._style.dpi,
bbox_inches='tight')
im = Image.open(tmpfile)
_trim(im)
os.remove(tmpfile)
# ... and this is needed to delegate in matplotlib the generation of
# the proper format.
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
return im
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index, 'group': reg.name}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(zip_longest(self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
self._cond['n_lines'] += 1
idx += 1
# reverse bit order
if self._style.reverse:
self._reverse_bits(self._qreg_dict)
self._reverse_bits(self._creg_dict)
def _reverse_bits(self, target_dict):
coord = {}
# grouping
for dict_ in target_dict.values():
if dict_['group'] not in coord:
coord[dict_['group']] = [dict_['y']]
else:
coord[dict_['group']].insert(0, dict_['y'])
# reverse bit order
for key in target_dict.keys():
target_dict[key]['y'] = coord[target_dict[key]['group']].pop(0)
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc, ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qubits' in op.keys():
q_idxs = op['qubits']
else:
q_idxs = []
# get creg index
if 'clbits' in op.keys():
c_idxs = op['clbits']
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied), max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] == 'barrier' and not self._style.barrier:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg corrdinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc, ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] == 'barrier':
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self._style.barrier:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise QISKitError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if isclose(fmod(abs_val, 1.0), 0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
elif 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return Fraction(i, j)
return None
<|code_end|>
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
1. LaTeX
2. Matplotlib
"""
import json
import logging
import operator
import os
import re
import subprocess
import tempfile
from collections import namedtuple, OrderedDict
from fractions import Fraction
from io import StringIO
from itertools import groupby, zip_longest
from math import fmod, isclose, ceil
import warnings
import numpy as np
from PIL import Image, ImageChops
from matplotlib import get_backend as get_matplotlib_backend, \
patches as patches, pyplot as plt
from qiskit._qiskiterror import QISKitError
from qiskit.wrapper import load_qasm_file
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization._error import VisualizationError
from qiskit.transpiler import transpile
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False):
"""Draw a quantum circuit, via 2 methods (try 1st, if unsuccessful, 2nd):
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
output (str): Select the output method to use for drawing the circuit.
Valid choices are `latex`, `latex_source`, `python`. Note if one is
not specified it will use latex and if that fails fallback to
python. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
VisualizationError: when an invalid output method is selected
"""
im = None
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to python on failure it will just use '
'python by default', DeprecationWarning)
try:
im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError):
im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
else:
if output not in ['latex', 'latex_source', 'python']:
raise VisualizationError(
'Invalid output type %s selected. The only valid choices are '
'latex, latex_source, and python' % output)
if output == 'latex':
im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
elif output == 'latex_source':
return _generate_latex_source(circuit, basis, scale, filename, style)
elif output == 'python':
im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
if im and interactive:
im.show()
return im
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
class QCStyle:
def __init__(self):
self.tc = '#000000'
self.sc = '#000000'
self.lc = '#000000'
self.cc = '#778899'
self.gc = '#ffffff'
self.gt = '#000000'
self.bc = '#bdbdbd'
self.bg = '#ffffff'
self.fs = 13
self.sfs = 8
self.disptex = {
'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'
}
self.dispcol = {
'id': '#ffffff',
'u0': '#ffffff',
'u1': '#ffffff',
'u2': '#ffffff',
'u3': '#ffffff',
'x': '#ffffff',
'y': '#ffffff',
'z': '#ffffff',
'h': '#ffffff',
's': '#ffffff',
'sdg': '#ffffff',
't': '#ffffff',
'tdg': '#ffffff',
'rx': '#ffffff',
'ry': '#ffffff',
'rz': '#ffffff',
'reset': '#ffffff',
'target': '#ffffff',
'meas': '#ffffff'
}
self.latexmode = True
self.pimode = False
self.fold = 20
self.bundle = False
self.barrier = False
self.index = False
self.compress = True
self.figwidth = -1
self.dpi = 150
self.margin = [2.0, 0.0, 0.0, 0.3]
self.cline = 'doublet'
self.reverse = False
def set_style(self, dic):
self.tc = dic.get('textcolor', self.tc)
self.sc = dic.get('subtextcolor', self.sc)
self.lc = dic.get('linecolor', self.lc)
self.cc = dic.get('creglinecolor', self.cc)
self.gt = dic.get('gatetextcolor', self.tc)
self.gc = dic.get('gatefacecolor', self.gc)
self.bc = dic.get('barrierfacecolor', self.bc)
self.bg = dic.get('backgroundcolor', self.bg)
self.fs = dic.get('fontsize', self.fs)
self.sfs = dic.get('subfontsize', self.sfs)
self.disptex = dic.get('displaytext', self.disptex)
for key in self.dispcol.keys():
self.dispcol[key] = self.gc
self.dispcol = dic.get('displaycolor', self.dispcol)
self.latexmode = dic.get('latexdrawerstyle', self.latexmode)
self.pimode = dic.get('usepiformat', self.pimode)
self.fold = dic.get('fold', self.fold)
if self.fold < 2:
self.fold = -1
self.bundle = dic.get('cregbundle', self.bundle)
self.barrier = dic.get('plotbarrier', self.barrier)
self.index = dic.get('showindex', self.index)
self.compress = dic.get('compress', self.compress)
self.figwidth = dic.get('figwidth', self.figwidth)
self.dpi = dic.get('dpi', self.dpi)
self.margin = dic.get('margin', self.margin)
self.cline = dic.get('creglinestyle', self.cline)
self.reverse = dic.get('reversebits', self.reverse)
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to complile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def _trim(im):
"""Trim image and remove white space
"""
bg = Image.new(im.mode, im.size, im.getpixel((0, 0)))
diff = ImageChops.difference(im, bg)
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
im = im.crop(bbox)
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename, basis=basis,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
qcimg = QCircuitImage(json_circuit, scale, style=style)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, circuit, scale, style=None):
"""
Args:
circuit (dict): compiled_circuit from qobj
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
"""
# style sheet
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.circuit = circuit
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
#################################
self.header = self.circuit['header']
self.qregs = OrderedDict(_get_register_specs(
self.header['qubit_labels']))
self.qubit_list = []
for qr in self.qregs:
for i in range(self.qregs[qr]):
self.qubit_list.append((qr, i))
self.cregs = OrderedDict()
if 'clbit_labels' in self.header:
for item in self.header['clbit_labels']:
self.cregs[item[0]] = item[1]
self.clbit_list = []
cregs = self.cregs
if self._style.reverse:
self.orig_cregs = self.cregs
cregs = reversed(self.cregs)
for cr in cregs:
for i in range(self.cregs[cr]):
self.clbit_list.append((cr, i))
self.ordered_regs = [(item[0], item[1]) for
item in self.header['qubit_labels']]
if self._style.reverse:
reg_size = []
reg_labels = []
new_ordered_regs = []
for regs in self.ordered_regs:
if regs[0] in reg_labels:
continue
reg_labels.append(regs[0])
reg_size.append(len(
[x for x in self.ordered_regs if x[0] == regs[0]]))
index = 0
for size in reg_size:
new_index = index + size
for i in range(new_index - 1, index - 1, -1):
new_ordered_regs.append(self.ordered_regs[i])
index = new_index
self.ordered_regs = new_ordered_regs
if 'clbit_labels' in self.header:
for clabel in self.header['clbit_labels']:
if self._style.reverse:
for cind in reversed(range(clabel[1])):
self.ordered_regs.append((clabel[0], cind))
else:
for cind in range(clabel[1]):
self.ordered_regs.append((clabel[0], cind))
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\'+'\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
QISKitError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.circuit['instructions']:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's', 'sdg',
't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy', 'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['texparams']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, arg)
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
assert len(op['clbits']) == 1 and len(op['qubits']) == 1
if 'conditional' in op:
raise QISKitError('conditional measures currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise QISKitError('conditional reset currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
assert False, "bad node data"
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns+1, ceil(sum_column_widths)+4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above example,
index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _convert_mask(self, mask):
orig_clbit_list = []
for cr in self.orig_cregs:
for i in range(self.orig_cregs[cr]):
orig_clbit_list.append((cr, i))
bit_list = [(mask >> bit) & 1 for bit in range(
len(orig_clbit_list) - 1, -1, -1)]
converted_mask_list = [None] * len(bit_list)
converted_mask = 0
for pos, bit in enumerate(reversed(bit_list)):
new_pos = self.clbit_list.index(orig_clbit_list[pos])
converted_mask_list[new_pos] = bit
if None in converted_mask_list:
raise VisualizationError('Reverse mask creation failed')
converted_mask_list = list(reversed(converted_mask_list))
for bit in converted_mask_list:
converted_mask = (converted_mask << 1) | bit
return converted_mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.circuit['instructions']):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier']:
nm = op['name']
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] =\
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
elif nm == "reset":
self._latex[pos_1][columns] = \
"\\push{\\rule{.6em}{0em}\\ket{0}\\rule{.2em}{0em}} \\qw"
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-0.65em]{')
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-0.65em]{')
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
assert len(op['clbits']) == 1 and \
len(op['qubits']) == 1 and \
'params' not in op, "bad operation record"
if 'conditional' in op:
assert False, "If controlled measures currently not supported."
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise QISKitError('Error during Latex building: %s' %
str(e))
elif op['name'] == "barrier":
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qubits']) - 1
self._latex[start][columns] += " \\barrier{" + str(span) + "}"
else:
assert False, "bad node data"
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
if self._style.reverse:
return origin + 1
return origin - 1
def _get_register_specs(bit_labels):
"""
Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`python`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,'
'ry,rz,cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,'
'cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = MatplotlibDrawer(basis=basis, scale=scale, style=style)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
Register = namedtuple('Register', 'name index')
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=1.0, style=None):
self._ast = None
self._basis = basis
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = OrderedDict()
self._creg_dict = OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False, labelleft=False, labelright=False)
def load_qasm_file(self, filename):
circuit = load_qasm_file(filename, name='draw', basis_gates=self._basis)
self.parse_circuit(circuit)
def parse_circuit(self, circuit):
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
self._ast = transpile(dag_circuit, basis_gates=self._basis, format='json')
self._registers()
self._ops = self._ast['instructions']
def _registers(self):
# NOTE: formats of clbit and qubit are different!
header = self._ast['header']
self._creg = []
for e in header['clbit_labels']:
for i in range(e[1]):
self._creg.append(Register(name=e[0], index=i))
assert len(self._creg) == header['number_of_clbits']
self._qreg = []
for e in header['qubit_labels']:
self._qreg.append(Register(name=e[0], index=e[1]))
assert len(self._qreg) == header['number_of_qubits']
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.sc,
clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7, height=HIG * 0.7,
theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID], [qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy+0.35*WID], lc=self._style.cc, ls=self._style.cline)
arrowhead = patches.Polygon(((cx-0.20*WID, cy+0.35*WID),
(cx+0.20*WID, cy+0.35*WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'], ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if get_matplotlib_backend() == 'module://ipykernel.pylab.backend_inline':
# returns None when matplotlib is inline mode to prevent Jupyter
# with matplotlib inlining enabled to draw the diagram twice.
im = None
else:
# when matplotlib is not inline mode,
# self.figure.savefig is called twice because...
# ... this is needed to get the in-memory representation
with tempfile.TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, 'circuit.png')
self.figure.savefig(tmpfile, dpi=self._style.dpi,
bbox_inches='tight')
im = Image.open(tmpfile)
_trim(im)
os.remove(tmpfile)
# ... and this is needed to delegate in matplotlib the generation of
# the proper format.
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
return im
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index, 'group': reg.name}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(zip_longest(self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
self._cond['n_lines'] += 1
idx += 1
# reverse bit order
if self._style.reverse:
self._reverse_bits(self._qreg_dict)
self._reverse_bits(self._creg_dict)
def _reverse_bits(self, target_dict):
coord = {}
# grouping
for dict_ in target_dict.values():
if dict_['group'] not in coord:
coord[dict_['group']] = [dict_['y']]
else:
coord[dict_['group']].insert(0, dict_['y'])
# reverse bit order
for key in target_dict.keys():
target_dict[key]['y'] = coord[target_dict[key]['group']].pop(0)
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc, ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qubits' in op.keys():
q_idxs = op['qubits']
else:
q_idxs = []
# get creg index
if 'clbits' in op.keys():
c_idxs = op['clbits']
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied), max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] == 'barrier' and not self._style.barrier:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg corrdinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc, ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] == 'barrier':
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self._style.barrier:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise QISKitError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if isclose(fmod(abs_val, 1.0), 0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
elif 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return Fraction(i, j)
return None
<|code_end|>
|
Issues with unified circuit drawer
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**:
- **Python version**:
- **Operating system**:
### What is the current behavior?
I think the following should be fixed regarding the merge of #1055:
1- Remove `DeprecationWarning`: This is a bit annoying as it gets printed all the time. I think deprecation warnings should be about something the user should update in their code. Here, we are just announcing plans for changing a default. Most people just want to write `circuit_drawer(circuit)`.
2- ```circuit_drawer(circ, output='python')```: can we force the output to be shown here? Otherwise, changing the default will mean everyone has to add a ```%matplotlib inline``` to their notebooks.
3- ```circuit_drawer(circ, output='latex_source')``` raises an AttributeError.
4- ```interactive=True``` has no effect with ```ouput='python'``` either. I should it should display it, right? The docstring only says
```Note when used with the latex_source output type this has no effect```
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
1. LaTeX
2. Matplotlib
"""
import json
import logging
import operator
import os
import re
import subprocess
import tempfile
from collections import namedtuple, OrderedDict
from fractions import Fraction
from io import StringIO
from itertools import groupby, zip_longest
from math import fmod, isclose, ceil
import warnings
import numpy as np
from PIL import Image, ImageChops
from matplotlib import get_backend as get_matplotlib_backend, \
patches as patches, pyplot as plt
from qiskit._qiskiterror import QISKitError
from qiskit.wrapper import load_qasm_file
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization._error import VisualizationError
from qiskit.transpiler import transpile
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False):
"""Draw a quantum circuit, via 2 methods (try 1st, if unsuccessful, 2nd):
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
output (str): Select the output method to use for drawing the circuit.
Valid choices are `latex`, `latex_source`, `python`. Note if one is
not specified it will use latex and if that fails fallback to
python. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
VisualizationError: when an invalid output method is selected
"""
im = None
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to python on failure it will just use '
'python by default', DeprecationWarning)
try:
im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError):
im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
else:
if output not in ['latex', 'latex_source', 'python']:
raise VisualizationError(
'Invalid output type %s selected. The only valid choices are '
'latex, latex_source, and python' % output)
if output == 'latex':
im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
elif output == 'latex_source':
return _generate_latex_source(circuit, basis, scale, filename, style)
elif output == 'python':
im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
if im and interactive:
im.show()
return im
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
class QCStyle:
def __init__(self):
self.tc = '#000000'
self.sc = '#000000'
self.lc = '#000000'
self.cc = '#778899'
self.gc = '#ffffff'
self.gt = '#000000'
self.bc = '#bdbdbd'
self.bg = '#ffffff'
self.fs = 13
self.sfs = 8
self.disptex = {
'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'
}
self.dispcol = {
'id': '#ffffff',
'u0': '#ffffff',
'u1': '#ffffff',
'u2': '#ffffff',
'u3': '#ffffff',
'x': '#ffffff',
'y': '#ffffff',
'z': '#ffffff',
'h': '#ffffff',
's': '#ffffff',
'sdg': '#ffffff',
't': '#ffffff',
'tdg': '#ffffff',
'rx': '#ffffff',
'ry': '#ffffff',
'rz': '#ffffff',
'reset': '#ffffff',
'target': '#ffffff',
'meas': '#ffffff'
}
self.latexmode = True
self.pimode = False
self.fold = 20
self.bundle = False
self.barrier = False
self.index = False
self.compress = True
self.figwidth = -1
self.dpi = 150
self.margin = [2.0, 0.0, 0.0, 0.3]
self.cline = 'doublet'
self.reverse = False
def set_style(self, dic):
self.tc = dic.get('textcolor', self.tc)
self.sc = dic.get('subtextcolor', self.sc)
self.lc = dic.get('linecolor', self.lc)
self.cc = dic.get('creglinecolor', self.cc)
self.gt = dic.get('gatetextcolor', self.tc)
self.gc = dic.get('gatefacecolor', self.gc)
self.bc = dic.get('barrierfacecolor', self.bc)
self.bg = dic.get('backgroundcolor', self.bg)
self.fs = dic.get('fontsize', self.fs)
self.sfs = dic.get('subfontsize', self.sfs)
self.disptex = dic.get('displaytext', self.disptex)
for key in self.dispcol.keys():
self.dispcol[key] = self.gc
self.dispcol = dic.get('displaycolor', self.dispcol)
self.latexmode = dic.get('latexdrawerstyle', self.latexmode)
self.pimode = dic.get('usepiformat', self.pimode)
self.fold = dic.get('fold', self.fold)
if self.fold < 2:
self.fold = -1
self.bundle = dic.get('cregbundle', self.bundle)
self.barrier = dic.get('plotbarrier', self.barrier)
self.index = dic.get('showindex', self.index)
self.compress = dic.get('compress', self.compress)
self.figwidth = dic.get('figwidth', self.figwidth)
self.dpi = dic.get('dpi', self.dpi)
self.margin = dic.get('margin', self.margin)
self.cline = dic.get('creglinestyle', self.cline)
self.reverse = dic.get('reversebits', self.reverse)
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to complile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def _trim(im):
"""Trim image and remove white space
"""
bg = Image.new(im.mode, im.size, im.getpixel((0, 0)))
diff = ImageChops.difference(im, bg)
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
im = im.crop(bbox)
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename, basis=basis,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
qcimg = QCircuitImage(json_circuit, scale, style=style)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, circuit, scale, style=None):
"""
Args:
circuit (dict): compiled_circuit from qobj
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
"""
# style sheet
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.circuit = circuit
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
#################################
self.header = self.circuit['header']
self.qregs = OrderedDict(_get_register_specs(
self.header['qubit_labels']))
self.qubit_list = []
for qr in self.qregs:
for i in range(self.qregs[qr]):
self.qubit_list.append((qr, i))
self.cregs = OrderedDict()
if 'clbit_labels' in self.header:
for item in self.header['clbit_labels']:
self.cregs[item[0]] = item[1]
self.clbit_list = []
cregs = self.cregs
if self._style.reverse:
self.orig_cregs = self.cregs
cregs = reversed(self.cregs)
for cr in cregs:
for i in range(self.cregs[cr]):
self.clbit_list.append((cr, i))
self.ordered_regs = [(item[0], item[1]) for
item in self.header['qubit_labels']]
if self._style.reverse:
reg_size = []
reg_labels = []
new_ordered_regs = []
for regs in self.ordered_regs:
if regs[0] in reg_labels:
continue
reg_labels.append(regs[0])
reg_size.append(len(
[x for x in self.ordered_regs if x[0] == regs[0]]))
index = 0
for size in reg_size:
new_index = index + size
for i in range(new_index - 1, index - 1, -1):
new_ordered_regs.append(self.ordered_regs[i])
index = new_index
self.ordered_regs = new_ordered_regs
if 'clbit_labels' in self.header:
for clabel in self.header['clbit_labels']:
if self._style.reverse:
for cind in reversed(range(clabel[1])):
self.ordered_regs.append((clabel[0], cind))
else:
for cind in range(clabel[1]):
self.ordered_regs.append((clabel[0], cind))
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\'+'\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
QISKitError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.circuit['instructions']:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's', 'sdg',
't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy', 'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['texparams']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, arg)
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
assert len(op['clbits']) == 1 and len(op['qubits']) == 1
if 'conditional' in op:
raise QISKitError('conditional measures currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise QISKitError('conditional reset currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
assert False, "bad node data"
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns+1, ceil(sum_column_widths)+4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above example,
index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _convert_mask(self, mask):
orig_clbit_list = []
for cr in self.orig_cregs:
for i in range(self.orig_cregs[cr]):
orig_clbit_list.append((cr, i))
bit_list = [(mask >> bit) & 1 for bit in range(
len(orig_clbit_list) - 1, -1, -1)]
converted_mask_list = [None] * len(bit_list)
converted_mask = 0
for pos, bit in enumerate(reversed(bit_list)):
new_pos = self.clbit_list.index(orig_clbit_list[pos])
converted_mask_list[new_pos] = bit
if None in converted_mask_list:
raise VisualizationError('Reverse mask creation failed')
converted_mask_list = list(reversed(converted_mask_list))
for bit in converted_mask_list:
converted_mask = (converted_mask << 1) | bit
return converted_mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.circuit['instructions']):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier']:
nm = op['name']
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] =\
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
elif nm == "reset":
self._latex[pos_1][columns] = \
"\\push{\\rule{.6em}{0em}\\ket{0}\\rule{.2em}{0em}} \\qw"
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-0.65em]{')
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-0.65em]{')
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
assert len(op['clbits']) == 1 and \
len(op['qubits']) == 1 and \
'params' not in op, "bad operation record"
if 'conditional' in op:
assert False, "If controlled measures currently not supported."
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise QISKitError('Error during Latex building: %s' %
str(e))
elif op['name'] == "barrier":
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qubits']) - 1
self._latex[start][columns] += " \\barrier{" + str(span) + "}"
else:
assert False, "bad node data"
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
if self._style.reverse:
return origin + 1
return origin - 1
def _get_register_specs(bit_labels):
"""
Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`python`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,'
'ry,rz,cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,'
'cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = MatplotlibDrawer(basis=basis, scale=scale, style=style)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
Register = namedtuple('Register', 'name index')
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=1.0, style=None):
self._ast = None
self._basis = basis
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = OrderedDict()
self._creg_dict = OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False, labelleft=False, labelright=False)
def load_qasm_file(self, filename):
circuit = load_qasm_file(filename, name='draw', basis_gates=self._basis)
self.parse_circuit(circuit)
def parse_circuit(self, circuit):
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
self._ast = transpile(dag_circuit, basis_gates=self._basis, format='json')
self._registers()
self._ops = self._ast['instructions']
def _registers(self):
# NOTE: formats of clbit and qubit are different!
header = self._ast['header']
self._creg = []
for e in header['clbit_labels']:
for i in range(e[1]):
self._creg.append(Register(name=e[0], index=i))
assert len(self._creg) == header['number_of_clbits']
self._qreg = []
for e in header['qubit_labels']:
self._qreg.append(Register(name=e[0], index=e[1]))
assert len(self._qreg) == header['number_of_qubits']
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.sc,
clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7, height=HIG * 0.7,
theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID], [qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy+0.35*WID], lc=self._style.cc, ls=self._style.cline)
arrowhead = patches.Polygon(((cx-0.20*WID, cy+0.35*WID),
(cx+0.20*WID, cy+0.35*WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'], ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if get_matplotlib_backend() == 'module://ipykernel.pylab.backend_inline':
# returns None when matplotlib is inline mode to prevent Jupyter
# with matplotlib inlining enabled to draw the diagram twice.
im = None
else:
# when matplotlib is not inline mode,
# self.figure.savefig is called twice because...
# ... this is needed to get the in-memory representation
with tempfile.TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, 'circuit.png')
self.figure.savefig(tmpfile, dpi=self._style.dpi,
bbox_inches='tight')
im = Image.open(tmpfile)
_trim(im)
os.remove(tmpfile)
# ... and this is needed to delegate in matplotlib the generation of
# the proper format.
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
return im
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index, 'group': reg.name}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(zip_longest(self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
self._cond['n_lines'] += 1
idx += 1
# reverse bit order
if self._style.reverse:
self._reverse_bits(self._qreg_dict)
self._reverse_bits(self._creg_dict)
def _reverse_bits(self, target_dict):
coord = {}
# grouping
for dict_ in target_dict.values():
if dict_['group'] not in coord:
coord[dict_['group']] = [dict_['y']]
else:
coord[dict_['group']].insert(0, dict_['y'])
# reverse bit order
for key in target_dict.keys():
target_dict[key]['y'] = coord[target_dict[key]['group']].pop(0)
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc, ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qubits' in op.keys():
q_idxs = op['qubits']
else:
q_idxs = []
# get creg index
if 'clbits' in op.keys():
c_idxs = op['clbits']
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied), max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] == 'barrier' and not self._style.barrier:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg corrdinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc, ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] == 'barrier':
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self._style.barrier:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise QISKitError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if isclose(fmod(abs_val, 1.0), 0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
elif 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return Fraction(i, j)
return None
<|code_end|>
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
1. LaTeX
2. Matplotlib
"""
import json
import logging
import operator
import os
import re
import subprocess
import tempfile
from collections import namedtuple, OrderedDict
from fractions import Fraction
from io import StringIO
from itertools import groupby, zip_longest
from math import fmod, isclose, ceil
import warnings
import numpy as np
from PIL import Image, ImageChops
from matplotlib import get_backend as get_matplotlib_backend, \
patches as patches, pyplot as plt
from qiskit._qiskiterror import QISKitError
from qiskit.wrapper import load_qasm_file
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization._error import VisualizationError
from qiskit.transpiler import transpile
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False):
"""Draw a quantum circuit, via 2 methods (try 1st, if unsuccessful, 2nd):
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
output (str): Select the output method to use for drawing the circuit.
Valid choices are `latex`, `latex_source`, `python`. Note if one is
not specified it will use latex and if that fails fallback to
python. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
VisualizationError: when an invalid output method is selected
"""
im = None
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to python on failure it will just use '
'python by default', DeprecationWarning)
try:
im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError):
im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
else:
if output not in ['latex', 'latex_source', 'python']:
raise VisualizationError(
'Invalid output type %s selected. The only valid choices are '
'latex, latex_source, and python' % output)
if output == 'latex':
im = _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
elif output == 'latex_source':
return _generate_latex_source(circuit, basis=basis,
filename=filename, scale=scale,
style=style)
elif output == 'python':
im = _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
if im and interactive:
im.show()
return im
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
class QCStyle:
def __init__(self):
self.tc = '#000000'
self.sc = '#000000'
self.lc = '#000000'
self.cc = '#778899'
self.gc = '#ffffff'
self.gt = '#000000'
self.bc = '#bdbdbd'
self.bg = '#ffffff'
self.fs = 13
self.sfs = 8
self.disptex = {
'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'
}
self.dispcol = {
'id': '#ffffff',
'u0': '#ffffff',
'u1': '#ffffff',
'u2': '#ffffff',
'u3': '#ffffff',
'x': '#ffffff',
'y': '#ffffff',
'z': '#ffffff',
'h': '#ffffff',
's': '#ffffff',
'sdg': '#ffffff',
't': '#ffffff',
'tdg': '#ffffff',
'rx': '#ffffff',
'ry': '#ffffff',
'rz': '#ffffff',
'reset': '#ffffff',
'target': '#ffffff',
'meas': '#ffffff'
}
self.latexmode = True
self.pimode = False
self.fold = 20
self.bundle = False
self.barrier = False
self.index = False
self.compress = True
self.figwidth = -1
self.dpi = 150
self.margin = [2.0, 0.0, 0.0, 0.3]
self.cline = 'doublet'
self.reverse = False
def set_style(self, dic):
self.tc = dic.get('textcolor', self.tc)
self.sc = dic.get('subtextcolor', self.sc)
self.lc = dic.get('linecolor', self.lc)
self.cc = dic.get('creglinecolor', self.cc)
self.gt = dic.get('gatetextcolor', self.tc)
self.gc = dic.get('gatefacecolor', self.gc)
self.bc = dic.get('barrierfacecolor', self.bc)
self.bg = dic.get('backgroundcolor', self.bg)
self.fs = dic.get('fontsize', self.fs)
self.sfs = dic.get('subfontsize', self.sfs)
self.disptex = dic.get('displaytext', self.disptex)
for key in self.dispcol.keys():
self.dispcol[key] = self.gc
self.dispcol = dic.get('displaycolor', self.dispcol)
self.latexmode = dic.get('latexdrawerstyle', self.latexmode)
self.pimode = dic.get('usepiformat', self.pimode)
self.fold = dic.get('fold', self.fold)
if self.fold < 2:
self.fold = -1
self.bundle = dic.get('cregbundle', self.bundle)
self.barrier = dic.get('plotbarrier', self.barrier)
self.index = dic.get('showindex', self.index)
self.compress = dic.get('compress', self.compress)
self.figwidth = dic.get('figwidth', self.figwidth)
self.dpi = dic.get('dpi', self.dpi)
self.margin = dic.get('margin', self.margin)
self.cline = dic.get('creglinestyle', self.cline)
self.reverse = dic.get('reversebits', self.reverse)
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to complile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def _trim(im):
"""Trim image and remove white space
"""
bg = Image.new(im.mode, im.size, im.getpixel((0, 0)))
diff = ImageChops.difference(im, bg)
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
im = im.crop(bbox)
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename, basis=basis,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
qcimg = QCircuitImage(json_circuit, scale, style=style)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, circuit, scale, style=None):
"""
Args:
circuit (dict): compiled_circuit from qobj
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
"""
# style sheet
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.circuit = circuit
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
#################################
self.header = self.circuit['header']
self.qregs = OrderedDict(_get_register_specs(
self.header['qubit_labels']))
self.qubit_list = []
for qr in self.qregs:
for i in range(self.qregs[qr]):
self.qubit_list.append((qr, i))
self.cregs = OrderedDict()
if 'clbit_labels' in self.header:
for item in self.header['clbit_labels']:
self.cregs[item[0]] = item[1]
self.clbit_list = []
cregs = self.cregs
if self._style.reverse:
self.orig_cregs = self.cregs
cregs = reversed(self.cregs)
for cr in cregs:
for i in range(self.cregs[cr]):
self.clbit_list.append((cr, i))
self.ordered_regs = [(item[0], item[1]) for
item in self.header['qubit_labels']]
if self._style.reverse:
reg_size = []
reg_labels = []
new_ordered_regs = []
for regs in self.ordered_regs:
if regs[0] in reg_labels:
continue
reg_labels.append(regs[0])
reg_size.append(len(
[x for x in self.ordered_regs if x[0] == regs[0]]))
index = 0
for size in reg_size:
new_index = index + size
for i in range(new_index - 1, index - 1, -1):
new_ordered_regs.append(self.ordered_regs[i])
index = new_index
self.ordered_regs = new_ordered_regs
if 'clbit_labels' in self.header:
for clabel in self.header['clbit_labels']:
if self._style.reverse:
for cind in reversed(range(clabel[1])):
self.ordered_regs.append((clabel[0], cind))
else:
for cind in range(clabel[1]):
self.ordered_regs.append((clabel[0], cind))
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\'+'\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
QISKitError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.circuit['instructions']:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's', 'sdg',
't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy', 'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['texparams']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, arg)
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
assert len(op['clbits']) == 1 and len(op['qubits']) == 1
if 'conditional' in op:
raise QISKitError('conditional measures currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise QISKitError('conditional reset currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
assert False, "bad node data"
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns+1, ceil(sum_column_widths)+4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above example,
index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _convert_mask(self, mask):
orig_clbit_list = []
for cr in self.orig_cregs:
for i in range(self.orig_cregs[cr]):
orig_clbit_list.append((cr, i))
bit_list = [(mask >> bit) & 1 for bit in range(
len(orig_clbit_list) - 1, -1, -1)]
converted_mask_list = [None] * len(bit_list)
converted_mask = 0
for pos, bit in enumerate(reversed(bit_list)):
new_pos = self.clbit_list.index(orig_clbit_list[pos])
converted_mask_list[new_pos] = bit
if None in converted_mask_list:
raise VisualizationError('Reverse mask creation failed')
converted_mask_list = list(reversed(converted_mask_list))
for bit in converted_mask_list:
converted_mask = (converted_mask << 1) | bit
return converted_mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.circuit['instructions']):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier']:
nm = op['name']
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] =\
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
elif nm == "reset":
self._latex[pos_1][columns] = \
"\\push{\\rule{.6em}{0em}\\ket{0}\\rule{.2em}{0em}} \\qw"
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-0.65em]{')
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-0.65em]{')
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
assert len(op['clbits']) == 1 and \
len(op['qubits']) == 1 and \
'params' not in op, "bad operation record"
if 'conditional' in op:
assert False, "If controlled measures currently not supported."
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise QISKitError('Error during Latex building: %s' %
str(e))
elif op['name'] == "barrier":
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qubits']) - 1
self._latex[start][columns] += " \\barrier{" + str(span) + "}"
else:
assert False, "bad node data"
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
if self._style.reverse:
return origin + 1
return origin - 1
def _get_register_specs(bit_labels):
"""
Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`python`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,'
'ry,rz,cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,'
'cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = MatplotlibDrawer(basis=basis, scale=scale, style=style)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
Register = namedtuple('Register', 'name index')
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=1.0, style=None):
self._ast = None
self._basis = basis
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = OrderedDict()
self._creg_dict = OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False, labelleft=False, labelright=False)
def load_qasm_file(self, filename):
circuit = load_qasm_file(filename, name='draw', basis_gates=self._basis)
self.parse_circuit(circuit)
def parse_circuit(self, circuit):
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
self._ast = transpile(dag_circuit, basis_gates=self._basis, format='json')
self._registers()
self._ops = self._ast['instructions']
def _registers(self):
# NOTE: formats of clbit and qubit are different!
header = self._ast['header']
self._creg = []
for e in header['clbit_labels']:
for i in range(e[1]):
self._creg.append(Register(name=e[0], index=i))
assert len(self._creg) == header['number_of_clbits']
self._qreg = []
for e in header['qubit_labels']:
self._qreg.append(Register(name=e[0], index=e[1]))
assert len(self._qreg) == header['number_of_qubits']
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.sc,
clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7, height=HIG * 0.7,
theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID], [qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy+0.35*WID], lc=self._style.cc, ls=self._style.cline)
arrowhead = patches.Polygon(((cx-0.20*WID, cy+0.35*WID),
(cx+0.20*WID, cy+0.35*WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'], ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if get_matplotlib_backend() == 'module://ipykernel.pylab.backend_inline':
# returns None when matplotlib is inline mode to prevent Jupyter
# with matplotlib inlining enabled to draw the diagram twice.
im = None
else:
# when matplotlib is not inline mode,
# self.figure.savefig is called twice because...
# ... this is needed to get the in-memory representation
with tempfile.TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, 'circuit.png')
self.figure.savefig(tmpfile, dpi=self._style.dpi,
bbox_inches='tight')
im = Image.open(tmpfile)
_trim(im)
os.remove(tmpfile)
# ... and this is needed to delegate in matplotlib the generation of
# the proper format.
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
return im
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index, 'group': reg.name}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(zip_longest(self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
self._cond['n_lines'] += 1
idx += 1
# reverse bit order
if self._style.reverse:
self._reverse_bits(self._qreg_dict)
self._reverse_bits(self._creg_dict)
def _reverse_bits(self, target_dict):
coord = {}
# grouping
for dict_ in target_dict.values():
if dict_['group'] not in coord:
coord[dict_['group']] = [dict_['y']]
else:
coord[dict_['group']].insert(0, dict_['y'])
# reverse bit order
for key in target_dict.keys():
target_dict[key]['y'] = coord[target_dict[key]['group']].pop(0)
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc, ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qubits' in op.keys():
q_idxs = op['qubits']
else:
q_idxs = []
# get creg index
if 'clbits' in op.keys():
c_idxs = op['clbits']
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied), max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] == 'barrier' and not self._style.barrier:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg corrdinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc, ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] == 'barrier':
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self._style.barrier:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise QISKitError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if isclose(fmod(abs_val, 1.0), 0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
elif 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return Fraction(i, j)
return None
<|code_end|>
|
rename "python" drawer to "matplot"
The name options for the `circuit_drawer` are `['latex', 'latex_source', 'python', 'text']`. The output `python` is no very descriptive of the expected output. I suggest to rename it to `'matplot'`.
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
1. LaTeX
2. Matplotlib
"""
import json
import logging
import operator
import os
import re
import subprocess
import tempfile
from collections import namedtuple, OrderedDict
from fractions import Fraction
from io import StringIO
from itertools import groupby, zip_longest
from math import fmod, isclose, ceil
import warnings
import numpy as np
from PIL import Image, ImageChops
from matplotlib import get_backend as get_matplotlib_backend, \
patches as patches, pyplot as plt
from qiskit._qiskiterror import QISKitError
from qiskit.wrapper import load_qasm_file
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization._error import VisualizationError
from qiskit.transpiler import transpile
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False):
"""Draw a quantum circuit, via 2 methods (try 1st, if unsuccessful, 2nd):
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
output (str): Select the output method to use for drawing the circuit.
Valid choices are `latex`, `latex_source`, `python`. Note if one is
not specified it will use latex and if that fails fallback to
python. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
VisualizationError: when an invalid output method is selected
"""
im = None
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to python on failure it will just use '
'python by default', DeprecationWarning)
try:
im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError):
im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
else:
if output not in ['latex', 'latex_source', 'python']:
raise VisualizationError(
'Invalid output type %s selected. The only valid choices are '
'latex, latex_source, and python' % output)
if output == 'latex':
im = _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
elif output == 'latex_source':
return _generate_latex_source(circuit, basis=basis,
filename=filename, scale=scale,
style=style)
elif output == 'python':
im = _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
if im and interactive:
im.show()
return im
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
class QCStyle:
def __init__(self):
self.tc = '#000000'
self.sc = '#000000'
self.lc = '#000000'
self.cc = '#778899'
self.gc = '#ffffff'
self.gt = '#000000'
self.bc = '#bdbdbd'
self.bg = '#ffffff'
self.fs = 13
self.sfs = 8
self.disptex = {
'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'
}
self.dispcol = {
'id': '#ffffff',
'u0': '#ffffff',
'u1': '#ffffff',
'u2': '#ffffff',
'u3': '#ffffff',
'x': '#ffffff',
'y': '#ffffff',
'z': '#ffffff',
'h': '#ffffff',
's': '#ffffff',
'sdg': '#ffffff',
't': '#ffffff',
'tdg': '#ffffff',
'rx': '#ffffff',
'ry': '#ffffff',
'rz': '#ffffff',
'reset': '#ffffff',
'target': '#ffffff',
'meas': '#ffffff'
}
self.latexmode = True
self.pimode = False
self.fold = 20
self.bundle = False
self.barrier = False
self.index = False
self.compress = True
self.figwidth = -1
self.dpi = 150
self.margin = [2.0, 0.0, 0.0, 0.3]
self.cline = 'doublet'
self.reverse = False
def set_style(self, dic):
self.tc = dic.get('textcolor', self.tc)
self.sc = dic.get('subtextcolor', self.sc)
self.lc = dic.get('linecolor', self.lc)
self.cc = dic.get('creglinecolor', self.cc)
self.gt = dic.get('gatetextcolor', self.tc)
self.gc = dic.get('gatefacecolor', self.gc)
self.bc = dic.get('barrierfacecolor', self.bc)
self.bg = dic.get('backgroundcolor', self.bg)
self.fs = dic.get('fontsize', self.fs)
self.sfs = dic.get('subfontsize', self.sfs)
self.disptex = dic.get('displaytext', self.disptex)
for key in self.dispcol.keys():
self.dispcol[key] = self.gc
self.dispcol = dic.get('displaycolor', self.dispcol)
self.latexmode = dic.get('latexdrawerstyle', self.latexmode)
self.pimode = dic.get('usepiformat', self.pimode)
self.fold = dic.get('fold', self.fold)
if self.fold < 2:
self.fold = -1
self.bundle = dic.get('cregbundle', self.bundle)
self.barrier = dic.get('plotbarrier', self.barrier)
self.index = dic.get('showindex', self.index)
self.compress = dic.get('compress', self.compress)
self.figwidth = dic.get('figwidth', self.figwidth)
self.dpi = dic.get('dpi', self.dpi)
self.margin = dic.get('margin', self.margin)
self.cline = dic.get('creglinestyle', self.cline)
self.reverse = dic.get('reversebits', self.reverse)
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to complile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def _trim(im):
"""Trim image and remove white space
"""
bg = Image.new(im.mode, im.size, im.getpixel((0, 0)))
diff = ImageChops.difference(im, bg)
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
im = im.crop(bbox)
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename, basis=basis,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
qcimg = QCircuitImage(json_circuit, scale, style=style)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, circuit, scale, style=None):
"""
Args:
circuit (dict): compiled_circuit from qobj
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
"""
# style sheet
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.circuit = circuit
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
#################################
self.header = self.circuit['header']
self.qregs = OrderedDict(_get_register_specs(
self.header['qubit_labels']))
self.qubit_list = []
for qr in self.qregs:
for i in range(self.qregs[qr]):
self.qubit_list.append((qr, i))
self.cregs = OrderedDict()
if 'clbit_labels' in self.header:
for item in self.header['clbit_labels']:
self.cregs[item[0]] = item[1]
self.clbit_list = []
cregs = self.cregs
if self._style.reverse:
self.orig_cregs = self.cregs
cregs = reversed(self.cregs)
for cr in cregs:
for i in range(self.cregs[cr]):
self.clbit_list.append((cr, i))
self.ordered_regs = [(item[0], item[1]) for
item in self.header['qubit_labels']]
if self._style.reverse:
reg_size = []
reg_labels = []
new_ordered_regs = []
for regs in self.ordered_regs:
if regs[0] in reg_labels:
continue
reg_labels.append(regs[0])
reg_size.append(len(
[x for x in self.ordered_regs if x[0] == regs[0]]))
index = 0
for size in reg_size:
new_index = index + size
for i in range(new_index - 1, index - 1, -1):
new_ordered_regs.append(self.ordered_regs[i])
index = new_index
self.ordered_regs = new_ordered_regs
if 'clbit_labels' in self.header:
for clabel in self.header['clbit_labels']:
if self._style.reverse:
for cind in reversed(range(clabel[1])):
self.ordered_regs.append((clabel[0], cind))
else:
for cind in range(clabel[1]):
self.ordered_regs.append((clabel[0], cind))
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\'+'\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
QISKitError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.circuit['instructions']:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's', 'sdg',
't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy', 'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['texparams']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, arg)
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
assert len(op['clbits']) == 1 and len(op['qubits']) == 1
if 'conditional' in op:
raise QISKitError('conditional measures currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise QISKitError('conditional reset currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
assert False, "bad node data"
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns+1, ceil(sum_column_widths)+4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above example,
index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _convert_mask(self, mask):
orig_clbit_list = []
for cr in self.orig_cregs:
for i in range(self.orig_cregs[cr]):
orig_clbit_list.append((cr, i))
bit_list = [(mask >> bit) & 1 for bit in range(
len(orig_clbit_list) - 1, -1, -1)]
converted_mask_list = [None] * len(bit_list)
converted_mask = 0
for pos, bit in enumerate(reversed(bit_list)):
new_pos = self.clbit_list.index(orig_clbit_list[pos])
converted_mask_list[new_pos] = bit
if None in converted_mask_list:
raise VisualizationError('Reverse mask creation failed')
converted_mask_list = list(reversed(converted_mask_list))
for bit in converted_mask_list:
converted_mask = (converted_mask << 1) | bit
return converted_mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.circuit['instructions']):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier']:
nm = op['name']
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] =\
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
elif nm == "reset":
self._latex[pos_1][columns] = \
"\\push{\\rule{.6em}{0em}\\ket{0}\\rule{.2em}{0em}} \\qw"
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-0.65em]{')
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-0.65em]{')
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
assert len(op['clbits']) == 1 and \
len(op['qubits']) == 1 and \
'params' not in op, "bad operation record"
if 'conditional' in op:
assert False, "If controlled measures currently not supported."
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise QISKitError('Error during Latex building: %s' %
str(e))
elif op['name'] == "barrier":
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qubits']) - 1
self._latex[start][columns] += " \\barrier{" + str(span) + "}"
else:
assert False, "bad node data"
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
if self._style.reverse:
return origin + 1
return origin - 1
def _get_register_specs(bit_labels):
"""
Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`python`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,'
'ry,rz,cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,'
'cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = MatplotlibDrawer(basis=basis, scale=scale, style=style)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
Register = namedtuple('Register', 'name index')
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=1.0, style=None):
self._ast = None
self._basis = basis
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = OrderedDict()
self._creg_dict = OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False, labelleft=False, labelright=False)
def load_qasm_file(self, filename):
circuit = load_qasm_file(filename, name='draw', basis_gates=self._basis)
self.parse_circuit(circuit)
def parse_circuit(self, circuit):
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
self._ast = transpile(dag_circuit, basis_gates=self._basis, format='json')
self._registers()
self._ops = self._ast['instructions']
def _registers(self):
# NOTE: formats of clbit and qubit are different!
header = self._ast['header']
self._creg = []
for e in header['clbit_labels']:
for i in range(e[1]):
self._creg.append(Register(name=e[0], index=i))
assert len(self._creg) == header['number_of_clbits']
self._qreg = []
for e in header['qubit_labels']:
self._qreg.append(Register(name=e[0], index=e[1]))
assert len(self._qreg) == header['number_of_qubits']
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.sc,
clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7, height=HIG * 0.7,
theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID], [qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy+0.35*WID], lc=self._style.cc, ls=self._style.cline)
arrowhead = patches.Polygon(((cx-0.20*WID, cy+0.35*WID),
(cx+0.20*WID, cy+0.35*WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'], ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if get_matplotlib_backend() == 'module://ipykernel.pylab.backend_inline':
# returns None when matplotlib is inline mode to prevent Jupyter
# with matplotlib inlining enabled to draw the diagram twice.
im = None
else:
# when matplotlib is not inline mode,
# self.figure.savefig is called twice because...
# ... this is needed to get the in-memory representation
with tempfile.TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, 'circuit.png')
self.figure.savefig(tmpfile, dpi=self._style.dpi,
bbox_inches='tight')
im = Image.open(tmpfile)
_trim(im)
os.remove(tmpfile)
# ... and this is needed to delegate in matplotlib the generation of
# the proper format.
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
return im
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index, 'group': reg.name}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(zip_longest(self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
self._cond['n_lines'] += 1
idx += 1
# reverse bit order
if self._style.reverse:
self._reverse_bits(self._qreg_dict)
self._reverse_bits(self._creg_dict)
def _reverse_bits(self, target_dict):
coord = {}
# grouping
for dict_ in target_dict.values():
if dict_['group'] not in coord:
coord[dict_['group']] = [dict_['y']]
else:
coord[dict_['group']].insert(0, dict_['y'])
# reverse bit order
for key in target_dict.keys():
target_dict[key]['y'] = coord[target_dict[key]['group']].pop(0)
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc, ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qubits' in op.keys():
q_idxs = op['qubits']
else:
q_idxs = []
# get creg index
if 'clbits' in op.keys():
c_idxs = op['clbits']
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied), max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] == 'barrier' and not self._style.barrier:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg corrdinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc, ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] == 'barrier':
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self._style.barrier:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise QISKitError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if isclose(fmod(abs_val, 1.0), 0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
elif 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return Fraction(i, j)
return None
<|code_end|>
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
1. LaTeX
2. Matplotlib
"""
import json
import logging
import operator
import os
import re
import subprocess
import tempfile
from collections import namedtuple, OrderedDict
from fractions import Fraction
from io import StringIO
from itertools import groupby, zip_longest
from math import fmod, isclose, ceil
import warnings
import numpy as np
from PIL import Image, ImageChops
from matplotlib import get_backend as get_matplotlib_backend, \
patches as patches, pyplot as plt
from qiskit._qiskiterror import QISKitError
from qiskit.wrapper import load_qasm_file
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization._error import VisualizationError
from qiskit.transpiler import transpile
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False):
"""Draw a quantum circuit, via 2 methods (try 1st, if unsuccessful, 2nd):
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
output (str): Select the output method to use for drawing the circuit.
Valid choices are `latex`, `latex_source`, `mpl`. Note if one is
not specified it will use latex and if that fails fallback to
mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
VisualizationError: when an invalid output method is selected
"""
im = None
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'mpl by default', DeprecationWarning)
try:
im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError):
im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
else:
if output not in ['latex', 'latex_source', 'mpl']:
raise VisualizationError(
'Invalid output type %s selected. The only valid choices are '
'latex, latex_source, and mpl' % output)
if output == 'latex':
im = _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
elif output == 'latex_source':
return _generate_latex_source(circuit, basis=basis,
filename=filename, scale=scale,
style=style)
elif output == 'mpl':
im = _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
if im and interactive:
im.show()
return im
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
class QCStyle:
def __init__(self):
self.tc = '#000000'
self.sc = '#000000'
self.lc = '#000000'
self.cc = '#778899'
self.gc = '#ffffff'
self.gt = '#000000'
self.bc = '#bdbdbd'
self.bg = '#ffffff'
self.fs = 13
self.sfs = 8
self.disptex = {
'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'
}
self.dispcol = {
'id': '#ffffff',
'u0': '#ffffff',
'u1': '#ffffff',
'u2': '#ffffff',
'u3': '#ffffff',
'x': '#ffffff',
'y': '#ffffff',
'z': '#ffffff',
'h': '#ffffff',
's': '#ffffff',
'sdg': '#ffffff',
't': '#ffffff',
'tdg': '#ffffff',
'rx': '#ffffff',
'ry': '#ffffff',
'rz': '#ffffff',
'reset': '#ffffff',
'target': '#ffffff',
'meas': '#ffffff'
}
self.latexmode = True
self.pimode = False
self.fold = 20
self.bundle = False
self.barrier = False
self.index = False
self.compress = True
self.figwidth = -1
self.dpi = 150
self.margin = [2.0, 0.0, 0.0, 0.3]
self.cline = 'doublet'
self.reverse = False
def set_style(self, dic):
self.tc = dic.get('textcolor', self.tc)
self.sc = dic.get('subtextcolor', self.sc)
self.lc = dic.get('linecolor', self.lc)
self.cc = dic.get('creglinecolor', self.cc)
self.gt = dic.get('gatetextcolor', self.tc)
self.gc = dic.get('gatefacecolor', self.gc)
self.bc = dic.get('barrierfacecolor', self.bc)
self.bg = dic.get('backgroundcolor', self.bg)
self.fs = dic.get('fontsize', self.fs)
self.sfs = dic.get('subfontsize', self.sfs)
self.disptex = dic.get('displaytext', self.disptex)
for key in self.dispcol.keys():
self.dispcol[key] = self.gc
self.dispcol = dic.get('displaycolor', self.dispcol)
self.latexmode = dic.get('latexdrawerstyle', self.latexmode)
self.pimode = dic.get('usepiformat', self.pimode)
self.fold = dic.get('fold', self.fold)
if self.fold < 2:
self.fold = -1
self.bundle = dic.get('cregbundle', self.bundle)
self.barrier = dic.get('plotbarrier', self.barrier)
self.index = dic.get('showindex', self.index)
self.compress = dic.get('compress', self.compress)
self.figwidth = dic.get('figwidth', self.figwidth)
self.dpi = dic.get('dpi', self.dpi)
self.margin = dic.get('margin', self.margin)
self.cline = dic.get('creglinestyle', self.cline)
self.reverse = dic.get('reversebits', self.reverse)
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to complile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def _trim(im):
"""Trim image and remove white space
"""
bg = Image.new(im.mode, im.size, im.getpixel((0, 0)))
diff = ImageChops.difference(im, bg)
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
im = im.crop(bbox)
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename, basis=basis,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
qcimg = QCircuitImage(json_circuit, scale, style=style)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, circuit, scale, style=None):
"""
Args:
circuit (dict): compiled_circuit from qobj
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
"""
# style sheet
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.circuit = circuit
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
#################################
self.header = self.circuit['header']
self.qregs = OrderedDict(_get_register_specs(
self.header['qubit_labels']))
self.qubit_list = []
for qr in self.qregs:
for i in range(self.qregs[qr]):
self.qubit_list.append((qr, i))
self.cregs = OrderedDict()
if 'clbit_labels' in self.header:
for item in self.header['clbit_labels']:
self.cregs[item[0]] = item[1]
self.clbit_list = []
cregs = self.cregs
if self._style.reverse:
self.orig_cregs = self.cregs
cregs = reversed(self.cregs)
for cr in cregs:
for i in range(self.cregs[cr]):
self.clbit_list.append((cr, i))
self.ordered_regs = [(item[0], item[1]) for
item in self.header['qubit_labels']]
if self._style.reverse:
reg_size = []
reg_labels = []
new_ordered_regs = []
for regs in self.ordered_regs:
if regs[0] in reg_labels:
continue
reg_labels.append(regs[0])
reg_size.append(len(
[x for x in self.ordered_regs if x[0] == regs[0]]))
index = 0
for size in reg_size:
new_index = index + size
for i in range(new_index - 1, index - 1, -1):
new_ordered_regs.append(self.ordered_regs[i])
index = new_index
self.ordered_regs = new_ordered_regs
if 'clbit_labels' in self.header:
for clabel in self.header['clbit_labels']:
if self._style.reverse:
for cind in reversed(range(clabel[1])):
self.ordered_regs.append((clabel[0], cind))
else:
for cind in range(clabel[1]):
self.ordered_regs.append((clabel[0], cind))
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\'+'\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
QISKitError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.circuit['instructions']:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's', 'sdg',
't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy', 'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['texparams']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, arg)
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
assert len(op['clbits']) == 1 and len(op['qubits']) == 1
if 'conditional' in op:
raise QISKitError('conditional measures currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise QISKitError('conditional reset currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
assert False, "bad node data"
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns+1, ceil(sum_column_widths)+4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above example,
index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _convert_mask(self, mask):
orig_clbit_list = []
for cr in self.orig_cregs:
for i in range(self.orig_cregs[cr]):
orig_clbit_list.append((cr, i))
bit_list = [(mask >> bit) & 1 for bit in range(
len(orig_clbit_list) - 1, -1, -1)]
converted_mask_list = [None] * len(bit_list)
converted_mask = 0
for pos, bit in enumerate(reversed(bit_list)):
new_pos = self.clbit_list.index(orig_clbit_list[pos])
converted_mask_list[new_pos] = bit
if None in converted_mask_list:
raise VisualizationError('Reverse mask creation failed')
converted_mask_list = list(reversed(converted_mask_list))
for bit in converted_mask_list:
converted_mask = (converted_mask << 1) | bit
return converted_mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.circuit['instructions']):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier']:
nm = op['name']
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] =\
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
elif nm == "reset":
self._latex[pos_1][columns] = \
"\\push{\\rule{.6em}{0em}\\ket{0}\\rule{.2em}{0em}} \\qw"
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns-1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns-1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1], op["texparams"][2])
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-0.65em]{')
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-0.65em]{')
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
assert len(op['clbits']) == 1 and \
len(op['qubits']) == 1 and \
'params' not in op, "bad operation record"
if 'conditional' in op:
assert False, "If controlled measures currently not supported."
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[
item][columns - 1] = prev_entry.replace(
'\\barrier{', '\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise QISKitError('Error during Latex building: %s' %
str(e))
elif op['name'] == "barrier":
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qubits']) - 1
self._latex[start][columns] += " \\barrier{" + str(span) + "}"
else:
assert False, "bad node data"
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
if self._style.reverse:
return origin + 1
return origin - 1
def _get_register_specs(bit_labels):
"""
Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,'
'ry,rz,cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,'
'cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = MatplotlibDrawer(basis=basis, scale=scale, style=style)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
Register = namedtuple('Register', 'name index')
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=1.0, style=None):
self._ast = None
self._basis = basis
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = OrderedDict()
self._creg_dict = OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False, labelleft=False, labelright=False)
def load_qasm_file(self, filename):
circuit = load_qasm_file(filename, name='draw', basis_gates=self._basis)
self.parse_circuit(circuit)
def parse_circuit(self, circuit):
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
self._ast = transpile(dag_circuit, basis_gates=self._basis, format='json')
self._registers()
self._ops = self._ast['instructions']
def _registers(self):
# NOTE: formats of clbit and qubit are different!
header = self._ast['header']
self._creg = []
for e in header['clbit_labels']:
for i in range(e[1]):
self._creg.append(Register(name=e[0], index=i))
assert len(self._creg) == header['number_of_clbits']
self._qreg = []
for e in header['qubit_labels']:
self._qreg.append(Register(name=e[0], index=e[1]))
assert len(self._qreg) == header['number_of_qubits']
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.sc,
clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7, height=HIG * 0.7,
theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID], [qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy+0.35*WID], lc=self._style.cc, ls=self._style.cline)
arrowhead = patches.Polygon(((cx-0.20*WID, cy+0.35*WID),
(cx+0.20*WID, cy+0.35*WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'], ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if get_matplotlib_backend() == 'module://ipykernel.pylab.backend_inline':
# returns None when matplotlib is inline mode to prevent Jupyter
# with matplotlib inlining enabled to draw the diagram twice.
im = None
else:
# when matplotlib is not inline mode,
# self.figure.savefig is called twice because...
# ... this is needed to get the in-memory representation
with tempfile.TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, 'circuit.png')
self.figure.savefig(tmpfile, dpi=self._style.dpi,
bbox_inches='tight')
im = Image.open(tmpfile)
_trim(im)
os.remove(tmpfile)
# ... and this is needed to delegate in matplotlib the generation of
# the proper format.
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
return im
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index, 'group': reg.name}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(zip_longest(self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
self._cond['n_lines'] += 1
idx += 1
# reverse bit order
if self._style.reverse:
self._reverse_bits(self._qreg_dict)
self._reverse_bits(self._creg_dict)
def _reverse_bits(self, target_dict):
coord = {}
# grouping
for dict_ in target_dict.values():
if dict_['group'] not in coord:
coord[dict_['group']] = [dict_['y']]
else:
coord[dict_['group']].insert(0, dict_['y'])
# reverse bit order
for key in target_dict.keys():
target_dict[key]['y'] = coord[target_dict[key]['group']].pop(0)
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc, ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qubits' in op.keys():
q_idxs = op['qubits']
else:
q_idxs = []
# get creg index
if 'clbits' in op.keys():
c_idxs = op['clbits']
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied), max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] == 'barrier' and not self._style.barrier:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg corrdinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc, ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] == 'barrier':
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self._style.barrier:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise QISKitError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if isclose(fmod(abs_val, 1.0), 0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
elif 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return Fraction(i, j)
return None
<|code_end|>
|
backend.view_jobs()
Many times we want to be able to view the jobs we have ran and save on the cloud.
In the spec, we defined a backend.jobs() method which returns job objects. The problem is if this returns a job object then service that requires the job to be deleted after it has been called it removes it from the cloud. Since the use case is just to have a way of checking on all my jobs
```
for ran_job in backend.jobs(limit=5):
print(str(ran_job.job_id()) + " " + str(ran_job.status()))
```
```
5bba0ceb1a814c003cbfdda2 JobStatus.CANCELLED
5bba0c3d5d72db004c6e1867 JobStatus.DONE
5bba0c3dc6992500552f155c JobStatus.DONE
5bb9b0f19458ec0044ab4954 JobStatus.DONE
5bb9abd60b99f20045d26437 JobStatus.DONE
```
I suggest that we change this to
```
backend.view_jobs()
```
Are there any other things that should be displayed. I think something like a message to add that is human readable if an error occuers.
|
qiskit/backends/ibmq/ibmqbackend.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""IbmQ module
This module is used for connecting to the Quantum Experience.
"""
import warnings
import logging
from IBMQuantumExperience import ApiError
from qiskit import QISKitError
from qiskit._util import _camel_case_to_snake_case, AvailableToOperationalDict, _dict_merge
from qiskit.backends import BaseBackend
from qiskit.backends.ibmq.ibmqjob import IBMQJob, IBMQJobPreQobj
from qiskit.backends import JobStatus
logger = logging.getLogger(__name__)
class IBMQBackend(BaseBackend):
"""Backend class interfacing with the Quantum Experience remotely.
"""
def __init__(self, configuration, provider, credentials, api):
"""Initialize remote backend for IBM Quantum Experience.
Args:
configuration (dict): configuration of backend.
provider (IBMQProvider): provider.
credentials (Credentials): credentials.
api (IBMQuantumExperience.IBMQuantumExperience.IBMQuantumExperience):
api for communicating with the Quantum Experience.
"""
super().__init__(provider=provider, configuration=configuration)
self._api = api
if self._configuration:
configuration_edit = {}
for key, vals in self._configuration.items():
new_key = _camel_case_to_snake_case(key)
configuration_edit[new_key] = vals
self._configuration = configuration_edit
# FIXME: This is a hack to make sure that the
# local : False is added to the online device
self._configuration['local'] = False
self._credentials = credentials
self.hub = credentials.hub
self.group = credentials.group
self.project = credentials.project
def run(self, qobj):
"""Run qobj asynchronously.
Args:
qobj (dict): description of job
Returns:
IBMQJob: an instance derived from BaseJob
"""
job_class = _job_class_from_backend_support(self)
job = job_class(self, None, self._api, not self.configuration()['simulator'], qobj=qobj)
job.submit()
return job
def calibration(self):
"""Return the online backend calibrations.
The return is via QX API call.
Returns:
dict: The calibration of the backend.
Raises:
LookupError: If a calibration for the backend can't be found.
:deprecated: will be removed after 0.7
"""
warnings.warn("Backends will no longer return a calibration dictionary, "
"use backend.properties() instead.", DeprecationWarning)
try:
backend_name = self.name()
calibrations = self._api.backend_calibration(backend_name)
# FIXME a hack to remove calibration data that is none.
# Needs to be fixed in api
if backend_name == 'ibmq_qasm_simulator':
calibrations = {}
except Exception as ex:
raise LookupError(
"Couldn't get backend calibration: {0}".format(ex))
calibrations_edit = {}
for key, vals in calibrations.items():
new_key = _camel_case_to_snake_case(key)
calibrations_edit[new_key] = vals
return calibrations_edit
def parameters(self):
"""Return the online backend parameters.
Returns:
dict: The parameters of the backend.
Raises:
LookupError: If parameters for the backend can't be found.
:deprecated: will be removed after 0.7
"""
warnings.warn("Backends will no longer return a parameters dictionary, "
"use backend.properties() instead.", DeprecationWarning)
try:
backend_name = self.name()
parameters = self._api.backend_parameters(backend_name)
# FIXME a hack to remove parameters data that is none.
# Needs to be fixed in api
if backend_name == 'ibmq_qasm_simulator':
parameters = {}
except Exception as ex:
raise LookupError(
"Couldn't get backend parameters: {0}".format(ex))
parameters_edit = {}
for key, vals in parameters.items():
new_key = _camel_case_to_snake_case(key)
parameters_edit[new_key] = vals
return parameters_edit
def properties(self):
"""Return the online backend properties.
The return is via QX API call.
Returns:
dict: The properties of the backend.
Raises:
LookupError: If properties for the backend can't be found.
"""
# FIXME: make this an actual call to _api.backend_properties
# for now this api endpoint does not exist.
warnings.simplefilter("ignore")
calibration = self.calibration()
parameters = self.parameters()
_dict_merge(calibration, parameters)
properties = calibration
warnings.simplefilter("default")
return properties
def status(self):
"""Return the online backend status.
Returns:
dict: The status of the backend.
Raises:
LookupError: If status for the backend can't be found.
"""
try:
backend_name = self.configuration()['name']
status = self._api.backend_status(backend_name)
# FIXME a hack to rename the key. Needs to be fixed in api
status['name'] = status['backend']
del status['backend']
# FIXME a hack to remove the key busy. Needs to be fixed in api
if 'busy' in status:
del status['busy']
# FIXME a hack to add available to the hpc simulator. Needs to
# be fixed in api
if status['name'] == 'ibmqx_hpc_qasm_simulator':
status['available'] = True
# FIXME: this needs to be replaced at the API level - eventually
# it will.
if 'available' in status:
status['operational'] = status['available']
del status['available']
except Exception as ex:
raise LookupError(
"Couldn't get backend status: {0}".format(ex))
return AvailableToOperationalDict(status)
def jobs(self, limit=50, skip=0, status=None, db_filter=None):
"""Attempt to get the jobs submitted to the backend.
Args:
limit (int): number of jobs to retrieve
skip (int): starting index of retrieval
status (None or JobStatus or str): only get jobs with this status,
where status is e.g. `JobStatus.RUNNING` or `'RUNNING'`
db_filter (dict): `loopback-based filter
<https://loopback.io/doc/en/lb2/Querying-data.html>`_.
This is an interface to a database ``where`` filter. Some
examples of its usage are:
Filter last five jobs with errors::
job_list = backend.jobs(limit=5, status=JobStatus.ERROR)
Filter last five jobs with counts=1024, and counts for
states ``00`` and ``11`` each exceeding 400::
cnts_filter = {'shots': 1024,
'qasms.result.data.counts.00': {'gt': 400},
'qasms.result.data.counts.11': {'gt': 400}}
job_list = backend.jobs(limit=5, db_filter=cnts_filter)
Filter last five jobs from 30 days ago::
past_date = datetime.datetime.now() - datetime.timedelta(days=30)
date_filter = {'creationDate': {'lt': past_date.isoformat()}}
job_list = backend.jobs(limit=5, db_filter=date_filter)
Returns:
list(IBMQJob): list of IBMQJob instances
Raises:
IBMQBackendValueError: status keyword value unrecognized
"""
backend_name = self.configuration()['name']
api_filter = {'backend.name': backend_name}
if status:
if isinstance(status, str):
status = JobStatus[status]
if status == JobStatus.RUNNING:
this_filter = {'status': 'RUNNING',
'infoQueue': {'exists': False}}
elif status == JobStatus.QUEUED:
this_filter = {'status': 'RUNNING',
'infoQueue.status': 'PENDING_IN_QUEUE'}
elif status == JobStatus.CANCELLED:
this_filter = {'status': 'CANCELLED'}
elif status == JobStatus.DONE:
this_filter = {'status': 'COMPLETED'}
elif status == JobStatus.ERROR:
this_filter = {'status': {'regexp': '^ERROR'}}
else:
raise IBMQBackendValueError('unrecongized value for "status" keyword '
'in job filter')
api_filter.update(this_filter)
if db_filter:
# status takes precendence over db_filter for same keys
api_filter = {**db_filter, **api_filter}
job_info_list = self._api.get_jobs(limit=limit, skip=skip,
filter=api_filter)
job_list = []
for job_info in job_info_list:
job_class = _job_class_from_job_response(job_info)
is_device = not bool(self._configuration.get('simulator'))
job = job_class(self, job_info.get('id'), self._api, is_device,
creation_date=job_info.get('creationDate'))
job_list.append(job)
return job_list
def retrieve_job(self, job_id):
"""Attempt to get the specified job by job_id
Args:
job_id (str): the job id of the job to retrieve
Returns:
IBMQJob: class instance
Raises:
IBMQBackendError: if retrieval failed
"""
try:
job_info = self._api.get_job(job_id)
if 'error' in job_info:
raise IBMQBackendError('Failed to get job "{}": {}'
.format(job_id, job_info['error']))
except ApiError as ex:
raise IBMQBackendError('Failed to get job "{}":{}'
.format(job_id, str(ex)))
job_class = _job_class_from_job_response(job_info)
is_device = not bool(self._configuration.get('simulator'))
job = job_class(self, job_info.get('id'), self._api, is_device,
creation_date=job_info.get('creationDate'))
return job
def __repr__(self):
credentials_info = ''
if self.hub:
credentials_info = '{}, {}, {}'.format(self.hub, self.group,
self.project)
return "<{}('{}') from IBMQ({})>".format(
self.__class__.__name__, self.name(), credentials_info)
class IBMQBackendError(QISKitError):
"""IBM Q Backend Errors"""
pass
class IBMQBackendValueError(IBMQBackendError, ValueError):
""" Value errors thrown within IBMQBackend """
pass
def _job_class_from_job_response(job_response):
is_qobj = job_response.get('kind', None) == 'q-object'
return IBMQJob if is_qobj else IBMQJobPreQobj
def _job_class_from_backend_support(backend):
support_qobj = backend.configuration().get('allow_q_object')
return IBMQJob if support_qobj else IBMQJobPreQobj
<|code_end|>
qiskit/backends/ibmq/ibmqjob.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""IBMQJob module
This module is used for creating asynchronous job objects for the
IBM Q Experience.
"""
from concurrent import futures
import warnings
import time
import logging
import pprint
import contextlib
import json
import datetime
import numpy
from IBMQuantumExperience import ApiError
from qiskit.qobj import qobj_to_dict
from qiskit.transpiler import transpile
from qiskit.backends import BaseJob, JobError, JobTimeoutError
from qiskit.backends.jobstatus import JobStatus, JOB_FINAL_STATES
from qiskit.result import Result
from qiskit.result._utils import result_from_old_style_dict
from qiskit.qobj import Result as QobjResult
from qiskit.qobj import ExperimentResult as QobjExperimentResult
from qiskit.qobj import validate_qobj_against_schema
logger = logging.getLogger(__name__)
API_FINAL_STATES = (
'COMPLETED',
'CANCELLED',
'ERROR_CREATING_JOB',
'ERROR_VALIDATING_JOB',
'ERROR_RUNNING_JOB'
)
class IBMQJob(BaseJob):
"""Represent the jobs that will be executed on IBM-Q simulators and real
devices. Jobs are intended to be created calling ``run()`` on a particular
backend.
Creating a ``Job`` instance does not imply running it. You need to do it in
separate steps::
job = IBMQJob(...)
job.submit() # It won't block.
An error while submitting a job will cause the next call to ``status()`` to
raise. If submitting the job successes, you can inspect the job's status by
using ``status()``. Status can be one of ``JobStatus`` members::
from qiskit.backends.jobstatus import JobStatus
job = IBMQJob(...)
job.submit()
try:
job_status = job.status() # It won't block. It will query the backend API.
if job_status is JobStatus.RUNNING:
print('The job is still running')
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
A call to ``status()`` can raise if something happens at the API level that
prevents Qiskit from determining the status of the job. An example of this
is a temporary connection lose or a network failure.
The ``submit()`` and ``status()`` methods are examples of non-blocking API.
``Job`` instances also have `id()` and ``result()`` methods which will
block::
job = IBMQJob(...)
job.submit()
try:
job_id = job.id() # It will block until completing submission.
print('The job {} was successfully submitted'.format(job_id))
job_result = job.result() # It will block until finishing.
print('The job finished with result {}'.format(job_result))
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
Both methods can raise if something ath the API level happens that prevent
Qiskit from determining the status of the job.
.. NOTE::
When querying the API for getting the status, two kinds of errors are
possible. The most severe is the one preventing Qiskit from getting a
response from the backend. This can be caused by a network failure or a
temporary system break. In these cases, calling ``status()`` will raise.
If Qiskit successfully retrieves the status of a job, it could be it
finished with errors. In that case, ``status()`` will simply return
``JobStatus.ERROR`` and you can call ``error_message()`` to get more
info.
Attributes:
_executor (futures.Executor): executor to handle asynchronous jobs
"""
_executor = futures.ThreadPoolExecutor()
def __init__(self, backend, job_id, api, is_device, qobj=None,
creation_date=None, **kwargs):
"""IBMQJob init function.
We can instantiate jobs from two sources: A QObj, and an already submitted job returned by
the API servers.
Args:
api (IBMQuantumExperience): IBM Q API
is_device (bool): whether backend is a real device # TODO: remove this after Qobj
qobj (Qobj): The Quantum Object. See notes below
job_id (String): The job ID of an already submitted job. Pass `None`
if you are creating a new one.
creation_date(String): When the job was run.
backend (str): The backend instance used to run this job.
kwargs (dict): You can pass `backend_name` to this function although
it has been deprecated.
Notes:
It is mandatory to pass either ``qobj`` or ``job_id``. Passing a ``qobj``
will ignore ``job_id`` and will create an instance representing
an already-created job retrieved from the API server.
"""
if 'backend_name' in kwargs:
warnings.warn('Passing the parameter `backend_name` is deprecated, '
'pass the `backend` parameter with the instance of '
'the backend running the job.', DeprecationWarning)
super().__init__(backend, job_id)
self._job_data = None
if qobj is not None:
validate_qobj_against_schema(qobj)
self._qobj_payload = qobj_to_dict(qobj, version='1.0.0')
# TODO: No need for this conversion, just use the new equivalent members above
old_qobj = qobj_to_dict(qobj, version='0.0.1')
self._job_data = {
'circuits': old_qobj['circuits'],
'hpc': old_qobj['config'].get('hpc'),
'seed': old_qobj['circuits'][0]['config']['seed'],
'shots': old_qobj['config']['shots'],
'max_credits': old_qobj['config']['max_credits']
}
self._future_captured_exception = None
self._api = api
self._backend = backend
self._status = JobStatus.INITIALIZING
# In case of not providing a qobj, it assumes job_id has been provided
# and query the API for updating the status.
if qobj is None:
self.status()
self._queue_position = None
self._cancelled = False
self._is_device = is_device
def current_utc_time():
"""Gets the current time in UTC format"""
datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
self._creation_date = creation_date or current_utc_time()
self._future = None
self._api_error_msg = None
# pylint: disable=arguments-differ
def result(self, timeout=None, wait=5):
"""Return the result from the job.
Args:
timeout (int): number of seconds to wait for job
wait (int): time between queries to IBM Q server
Returns:
qiskit.Result: Result object
Raises:
JobError: exception raised during job initialization
"""
job_response = self._wait_for_result(timeout=timeout, wait=wait)
return self._result_from_job_response(job_response)
def _wait_for_result(self, timeout=None, wait=5):
self._wait_for_submission()
try:
job_response = self._wait_for_job(timeout=timeout, wait=wait)
except ApiError as api_err:
raise JobError(str(api_err))
status = self.status()
if status is not JobStatus.DONE:
raise JobError('Invalid job state. The job should be DONE but '
'it is {}'.format(str(status)))
return job_response
def _result_from_job_response(self, job_response):
experiment_results = []
result_json = job_response['qObjectResult']
for experiment_result_json in result_json['results']:
qobj_experiment_result = QobjExperimentResult(**experiment_result_json)
experiment_results.append(qobj_experiment_result)
result_kwargs = {**result_json, 'results': experiment_results}
return Result(QobjResult(**result_kwargs))
def cancel(self):
"""Attempt to cancel a job.
Returns:
bool: True if job can be cancelled, else False. Currently this is
only possible on commercial systems.
Raises:
JobError: if there was some unexpected failure in the server
"""
hub = self._api.config.get('hub', None)
group = self._api.config.get('group', None)
project = self._api.config.get('project', None)
try:
response = self._api.cancel_job(self._job_id, hub, group, project)
self._cancelled = 'error' not in response
return self._cancelled
except ApiError as error:
self._cancelled = False
raise JobError('Error cancelling job: %s' % error.usr_msg)
def status(self):
"""Query the API to update the status.
Returns:
JobStatus: The status of the job, once updated.
Raises:
JobError: if there was an exception in the future being executed
or the server sent an unknown answer.
"""
# Implies self._job_id is None
if self._future_captured_exception is not None:
raise JobError(str(self._future_captured_exception))
if self._job_id is None or self._status in JOB_FINAL_STATES:
return self._status
try:
# TODO: See result values
api_job = self._api.get_status_job(self._job_id)
if 'status' not in api_job:
raise JobError('get_job didn\'t return status: %s' %
pprint.pformat(api_job))
# pylint: disable=broad-except
except Exception as err:
raise JobError(str(err))
if api_job['status'] == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_job['status'] == 'RUNNING':
self._status = JobStatus.RUNNING
queued, self._queue_position = _is_job_queued(api_job)
if queued:
self._status = JobStatus.QUEUED
elif api_job['status'] == 'COMPLETED':
self._status = JobStatus.DONE
elif api_job['status'] == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
elif 'ERROR' in api_job['status']:
# Error status are of the form "ERROR_*_JOB"
self._status = JobStatus.ERROR
# TODO: This seems to be an inconsistency in the API package.
self._api_error_msg = api_job.get('error') or api_job.get('Error')
else:
raise JobError('Unrecognized answer from server: \n{}'
.format(pprint.pformat(api_job)))
return self._status
def error_message(self):
"""Return the error message returned from the API server response."""
return self._api_error_msg
def queue_position(self):
"""Return the position in the server queue.
Returns:
Number: Position in the queue.
"""
return self._queue_position
def creation_date(self):
"""
Return creation date.
"""
return self._creation_date
# pylint: disable=invalid-name
def id(self):
"""Return backend determined id.
If the Id is not set because the job is already initializing, this call
will block until we have an Id.
.. deprecated:: 0.6+
After 0.6, this function is deprecated. Please use
`job.job_id()` instead.
"""
warnings.warn('The method `job.id()` is deprecated, use '
'``job.job_id()`` instead.', DeprecationWarning)
return self.job_id()
def job_id(self):
"""Return backend determined id.
If the Id is not set because the job is already initializing, this call
will block until we have an Id.
"""
self._wait_for_submission()
return self._job_id
def backend_name(self):
"""
Return backend name used for this job.
.. deprecated:: 0.6+
After 0.6, this function is deprecated. Please use
`job.backend().name()` instead.
"""
warnings.warn('The use of `job.backend_name()` is deprecated, '
'use `job.backend().name()` instead', DeprecationWarning)
return self.backend().name()
def submit(self):
"""Submit job to IBM-Q.
Raises:
JobError: If we have already submitted the job.
"""
# TODO: Validation against the schema should be done here and not
# during initiliazation. Once done, we should document that the method
# can raise QobjValidationError.
if self._future is not None or self._job_id is not None:
raise JobError("We have already submitted the job!")
self._future = self._executor.submit(self._submit_callback)
def _submit_callback(self):
"""Submit qobj job to IBM-Q.
Returns:
dict: A dictionary with the response of the submitted job
"""
backend_name = self.backend().name()
try:
submit_info = self._api.run_job(self._qobj_payload, backend=backend_name)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submisssion success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _wait_for_job(self, timeout=60, wait=5):
"""Wait until all online ran circuits of a qobj are 'COMPLETED'.
Args:
timeout (float or None): seconds to wait for job. If None, wait
indefinitely.
wait (float): seconds between queries
Returns:
dict: A dict with the contents of the API request.
Raises:
JobTimeoutError: if the job does not return results before a specified timeout.
JobError: if something wrong happened in some of the server API calls
"""
start_time = time.time()
while self.status() not in JOB_FINAL_STATES:
elapsed_time = time.time() - start_time
if timeout is not None and elapsed_time >= timeout:
raise JobTimeoutError(
'Timeout while waiting for the job: {}'.format(self._job_id)
)
logger.info('status = %s (%d seconds)', self._status, elapsed_time)
time.sleep(wait)
if self._cancelled:
raise JobError(
'Job result impossible to retrieve. The job was cancelled.')
return self._api.get_job(self._job_id)
def _wait_for_submission(self, timeout=60):
"""Waits for the request to return a job ID"""
if self._job_id is None:
if self._future is None:
raise JobError("You have to submit before asking for status or results!")
try:
submit_info = self._future.result(timeout=timeout)
if self._future_captured_exception is not None:
# pylint can't see if catch of None type
# pylint: disable=raising-bad-type
raise self._future_captured_exception
except TimeoutError as ex:
raise JobTimeoutError(
"Timeout waiting for the job being submitted: {}".format(ex)
)
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
raise JobError(str(submit_info['error']))
class IBMQJobPreQobj(IBMQJob):
"""
Subclass of IBMQJob for handling pre-qobj jobs.
"""
def _submit_callback(self):
"""Submit old style qasms job to IBM-Q. Can remove when all devices
understand Qobj.
Returns:
dict: A dictionary with the response of the submitted job
"""
api_jobs = []
circuits = self._job_data['circuits']
for circuit in circuits:
job = _create_api_job_from_circuit(circuit)
api_jobs.append(job)
hpc_camel_cased = _format_hpc_parameters(self._job_data['hpc'])
seed = self._job_data['seed']
shots = self._job_data['shots']
max_credits = self._job_data['max_credits']
try:
submit_info = self._api.run_job(api_jobs, backend=self.backend().name(),
shots=shots, max_credits=max_credits,
seed=seed, hpc=hpc_camel_cased)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submisssion success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _result_from_job_response(self, job_response):
if self._is_device:
_reorder_bits(job_response)
experiment_results = []
for circuit_result in job_response['qasms']:
this_result = {'data': circuit_result['data'],
'name': circuit_result.get('name'),
'compiled_circuit_qasm': circuit_result.get('qasm'),
'status': circuit_result['status'],
'success': circuit_result['status'] == 'DONE',
'shots': job_response['shots']}
if 'metadata' in circuit_result:
this_result['metadata'] = circuit_result['metadata']
experiment_results.append(this_result)
return result_from_old_style_dict({
'id': self._job_id,
'status': job_response['status'],
'used_credits': job_response.get('usedCredits'),
'result': experiment_results,
'backend_name': self.backend().name(),
'success': job_response['status'] == 'DONE'
}, [circuit_result['name'] for circuit_result in job_response['qasms']])
def _reorder_bits(job_data):
"""Temporary fix for ibmq backends.
For every ran circuit, get reordering information from qobj
and apply reordering on result.
Args:
job_data (dict): dict with the bare contents of the API.get_job request.
Raises:
JobError: raised if the creg sizes don't add up in result header.
"""
for circuit_result in job_data['qasms']:
if 'metadata' in circuit_result:
circ = circuit_result['metadata'].get('compiled_circuit')
else:
logger.warning('result object missing metadata for reordering'
' bits: bits may be out of order')
return
# device_qubit -> device_clbit (how it should have been)
measure_dict = {op['qubits'][0]: op['clbits'][0]
for op in circ['operations']
if op['name'] == 'measure'}
counts_dict_new = {}
for item in circuit_result['data']['counts'].items():
# fix clbit ordering to what it should have been
bits = list(item[0])
bits.reverse() # lsb in 0th position
count = item[1]
reordered_bits = list('x' * len(bits))
for device_clbit, bit in enumerate(bits):
if device_clbit in measure_dict:
correct_device_clbit = measure_dict[device_clbit]
reordered_bits[correct_device_clbit] = bit
reordered_bits.reverse()
# only keep the clbits specified by circuit, not everything on device
num_clbits = circ['header']['number_of_clbits']
compact_key = reordered_bits[-num_clbits:]
compact_key = "".join([b if b != 'x' else '0'
for b in compact_key])
# insert spaces to signify different classical registers
cregs = circ['header']['clbit_labels']
if sum([creg[1] for creg in cregs]) != num_clbits:
raise JobError("creg sizes don't add up in result header.")
creg_begin_pos = []
creg_end_pos = []
acc = 0
for creg in reversed(cregs):
creg_size = creg[1]
creg_begin_pos.append(acc)
creg_end_pos.append(acc + creg_size)
acc += creg_size
compact_key = " ".join([compact_key[creg_begin_pos[i]:creg_end_pos[i]]
for i in range(len(cregs))])
# marginalize over unwanted measured qubits
if compact_key not in counts_dict_new:
counts_dict_new[compact_key] = count
else:
counts_dict_new[compact_key] += count
circuit_result['data']['counts'] = counts_dict_new
def _numpy_type_converter(obj):
ret = obj
if isinstance(obj, numpy.integer):
ret = int(obj)
elif isinstance(obj, numpy.floating): # pylint: disable=no-member
ret = float(obj)
elif isinstance(obj, numpy.ndarray):
ret = obj.tolist()
return ret
def _create_api_job_from_circuit(circuit):
"""Helper function that creates a special job required by the API, from a circuit."""
api_job = {}
if not circuit.get('compiled_circuit_qasm'):
compiled_circuit = transpile(circuit['circuit'])
circuit['compiled_circuit_qasm'] = compiled_circuit.qasm(qeflag=True)
if isinstance(circuit['compiled_circuit_qasm'], bytes):
api_job['qasm'] = circuit['compiled_circuit_qasm'].decode()
else:
api_job['qasm'] = circuit['compiled_circuit_qasm']
if circuit.get('name'):
api_job['name'] = circuit['name']
# convert numpy types for json serialization
compiled_circuit = json.loads(json.dumps(circuit['compiled_circuit'],
default=_numpy_type_converter))
api_job['metadata'] = {'compiled_circuit': compiled_circuit}
return api_job
def _is_job_queued(api_job_response):
"""Checks whether a job has been queued or not."""
is_queued, position = False, 0
if 'infoQueue' in api_job_response:
if 'status' in api_job_response['infoQueue']:
queue_status = api_job_response['infoQueue']['status']
is_queued = queue_status == 'PENDING_IN_QUEUE'
if 'position' in api_job_response['infoQueue']:
position = api_job_response['infoQueue']['position']
return is_queued, position
def _format_hpc_parameters(hpc):
"""Helper function to get HPC parameters with the correct format"""
if hpc is None:
return None
hpc_camel_cased = None
with contextlib.suppress(KeyError, TypeError):
# Use CamelCase when passing the hpc parameters to the API.
hpc_camel_cased = {
'multiShotOptimization': hpc['multi_shot_optimization'],
'ompNumThreads': hpc['omp_num_threads']
}
return hpc_camel_cased
<|code_end|>
setup.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
import os
import platform
from distutils.command.build import build
from multiprocessing import cpu_count
from subprocess import call
from setuptools import setup, find_packages
from setuptools.dist import Distribution
requirements = [
"jsonschema>=2.6,<2.7",
"IBMQuantumExperience>=2.0.3",
"matplotlib>=2.1",
"networkx>=2.0",
"numpy>=1.13",
"ply>=3.10",
"scipy>=0.19,!=0.19.1",
"sympy>=1.0",
"pillow>=4.2.1",
"psutil>=5",
"nxpd>=0.2"
]
# C++ components compilation
class QasmSimulatorCppBuild(build):
def run(self):
super().run()
# Store the current working directory, as invoking cmake involves
# an out of source build and might interfere with the rest of the steps.
current_directory = os.getcwd()
try:
supported_platforms = ['Linux', 'Darwin', 'Windows']
current_platform = platform.system()
if current_platform not in supported_platforms:
# TODO: stdout is silenced by pip if the full setup.py invocation is
# successful, unless using '-v' - hence the warnings are not printed.
print('WARNING: Qiskit cpp simulator is meant to be built with these '
'platforms: {}. We will support other platforms soon!'
.format(supported_platforms))
return
cmd_cmake = ['cmake', '-vvv']
if 'USER_LIB_PATH' in os.environ:
cmd_cmake.append('-DUSER_LIB_PATH={}'.format(os.environ['USER_LIB_PATH']))
if current_platform == 'Windows':
# We only support MinGW so far
cmd_cmake.append("-GMinGW Makefiles")
cmd_cmake.append('..')
cmd_make = ['make', 'pypi_package_copy_qasm_simulator_cpp']
try:
cmd_make.append('-j%d' % cpu_count())
except NotImplementedError:
print('WARNING: Unable to determine number of CPUs. Using single threaded make.')
def compile_simulator():
self.mkpath('out')
os.chdir('out')
call(cmd_cmake)
call(cmd_make)
self.execute(compile_simulator, [], 'Compiling C++ QASM Simulator')
except Exception as e:
print(str(e))
print("WARNING: Seems like the cpp simulator can't be built, Qiskit will "
"install anyway, but won't have this simulator support.")
# Restore working directory.
os.chdir(current_directory)
# This is for creating wheel specific platforms
class BinaryDistribution(Distribution):
def has_ext_modules(self):
return True
setup(
name="qiskit",
version="0.7.0",
description="Software for developing quantum computing programs",
long_description="""Qiskit is a software development kit for writing
quantum computing experiments, programs, and applications. Works with
Python 3.5 and 3.6""",
url="https://github.com/Qiskit/qiskit-terra",
author="Qiskit Development Team",
author_email="qiskit@us.ibm.com",
license="Apache 2.0",
classifiers=[
"Environment :: Console",
"License :: OSI Approved :: Apache Software License",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"Operating System :: Microsoft :: Windows",
"Operating System :: MacOS",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Topic :: Scientific/Engineering",
],
keywords="qiskit sdk quantum",
packages=find_packages(exclude=['test*']),
install_requires=requirements,
include_package_data=True,
python_requires=">=3.5",
cmdclass={
'build': QasmSimulatorCppBuild,
},
distclass=BinaryDistribution
)
<|code_end|>
|
qiskit/backends/ibmq/ibmqbackend.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""IbmQ module
This module is used for connecting to the Quantum Experience.
"""
import warnings
import logging
from IBMQuantumExperience import ApiError
from qiskit import QISKitError
from qiskit._util import _camel_case_to_snake_case, AvailableToOperationalDict, _dict_merge
from qiskit.backends import BaseBackend
from qiskit.backends.ibmq.ibmqjob import IBMQJob, IBMQJobPreQobj
from qiskit.backends import JobStatus
logger = logging.getLogger(__name__)
class IBMQBackend(BaseBackend):
"""Backend class interfacing with the Quantum Experience remotely.
"""
def __init__(self, configuration, provider, credentials, api):
"""Initialize remote backend for IBM Quantum Experience.
Args:
configuration (dict): configuration of backend.
provider (IBMQProvider): provider.
credentials (Credentials): credentials.
api (IBMQuantumExperience.IBMQuantumExperience.IBMQuantumExperience):
api for communicating with the Quantum Experience.
"""
super().__init__(provider=provider, configuration=configuration)
self._api = api
if self._configuration:
configuration_edit = {}
for key, vals in self._configuration.items():
new_key = _camel_case_to_snake_case(key)
configuration_edit[new_key] = vals
self._configuration = configuration_edit
# FIXME: This is a hack to make sure that the
# local : False is added to the online device
self._configuration['local'] = False
self._credentials = credentials
self.hub = credentials.hub
self.group = credentials.group
self.project = credentials.project
def run(self, qobj):
"""Run qobj asynchronously.
Args:
qobj (dict): description of job
Returns:
IBMQJob: an instance derived from BaseJob
"""
job_class = _job_class_from_backend_support(self)
job = job_class(self, None, self._api, not self.configuration()['simulator'], qobj=qobj)
job.submit()
return job
def calibration(self):
"""Return the online backend calibrations.
The return is via QX API call.
Returns:
dict: The calibration of the backend.
Raises:
LookupError: If a calibration for the backend can't be found.
:deprecated: will be removed after 0.7
"""
warnings.warn("Backends will no longer return a calibration dictionary, "
"use backend.properties() instead.", DeprecationWarning)
try:
backend_name = self.name()
calibrations = self._api.backend_calibration(backend_name)
# FIXME a hack to remove calibration data that is none.
# Needs to be fixed in api
if backend_name == 'ibmq_qasm_simulator':
calibrations = {}
except Exception as ex:
raise LookupError(
"Couldn't get backend calibration: {0}".format(ex))
calibrations_edit = {}
for key, vals in calibrations.items():
new_key = _camel_case_to_snake_case(key)
calibrations_edit[new_key] = vals
return calibrations_edit
def parameters(self):
"""Return the online backend parameters.
Returns:
dict: The parameters of the backend.
Raises:
LookupError: If parameters for the backend can't be found.
:deprecated: will be removed after 0.7
"""
warnings.warn("Backends will no longer return a parameters dictionary, "
"use backend.properties() instead.", DeprecationWarning)
try:
backend_name = self.name()
parameters = self._api.backend_parameters(backend_name)
# FIXME a hack to remove parameters data that is none.
# Needs to be fixed in api
if backend_name == 'ibmq_qasm_simulator':
parameters = {}
except Exception as ex:
raise LookupError(
"Couldn't get backend parameters: {0}".format(ex))
parameters_edit = {}
for key, vals in parameters.items():
new_key = _camel_case_to_snake_case(key)
parameters_edit[new_key] = vals
return parameters_edit
def properties(self):
"""Return the online backend properties.
The return is via QX API call.
Returns:
dict: The properties of the backend.
Raises:
LookupError: If properties for the backend can't be found.
"""
# FIXME: make this an actual call to _api.backend_properties
# for now this api endpoint does not exist.
warnings.simplefilter("ignore")
calibration = self.calibration()
parameters = self.parameters()
_dict_merge(calibration, parameters)
properties = calibration
warnings.simplefilter("default")
return properties
def status(self):
"""Return the online backend status.
Returns:
dict: The status of the backend.
Raises:
LookupError: If status for the backend can't be found.
"""
try:
backend_name = self.configuration()['name']
status = self._api.backend_status(backend_name)
# FIXME a hack to rename the key. Needs to be fixed in api
status['name'] = status['backend']
del status['backend']
# FIXME a hack to remove the key busy. Needs to be fixed in api
if 'busy' in status:
del status['busy']
# FIXME a hack to add available to the hpc simulator. Needs to
# be fixed in api
if status['name'] == 'ibmqx_hpc_qasm_simulator':
status['available'] = True
# FIXME: this needs to be replaced at the API level - eventually
# it will.
if 'available' in status:
status['operational'] = status['available']
del status['available']
except Exception as ex:
raise LookupError(
"Couldn't get backend status: {0}".format(ex))
return AvailableToOperationalDict(status)
def jobs(self, limit=50, skip=0, status=None, db_filter=None):
"""Attempt to get the jobs submitted to the backend.
Args:
limit (int): number of jobs to retrieve
skip (int): starting index of retrieval
status (None or JobStatus or str): only get jobs with this status,
where status is e.g. `JobStatus.RUNNING` or `'RUNNING'`
db_filter (dict): `loopback-based filter
<https://loopback.io/doc/en/lb2/Querying-data.html>`_.
This is an interface to a database ``where`` filter. Some
examples of its usage are:
Filter last five jobs with errors::
job_list = backend.jobs(limit=5, status=JobStatus.ERROR)
Filter last five jobs with counts=1024, and counts for
states ``00`` and ``11`` each exceeding 400::
cnts_filter = {'shots': 1024,
'qasms.result.data.counts.00': {'gt': 400},
'qasms.result.data.counts.11': {'gt': 400}}
job_list = backend.jobs(limit=5, db_filter=cnts_filter)
Filter last five jobs from 30 days ago::
past_date = datetime.datetime.now() - datetime.timedelta(days=30)
date_filter = {'creationDate': {'lt': past_date.isoformat()}}
job_list = backend.jobs(limit=5, db_filter=date_filter)
Returns:
list(IBMQJob): list of IBMQJob instances
Raises:
IBMQBackendValueError: status keyword value unrecognized
"""
backend_name = self.configuration()['name']
api_filter = {'backend.name': backend_name}
if status:
if isinstance(status, str):
status = JobStatus[status]
if status == JobStatus.RUNNING:
this_filter = {'status': 'RUNNING',
'infoQueue': {'exists': False}}
elif status == JobStatus.QUEUED:
this_filter = {'status': 'RUNNING',
'infoQueue.status': 'PENDING_IN_QUEUE'}
elif status == JobStatus.CANCELLED:
this_filter = {'status': 'CANCELLED'}
elif status == JobStatus.DONE:
this_filter = {'status': 'COMPLETED'}
elif status == JobStatus.ERROR:
this_filter = {'status': {'regexp': '^ERROR'}}
else:
raise IBMQBackendValueError('unrecognized value for "status" keyword '
'in job filter')
api_filter.update(this_filter)
if db_filter:
# status takes precedence over db_filter for same keys
api_filter = {**db_filter, **api_filter}
job_info_list = self._api.get_status_jobs(limit=limit, skip=skip,
filter=api_filter)
job_list = []
for job_info in job_info_list:
job_class = _job_class_from_job_response(job_info)
is_device = not bool(self._configuration.get('simulator'))
job = job_class(self, job_info.get('id'), self._api, is_device,
creation_date=job_info.get('creationDate'),
api_status=job_info.get('status'))
job_list.append(job)
return job_list
def retrieve_job(self, job_id):
"""Attempt to get the specified job by job_id
Args:
job_id (str): the job id of the job to retrieve
Returns:
IBMQJob: class instance
Raises:
IBMQBackendError: if retrieval failed
"""
try:
job_info = self._api.get_status_job(job_id)
if 'error' in job_info:
raise IBMQBackendError('Failed to get job "{}": {}'
.format(job_id, job_info['error']))
except ApiError as ex:
raise IBMQBackendError('Failed to get job "{}":{}'
.format(job_id, str(ex)))
job_class = _job_class_from_job_response(job_info)
is_device = not bool(self._configuration.get('simulator'))
job = job_class(self, job_info.get('id'), self._api, is_device,
creation_date=job_info.get('creationDate'),
api_status=job_info.get('status'))
return job
def __repr__(self):
credentials_info = ''
if self.hub:
credentials_info = '{}, {}, {}'.format(self.hub, self.group,
self.project)
return "<{}('{}') from IBMQ({})>".format(
self.__class__.__name__, self.name(), credentials_info)
class IBMQBackendError(QISKitError):
"""IBM Q Backend Errors"""
pass
class IBMQBackendValueError(IBMQBackendError, ValueError):
""" Value errors thrown within IBMQBackend """
pass
def _job_class_from_job_response(job_response):
is_qobj = job_response.get('kind', None) == 'q-object'
return IBMQJob if is_qobj else IBMQJobPreQobj
def _job_class_from_backend_support(backend):
support_qobj = backend.configuration().get('allow_q_object')
return IBMQJob if support_qobj else IBMQJobPreQobj
<|code_end|>
qiskit/backends/ibmq/ibmqjob.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""IBMQJob module
This module is used for creating asynchronous job objects for the
IBM Q Experience.
"""
from concurrent import futures
import warnings
import time
import logging
import pprint
import contextlib
import json
import datetime
import numpy
from IBMQuantumExperience import ApiError
from qiskit.qobj import qobj_to_dict
from qiskit.transpiler import transpile
from qiskit.backends import BaseJob, JobError, JobTimeoutError
from qiskit.backends.jobstatus import JobStatus, JOB_FINAL_STATES
from qiskit.result import Result
from qiskit.result._utils import result_from_old_style_dict
from qiskit.qobj import Result as QobjResult
from qiskit.qobj import ExperimentResult as QobjExperimentResult
from qiskit.qobj import validate_qobj_against_schema
logger = logging.getLogger(__name__)
API_FINAL_STATES = (
'COMPLETED',
'CANCELLED',
'ERROR_CREATING_JOB',
'ERROR_VALIDATING_JOB',
'ERROR_RUNNING_JOB'
)
class IBMQJob(BaseJob):
"""Represent the jobs that will be executed on IBM-Q simulators and real
devices. Jobs are intended to be created calling ``run()`` on a particular
backend.
Creating a ``Job`` instance does not imply running it. You need to do it in
separate steps::
job = IBMQJob(...)
job.submit() # It won't block.
An error while submitting a job will cause the next call to ``status()`` to
raise. If submitting the job successes, you can inspect the job's status by
using ``status()``. Status can be one of ``JobStatus`` members::
from qiskit.backends.jobstatus import JobStatus
job = IBMQJob(...)
job.submit()
try:
job_status = job.status() # It won't block. It will query the backend API.
if job_status is JobStatus.RUNNING:
print('The job is still running')
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
A call to ``status()`` can raise if something happens at the API level that
prevents Qiskit from determining the status of the job. An example of this
is a temporary connection lose or a network failure.
The ``submit()`` and ``status()`` methods are examples of non-blocking API.
``Job`` instances also have `id()` and ``result()`` methods which will
block::
job = IBMQJob(...)
job.submit()
try:
job_id = job.id() # It will block until completing submission.
print('The job {} was successfully submitted'.format(job_id))
job_result = job.result() # It will block until finishing.
print('The job finished with result {}'.format(job_result))
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
Both methods can raise if something ath the API level happens that prevent
Qiskit from determining the status of the job.
.. NOTE::
When querying the API for getting the status, two kinds of errors are
possible. The most severe is the one preventing Qiskit from getting a
response from the backend. This can be caused by a network failure or a
temporary system break. In these cases, calling ``status()`` will raise.
If Qiskit successfully retrieves the status of a job, it could be it
finished with errors. In that case, ``status()`` will simply return
``JobStatus.ERROR`` and you can call ``error_message()`` to get more
info.
Attributes:
_executor (futures.Executor): executor to handle asynchronous jobs
"""
_executor = futures.ThreadPoolExecutor()
def __init__(self, backend, job_id, api, is_device, qobj=None,
creation_date=None, api_status=None, **kwargs):
"""IBMQJob init function.
We can instantiate jobs from two sources: A QObj, and an already submitted job returned by
the API servers.
Args:
backend (str): The backend instance used to run this job.
job_id (str): The job ID of an already submitted job. Pass `None`
if you are creating a new one.
api (IBMQuantumExperience): IBM Q API
is_device (bool): whether backend is a real device # TODO: remove this after Qobj
qobj (Qobj): The Quantum Object. See notes below
creation_date (str): When the job was run.
api_status (str): `status` field directly from the API response.
kwargs (dict): You can pass `backend_name` to this function although
it has been deprecated.
Notes:
It is mandatory to pass either ``qobj`` or ``job_id``. Passing a ``qobj``
will ignore ``job_id`` and will create an instance representing
an already-created job retrieved from the API server.
"""
if 'backend_name' in kwargs:
warnings.warn('Passing the parameter `backend_name` is deprecated, '
'pass the `backend` parameter with the instance of '
'the backend running the job.', DeprecationWarning)
super().__init__(backend, job_id)
self._job_data = None
if qobj is not None:
validate_qobj_against_schema(qobj)
self._qobj_payload = qobj_to_dict(qobj, version='1.0.0')
# TODO: No need for this conversion, just use the new equivalent members above
old_qobj = qobj_to_dict(qobj, version='0.0.1')
self._job_data = {
'circuits': old_qobj['circuits'],
'hpc': old_qobj['config'].get('hpc'),
'seed': old_qobj['circuits'][0]['config']['seed'],
'shots': old_qobj['config']['shots'],
'max_credits': old_qobj['config']['max_credits']
}
self._future_captured_exception = None
self._api = api
self._backend = backend
self._cancelled = False
self._status = JobStatus.INITIALIZING
# In case of not providing a `qobj`, it is assumed the job already
# exists in the API (with `job_id`).
if qobj is None:
# Some API calls (`get_status_jobs`, `get_status_job`) provide
# enough information to recreate the `Job`. If that is the case, try
# to make use of that information during instantiation, as
# `self.status()` involves an extra call to the API.
if api_status == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_status == 'COMPLETED':
self._status = JobStatus.DONE
elif api_status == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
else:
self.status()
self._queue_position = None
self._is_device = is_device
def current_utc_time():
"""Gets the current time in UTC format"""
datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
self._creation_date = creation_date or current_utc_time()
self._future = None
self._api_error_msg = None
# pylint: disable=arguments-differ
def result(self, timeout=None, wait=5):
"""Return the result from the job.
Args:
timeout (int): number of seconds to wait for job
wait (int): time between queries to IBM Q server
Returns:
qiskit.Result: Result object
Raises:
JobError: exception raised during job initialization
"""
job_response = self._wait_for_result(timeout=timeout, wait=wait)
return self._result_from_job_response(job_response)
def _wait_for_result(self, timeout=None, wait=5):
self._wait_for_submission()
try:
job_response = self._wait_for_job(timeout=timeout, wait=wait)
except ApiError as api_err:
raise JobError(str(api_err))
status = self.status()
if status is not JobStatus.DONE:
raise JobError('Invalid job state. The job should be DONE but '
'it is {}'.format(str(status)))
return job_response
def _result_from_job_response(self, job_response):
experiment_results = []
result_json = job_response['qObjectResult']
for experiment_result_json in result_json['results']:
qobj_experiment_result = QobjExperimentResult(**experiment_result_json)
experiment_results.append(qobj_experiment_result)
result_kwargs = {**result_json, 'results': experiment_results}
return Result(QobjResult(**result_kwargs))
def cancel(self):
"""Attempt to cancel a job.
Returns:
bool: True if job can be cancelled, else False. Currently this is
only possible on commercial systems.
Raises:
JobError: if there was some unexpected failure in the server
"""
hub = self._api.config.get('hub', None)
group = self._api.config.get('group', None)
project = self._api.config.get('project', None)
try:
response = self._api.cancel_job(self._job_id, hub, group, project)
self._cancelled = 'error' not in response
return self._cancelled
except ApiError as error:
self._cancelled = False
raise JobError('Error cancelling job: %s' % error.usr_msg)
def status(self):
"""Query the API to update the status.
Returns:
JobStatus: The status of the job, once updated.
Raises:
JobError: if there was an exception in the future being executed
or the server sent an unknown answer.
"""
# Implies self._job_id is None
if self._future_captured_exception is not None:
raise JobError(str(self._future_captured_exception))
if self._job_id is None or self._status in JOB_FINAL_STATES:
return self._status
try:
# TODO: See result values
api_job = self._api.get_status_job(self._job_id)
if 'status' not in api_job:
raise JobError('get_status_job didn\'t return status: %s' %
pprint.pformat(api_job))
# pylint: disable=broad-except
except Exception as err:
raise JobError(str(err))
if api_job['status'] == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_job['status'] == 'RUNNING':
self._status = JobStatus.RUNNING
queued, self._queue_position = _is_job_queued(api_job)
if queued:
self._status = JobStatus.QUEUED
elif api_job['status'] == 'COMPLETED':
self._status = JobStatus.DONE
elif api_job['status'] == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
elif 'ERROR' in api_job['status']:
# Error status are of the form "ERROR_*_JOB"
self._status = JobStatus.ERROR
# TODO: This seems to be an inconsistency in the API package.
self._api_error_msg = api_job.get('error') or api_job.get('Error')
else:
raise JobError('Unrecognized answer from server: \n{}'
.format(pprint.pformat(api_job)))
return self._status
def error_message(self):
"""Return the error message returned from the API server response."""
return self._api_error_msg
def queue_position(self):
"""Return the position in the server queue.
Returns:
Number: Position in the queue.
"""
return self._queue_position
def creation_date(self):
"""
Return creation date.
"""
return self._creation_date
# pylint: disable=invalid-name
def id(self):
"""Return backend determined id.
If the Id is not set because the job is already initializing, this call
will block until we have an Id.
.. deprecated:: 0.6+
After 0.6, this function is deprecated. Please use
`job.job_id()` instead.
"""
warnings.warn('The method `job.id()` is deprecated, use '
'``job.job_id()`` instead.', DeprecationWarning)
return self.job_id()
def job_id(self):
"""Return backend determined id.
If the Id is not set because the job is already initializing, this call
will block until we have an Id.
"""
self._wait_for_submission()
return self._job_id
def backend_name(self):
"""
Return backend name used for this job.
.. deprecated:: 0.6+
After 0.6, this function is deprecated. Please use
`job.backend().name()` instead.
"""
warnings.warn('The use of `job.backend_name()` is deprecated, '
'use `job.backend().name()` instead', DeprecationWarning)
return self.backend().name()
def submit(self):
"""Submit job to IBM-Q.
Raises:
JobError: If we have already submitted the job.
"""
# TODO: Validation against the schema should be done here and not
# during initiliazation. Once done, we should document that the method
# can raise QobjValidationError.
if self._future is not None or self._job_id is not None:
raise JobError("We have already submitted the job!")
self._future = self._executor.submit(self._submit_callback)
def _submit_callback(self):
"""Submit qobj job to IBM-Q.
Returns:
dict: A dictionary with the response of the submitted job
"""
backend_name = self.backend().name()
try:
submit_info = self._api.run_job(self._qobj_payload, backend=backend_name)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submisssion success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _wait_for_job(self, timeout=60, wait=5):
"""Wait until all online ran circuits of a qobj are 'COMPLETED'.
Args:
timeout (float or None): seconds to wait for job. If None, wait
indefinitely.
wait (float): seconds between queries
Returns:
dict: A dict with the contents of the API request.
Raises:
JobTimeoutError: if the job does not return results before a specified timeout.
JobError: if something wrong happened in some of the server API calls
"""
start_time = time.time()
while self.status() not in JOB_FINAL_STATES:
elapsed_time = time.time() - start_time
if timeout is not None and elapsed_time >= timeout:
raise JobTimeoutError(
'Timeout while waiting for the job: {}'.format(self._job_id)
)
logger.info('status = %s (%d seconds)', self._status, elapsed_time)
time.sleep(wait)
if self._cancelled:
raise JobError(
'Job result impossible to retrieve. The job was cancelled.')
return self._api.get_job(self._job_id)
def _wait_for_submission(self, timeout=60):
"""Waits for the request to return a job ID"""
if self._job_id is None:
if self._future is None:
raise JobError("You have to submit before asking for status or results!")
try:
submit_info = self._future.result(timeout=timeout)
if self._future_captured_exception is not None:
# pylint can't see if catch of None type
# pylint: disable=raising-bad-type
raise self._future_captured_exception
except TimeoutError as ex:
raise JobTimeoutError(
"Timeout waiting for the job being submitted: {}".format(ex)
)
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
raise JobError(str(submit_info['error']))
class IBMQJobPreQobj(IBMQJob):
"""
Subclass of IBMQJob for handling pre-qobj jobs.
"""
def _submit_callback(self):
"""Submit old style qasms job to IBM-Q. Can remove when all devices
understand Qobj.
Returns:
dict: A dictionary with the response of the submitted job
"""
api_jobs = []
circuits = self._job_data['circuits']
for circuit in circuits:
job = _create_api_job_from_circuit(circuit)
api_jobs.append(job)
hpc_camel_cased = _format_hpc_parameters(self._job_data['hpc'])
seed = self._job_data['seed']
shots = self._job_data['shots']
max_credits = self._job_data['max_credits']
try:
submit_info = self._api.run_job(api_jobs, backend=self.backend().name(),
shots=shots, max_credits=max_credits,
seed=seed, hpc=hpc_camel_cased)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submisssion success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _result_from_job_response(self, job_response):
if self._is_device:
_reorder_bits(job_response)
experiment_results = []
for circuit_result in job_response['qasms']:
this_result = {'data': circuit_result['data'],
'name': circuit_result.get('name'),
'compiled_circuit_qasm': circuit_result.get('qasm'),
'status': circuit_result['status'],
'success': circuit_result['status'] == 'DONE',
'shots': job_response['shots']}
if 'metadata' in circuit_result:
this_result['metadata'] = circuit_result['metadata']
experiment_results.append(this_result)
return result_from_old_style_dict({
'id': self._job_id,
'status': job_response['status'],
'used_credits': job_response.get('usedCredits'),
'result': experiment_results,
'backend_name': self.backend().name(),
'success': job_response['status'] == 'DONE'
}, [circuit_result['name'] for circuit_result in job_response['qasms']])
def _reorder_bits(job_data):
"""Temporary fix for ibmq backends.
For every ran circuit, get reordering information from qobj
and apply reordering on result.
Args:
job_data (dict): dict with the bare contents of the API.get_job request.
Raises:
JobError: raised if the creg sizes don't add up in result header.
"""
for circuit_result in job_data['qasms']:
if 'metadata' in circuit_result:
circ = circuit_result['metadata'].get('compiled_circuit')
else:
logger.warning('result object missing metadata for reordering'
' bits: bits may be out of order')
return
# device_qubit -> device_clbit (how it should have been)
measure_dict = {op['qubits'][0]: op['clbits'][0]
for op in circ['operations']
if op['name'] == 'measure'}
counts_dict_new = {}
for item in circuit_result['data']['counts'].items():
# fix clbit ordering to what it should have been
bits = list(item[0])
bits.reverse() # lsb in 0th position
count = item[1]
reordered_bits = list('x' * len(bits))
for device_clbit, bit in enumerate(bits):
if device_clbit in measure_dict:
correct_device_clbit = measure_dict[device_clbit]
reordered_bits[correct_device_clbit] = bit
reordered_bits.reverse()
# only keep the clbits specified by circuit, not everything on device
num_clbits = circ['header']['number_of_clbits']
compact_key = reordered_bits[-num_clbits:]
compact_key = "".join([b if b != 'x' else '0'
for b in compact_key])
# insert spaces to signify different classical registers
cregs = circ['header']['clbit_labels']
if sum([creg[1] for creg in cregs]) != num_clbits:
raise JobError("creg sizes don't add up in result header.")
creg_begin_pos = []
creg_end_pos = []
acc = 0
for creg in reversed(cregs):
creg_size = creg[1]
creg_begin_pos.append(acc)
creg_end_pos.append(acc + creg_size)
acc += creg_size
compact_key = " ".join([compact_key[creg_begin_pos[i]:creg_end_pos[i]]
for i in range(len(cregs))])
# marginalize over unwanted measured qubits
if compact_key not in counts_dict_new:
counts_dict_new[compact_key] = count
else:
counts_dict_new[compact_key] += count
circuit_result['data']['counts'] = counts_dict_new
def _numpy_type_converter(obj):
ret = obj
if isinstance(obj, numpy.integer):
ret = int(obj)
elif isinstance(obj, numpy.floating): # pylint: disable=no-member
ret = float(obj)
elif isinstance(obj, numpy.ndarray):
ret = obj.tolist()
return ret
def _create_api_job_from_circuit(circuit):
"""Helper function that creates a special job required by the API, from a circuit."""
api_job = {}
if not circuit.get('compiled_circuit_qasm'):
compiled_circuit = transpile(circuit['circuit'])
circuit['compiled_circuit_qasm'] = compiled_circuit.qasm(qeflag=True)
if isinstance(circuit['compiled_circuit_qasm'], bytes):
api_job['qasm'] = circuit['compiled_circuit_qasm'].decode()
else:
api_job['qasm'] = circuit['compiled_circuit_qasm']
if circuit.get('name'):
api_job['name'] = circuit['name']
# convert numpy types for json serialization
compiled_circuit = json.loads(json.dumps(circuit['compiled_circuit'],
default=_numpy_type_converter))
api_job['metadata'] = {'compiled_circuit': compiled_circuit}
return api_job
def _is_job_queued(api_job_response):
"""Checks whether a job has been queued or not."""
is_queued, position = False, 0
if 'infoQueue' in api_job_response:
if 'status' in api_job_response['infoQueue']:
queue_status = api_job_response['infoQueue']['status']
is_queued = queue_status == 'PENDING_IN_QUEUE'
if 'position' in api_job_response['infoQueue']:
position = api_job_response['infoQueue']['position']
return is_queued, position
def _format_hpc_parameters(hpc):
"""Helper function to get HPC parameters with the correct format"""
if hpc is None:
return None
hpc_camel_cased = None
with contextlib.suppress(KeyError, TypeError):
# Use CamelCase when passing the hpc parameters to the API.
hpc_camel_cased = {
'multiShotOptimization': hpc['multi_shot_optimization'],
'ompNumThreads': hpc['omp_num_threads']
}
return hpc_camel_cased
<|code_end|>
setup.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
import os
import platform
from distutils.command.build import build
from multiprocessing import cpu_count
from subprocess import call
from setuptools import setup, find_packages
from setuptools.dist import Distribution
requirements = [
"jsonschema>=2.6,<2.7",
"IBMQuantumExperience>=2.0.4",
"matplotlib>=2.1",
"networkx>=2.0",
"numpy>=1.13",
"ply>=3.10",
"scipy>=0.19,!=0.19.1",
"sympy>=1.0",
"pillow>=4.2.1",
"psutil>=5",
"nxpd>=0.2"
]
# C++ components compilation
class QasmSimulatorCppBuild(build):
def run(self):
super().run()
# Store the current working directory, as invoking cmake involves
# an out of source build and might interfere with the rest of the steps.
current_directory = os.getcwd()
try:
supported_platforms = ['Linux', 'Darwin', 'Windows']
current_platform = platform.system()
if current_platform not in supported_platforms:
# TODO: stdout is silenced by pip if the full setup.py invocation is
# successful, unless using '-v' - hence the warnings are not printed.
print('WARNING: Qiskit cpp simulator is meant to be built with these '
'platforms: {}. We will support other platforms soon!'
.format(supported_platforms))
return
cmd_cmake = ['cmake', '-vvv']
if 'USER_LIB_PATH' in os.environ:
cmd_cmake.append('-DUSER_LIB_PATH={}'.format(os.environ['USER_LIB_PATH']))
if current_platform == 'Windows':
# We only support MinGW so far
cmd_cmake.append("-GMinGW Makefiles")
cmd_cmake.append('..')
cmd_make = ['make', 'pypi_package_copy_qasm_simulator_cpp']
try:
cmd_make.append('-j%d' % cpu_count())
except NotImplementedError:
print('WARNING: Unable to determine number of CPUs. Using single threaded make.')
def compile_simulator():
self.mkpath('out')
os.chdir('out')
call(cmd_cmake)
call(cmd_make)
self.execute(compile_simulator, [], 'Compiling C++ QASM Simulator')
except Exception as e:
print(str(e))
print("WARNING: Seems like the cpp simulator can't be built, Qiskit will "
"install anyway, but won't have this simulator support.")
# Restore working directory.
os.chdir(current_directory)
# This is for creating wheel specific platforms
class BinaryDistribution(Distribution):
def has_ext_modules(self):
return True
setup(
name="qiskit",
version="0.7.0",
description="Software for developing quantum computing programs",
long_description="""Qiskit is a software development kit for writing
quantum computing experiments, programs, and applications. Works with
Python 3.5 and 3.6""",
url="https://github.com/Qiskit/qiskit-terra",
author="Qiskit Development Team",
author_email="qiskit@us.ibm.com",
license="Apache 2.0",
classifiers=[
"Environment :: Console",
"License :: OSI Approved :: Apache Software License",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"Operating System :: Microsoft :: Windows",
"Operating System :: MacOS",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Topic :: Scientific/Engineering",
],
keywords="qiskit sdk quantum",
packages=find_packages(exclude=['test*']),
install_requires=requirements,
include_package_data=True,
python_requires=">=3.5",
cmdclass={
'build': QasmSimulatorCppBuild,
},
distclass=BinaryDistribution
)
<|code_end|>
|
transpiler pass return value is still ignored
### Informations
- **Qiskit Terra version**: 0.7.0
- **Python version**: 3.7.0
- **Operating system**: Mac OS 10.13.6
### What is the current behavior?
The transpile method [here](https://github.com/Qiskit/qiskit-terra/blob/master/qiskit/transpiler/_transpiler.py#L339) relies on the pass manager to modify the DAG in place. The pass manager uses the values returned by the passes and then discards them. See [here](https://github.com/Qiskit/qiskit-terra/blob/master/qiskit/transpiler/_passmanager.py#L107). See also #897
### Steps to reproduce the problem
```
from qiskit.wrapper import load_qasm_string
from qiskit.dagcircuit import DAGCircuit
from qiskit.transpiler import PassManager, transpile
from qiskit.transpiler._basepasses import TransformationPass
class BugPass(TransformationPass) :
def run(self, dag):
print("Activating")
return DAGCircuit()
qasm = "OPENQASM 2.0;\ninclude \"qelib1.inc\";\nqreg q[2];\nh q[0];\ncx q[0],q[1];"
dag = DAGCircuit.fromQuantumCircuit(load_qasm_string(qasm))
pm = PassManager()
pm.add_passes(BugPass())
dag2 = transpile(dag,pass_manager=pm)
dag == dag2 # returns true but should be false
```
### What is the expected behavior?
The transpiler should use the values returned by the passes.
### Suggested solutions
Make PassManager.run_passes() return a DAG. Make transpile() use this return value.
|
qiskit/transpiler/_passmanager.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""PassManager class for the transpiler."""
from functools import partial
from collections import OrderedDict
from qiskit.dagcircuit import DAGCircuit
from ._propertyset import PropertySet
from ._basepasses import BasePass
from ._fencedobjs import FencedPropertySet, FencedDAGCircuit
from ._transpilererror import TranspilerError
class PassManager():
""" A PassManager schedules the passes """
def __init__(self, ignore_requires=None, ignore_preserves=None, max_iteration=None):
"""
Initialize an empty PassManager object (with no passes scheduled).
Args:
ignore_requires (bool): The schedule ignores the requires field in the passes. The
default setting in the pass is False.
ignore_preserves (bool): The schedule ignores the preserves field in the passes. The
default setting in the pass is False.
max_iteration (int): The schedule looping iterates until the condition is met or until
max_iteration is reached.
"""
# the pass manager's schedule of passes, including any control-flow.
# Populated via PassManager.add_passes().
self.working_list = []
# global property set is the context of the circuit held by the pass manager
# as it runs through its scheduled passes. Analysis passes may update the property_set,
# but transformation passes have read-only access (via the fenced_property_set).
self.property_set = PropertySet()
self.fenced_property_set = FencedPropertySet(self.property_set)
# passes already run that have not been invalidated
self.valid_passes = set()
# pass manager's overriding options for the passes it runs (for debugging)
self.passmanager_options = {'ignore_requires': ignore_requires,
'ignore_preserves': ignore_preserves,
'max_iteration': max_iteration}
def _join_options(self, passset_options):
""" Set the options of each passset, based on precedence rules:
passset options (set via ``PassManager.add_passes()``) override
passmanager options (set via ``PassManager.__init__()``), which override Default.
.
"""
default = {'ignore_preserves': False, # Ignore preserves for this pass
'ignore_requires': False, # Ignore requires for this pass
'max_iteration': 1000} # Maximum allowed iteration on this pass
passmanager_level = {k: v for k, v in self.passmanager_options.items() if v is not None}
passset_level = {k: v for k, v in passset_options.items() if v is not None}
return {**default, **passmanager_level, **passset_level}
def add_passes(self, passes, ignore_requires=None, ignore_preserves=None, max_iteration=None,
**flow_controller_conditions):
"""
Args:
passes (list[BasePass] or BasePass): pass(es) to be added to schedule
ignore_preserves (bool): ignore the preserves claim of passes. Default: False
ignore_requires (bool): ignore the requires need of passes. Default: False
max_iteration (int): max number of iterations of passes. Default: 1000
flow_controller_conditions (kwargs): See add_flow_controller(): Dictionary of
control flow plugins. Default:
do_while (callable property_set -> boolean): The passes repeat until the
callable returns False.
Default: lambda x: False # i.e. passes run once
condition (callable property_set -> boolean): The passes run only if the
callable returns True.
Default: lambda x: True # i.e. passes run
Raises:
TranspilerError: if a pass in passes is not a proper pass.
"""
passset_options = {'ignore_requires': ignore_requires,
'ignore_preserves': ignore_preserves,
'max_iteration': max_iteration}
options = self._join_options(passset_options)
if isinstance(passes, BasePass):
passes = [passes]
for pass_ in passes:
if not isinstance(pass_, BasePass):
raise TranspilerError('%s is not a pass instance' % pass_.__class__)
for name, param in flow_controller_conditions.items():
if callable(param):
flow_controller_conditions[name] = partial(param, self.fenced_property_set)
else:
raise TranspilerError('The flow controller parameter %s is not callable' % name)
self.working_list.append(
FlowController.controller_factory(passes, options, **flow_controller_conditions))
def run_passes(self, dag):
"""Run all the passes on the dag.
Args:
dag (DAGCircuit): dag circuit to transform via all the registered passes
"""
for passset in self.working_list:
for pass_ in passset:
dag = self._do_pass(pass_, dag, passset.options)
def _do_pass(self, pass_, dag, options):
"""Do a pass and its "requires".
Args:
pass_ (BasePass): Pass to do.
dag (DAGCircuit): The dag on which the pass is ran.
options (dict): PassManager options.
Returns:
DAGCircuit: The transformed dag in case of a transformation pass.
The same input dag in case of an analysis pass.
Raises:
TranspilerError: If the pass is not a proper pass instance.
"""
# First, do the requires of pass_
if not options["ignore_requires"]:
for required_pass in pass_.requires:
self._do_pass(required_pass, dag, options)
# Run the pass itself, if not already run
if pass_ not in self.valid_passes:
if pass_.is_transformation_pass:
pass_.property_set = self.fenced_property_set
new_dag = pass_.run(dag)
if not isinstance(new_dag, DAGCircuit):
raise TranspilerError("Transformation passes should return a transformed dag."
"The pass %s is returning a %s" % (type(pass_).__name__,
type(new_dag)))
dag = new_dag
elif pass_.is_analysis_pass:
pass_.property_set = self.property_set
pass_.run(FencedDAGCircuit(dag))
else:
raise TranspilerError("I dont know how to handle this type of pass")
# update the valid_passes property
self._update_valid_passes(pass_, options['ignore_preserves'])
return dag
def _update_valid_passes(self, pass_, ignore_preserves):
self.valid_passes.add(pass_)
if not pass_.is_analysis_pass: # Analysis passes preserve all
if ignore_preserves:
self.valid_passes.clear()
else:
self.valid_passes.intersection_update(set(pass_.preserves))
class FlowController():
"""This class is a base class for multiple types of working list. When you iterate on it, it
returns the next pass to run. """
registered_controllers = OrderedDict()
def __init__(self, passes, options, **partial_controller):
self.passes = FlowController.controller_factory(passes, options, **partial_controller)
self.options = options
def __iter__(self):
for pass_ in self.passes:
yield pass_
@classmethod
def add_flow_controller(cls, name, controller):
"""
Adds a flow controller.
Args:
name (string): Name of the controller to add.
controller (type(FlowController)): The class implementing a flow controller.
"""
cls.registered_controllers[name] = controller
@classmethod
def remove_flow_controller(cls, name):
"""
Removes a flow controller.
Args:
name (string): Name of the controller to remove.
Raises:
KeyError: If the controller to remove was not registered.
"""
if name not in cls.registered_controllers:
raise KeyError("Flow controller not found: %s" % name)
del cls.registered_controllers[name]
@classmethod
def controller_factory(cls, passes, options, **partial_controller):
"""
Constructs a flow controller based on the partially evaluated controller arguments.
Args:
passes (list[BasePass]): passes to add to the flow controller.
options (dict): PassManager options.
**partial_controller (dict): Partially evaluated controller arguments in the form
{name:partial}
Raises:
TranspilerError: When partial_controller is not well-formed.
Returns:
FlowController: A FlowController instance.
"""
if None in partial_controller.values():
raise TranspilerError('The controller needs a condition.')
if partial_controller:
for registered_controller in cls.registered_controllers.keys():
if registered_controller in partial_controller:
return cls.registered_controllers[registered_controller](passes, options,
**partial_controller)
raise TranspilerError("The controllers for %s are not registered" % partial_controller)
else:
return FlowControllerLinear(passes, options)
class FlowControllerLinear(FlowController):
""" The basic controller run the passes one after the other one. """
def __init__(self, passes, options): # pylint: disable=super-init-not-called
self.passes = passes
self.options = options
class DoWhileController(FlowController):
"""Implements a set of passes in a do while loop. """
def __init__(self, passes, options, do_while=None,
**partial_controller):
self.do_while = do_while
self.max_iteration = options['max_iteration']
super().__init__(passes, options, **partial_controller)
def __iter__(self):
for _ in range(self.max_iteration):
for pass_ in self.passes:
yield pass_
if not self.do_while():
return
raise TranspilerError("Maximum iteration reached. max_iteration=%i" % self.max_iteration)
class ConditionalController(FlowController):
"""Implements a set of passes under certain condition. """
def __init__(self, passes, options, condition=None,
**partial_controller):
self.condition = condition
super().__init__(passes, options, **partial_controller)
def __iter__(self):
if self.condition():
for pass_ in self.passes:
yield pass_
# Default controllers
FlowController.add_flow_controller('condition', ConditionalController)
FlowController.add_flow_controller('do_while', DoWhileController)
<|code_end|>
qiskit/transpiler/_transpiler.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Tools for compiling a batch of quantum circuits."""
from copy import deepcopy
import logging
import uuid
import numpy as np
import scipy.sparse as sp
import scipy.sparse.csgraph as cs
from qiskit.transpiler._transpilererror import TranspilerError
from qiskit._qiskiterror import QISKitError
from qiskit import QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.unroll import DagUnroller, DAGBackend, JsonBackend
from qiskit.mapper import (Coupling, optimize_1q_gates, coupling_list2dict, swap_mapper,
cx_cancellation, direction_mapper,
remove_last_measurements, return_last_measurements)
from qiskit.qobj import Qobj, QobjConfig, QobjExperiment, QobjItem, QobjHeader
from ._parallel import parallel_map
logger = logging.getLogger(__name__)
# pylint: disable=redefined-builtin
def compile(circuits, backend,
config=None, basis_gates=None, coupling_map=None, initial_layout=None,
shots=1024, max_credits=10, seed=None, qobj_id=None, hpc=None,
pass_manager=None):
"""Compile a list of circuits into a qobj.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend): a backend to compile for
config (dict): dictionary of parameters (e.g. noise) used by runner
basis_gates (str): comma-separated basis gate set to compile to
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
shots (int): number of repetitions of each circuit, for sampling
max_credits (int): maximum credits to use
seed (int): random seed for simulators
qobj_id (int): identifier for the generated qobj
hpc (dict): HPC simulator parameters
pass_manager (PassManager): a pass_manager for the transpiler stage
Returns:
QobjExperiment: Experiment to be wrapped in a Qobj.
Raises:
TranspilerError: in case of bad compile options, e.g. the hpc options.
"""
if isinstance(circuits, QuantumCircuit):
circuits = [circuits]
# FIXME: THIS NEEDS TO BE CLEANED UP -- some things to decide for list of circuits:
# 1. do all circuits have same coupling map?
# 2. do all circuit have the same basis set?
# 3. do they all have same registers etc?
backend_conf = backend.configuration()
backend_name = backend_conf['name']
# Check for valid parameters for the experiments.
if hpc is not None and \
not all(key in hpc for key in ('multi_shot_optimization', 'omp_num_threads')):
raise TranspilerError('Unknown HPC parameter format!')
basis_gates = basis_gates or backend_conf['basis_gates']
coupling_map = coupling_map or backend_conf['coupling_map']
# step 1: Making the list of dag circuits
dags = _circuits_2_dags(circuits)
# step 2: Transpile all the dags
# FIXME: Work-around for transpiling multiple circuits with different qreg names.
# Make compile take a list of initial_layouts.
_initial_layout = initial_layout
# Pick a good initial layout if coupling_map is not already satisfied
# otherwise keep it as q[i]->q[i].
# TODO: move this inside mapper pass.
initial_layouts = []
for dag in dags:
if (initial_layout is None and not backend.configuration()['simulator']
and not _matches_coupling_map(dag, coupling_map)):
_initial_layout = _pick_best_layout(dag, backend)
initial_layouts.append(_initial_layout)
dags = _transpile_dags(dags, basis_gates=basis_gates, coupling_map=coupling_map,
initial_layouts=initial_layouts, seed=seed,
pass_manager=pass_manager)
# step 3: Making a qobj
qobj = _dags_2_qobj(dags, backend_name=backend_name,
config=config, shots=shots, max_credits=max_credits,
qobj_id=qobj_id, basis_gates=basis_gates,
coupling_map=coupling_map, seed=seed)
return qobj
def _circuits_2_dags(circuits):
"""Convert a list of circuits into a list of dags.
Args:
circuits (list[QuantumCircuit]): circuit to compile
Returns:
list[DAGCircuit]: the dag representation of the circuits
to be used in the transpiler
"""
dags = parallel_map(DAGCircuit.fromQuantumCircuit, circuits)
return dags
def _transpile_dags(dags, basis_gates='u1,u2,u3,cx,id', coupling_map=None,
initial_layouts=None, seed=None, pass_manager=None):
"""Transform multiple dags through a sequence of passes.
Args:
dags (list[DAGCircuit]): dag circuits to transform
basis_gates (str): a comma seperated string for the target basis gates
coupling_map (list): A graph of coupling
initial_layouts (list[dict]): A mapping of qubit to qubit for each dag
seed (int): random seed for the swap mapper
pass_manager (PassManager): pass manager instance for the tranpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
list[DAGCircuit]: the dag circuits after going through transpilation
Raises:
TranspilerError: if the format is not valid.
"""
index = list(range(len(dags)))
final_dags = parallel_map(_transpile_dags_parallel, index,
task_args=(dags, initial_layouts),
task_kwargs={'basis_gates': basis_gates,
'coupling_map': coupling_map,
'seed': seed,
'pass_manager': pass_manager})
return final_dags
def _transpile_dags_parallel(idx, dags, initial_layouts, basis_gates='u1,u2,u3,cx,id',
coupling_map=None, seed=None, pass_manager=None):
"""Helper function for transpiling in parallel (if available).
Args:
idx (int): Index for dag of interest
dags (list): List of dags
initial_layouts (list): List of initial layouts
basis_gates (str): a comma seperated string for the target basis gates
coupling_map (list): A graph of coupling
seed (int): random seed for the swap mapper
pass_manager (PassManager): pass manager instance for the tranpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
DAGCircuit: DAG circuit after going through transpilation.
"""
dag = dags[idx]
initial_layout = initial_layouts[idx]
final_dag, final_layout = transpile(
dag,
basis_gates=basis_gates,
coupling_map=coupling_map,
initial_layout=initial_layout,
get_layout=True,
seed=seed,
pass_manager=pass_manager)
final_dag.layout = [[k, v]
for k, v in final_layout.items()] if final_layout else None
return final_dag
def _dags_2_qobj(dags, backend_name, config=None, shots=None,
max_credits=None, qobj_id=None, basis_gates=None, coupling_map=None,
seed=None):
"""Convert a list of dags into a qobj.
Args:
dags (list[DAGCircuit]): dags to compile
backend_name (str): name of runner backend
config (dict): dictionary of parameters (e.g. noise) used by runner
shots (int): number of repetitions of each circuit, for sampling
max_credits (int): maximum credits to use
qobj_id (int): identifier for the generated qobj
basis_gates (list[str])): basis gates for the experiment
coupling_map (list): coupling map (perhaps custom) to target in mapping
seed (int): random seed for simulators
Returns:
Qobj: the Qobj to be run on the backends
"""
# TODO: the following will be removed from qobj and thus removed here:
# `basis_gates`, `coupling_map`
# Step 1: create the Qobj, with empty experiments.
# Copy the configuration: the values in `config` have preference
qobj_config = deepcopy(config or {})
# TODO: "memory_slots" is required by the qobj schema in the top-level
# qobj.config, and is user-defined. At the moment is set to the maximum
# number of *register* slots for the circuits, in order to have `measure`
# behave properly until the transition is over; and each circuit stores
# its memory_slots in its configuration.
qobj_config.update({'shots': shots,
'max_credits': max_credits,
'memory_slots': 0})
qobj = Qobj(qobj_id=qobj_id or str(uuid.uuid4()),
config=QobjConfig(**qobj_config),
experiments=[],
header=QobjHeader(backend_name=backend_name))
if seed:
qobj.config.seed = seed
qobj.experiments = parallel_map(_dags_2_qobj_parallel, dags,
task_kwargs={'basis_gates': basis_gates,
'config': config,
'coupling_map': coupling_map})
# Update the `memory_slots` value.
# TODO: remove when `memory_slots` can be provided by the user.
qobj.config.memory_slots = max(experiment.config.memory_slots for
experiment in qobj.experiments)
# Update the `n_qubits` global value.
# TODO: num_qubits is not part of the qobj specification, but needed
# for the simulator.
qobj.config.n_qubits = max(experiment.config.n_qubits for
experiment in qobj.experiments)
return qobj
def _dags_2_qobj_parallel(dag, config=None, basis_gates=None,
coupling_map=None):
"""Helper function for dags to qobj in parallel (if available).
Args:
dag (DAGCircuit): DAG to compile
config (dict): dictionary of parameters (e.g. noise) used by runner
basis_gates (list[str])): basis gates for the experiment
coupling_map (list): coupling map (perhaps custom) to target in mapping
Returns:
Qobj: Qobj to be run on the backends
"""
json_circuit = DagUnroller(dag, JsonBackend(dag.basis)).execute()
# Step 3a: create the Experiment based on json_circuit
experiment = QobjExperiment.from_dict(json_circuit)
# Step 3b: populate the Experiment configuration and header
experiment.header.name = dag.name
# TODO: place in header or config?
experiment_config = deepcopy(config or {})
experiment_config.update({
'coupling_map': coupling_map,
'basis_gates': basis_gates,
'layout': dag.layout,
'memory_slots': sum(dag.cregs.values()),
# TODO: `n_qubits` is not part of the qobj spec, but needed for the simulator.
'n_qubits': sum(dag.qregs.values())})
experiment.config = QobjItem(**experiment_config)
# set eval_symbols=True to evaluate each symbolic expression
# TODO: after transition to qobj, we can drop this
experiment.header.compiled_circuit_qasm = dag.qasm(
qeflag=True, eval_symbols=True)
# Step 3c: add the Experiment to the Qobj
return experiment
def transpile(dag, basis_gates='u1,u2,u3,cx,id', coupling_map=None,
initial_layout=None, get_layout=False,
format='dag', seed=None, pass_manager=None):
"""Transform a dag circuit into another dag circuit (transpile), through
consecutive passes on the dag.
Args:
dag (DAGCircuit): dag circuit to transform via transpilation
basis_gates (str): a comma seperated string for the target basis gates
coupling_map (list): A graph of coupling::
[
[control0(int), target0(int)],
[control1(int), target1(int)],
]
eg. [[0, 2], [1, 2], [1, 3], [3, 4]}
initial_layout (dict): A mapping of qubit to qubit::
{
("q", start(int)): ("q", final(int)),
...
}
eg.
{
("q", 0): ("q", 0),
("q", 1): ("q", 1),
("q", 2): ("q", 2),
("q", 3): ("q", 3)
}
get_layout (bool): flag for returning the final layout after mapping
format (str): The target format of the compilation:
{'dag', 'json', 'qasm'}
seed (int): random seed for the swap mapper
pass_manager (PassManager): pass manager instance for the tranpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
DAGCircuit: transformed dag
DAGCircuit, dict: transformed dag along with the final layout on backend qubits
Raises:
TranspilerError: if the format is not valid.
"""
# TODO: `basis_gates` will be removed after we have the unroller pass.
# TODO: `coupling_map`, `initial_layout`, `get_layout`, `seed` removed after mapper pass.
# TODO: move this to the mapper pass
num_qubits = sum(dag.qregs.values())
if num_qubits == 1 or coupling_map == "all-to-all":
coupling_map = None
final_layout = None
if pass_manager:
# run the passes specified by the pass manager
pass_manager.run_passes(dag)
else:
# default set of passes
# TODO: move each step here to a pass, and use a default passmanager below
basis = basis_gates.split(',') if basis_gates else []
dag_unroller = DagUnroller(dag, DAGBackend(basis))
dag = dag_unroller.expand_gates()
# if a coupling map is given compile to the map
if coupling_map:
logger.info("pre-mapping properties: %s",
dag.property_summary())
# Insert swap gates
coupling = Coupling(coupling_list2dict(coupling_map))
removed_meas = remove_last_measurements(dag)
logger.info("measurements moved: %s", removed_meas)
logger.info("initial layout: %s", initial_layout)
dag, final_layout, last_layout = swap_mapper(
dag, coupling, initial_layout, trials=20, seed=seed)
logger.info("final layout: %s", final_layout)
# Expand swaps
dag_unroller = DagUnroller(dag, DAGBackend(basis))
dag = dag_unroller.expand_gates()
# Change cx directions
dag = direction_mapper(dag, coupling)
# Simplify cx gates
cx_cancellation(dag)
# Simplify single qubit gates
dag = optimize_1q_gates(dag)
return_last_measurements(dag, removed_meas,
last_layout)
logger.info("post-mapping properties: %s",
dag.property_summary())
# choose output format
# TODO: do we need all of these formats, or just the dag?
if format == 'dag':
compiled_circuit = dag
elif format == 'json':
# FIXME: JsonBackend is wrongly taking an ordered dict as basis, not list
dag_unroller = DagUnroller(dag, JsonBackend(dag.basis))
compiled_circuit = dag_unroller.execute()
elif format == 'qasm':
compiled_circuit = dag.qasm()
else:
raise TranspilerError('unrecognized circuit format')
if get_layout:
return compiled_circuit, final_layout
return compiled_circuit
def _best_subset(backend, n_qubits):
"""Computes the qubit mapping with the best
connectivity.
Parameters:
backend (Qiskit.BaseBackend): A QISKit backend instance.
n_qubits (int): Number of subset qubits to consider.
Returns:
ndarray: Array of qubits to use for best
connectivity mapping.
Raises:
QISKitError: Wrong number of qubits given.
"""
if n_qubits == 1:
return np.array([0])
elif n_qubits <= 0:
raise QISKitError('Number of qubits <= 0.')
device_qubits = backend.configuration()['n_qubits']
if n_qubits > device_qubits:
raise QISKitError('Number of qubits greater than device.')
cmap = np.asarray(backend.configuration()['coupling_map'])
data = np.ones_like(cmap[:, 0])
sp_cmap = sp.coo_matrix((data, (cmap[:, 0], cmap[:, 1])),
shape=(device_qubits, device_qubits)).tocsr()
best = 0
best_map = None
# do bfs with each node as starting point
for k in range(sp_cmap.shape[0]):
bfs = cs.breadth_first_order(sp_cmap, i_start=k, directed=False,
return_predecessors=False)
connection_count = 0
for i in range(n_qubits):
node_idx = bfs[i]
for j in range(sp_cmap.indptr[node_idx],
sp_cmap.indptr[node_idx + 1]):
node = sp_cmap.indices[j]
for counter in range(n_qubits):
if node == bfs[counter]:
connection_count += 1
break
if connection_count > best:
best = connection_count
best_map = bfs[0:n_qubits]
return best_map
def _matches_coupling_map(dag, coupling_map):
"""Iterate over circuit gates to check if all multi-qubit couplings
match the qubit coupling graph in the backend.
Parameters:
dag (DAGCircuit): DAG representation of circuit.
coupling_map (list): Backend coupling map, represented as an adjacency list.
Returns:
bool: True if all gates readily fit the backend coupling graph.
False if there's at least one gate that uses multiple qubits
which does not match the backend couplings.
"""
match = True
for _, data in dag.multi_graph.nodes(data=True):
if data['type'] == 'op':
gate_map = [qr[1] for qr in data['qargs']]
if len(gate_map) > 1:
if gate_map not in coupling_map:
match = False
break
return match
def _pick_best_layout(dag, backend):
"""Pick a convenient layout depending on the best matching qubit connectivity
Parameters:
dag (DAGCircuit): DAG representation of circuit.
backend (BaseBackend) : The backend with the coupling_map for searching
Returns:
dict: A special ordered initial_layout
"""
num_qubits = sum(dag.qregs.values())
best_sub = _best_subset(backend, num_qubits)
layout = {}
map_iter = 0
for key, value in dag.qregs.items():
for i in range(value):
layout[(key, i)] = ('q', best_sub[map_iter])
map_iter += 1
return layout
<|code_end|>
|
qiskit/transpiler/_passmanager.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""PassManager class for the transpiler."""
from functools import partial
from collections import OrderedDict
from qiskit.dagcircuit import DAGCircuit
from ._propertyset import PropertySet
from ._basepasses import BasePass
from ._fencedobjs import FencedPropertySet, FencedDAGCircuit
from ._transpilererror import TranspilerError
class PassManager():
""" A PassManager schedules the passes """
def __init__(self, ignore_requires=None, ignore_preserves=None, max_iteration=None):
"""
Initialize an empty PassManager object (with no passes scheduled).
Args:
ignore_requires (bool): The schedule ignores the requires field in the passes. The
default setting in the pass is False.
ignore_preserves (bool): The schedule ignores the preserves field in the passes. The
default setting in the pass is False.
max_iteration (int): The schedule looping iterates until the condition is met or until
max_iteration is reached.
"""
# the pass manager's schedule of passes, including any control-flow.
# Populated via PassManager.add_passes().
self.working_list = []
# global property set is the context of the circuit held by the pass manager
# as it runs through its scheduled passes. Analysis passes may update the property_set,
# but transformation passes have read-only access (via the fenced_property_set).
self.property_set = PropertySet()
self.fenced_property_set = FencedPropertySet(self.property_set)
# passes already run that have not been invalidated
self.valid_passes = set()
# pass manager's overriding options for the passes it runs (for debugging)
self.passmanager_options = {'ignore_requires': ignore_requires,
'ignore_preserves': ignore_preserves,
'max_iteration': max_iteration}
def _join_options(self, passset_options):
""" Set the options of each passset, based on precedence rules:
passset options (set via ``PassManager.add_passes()``) override
passmanager options (set via ``PassManager.__init__()``), which override Default.
.
"""
default = {'ignore_preserves': False, # Ignore preserves for this pass
'ignore_requires': False, # Ignore requires for this pass
'max_iteration': 1000} # Maximum allowed iteration on this pass
passmanager_level = {k: v for k, v in self.passmanager_options.items() if v is not None}
passset_level = {k: v for k, v in passset_options.items() if v is not None}
return {**default, **passmanager_level, **passset_level}
def add_passes(self, passes, ignore_requires=None, ignore_preserves=None, max_iteration=None,
**flow_controller_conditions):
"""
Args:
passes (list[BasePass] or BasePass): pass(es) to be added to schedule
ignore_preserves (bool): ignore the preserves claim of passes. Default: False
ignore_requires (bool): ignore the requires need of passes. Default: False
max_iteration (int): max number of iterations of passes. Default: 1000
flow_controller_conditions (kwargs): See add_flow_controller(): Dictionary of
control flow plugins. Default:
do_while (callable property_set -> boolean): The passes repeat until the
callable returns False.
Default: lambda x: False # i.e. passes run once
condition (callable property_set -> boolean): The passes run only if the
callable returns True.
Default: lambda x: True # i.e. passes run
Raises:
TranspilerError: if a pass in passes is not a proper pass.
"""
passset_options = {'ignore_requires': ignore_requires,
'ignore_preserves': ignore_preserves,
'max_iteration': max_iteration}
options = self._join_options(passset_options)
if isinstance(passes, BasePass):
passes = [passes]
for pass_ in passes:
if not isinstance(pass_, BasePass):
raise TranspilerError('%s is not a pass instance' % pass_.__class__)
for name, param in flow_controller_conditions.items():
if callable(param):
flow_controller_conditions[name] = partial(param, self.fenced_property_set)
else:
raise TranspilerError('The flow controller parameter %s is not callable' % name)
self.working_list.append(
FlowController.controller_factory(passes, options, **flow_controller_conditions))
def run_passes(self, dag):
"""Run all the passes on a DAG.
Args:
dag (DAGCircuit): DAG circuit to transform via all the registered passes
Returns:
DAGCircuit: Transformed DAG.
"""
for passset in self.working_list:
for pass_ in passset:
dag = self._do_pass(pass_, dag, passset.options)
return dag
def _do_pass(self, pass_, dag, options):
"""Do a pass and its "requires".
Args:
pass_ (BasePass): Pass to do.
dag (DAGCircuit): The dag on which the pass is ran.
options (dict): PassManager options.
Returns:
DAGCircuit: The transformed dag in case of a transformation pass.
The same input dag in case of an analysis pass.
Raises:
TranspilerError: If the pass is not a proper pass instance.
"""
# First, do the requires of pass_
if not options["ignore_requires"]:
for required_pass in pass_.requires:
self._do_pass(required_pass, dag, options)
# Run the pass itself, if not already run
if pass_ not in self.valid_passes:
if pass_.is_transformation_pass:
pass_.property_set = self.fenced_property_set
new_dag = pass_.run(dag)
if not isinstance(new_dag, DAGCircuit):
raise TranspilerError("Transformation passes should return a transformed dag."
"The pass %s is returning a %s" % (type(pass_).__name__,
type(new_dag)))
dag = new_dag
elif pass_.is_analysis_pass:
pass_.property_set = self.property_set
pass_.run(FencedDAGCircuit(dag))
else:
raise TranspilerError("I dont know how to handle this type of pass")
# update the valid_passes property
self._update_valid_passes(pass_, options['ignore_preserves'])
return dag
def _update_valid_passes(self, pass_, ignore_preserves):
self.valid_passes.add(pass_)
if not pass_.is_analysis_pass: # Analysis passes preserve all
if ignore_preserves:
self.valid_passes.clear()
else:
self.valid_passes.intersection_update(set(pass_.preserves))
class FlowController():
"""This class is a base class for multiple types of working list. When you iterate on it, it
returns the next pass to run. """
registered_controllers = OrderedDict()
def __init__(self, passes, options, **partial_controller):
self.passes = FlowController.controller_factory(passes, options, **partial_controller)
self.options = options
def __iter__(self):
for pass_ in self.passes:
yield pass_
@classmethod
def add_flow_controller(cls, name, controller):
"""
Adds a flow controller.
Args:
name (string): Name of the controller to add.
controller (type(FlowController)): The class implementing a flow controller.
"""
cls.registered_controllers[name] = controller
@classmethod
def remove_flow_controller(cls, name):
"""
Removes a flow controller.
Args:
name (string): Name of the controller to remove.
Raises:
KeyError: If the controller to remove was not registered.
"""
if name not in cls.registered_controllers:
raise KeyError("Flow controller not found: %s" % name)
del cls.registered_controllers[name]
@classmethod
def controller_factory(cls, passes, options, **partial_controller):
"""
Constructs a flow controller based on the partially evaluated controller arguments.
Args:
passes (list[BasePass]): passes to add to the flow controller.
options (dict): PassManager options.
**partial_controller (dict): Partially evaluated controller arguments in the form
{name:partial}
Raises:
TranspilerError: When partial_controller is not well-formed.
Returns:
FlowController: A FlowController instance.
"""
if None in partial_controller.values():
raise TranspilerError('The controller needs a condition.')
if partial_controller:
for registered_controller in cls.registered_controllers.keys():
if registered_controller in partial_controller:
return cls.registered_controllers[registered_controller](passes, options,
**partial_controller)
raise TranspilerError("The controllers for %s are not registered" % partial_controller)
else:
return FlowControllerLinear(passes, options)
class FlowControllerLinear(FlowController):
""" The basic controller run the passes one after the other one. """
def __init__(self, passes, options): # pylint: disable=super-init-not-called
self.passes = passes
self.options = options
class DoWhileController(FlowController):
"""Implements a set of passes in a do while loop. """
def __init__(self, passes, options, do_while=None,
**partial_controller):
self.do_while = do_while
self.max_iteration = options['max_iteration']
super().__init__(passes, options, **partial_controller)
def __iter__(self):
for _ in range(self.max_iteration):
for pass_ in self.passes:
yield pass_
if not self.do_while():
return
raise TranspilerError("Maximum iteration reached. max_iteration=%i" % self.max_iteration)
class ConditionalController(FlowController):
"""Implements a set of passes under certain condition. """
def __init__(self, passes, options, condition=None,
**partial_controller):
self.condition = condition
super().__init__(passes, options, **partial_controller)
def __iter__(self):
if self.condition():
for pass_ in self.passes:
yield pass_
# Default controllers
FlowController.add_flow_controller('condition', ConditionalController)
FlowController.add_flow_controller('do_while', DoWhileController)
<|code_end|>
qiskit/transpiler/_transpiler.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Tools for compiling a batch of quantum circuits."""
from copy import deepcopy
import logging
import uuid
import numpy as np
import scipy.sparse as sp
import scipy.sparse.csgraph as cs
from qiskit.transpiler._transpilererror import TranspilerError
from qiskit._qiskiterror import QISKitError
from qiskit import QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.unroll import DagUnroller, DAGBackend, JsonBackend
from qiskit.mapper import (Coupling, optimize_1q_gates, coupling_list2dict, swap_mapper,
cx_cancellation, direction_mapper,
remove_last_measurements, return_last_measurements)
from qiskit.qobj import Qobj, QobjConfig, QobjExperiment, QobjItem, QobjHeader
from ._parallel import parallel_map
logger = logging.getLogger(__name__)
# pylint: disable=redefined-builtin
def compile(circuits, backend,
config=None, basis_gates=None, coupling_map=None, initial_layout=None,
shots=1024, max_credits=10, seed=None, qobj_id=None, hpc=None,
pass_manager=None):
"""Compile a list of circuits into a qobj.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend): a backend to compile for
config (dict): dictionary of parameters (e.g. noise) used by runner
basis_gates (str): comma-separated basis gate set to compile to
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
shots (int): number of repetitions of each circuit, for sampling
max_credits (int): maximum credits to use
seed (int): random seed for simulators
qobj_id (int): identifier for the generated qobj
hpc (dict): HPC simulator parameters
pass_manager (PassManager): a pass_manager for the transpiler stage
Returns:
QobjExperiment: Experiment to be wrapped in a Qobj.
Raises:
TranspilerError: in case of bad compile options, e.g. the hpc options.
"""
if isinstance(circuits, QuantumCircuit):
circuits = [circuits]
# FIXME: THIS NEEDS TO BE CLEANED UP -- some things to decide for list of circuits:
# 1. do all circuits have same coupling map?
# 2. do all circuit have the same basis set?
# 3. do they all have same registers etc?
backend_conf = backend.configuration()
backend_name = backend_conf['name']
# Check for valid parameters for the experiments.
if hpc is not None and \
not all(key in hpc for key in ('multi_shot_optimization', 'omp_num_threads')):
raise TranspilerError('Unknown HPC parameter format!')
basis_gates = basis_gates or backend_conf['basis_gates']
coupling_map = coupling_map or backend_conf['coupling_map']
# step 1: Making the list of dag circuits
dags = _circuits_2_dags(circuits)
# step 2: Transpile all the dags
# FIXME: Work-around for transpiling multiple circuits with different qreg names.
# Make compile take a list of initial_layouts.
_initial_layout = initial_layout
# Pick a good initial layout if coupling_map is not already satisfied
# otherwise keep it as q[i]->q[i].
# TODO: move this inside mapper pass.
initial_layouts = []
for dag in dags:
if (initial_layout is None and not backend.configuration()['simulator']
and not _matches_coupling_map(dag, coupling_map)):
_initial_layout = _pick_best_layout(dag, backend)
initial_layouts.append(_initial_layout)
dags = _transpile_dags(dags, basis_gates=basis_gates, coupling_map=coupling_map,
initial_layouts=initial_layouts, seed=seed,
pass_manager=pass_manager)
# step 3: Making a qobj
qobj = _dags_2_qobj(dags, backend_name=backend_name,
config=config, shots=shots, max_credits=max_credits,
qobj_id=qobj_id, basis_gates=basis_gates,
coupling_map=coupling_map, seed=seed)
return qobj
def _circuits_2_dags(circuits):
"""Convert a list of circuits into a list of dags.
Args:
circuits (list[QuantumCircuit]): circuit to compile
Returns:
list[DAGCircuit]: the dag representation of the circuits
to be used in the transpiler
"""
dags = parallel_map(DAGCircuit.fromQuantumCircuit, circuits)
return dags
def _transpile_dags(dags, basis_gates='u1,u2,u3,cx,id', coupling_map=None,
initial_layouts=None, seed=None, pass_manager=None):
"""Transform multiple dags through a sequence of passes.
Args:
dags (list[DAGCircuit]): dag circuits to transform
basis_gates (str): a comma seperated string for the target basis gates
coupling_map (list): A graph of coupling
initial_layouts (list[dict]): A mapping of qubit to qubit for each dag
seed (int): random seed for the swap mapper
pass_manager (PassManager): pass manager instance for the tranpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
list[DAGCircuit]: the dag circuits after going through transpilation
Raises:
TranspilerError: if the format is not valid.
"""
index = list(range(len(dags)))
final_dags = parallel_map(_transpile_dags_parallel, index,
task_args=(dags, initial_layouts),
task_kwargs={'basis_gates': basis_gates,
'coupling_map': coupling_map,
'seed': seed,
'pass_manager': pass_manager})
return final_dags
def _transpile_dags_parallel(idx, dags, initial_layouts, basis_gates='u1,u2,u3,cx,id',
coupling_map=None, seed=None, pass_manager=None):
"""Helper function for transpiling in parallel (if available).
Args:
idx (int): Index for dag of interest
dags (list): List of dags
initial_layouts (list): List of initial layouts
basis_gates (str): a comma seperated string for the target basis gates
coupling_map (list): A graph of coupling
seed (int): random seed for the swap mapper
pass_manager (PassManager): pass manager instance for the tranpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
DAGCircuit: DAG circuit after going through transpilation.
"""
dag = dags[idx]
initial_layout = initial_layouts[idx]
final_dag, final_layout = transpile(
dag,
basis_gates=basis_gates,
coupling_map=coupling_map,
initial_layout=initial_layout,
get_layout=True,
seed=seed,
pass_manager=pass_manager)
final_dag.layout = [[k, v]
for k, v in final_layout.items()] if final_layout else None
return final_dag
def _dags_2_qobj(dags, backend_name, config=None, shots=None,
max_credits=None, qobj_id=None, basis_gates=None, coupling_map=None,
seed=None):
"""Convert a list of dags into a qobj.
Args:
dags (list[DAGCircuit]): dags to compile
backend_name (str): name of runner backend
config (dict): dictionary of parameters (e.g. noise) used by runner
shots (int): number of repetitions of each circuit, for sampling
max_credits (int): maximum credits to use
qobj_id (int): identifier for the generated qobj
basis_gates (list[str])): basis gates for the experiment
coupling_map (list): coupling map (perhaps custom) to target in mapping
seed (int): random seed for simulators
Returns:
Qobj: the Qobj to be run on the backends
"""
# TODO: the following will be removed from qobj and thus removed here:
# `basis_gates`, `coupling_map`
# Step 1: create the Qobj, with empty experiments.
# Copy the configuration: the values in `config` have preference
qobj_config = deepcopy(config or {})
# TODO: "memory_slots" is required by the qobj schema in the top-level
# qobj.config, and is user-defined. At the moment is set to the maximum
# number of *register* slots for the circuits, in order to have `measure`
# behave properly until the transition is over; and each circuit stores
# its memory_slots in its configuration.
qobj_config.update({'shots': shots,
'max_credits': max_credits,
'memory_slots': 0})
qobj = Qobj(qobj_id=qobj_id or str(uuid.uuid4()),
config=QobjConfig(**qobj_config),
experiments=[],
header=QobjHeader(backend_name=backend_name))
if seed:
qobj.config.seed = seed
qobj.experiments = parallel_map(_dags_2_qobj_parallel, dags,
task_kwargs={'basis_gates': basis_gates,
'config': config,
'coupling_map': coupling_map})
# Update the `memory_slots` value.
# TODO: remove when `memory_slots` can be provided by the user.
qobj.config.memory_slots = max(experiment.config.memory_slots for
experiment in qobj.experiments)
# Update the `n_qubits` global value.
# TODO: num_qubits is not part of the qobj specification, but needed
# for the simulator.
qobj.config.n_qubits = max(experiment.config.n_qubits for
experiment in qobj.experiments)
return qobj
def _dags_2_qobj_parallel(dag, config=None, basis_gates=None,
coupling_map=None):
"""Helper function for dags to qobj in parallel (if available).
Args:
dag (DAGCircuit): DAG to compile
config (dict): dictionary of parameters (e.g. noise) used by runner
basis_gates (list[str])): basis gates for the experiment
coupling_map (list): coupling map (perhaps custom) to target in mapping
Returns:
Qobj: Qobj to be run on the backends
"""
json_circuit = DagUnroller(dag, JsonBackend(dag.basis)).execute()
# Step 3a: create the Experiment based on json_circuit
experiment = QobjExperiment.from_dict(json_circuit)
# Step 3b: populate the Experiment configuration and header
experiment.header.name = dag.name
# TODO: place in header or config?
experiment_config = deepcopy(config or {})
experiment_config.update({
'coupling_map': coupling_map,
'basis_gates': basis_gates,
'layout': dag.layout,
'memory_slots': sum(dag.cregs.values()),
# TODO: `n_qubits` is not part of the qobj spec, but needed for the simulator.
'n_qubits': sum(dag.qregs.values())})
experiment.config = QobjItem(**experiment_config)
# set eval_symbols=True to evaluate each symbolic expression
# TODO: after transition to qobj, we can drop this
experiment.header.compiled_circuit_qasm = dag.qasm(
qeflag=True, eval_symbols=True)
# Step 3c: add the Experiment to the Qobj
return experiment
def transpile(dag, basis_gates='u1,u2,u3,cx,id', coupling_map=None,
initial_layout=None, get_layout=False,
format='dag', seed=None, pass_manager=None):
"""Transform a dag circuit into another dag circuit (transpile), through
consecutive passes on the dag.
Args:
dag (DAGCircuit): dag circuit to transform via transpilation
basis_gates (str): a comma seperated string for the target basis gates
coupling_map (list): A graph of coupling::
[
[control0(int), target0(int)],
[control1(int), target1(int)],
]
eg. [[0, 2], [1, 2], [1, 3], [3, 4]}
initial_layout (dict): A mapping of qubit to qubit::
{
("q", start(int)): ("q", final(int)),
...
}
eg.
{
("q", 0): ("q", 0),
("q", 1): ("q", 1),
("q", 2): ("q", 2),
("q", 3): ("q", 3)
}
get_layout (bool): flag for returning the final layout after mapping
format (str): The target format of the compilation:
{'dag', 'json', 'qasm'}
seed (int): random seed for the swap mapper
pass_manager (PassManager): pass manager instance for the tranpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
DAGCircuit: transformed dag
DAGCircuit, dict: transformed dag along with the final layout on backend qubits
Raises:
TranspilerError: if the format is not valid.
"""
# TODO: `basis_gates` will be removed after we have the unroller pass.
# TODO: `coupling_map`, `initial_layout`, `get_layout`, `seed` removed after mapper pass.
# TODO: move this to the mapper pass
num_qubits = sum(dag.qregs.values())
if num_qubits == 1 or coupling_map == "all-to-all":
coupling_map = None
final_layout = None
if pass_manager:
# run the passes specified by the pass manager
# TODO return the property set too. See #1086
dag = pass_manager.run_passes(dag)
else:
# default set of passes
# TODO: move each step here to a pass, and use a default passmanager below
basis = basis_gates.split(',') if basis_gates else []
dag_unroller = DagUnroller(dag, DAGBackend(basis))
dag = dag_unroller.expand_gates()
# if a coupling map is given compile to the map
if coupling_map:
logger.info("pre-mapping properties: %s",
dag.property_summary())
# Insert swap gates
coupling = Coupling(coupling_list2dict(coupling_map))
removed_meas = remove_last_measurements(dag)
logger.info("measurements moved: %s", removed_meas)
logger.info("initial layout: %s", initial_layout)
dag, final_layout, last_layout = swap_mapper(
dag, coupling, initial_layout, trials=20, seed=seed)
logger.info("final layout: %s", final_layout)
# Expand swaps
dag_unroller = DagUnroller(dag, DAGBackend(basis))
dag = dag_unroller.expand_gates()
# Change cx directions
dag = direction_mapper(dag, coupling)
# Simplify cx gates
cx_cancellation(dag)
# Simplify single qubit gates
dag = optimize_1q_gates(dag)
return_last_measurements(dag, removed_meas,
last_layout)
logger.info("post-mapping properties: %s",
dag.property_summary())
# choose output format
# TODO: do we need all of these formats, or just the dag?
if format == 'dag':
compiled_circuit = dag
elif format == 'json':
# FIXME: JsonBackend is wrongly taking an ordered dict as basis, not list
dag_unroller = DagUnroller(dag, JsonBackend(dag.basis))
compiled_circuit = dag_unroller.execute()
elif format == 'qasm':
compiled_circuit = dag.qasm()
else:
raise TranspilerError('unrecognized circuit format')
if get_layout:
return compiled_circuit, final_layout
return compiled_circuit
def _best_subset(backend, n_qubits):
"""Computes the qubit mapping with the best
connectivity.
Parameters:
backend (Qiskit.BaseBackend): A QISKit backend instance.
n_qubits (int): Number of subset qubits to consider.
Returns:
ndarray: Array of qubits to use for best
connectivity mapping.
Raises:
QISKitError: Wrong number of qubits given.
"""
if n_qubits == 1:
return np.array([0])
elif n_qubits <= 0:
raise QISKitError('Number of qubits <= 0.')
device_qubits = backend.configuration()['n_qubits']
if n_qubits > device_qubits:
raise QISKitError('Number of qubits greater than device.')
cmap = np.asarray(backend.configuration()['coupling_map'])
data = np.ones_like(cmap[:, 0])
sp_cmap = sp.coo_matrix((data, (cmap[:, 0], cmap[:, 1])),
shape=(device_qubits, device_qubits)).tocsr()
best = 0
best_map = None
# do bfs with each node as starting point
for k in range(sp_cmap.shape[0]):
bfs = cs.breadth_first_order(sp_cmap, i_start=k, directed=False,
return_predecessors=False)
connection_count = 0
for i in range(n_qubits):
node_idx = bfs[i]
for j in range(sp_cmap.indptr[node_idx],
sp_cmap.indptr[node_idx + 1]):
node = sp_cmap.indices[j]
for counter in range(n_qubits):
if node == bfs[counter]:
connection_count += 1
break
if connection_count > best:
best = connection_count
best_map = bfs[0:n_qubits]
return best_map
def _matches_coupling_map(dag, coupling_map):
"""Iterate over circuit gates to check if all multi-qubit couplings
match the qubit coupling graph in the backend.
Parameters:
dag (DAGCircuit): DAG representation of circuit.
coupling_map (list): Backend coupling map, represented as an adjacency list.
Returns:
bool: True if all gates readily fit the backend coupling graph.
False if there's at least one gate that uses multiple qubits
which does not match the backend couplings.
"""
match = True
for _, data in dag.multi_graph.nodes(data=True):
if data['type'] == 'op':
gate_map = [qr[1] for qr in data['qargs']]
if len(gate_map) > 1:
if gate_map not in coupling_map:
match = False
break
return match
def _pick_best_layout(dag, backend):
"""Pick a convenient layout depending on the best matching qubit connectivity
Parameters:
dag (DAGCircuit): DAG representation of circuit.
backend (BaseBackend) : The backend with the coupling_map for searching
Returns:
dict: A special ordered initial_layout
"""
num_qubits = sum(dag.qregs.values())
best_sub = _best_subset(backend, num_qubits)
layout = {}
map_iter = 0
for key, value in dag.qregs.items():
for i in range(value):
layout[(key, i)] = ('q', best_sub[map_iter])
map_iter += 1
return layout
<|code_end|>
|
Default circuit names are not zero-based
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: latest
- **Python version**: 3.7
- **Operating system**: OSX
### What is the current behavior?
When creating a quantum circuit with no name, the default name is set to `circuitX`. Currently, `X` starts from `1` rather than `0`, and can cause some confusion when trying to index circuits by name.
### Steps to reproduce the problem
```python
from qiskit import *
q = QuantumRegister(2, "q")
c = ClassicalRegister(2, "c")
# Create measurement subcircuit
qc = QuantumCircuit(q,c)
qc.name
```
gives `'circuit1'` for the initial circuit created. It should be `'circuit0'` to coincide with the the indexing in Python.
### What is the expected behavior?
### Suggested solutions
|
qiskit/_quantumcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Quantum circuit object.
"""
import itertools
from collections import OrderedDict
from ._qiskiterror import QISKitError
from ._register import Register
from ._quantumregister import QuantumRegister
from ._classicalregister import ClassicalRegister
from ._measure import Measure
from ._reset import Reset
from ._instructionset import InstructionSet
class QuantumCircuit(object):
"""Quantum circuit."""
instances = 0
prefix = 'circuit'
# Class variable OPENQASM header
header = "OPENQASM 2.0;"
# Class variable with gate definitions
# This is a dict whose values are dicts with the
# following keys:
# "print" = True or False
# "opaque" = True or False
# "n_args" = number of real parameters
# "n_bits" = number of qubits
# "args" = list of parameter names
# "bits" = list of qubit names
# "body" = GateBody AST node
definitions = OrderedDict()
def __init__(self, *regs, name=None):
"""Create a new circuit.
Args:
*regs (Registers): registers to include in the circuit.
name (str or None): the name of the quantum circuit. If
None, an automatically generated identifier will be
assigned.
Raises:
QISKitError: if the circuit name, if given, is not valid.
"""
self._increment_instances()
if name is None:
name = self.cls_prefix() + str(self.cls_instances())
if not isinstance(name, str):
raise QISKitError("The circuit name should be a string "
"(or None for autogenerate a name).")
self.name = name
# Data contains a list of instructions in the order they were applied.
self.data = []
# This is a map of registers bound to this circuit, by name.
self.regs = OrderedDict()
self.add(*regs)
@classmethod
def _increment_instances(cls):
cls.instances += 1
@classmethod
def cls_instances(cls):
"""Return the current number of instances of this class,
useful for auto naming."""
return cls.instances
@classmethod
def cls_prefix(cls):
"""Return the prefix to use for auto naming."""
return cls.prefix
def has_register(self, register):
"""
Test if this circuit has the register r.
Return True or False.
"""
if register.name in self.regs:
registers = self.regs[register.name]
if registers.size == register.size:
if ((isinstance(register, QuantumRegister) and
isinstance(registers, QuantumRegister)) or
(isinstance(register, ClassicalRegister) and
isinstance(registers, ClassicalRegister))):
return True
return False
def get_qregs(self):
"""Get the qregs from the registers."""
qregs = OrderedDict()
for name, register in self.regs.items():
if isinstance(register, QuantumRegister):
qregs[name] = register
return qregs
def get_cregs(self):
"""Get the cregs from the registers."""
cregs = OrderedDict()
for name, register in self.regs.items():
if isinstance(register, ClassicalRegister):
cregs[name] = register
return cregs
def combine(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Return self + rhs as a new object.
"""
combined_registers = []
# Check registers in LHS are compatible with RHS
for name, register in self.regs.items():
if name in rhs.regs and register != rhs.regs[name]:
raise QISKitError("circuits are not compatible")
else:
combined_registers.append(register)
# Add registers in RHS not in LHS
complement_registers = set(rhs.regs) - set(self.regs)
for name in complement_registers:
combined_registers.append(rhs.regs[name])
# Make new circuit with combined registers
circuit = QuantumCircuit(*combined_registers)
for gate in itertools.chain(self.data, rhs.data):
gate.reapply(circuit)
return circuit
def extend(self, rhs):
"""
Append rhs to self if self if it contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Modify and return self.
"""
# Check compatibility and add new registers
for name, register in rhs.regs.items():
if name not in self.regs:
self.add(register)
elif name in self.regs and register != self.regs[name]:
raise QISKitError("circuits are not compatible")
# Add new gates
for gate in rhs.data:
gate.reapply(self)
return self
def __add__(self, rhs):
"""Overload + to implement self.concatenate."""
return self.combine(rhs)
def __iadd__(self, rhs):
"""Overload += to implement self.extend."""
return self.extend(rhs)
def __len__(self):
"""Return number of operations in circuit."""
return len(self.data)
def __getitem__(self, item):
"""Return indexed operation."""
return self.data[item]
def _attach(self, gate):
"""Attach a gate."""
self.data.append(gate)
return gate
def add(self, *regs):
"""Add registers."""
for register in regs:
if not isinstance(register, Register):
raise QISKitError("expected a register")
if register.name not in self.regs:
self.regs[register.name] = register
else:
raise QISKitError("register name \"%s\" already exists"
% register.name)
def _check_qreg(self, register):
"""Raise exception if r is not in this circuit or not qreg."""
if not isinstance(register, QuantumRegister):
raise QISKitError("expected quantum register")
if not self.has_register(register):
raise QISKitError(
"register '%s' not in this circuit" %
register.name)
def _check_qubit(self, qubit):
"""Raise exception if qubit is not in this circuit or bad format."""
if not isinstance(qubit, tuple):
raise QISKitError("%s is not a tuple."
"A qubit should be formated as a tuple." % str(qubit))
if not len(qubit) == 2:
raise QISKitError("%s is not a tuple with two elements, but %i instead" % len(qubit))
if not isinstance(qubit[1], int):
raise QISKitError("The second element of a tuple defining a qubit should be an int:"
"%s was found instead" % type(qubit[1]).__name__)
self._check_qreg(qubit[0])
qubit[0].check_range(qubit[1])
def _check_creg(self, register):
"""Raise exception if r is not in this circuit or not creg."""
if not isinstance(register, ClassicalRegister):
raise QISKitError("expected classical register")
if not self.has_register(register):
raise QISKitError(
"register '%s' not in this circuit" %
register.name)
def _check_dups(self, qubits):
"""Raise exception if list of qubits contains duplicates."""
squbits = set(qubits)
if len(squbits) != len(qubits):
raise QISKitError("duplicate qubit arguments")
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.definitions[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.definitions[name]["n_args"] > 0:
out += "(" + ",".join(self.definitions[name]["args"]) + ")"
out += " " + ",".join(self.definitions[name]["bits"])
if self.definitions[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.definitions[name]["body"].qasm() + "}\n"
return out
def qasm(self):
"""Return OPENQASM string."""
string_temp = self.header + "\n"
for gate_name in self.definitions:
if self.definitions[gate_name]["print"]:
string_temp += self._gate_string(gate_name)
for register in self.regs.values():
string_temp += register.qasm() + "\n"
for instruction in self.data:
string_temp += instruction.qasm() + "\n"
return string_temp
def measure(self, qubit, cbit):
"""Measure quantum bit into classical bit (tuples).
Returns:
qiskit.Gate: the attached measure gate.
Raises:
QISKitError: if qubit is not in this circuit or bad format;
if cbit is not in this circuit or not creg.
"""
if isinstance(qubit, QuantumRegister) and \
isinstance(cbit, ClassicalRegister) and len(qubit) == len(cbit):
instructions = InstructionSet()
for i in range(qubit.size):
instructions.add(self.measure((qubit, i), (cbit, i)))
return instructions
self._check_qubit(qubit)
self._check_creg(cbit[0])
cbit[0].check_range(cbit[1])
return self._attach(Measure(qubit, cbit, self))
def reset(self, quantum_register):
"""Reset q."""
if isinstance(quantum_register, QuantumRegister):
instructions = InstructionSet()
for sizes in range(quantum_register.size):
instructions.add(self.reset((quantum_register, sizes)))
return instructions
self._check_qubit(quantum_register)
return self._attach(Reset(quantum_register, self))
<|code_end|>
|
qiskit/_quantumcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Quantum circuit object.
"""
import itertools
from collections import OrderedDict
from ._qiskiterror import QISKitError
from ._register import Register
from ._quantumregister import QuantumRegister
from ._classicalregister import ClassicalRegister
from ._measure import Measure
from ._reset import Reset
from ._instructionset import InstructionSet
class QuantumCircuit(object):
"""Quantum circuit."""
instances = 0
prefix = 'circuit'
# Class variable OPENQASM header
header = "OPENQASM 2.0;"
# Class variable with gate definitions
# This is a dict whose values are dicts with the
# following keys:
# "print" = True or False
# "opaque" = True or False
# "n_args" = number of real parameters
# "n_bits" = number of qubits
# "args" = list of parameter names
# "bits" = list of qubit names
# "body" = GateBody AST node
definitions = OrderedDict()
def __init__(self, *regs, name=None):
"""Create a new circuit.
Args:
*regs (Registers): registers to include in the circuit.
name (str or None): the name of the quantum circuit. If
None, an automatically generated identifier will be
assigned.
Raises:
QISKitError: if the circuit name, if given, is not valid.
"""
if name is None:
name = self.cls_prefix() + str(self.cls_instances())
self._increment_instances()
if not isinstance(name, str):
raise QISKitError("The circuit name should be a string "
"(or None for autogenerate a name).")
self.name = name
# Data contains a list of instructions in the order they were applied.
self.data = []
# This is a map of registers bound to this circuit, by name.
self.regs = OrderedDict()
self.add(*regs)
@classmethod
def _increment_instances(cls):
cls.instances += 1
@classmethod
def cls_instances(cls):
"""Return the current number of instances of this class,
useful for auto naming."""
return cls.instances
@classmethod
def cls_prefix(cls):
"""Return the prefix to use for auto naming."""
return cls.prefix
def has_register(self, register):
"""
Test if this circuit has the register r.
Return True or False.
"""
if register.name in self.regs:
registers = self.regs[register.name]
if registers.size == register.size:
if ((isinstance(register, QuantumRegister) and
isinstance(registers, QuantumRegister)) or
(isinstance(register, ClassicalRegister) and
isinstance(registers, ClassicalRegister))):
return True
return False
def get_qregs(self):
"""Get the qregs from the registers."""
qregs = OrderedDict()
for name, register in self.regs.items():
if isinstance(register, QuantumRegister):
qregs[name] = register
return qregs
def get_cregs(self):
"""Get the cregs from the registers."""
cregs = OrderedDict()
for name, register in self.regs.items():
if isinstance(register, ClassicalRegister):
cregs[name] = register
return cregs
def combine(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Return self + rhs as a new object.
"""
combined_registers = []
# Check registers in LHS are compatible with RHS
for name, register in self.regs.items():
if name in rhs.regs and register != rhs.regs[name]:
raise QISKitError("circuits are not compatible")
else:
combined_registers.append(register)
# Add registers in RHS not in LHS
complement_registers = set(rhs.regs) - set(self.regs)
for name in complement_registers:
combined_registers.append(rhs.regs[name])
# Make new circuit with combined registers
circuit = QuantumCircuit(*combined_registers)
for gate in itertools.chain(self.data, rhs.data):
gate.reapply(circuit)
return circuit
def extend(self, rhs):
"""
Append rhs to self if self if it contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Modify and return self.
"""
# Check compatibility and add new registers
for name, register in rhs.regs.items():
if name not in self.regs:
self.add(register)
elif name in self.regs and register != self.regs[name]:
raise QISKitError("circuits are not compatible")
# Add new gates
for gate in rhs.data:
gate.reapply(self)
return self
def __add__(self, rhs):
"""Overload + to implement self.concatenate."""
return self.combine(rhs)
def __iadd__(self, rhs):
"""Overload += to implement self.extend."""
return self.extend(rhs)
def __len__(self):
"""Return number of operations in circuit."""
return len(self.data)
def __getitem__(self, item):
"""Return indexed operation."""
return self.data[item]
def _attach(self, gate):
"""Attach a gate."""
self.data.append(gate)
return gate
def add(self, *regs):
"""Add registers."""
for register in regs:
if not isinstance(register, Register):
raise QISKitError("expected a register")
if register.name not in self.regs:
self.regs[register.name] = register
else:
raise QISKitError("register name \"%s\" already exists"
% register.name)
def _check_qreg(self, register):
"""Raise exception if r is not in this circuit or not qreg."""
if not isinstance(register, QuantumRegister):
raise QISKitError("expected quantum register")
if not self.has_register(register):
raise QISKitError(
"register '%s' not in this circuit" %
register.name)
def _check_qubit(self, qubit):
"""Raise exception if qubit is not in this circuit or bad format."""
if not isinstance(qubit, tuple):
raise QISKitError("%s is not a tuple."
"A qubit should be formated as a tuple." % str(qubit))
if not len(qubit) == 2:
raise QISKitError("%s is not a tuple with two elements, but %i instead" % len(qubit))
if not isinstance(qubit[1], int):
raise QISKitError("The second element of a tuple defining a qubit should be an int:"
"%s was found instead" % type(qubit[1]).__name__)
self._check_qreg(qubit[0])
qubit[0].check_range(qubit[1])
def _check_creg(self, register):
"""Raise exception if r is not in this circuit or not creg."""
if not isinstance(register, ClassicalRegister):
raise QISKitError("expected classical register")
if not self.has_register(register):
raise QISKitError(
"register '%s' not in this circuit" %
register.name)
def _check_dups(self, qubits):
"""Raise exception if list of qubits contains duplicates."""
squbits = set(qubits)
if len(squbits) != len(qubits):
raise QISKitError("duplicate qubit arguments")
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.definitions[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.definitions[name]["n_args"] > 0:
out += "(" + ",".join(self.definitions[name]["args"]) + ")"
out += " " + ",".join(self.definitions[name]["bits"])
if self.definitions[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.definitions[name]["body"].qasm() + "}\n"
return out
def qasm(self):
"""Return OPENQASM string."""
string_temp = self.header + "\n"
for gate_name in self.definitions:
if self.definitions[gate_name]["print"]:
string_temp += self._gate_string(gate_name)
for register in self.regs.values():
string_temp += register.qasm() + "\n"
for instruction in self.data:
string_temp += instruction.qasm() + "\n"
return string_temp
def measure(self, qubit, cbit):
"""Measure quantum bit into classical bit (tuples).
Returns:
qiskit.Gate: the attached measure gate.
Raises:
QISKitError: if qubit is not in this circuit or bad format;
if cbit is not in this circuit or not creg.
"""
if isinstance(qubit, QuantumRegister) and \
isinstance(cbit, ClassicalRegister) and len(qubit) == len(cbit):
instructions = InstructionSet()
for i in range(qubit.size):
instructions.add(self.measure((qubit, i), (cbit, i)))
return instructions
self._check_qubit(qubit)
self._check_creg(cbit[0])
cbit[0].check_range(cbit[1])
return self._attach(Measure(qubit, cbit, self))
def reset(self, quantum_register):
"""Reset q."""
if isinstance(quantum_register, QuantumRegister):
instructions = InstructionSet()
for sizes in range(quantum_register.size):
instructions.add(self.reset((quantum_register, sizes)))
return instructions
self._check_qubit(quantum_register)
return self._attach(Reset(quantum_register, self))
<|code_end|>
|
DAG visualization dependence on graphviz is not mentioned
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: latest
- **Python version**: 3.7
- **Operating system**: OSX
### What is the current behavior?
Calling `dag_drawer(dag)` gives the error:
```python
InvocationException: GraphViz's executables not found
```
indicating that `GraphViz` is a requirement for this function, but it is not listed anywhere.
### Steps to reproduce the problem
### What is the expected behavior?
### Suggested solutions
|
qiskit/tools/visualization/_dag_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""
Visualization function for DAG circuit representation.
"""
import sys
import copy
import nxpd
from ._error import VisualizationError
def dag_drawer(dag, scale=0.7, filename=None, style='color'):
"""Plot the directed acyclic graph (dag) to represent operation dependencies
in a quantum circuit.
Args:
dag (DAGCircuit): The dag to draw.
scale (float): scaling factor
filename (str): file path to save image to (format inferred from name)
style (str): 'plain': B&W graph
'color' (default): color input/output/op nodes
Returns:
Ipython.display.Image: if in Jupyter notebook and not saving to file,
otherwise None.
Raises:
VisualizationError: when style is not recognized.
"""
G = copy.deepcopy(dag.multi_graph) # don't modify the original graph attributes
G.graph['dpi'] = 100 * scale
if style == 'plain':
pass
elif style == 'color':
for node in G.nodes:
n = G.nodes[node]
if n['type'] == 'op':
n['label'] = str(n['name'])
n['color'] = 'blue'
n['style'] = 'filled'
n['fillcolor'] = 'lightblue'
if n['type'] == 'in':
n['label'] = n['name'][0] + '[' + str(n['name'][1]) + ']'
n['color'] = 'black'
n['style'] = 'filled'
n['fillcolor'] = 'green'
if n['type'] == 'out':
n['label'] = n['name'][0] + '[' + str(n['name'][1]) + ']'
n['color'] = 'black'
n['style'] = 'filled'
n['fillcolor'] = 'red'
for e in G.edges(data=True):
e[2]['label'] = e[2]['name'][0] + "[" + str(e[2]['name'][1]) + "]"
else:
raise VisualizationError("Unrecognized style for the dag_drawer.")
show = nxpd.nxpdParams['show']
if filename:
show = False
elif ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
show = 'ipynb'
else:
show = True
return nxpd.draw(G, filename=filename, show=show)
<|code_end|>
|
qiskit/tools/visualization/_dag_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""
Visualization function for DAG circuit representation.
"""
import sys
import copy
import nxpd
from ._error import VisualizationError
def dag_drawer(dag, scale=0.7, filename=None, style='color'):
"""Plot the directed acyclic graph (dag) to represent operation dependencies
in a quantum circuit.
Note this function leverages
`pydot <https://github.com/erocarrera/pydot>`_ (via
`nxpd <https://github.com/chebee7i/nxpd`_) to generate the graph, which
means that having `Graphviz <https://www.graphviz.org/>`_ installed on your
system is required for this to work.
Args:
dag (DAGCircuit): The dag to draw.
scale (float): scaling factor
filename (str): file path to save image to (format inferred from name)
style (str): 'plain': B&W graph
'color' (default): color input/output/op nodes
Returns:
Ipython.display.Image: if in Jupyter notebook and not saving to file,
otherwise None.
Raises:
VisualizationError: when style is not recognized.
"""
G = copy.deepcopy(dag.multi_graph) # don't modify the original graph attributes
G.graph['dpi'] = 100 * scale
if style == 'plain':
pass
elif style == 'color':
for node in G.nodes:
n = G.nodes[node]
if n['type'] == 'op':
n['label'] = str(n['name'])
n['color'] = 'blue'
n['style'] = 'filled'
n['fillcolor'] = 'lightblue'
if n['type'] == 'in':
n['label'] = n['name'][0] + '[' + str(n['name'][1]) + ']'
n['color'] = 'black'
n['style'] = 'filled'
n['fillcolor'] = 'green'
if n['type'] == 'out':
n['label'] = n['name'][0] + '[' + str(n['name'][1]) + ']'
n['color'] = 'black'
n['style'] = 'filled'
n['fillcolor'] = 'red'
for e in G.edges(data=True):
e[2]['label'] = e[2]['name'][0] + "[" + str(e[2]['name'][1]) + "]"
else:
raise VisualizationError("Unrecognized style for the dag_drawer.")
show = nxpd.nxpdParams['show']
if filename:
show = False
elif ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
show = 'ipynb'
else:
show = True
return nxpd.draw(G, filename=filename, show=show)
<|code_end|>
|
Bloch Sphere Visualization doesn't do anything with non-GUI backends
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: latest master (but should effect released versions too)
- **Python version**: 3.7
- **Operating system**: Linux
### What is the current behavior?
When calling `qiskit.tools.visualization.plot_bloch_vector()` it unconditionally calls show() on the figure to get an interactive 3d visualization of the bloch sphere for the provided vector. However if you're using a non-GUI matplotlib backend this doesn't have a user visible effect. All that happens is that matplotlib will emit a warning like:
`lib/python3.5/site-packages/matplotlib/figure.py:448: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.`
This comes up particularly if running on a system that doesn't have X or a graphical interface installed. All that happens is the warning is displayed and the script exits without failure.
### Steps to reproduce the problem
Call `qiskit.tools.visualization.plot_bloch_vector()` on a system with matplotlib configured with a non-GUI backend.
### What is the expected behavior?
The visualization is saved to disk somewhere, or the function returns the PIL.image object (or something else that represents the visualization)
### Suggested solutions
Add a filename flag and/or add a return for the function.
|
qiskit/tools/visualization/_state_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string
"""
Visualization functions for quantum states.
"""
from functools import reduce
from scipy import linalg
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
import numpy as np
from qiskit.tools.qi.pauli import pauli_group, pauli_singles
from qiskit.tools.visualization import VisualizationError
from qiskit.tools.visualization._bloch import Bloch
class Arrow3D(FancyArrowPatch):
"""Standard 3D arrow."""
def __init__(self, xs, ys, zs, *args, **kwargs):
"""Create arrow."""
FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
self._verts3d = xs, ys, zs
def draw(self, renderer):
"""Draw the arrow."""
xs3d, ys3d, zs3d = self._verts3d
xs, ys, _ = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
FancyArrowPatch.draw(self, renderer)
def plot_bloch_vector(bloch, title=""):
"""Plot the Bloch sphere.
Plot a sphere, axes, the Bloch vector, and its projections onto each axis.
Args:
bloch (list[double]): array of three elements where [<x>, <y>,<z>]
title (str): a string that represents the plot title
"""
B = Bloch()
B.add_vectors(bloch)
B.show(title=title)
def plot_state_city(rho, title=""):
"""Plot the cityscape of quantum state.
Plot two 3d bargraphs (two dimenstional) of the mixed state rho
Args:
rho (np.array[[complex]]): array of dimensions 2**n x 2**nn complex
numbers
title (str): a string that represents the plot title
"""
num = int(np.log2(len(rho)))
# get the real and imag parts of rho
datareal = np.real(rho)
dataimag = np.imag(rho)
# get the labels
column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
row_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
lx = len(datareal[0]) # Work out matrix dimensions
ly = len(datareal[:, 0])
xpos = np.arange(0, lx, 1) # Set up a mesh of positions
ypos = np.arange(0, ly, 1)
xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25)
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(lx*ly)
dx = 0.5 * np.ones_like(zpos) # width of bars
dy = dx.copy()
dzr = datareal.flatten()
dzi = dataimag.flatten()
fig = plt.figure(figsize=(8, 8))
ax1 = fig.add_subplot(2, 1, 1, projection='3d')
ax1.bar3d(xpos, ypos, zpos, dx, dy, dzr, color="g", alpha=0.5)
ax2 = fig.add_subplot(2, 1, 2, projection='3d')
ax2.bar3d(xpos, ypos, zpos, dx, dy, dzi, color="g", alpha=0.5)
ax1.set_xticks(np.arange(0.5, lx+0.5, 1))
ax1.set_yticks(np.arange(0.5, ly+0.5, 1))
ax1.axes.set_zlim3d(-1.0, 1.0001)
ax1.set_zticks(np.arange(-1, 1, 0.5))
ax1.w_xaxis.set_ticklabels(row_names, fontsize=12, rotation=45)
ax1.w_yaxis.set_ticklabels(column_names, fontsize=12, rotation=-22.5)
# ax1.set_xlabel('basis state', fontsize=12)
# ax1.set_ylabel('basis state', fontsize=12)
ax1.set_zlabel("Real[rho]")
ax2.set_xticks(np.arange(0.5, lx+0.5, 1))
ax2.set_yticks(np.arange(0.5, ly+0.5, 1))
ax2.axes.set_zlim3d(-1.0, 1.0001)
ax2.set_zticks(np.arange(-1, 1, 0.5))
ax2.w_xaxis.set_ticklabels(row_names, fontsize=12, rotation=45)
ax2.w_yaxis.set_ticklabels(column_names, fontsize=12, rotation=-22.5)
# ax2.set_xlabel('basis state', fontsize=12)
# ax2.set_ylabel('basis state', fontsize=12)
ax2.set_zlabel("Imag[rho]")
plt.title(title)
plt.show()
def plot_state_paulivec(rho, title=""):
"""Plot the paulivec representation of a quantum state.
Plot a bargraph of the mixed state rho over the pauli matricies
Args:
rho (np.array[[complex]]): array of dimensions 2**n x 2**nn complex
numbers
title (str): a string that represents the plot title
"""
num = int(np.log2(len(rho)))
labels = list(map(lambda x: x.to_label(), pauli_group(num)))
values = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_group(num)))
numelem = len(values)
ind = np.arange(numelem) # the x locations for the groups
width = 0.5 # the width of the bars
_, ax = plt.subplots()
ax.grid(zorder=0)
ax.bar(ind, values, width, color='seagreen')
# add some text for labels, title, and axes ticks
ax.set_ylabel('Expectation value', fontsize=12)
ax.set_xticks(ind)
ax.set_yticks([-1, -0.5, 0, 0.5, 1])
ax.set_xticklabels(labels, fontsize=12, rotation=70)
ax.set_xlabel('Pauli', fontsize=12)
ax.set_ylim([-1, 1])
plt.title(title)
plt.show()
def n_choose_k(n, k):
"""Return the number of combinations for n choose k.
Args:
n (int): the total number of options .
k (int): The number of elements.
Returns:
int: returns the binomial coefficient
"""
if n == 0:
return 0
return reduce(lambda x, y: x * y[0] / y[1],
zip(range(n - k + 1, n + 1),
range(1, k + 1)), 1)
def lex_index(n, k, lst):
"""Return the lex index of a combination..
Args:
n (int): the total number of options .
k (int): The number of elements.
lst (list): list
Returns:
int: returns int index for lex order
"""
assert len(lst) == k, "list should have length k"
comb = list(map(lambda x: n - 1 - x, lst))
dualm = sum([n_choose_k(comb[k - 1 - i], i + 1) for i in range(k)])
return int(dualm)
def bit_string_index(s):
"""Return the index of a string of 0s and 1s."""
n = len(s)
k = s.count("1")
assert s.count("0") == n - k, "s must be a string of 0 and 1"
ones = [pos for pos, char in enumerate(s) if char == "1"]
return lex_index(n, k, ones)
def phase_to_color_wheel(complex_number):
"""Map a phase of a complexnumber to a color in (r,g,b).
complex_number is phase is first mapped to angle in the range
[0, 2pi] and then to a color wheel with blue at zero phase.
"""
angles = np.angle(complex_number)
angle_round = int(((angles + 2 * np.pi) % (2 * np.pi))/np.pi*6)
color_map = {
0: (0, 0, 1), # blue,
1: (0.5, 0, 1), # blue-violet
2: (1, 0, 1), # violet
3: (1, 0, 0.5), # red-violet,
4: (1, 0, 0), # red
5: (1, 0.5, 0), # red-oranage,
6: (1, 1, 0), # orange
7: (0.5, 1, 0), # orange-yellow
8: (0, 1, 0), # yellow,
9: (0, 1, 0.5), # yellow-green,
10: (0, 1, 1), # green,
11: (0, 0.5, 1) # green-blue,
}
return color_map[angle_round]
def plot_state_qsphere(rho):
"""Plot the qsphere representation of a quantum state."""
num = int(np.log2(len(rho)))
# get the eigenvectors and egivenvalues
we, stateall = linalg.eigh(rho)
for k in range(2**num):
# start with the max
probmix = we.max()
prob_location = we.argmax()
if probmix > 0.001:
print("The " + str(k) + "th eigenvalue = " + str(probmix))
# get the max eigenvalue
state = stateall[:, prob_location]
loc = np.absolute(state).argmax()
# get the element location closes to lowest bin representation.
for j in range(2**num):
test = np.absolute(np.absolute(state[j]) -
np.absolute(state[loc]))
if test < 0.001:
loc = j
break
# remove the global phase
angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi)
angleset = np.exp(-1j*angles)
# print(state)
# print(angles)
state = angleset*state
# print(state)
state.flatten()
# start the plotting
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')
ax.axes.set_xlim3d(-1.0, 1.0)
ax.axes.set_ylim3d(-1.0, 1.0)
ax.axes.set_zlim3d(-1.0, 1.0)
ax.set_aspect("equal")
ax.axes.grid(False)
# Plot semi-transparent sphere
u = np.linspace(0, 2 * np.pi, 25)
v = np.linspace(0, np.pi, 25)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(x, y, z, rstride=1, cstride=1, color='k',
alpha=0.05, linewidth=0)
# wireframe
# Get rid of the panes
ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the spines
ax.w_xaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.w_yaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.w_zaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
d = num
for i in range(2**num):
# get x,y,z points
element = bin(i)[2:].zfill(num)
weight = element.count("1")
zvalue = -2 * weight / d + 1
number_of_divisions = n_choose_k(d, weight)
weight_order = bit_string_index(element)
# if weight_order >= number_of_divisions / 2:
# com_key = compliment(element)
# weight_order_temp = bit_string_index(com_key)
# weight_order = np.floor(
# number_of_divisions / 2) + weight_order_temp + 1
angle = weight_order * 2 * np.pi / number_of_divisions
xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle)
yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle)
ax.plot([xvalue], [yvalue], [zvalue],
markerfacecolor=(.5, .5, .5),
markeredgecolor=(.5, .5, .5),
marker='o', markersize=10, alpha=1)
# get prob and angle - prob will be shade and angle color
prob = np.real(np.dot(state[i], state[i].conj()))
colorstate = phase_to_color_wheel(state[i])
a = Arrow3D([0, xvalue], [0, yvalue], [0, zvalue],
mutation_scale=20, alpha=prob, arrowstyle="-",
color=colorstate, lw=10)
ax.add_artist(a)
# add weight lines
for weight in range(d + 1):
theta = np.linspace(-2 * np.pi, 2 * np.pi, 100)
z = -2 * weight / d + 1
r = np.sqrt(1 - z**2)
x = r * np.cos(theta)
y = r * np.sin(theta)
ax.plot(x, y, z, color=(.5, .5, .5))
# add center point
ax.plot([0], [0], [0], markerfacecolor=(.5, .5, .5),
markeredgecolor=(.5, .5, .5), marker='o', markersize=10,
alpha=1)
plt.show()
we[prob_location] = 0
else:
break
def plot_state(quantum_state, method='city'):
"""Plot the quantum state.
Args:
quantum_state (ndarray): statevector or density matrix
representation of a quantum state.
method (str): Plotting method to use.
Raises:
VisualizationError: if the input is not a statevector or density
matrix, or if the state is not an multi-qubit quantum state.
"""
# Check if input is a statevector, and convert to density matrix
rho = np.array(quantum_state)
if rho.ndim == 1:
rho = np.outer(rho, np.conj(rho))
# Check the shape of the input is a square matrix
shape = np.shape(rho)
if len(shape) != 2 or shape[0] != shape[1]:
raise VisualizationError("Input is not a valid quantum state.")
# Check state is an n-qubit state
num = int(np.log2(len(rho)))
if 2 ** num != len(rho):
raise VisualizationError("Input is not a multi-qubit quantum state.")
if method == 'city':
plot_state_city(rho)
elif method == "paulivec":
plot_state_paulivec(rho)
elif method == "qsphere":
plot_state_qsphere(rho)
elif method == "bloch":
for i in range(num):
bloch_state = list(
map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_singles(i, num)))
plot_bloch_vector(bloch_state, "qubit " + str(i))
elif method == "wigner":
plot_wigner_function(rho)
###############################################################
# Plotting Wigner functions
###############################################################
def plot_wigner_function(state, res=100):
"""Plot the equal angle slice spin Wigner function of an arbitrary
quantum state.
Args:
state (np.matrix[[complex]]):
- Matrix of 2**n x 2**n complex numbers
- State Vector of 2**n x 1 complex numbers
res (int) : number of theta and phi values in meshgrid
on sphere (creates a res x res grid of points)
References:
[1] T. Tilma, M. J. Everitt, J. H. Samson, W. J. Munro,
and K. Nemoto, Phys. Rev. Lett. 117, 180401 (2016).
[2] R. P. Rundle, P. W. Mills, T. Tilma, J. H. Samson, and
M. J. Everitt, Phys. Rev. A 96, 022117 (2017).
"""
state = np.array(state)
if state.ndim == 1:
state = np.outer(state,
state) # turns state vector to a density matrix
state = np.matrix(state)
num = int(np.log2(len(state))) # number of qubits
phi_vals = np.linspace(0, np.pi, num=res,
dtype=np.complex_)
theta_vals = np.linspace(0, 0.5*np.pi, num=res,
dtype=np.complex_) # phi and theta values for WF
w = np.empty([res, res])
harr = np.sqrt(3)
delta_su2 = np.zeros((2, 2), dtype=np.complex_)
# create the spin Wigner function
for theta in range(res):
costheta = harr*np.cos(2*theta_vals[theta])
sintheta = harr*np.sin(2*theta_vals[theta])
for phi in range(res):
delta_su2[0, 0] = 0.5*(1+costheta)
delta_su2[0, 1] = -0.5*(np.exp(2j*phi_vals[phi])*sintheta)
delta_su2[1, 0] = -0.5*(np.exp(-2j*phi_vals[phi])*sintheta)
delta_su2[1, 1] = 0.5*(1-costheta)
kernel = 1
for _ in range(num):
kernel = np.kron(kernel,
delta_su2) # creates phase point kernel
w[phi, theta] = np.real(np.trace(state*kernel)) # Wigner function
# Plot a sphere (x,y,z) with Wigner function facecolor data stored in Wc
fig = plt.figure(figsize=(11, 9))
ax = fig.gca(projection='3d')
w_max = np.amax(w)
# Color data for plotting
w_c = cm.seismic_r((w+w_max)/(2*w_max)) # color data for sphere
w_c2 = cm.seismic_r((w[0:res, int(res/2):res]+w_max)/(2*w_max)) # bottom
w_c3 = cm.seismic_r((w[int(res/4):int(3*res/4), 0:res]+w_max) /
(2*w_max)) # side
w_c4 = cm.seismic_r((w[int(res/2):res, 0:res]+w_max)/(2*w_max)) # back
u = np.linspace(0, 2 * np.pi, res)
v = np.linspace(0, np.pi, res)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones(np.size(u)), np.cos(v)) # creates a sphere mesh
ax.plot_surface(x, y, z, facecolors=w_c,
vmin=-w_max, vmax=w_max,
rcount=res, ccount=res,
linewidth=0, zorder=0.5,
antialiased=False) # plots Wigner Bloch sphere
ax.plot_surface(x[0:res, int(res/2):res],
y[0:res, int(res/2):res],
-1.5*np.ones((res, int(res/2))),
facecolors=w_c2,
vmin=-w_max, vmax=w_max,
rcount=res/2, ccount=res/2,
linewidth=0, zorder=0.5,
antialiased=False) # plots bottom reflection
ax.plot_surface(-1.5*np.ones((int(res/2), res)),
y[int(res/4):int(3*res/4), 0:res],
z[int(res/4):int(3*res/4), 0:res],
facecolors=w_c3,
vmin=-w_max, vmax=w_max,
rcount=res/2, ccount=res/2,
linewidth=0, zorder=0.5,
antialiased=False) # plots side reflection
ax.plot_surface(x[int(res/2):res, 0:res],
1.5*np.ones((int(res/2), res)),
z[int(res/2):res, 0:res],
facecolors=w_c4,
vmin=-w_max, vmax=w_max,
rcount=res/2, ccount=res/2,
linewidth=0, zorder=0.5,
antialiased=False) # plots back reflection
ax.w_xaxis.set_pane_color((0.4, 0.4, 0.4, 1.0))
ax.w_yaxis.set_pane_color((0.4, 0.4, 0.4, 1.0))
ax.w_zaxis.set_pane_color((0.4, 0.4, 0.4, 1.0))
ax.set_xticks([], [])
ax.set_yticks([], [])
ax.set_zticks([], [])
ax.grid(False)
ax.xaxis.pane.set_edgecolor('black')
ax.yaxis.pane.set_edgecolor('black')
ax.zaxis.pane.set_edgecolor('black')
ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_zlim(-1.5, 1.5)
m = cm.ScalarMappable(cmap=cm.seismic_r)
m.set_array([-w_max, w_max])
plt.colorbar(m, shrink=0.5, aspect=10)
plt.show()
def plot_wigner_curve(wigner_data, xaxis=None):
"""Plots a curve for points in phase space of the spin Wigner function.
Args:
wigner_data(np.array): an array of points to plot as a 2d curve
xaxis (np.array): the range of the x axis
"""
if not xaxis:
xaxis = np.linspace(0, len(wigner_data)-1, num=len(wigner_data))
plt.plot(xaxis, wigner_data)
plt.show()
def plot_wigner_plaquette(wigner_data, max_wigner='local'):
"""Plots plaquette of wigner function data, the plaquette will
consist of cicles each colored to match the value of the Wigner
function at the given point in phase space.
Args:
wigner_data (matrix): array of Wigner function data where the
rows are plotted along the x axis and the
columns are plotted along the y axis
max_wigner (str or float):
- 'local' puts the maximum value to maximum of the points
- 'unit' sets maximum to 1
- float for a custom maximum.
"""
wigner_data = np.matrix(wigner_data)
dim = wigner_data.shape
if max_wigner == 'local':
w_max = np.amax(wigner_data)
elif max_wigner == 'unit':
w_max = 1
else:
w_max = max_wigner # For a float input
w_max = float(w_max)
cmap = plt.cm.get_cmap('seismic_r')
xax = dim[1]-0.5
yax = dim[0]-0.5
norm = np.amax(dim)
fig = plt.figure(figsize=((xax+0.5)*6/norm, (yax+0.5)*6/norm))
ax = fig.gca()
for x in range(int(dim[1])):
for y in range(int(dim[0])):
circle = plt.Circle(
(x, y), 0.49, color=cmap((wigner_data[y, x]+w_max)/(2*w_max)))
ax.add_artist(circle)
ax.set_xlim(-1, xax+0.5)
ax.set_ylim(-1, yax+0.5)
ax.set_xticks([], [])
ax.set_yticks([], [])
m = cm.ScalarMappable(cmap=cm.seismic_r)
m.set_array([-w_max, w_max])
plt.colorbar(m, shrink=0.5, aspect=10)
plt.show()
def plot_wigner_data(wigner_data, phis=None, method=None):
"""Plots Wigner results in appropriate format.
Args:
wigner_data (numpy.array): Output returned from the wigner_data
function
phis (numpy.array): Values of phi
method (str or None): how the data is to be plotted, methods are:
point: a single point in phase space
curve: a two dimensional curve
plaquette: points plotted as circles
"""
if not method:
wig_dim = len(np.shape(wigner_data))
if wig_dim == 1:
if np.shape(wigner_data) == 1:
method = 'point'
else:
method = 'curve'
elif wig_dim == 2:
method = 'plaquette'
if method == 'curve':
plot_wigner_curve(wigner_data, xaxis=phis)
elif method == 'plaquette':
plot_wigner_plaquette(wigner_data)
elif method == 'state':
plot_wigner_function(wigner_data)
elif method == 'point':
plot_wigner_plaquette(wigner_data)
print('point in phase space is '+str(wigner_data))
else:
print("No method given")
<|code_end|>
|
qiskit/tools/visualization/_state_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string
"""
Visualization functions for quantum states.
"""
from functools import reduce
from scipy import linalg
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
import numpy as np
from qiskit.tools.qi.pauli import pauli_group, pauli_singles
from qiskit.tools.visualization import VisualizationError
from qiskit.tools.visualization._bloch import Bloch
class Arrow3D(FancyArrowPatch):
"""Standard 3D arrow."""
def __init__(self, xs, ys, zs, *args, **kwargs):
"""Create arrow."""
FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
self._verts3d = xs, ys, zs
def draw(self, renderer):
"""Draw the arrow."""
xs3d, ys3d, zs3d = self._verts3d
xs, ys, _ = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
FancyArrowPatch.draw(self, renderer)
def plot_bloch_vector(bloch, title="", filename=None):
"""Plot the Bloch sphere.
Plot a sphere, axes, the Bloch vector, and its projections onto each axis.
Args:
bloch (list[double]): array of three elements where [<x>, <y>,<z>]
title (str): a string that represents the plot title
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
"""
B = Bloch()
B.add_vectors(bloch)
if filename:
B.save(filename)
else:
B.show(title=title)
def plot_state_city(rho, title="", filename=None):
"""Plot the cityscape of quantum state.
Plot two 3d bargraphs (two dimenstional) of the mixed state rho
Args:
rho (np.array[[complex]]): array of dimensions 2**n x 2**nn complex
numbers
title (str): a string that represents the plot title
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
"""
num = int(np.log2(len(rho)))
# get the real and imag parts of rho
datareal = np.real(rho)
dataimag = np.imag(rho)
# get the labels
column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
row_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
lx = len(datareal[0]) # Work out matrix dimensions
ly = len(datareal[:, 0])
xpos = np.arange(0, lx, 1) # Set up a mesh of positions
ypos = np.arange(0, ly, 1)
xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25)
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(lx*ly)
dx = 0.5 * np.ones_like(zpos) # width of bars
dy = dx.copy()
dzr = datareal.flatten()
dzi = dataimag.flatten()
fig = plt.figure(figsize=(8, 8))
ax1 = fig.add_subplot(2, 1, 1, projection='3d')
ax1.bar3d(xpos, ypos, zpos, dx, dy, dzr, color="g", alpha=0.5)
ax2 = fig.add_subplot(2, 1, 2, projection='3d')
ax2.bar3d(xpos, ypos, zpos, dx, dy, dzi, color="g", alpha=0.5)
ax1.set_xticks(np.arange(0.5, lx+0.5, 1))
ax1.set_yticks(np.arange(0.5, ly+0.5, 1))
ax1.axes.set_zlim3d(-1.0, 1.0001)
ax1.set_zticks(np.arange(-1, 1, 0.5))
ax1.w_xaxis.set_ticklabels(row_names, fontsize=12, rotation=45)
ax1.w_yaxis.set_ticklabels(column_names, fontsize=12, rotation=-22.5)
# ax1.set_xlabel('basis state', fontsize=12)
# ax1.set_ylabel('basis state', fontsize=12)
ax1.set_zlabel("Real[rho]")
ax2.set_xticks(np.arange(0.5, lx+0.5, 1))
ax2.set_yticks(np.arange(0.5, ly+0.5, 1))
ax2.axes.set_zlim3d(-1.0, 1.0001)
ax2.set_zticks(np.arange(-1, 1, 0.5))
ax2.w_xaxis.set_ticklabels(row_names, fontsize=12, rotation=45)
ax2.w_yaxis.set_ticklabels(column_names, fontsize=12, rotation=-22.5)
# ax2.set_xlabel('basis state', fontsize=12)
# ax2.set_ylabel('basis state', fontsize=12)
ax2.set_zlabel("Imag[rho]")
plt.title(title)
if filename:
plt.savefig(filename)
else:
plt.show()
def plot_state_paulivec(rho, title="", filename=None):
"""Plot the paulivec representation of a quantum state.
Plot a bargraph of the mixed state rho over the pauli matricies
Args:
rho (np.array[[complex]]): array of dimensions 2**n x 2**nn complex
numbers
title (str): a string that represents the plot title
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
"""
num = int(np.log2(len(rho)))
labels = list(map(lambda x: x.to_label(), pauli_group(num)))
values = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_group(num)))
numelem = len(values)
ind = np.arange(numelem) # the x locations for the groups
width = 0.5 # the width of the bars
_, ax = plt.subplots()
ax.grid(zorder=0)
ax.bar(ind, values, width, color='seagreen')
# add some text for labels, title, and axes ticks
ax.set_ylabel('Expectation value', fontsize=12)
ax.set_xticks(ind)
ax.set_yticks([-1, -0.5, 0, 0.5, 1])
ax.set_xticklabels(labels, fontsize=12, rotation=70)
ax.set_xlabel('Pauli', fontsize=12)
ax.set_ylim([-1, 1])
plt.title(title)
if filename:
plt.savefig(filename)
else:
plt.show()
def n_choose_k(n, k):
"""Return the number of combinations for n choose k.
Args:
n (int): the total number of options .
k (int): The number of elements.
Returns:
int: returns the binomial coefficient
"""
if n == 0:
return 0
return reduce(lambda x, y: x * y[0] / y[1],
zip(range(n - k + 1, n + 1),
range(1, k + 1)), 1)
def lex_index(n, k, lst):
"""Return the lex index of a combination..
Args:
n (int): the total number of options .
k (int): The number of elements.
lst (list): list
Returns:
int: returns int index for lex order
"""
assert len(lst) == k, "list should have length k"
comb = list(map(lambda x: n - 1 - x, lst))
dualm = sum([n_choose_k(comb[k - 1 - i], i + 1) for i in range(k)])
return int(dualm)
def bit_string_index(s):
"""Return the index of a string of 0s and 1s."""
n = len(s)
k = s.count("1")
assert s.count("0") == n - k, "s must be a string of 0 and 1"
ones = [pos for pos, char in enumerate(s) if char == "1"]
return lex_index(n, k, ones)
def phase_to_color_wheel(complex_number):
"""Map a phase of a complexnumber to a color in (r,g,b).
complex_number is phase is first mapped to angle in the range
[0, 2pi] and then to a color wheel with blue at zero phase.
"""
angles = np.angle(complex_number)
angle_round = int(((angles + 2 * np.pi) % (2 * np.pi))/np.pi*6)
color_map = {
0: (0, 0, 1), # blue,
1: (0.5, 0, 1), # blue-violet
2: (1, 0, 1), # violet
3: (1, 0, 0.5), # red-violet,
4: (1, 0, 0), # red
5: (1, 0.5, 0), # red-oranage,
6: (1, 1, 0), # orange
7: (0.5, 1, 0), # orange-yellow
8: (0, 1, 0), # yellow,
9: (0, 1, 0.5), # yellow-green,
10: (0, 1, 1), # green,
11: (0, 0.5, 1) # green-blue,
}
return color_map[angle_round]
def plot_state_qsphere(rho, filename=None):
"""Plot the qsphere representation of a quantum state."""
num = int(np.log2(len(rho)))
# get the eigenvectors and egivenvalues
we, stateall = linalg.eigh(rho)
for k in range(2**num):
# start with the max
probmix = we.max()
prob_location = we.argmax()
if probmix > 0.001:
print("The " + str(k) + "th eigenvalue = " + str(probmix))
# get the max eigenvalue
state = stateall[:, prob_location]
loc = np.absolute(state).argmax()
# get the element location closes to lowest bin representation.
for j in range(2**num):
test = np.absolute(np.absolute(state[j]) -
np.absolute(state[loc]))
if test < 0.001:
loc = j
break
# remove the global phase
angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi)
angleset = np.exp(-1j*angles)
# print(state)
# print(angles)
state = angleset*state
# print(state)
state.flatten()
# start the plotting
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')
ax.axes.set_xlim3d(-1.0, 1.0)
ax.axes.set_ylim3d(-1.0, 1.0)
ax.axes.set_zlim3d(-1.0, 1.0)
ax.set_aspect("equal")
ax.axes.grid(False)
# Plot semi-transparent sphere
u = np.linspace(0, 2 * np.pi, 25)
v = np.linspace(0, np.pi, 25)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(x, y, z, rstride=1, cstride=1, color='k',
alpha=0.05, linewidth=0)
# wireframe
# Get rid of the panes
ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the spines
ax.w_xaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.w_yaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.w_zaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
d = num
for i in range(2**num):
# get x,y,z points
element = bin(i)[2:].zfill(num)
weight = element.count("1")
zvalue = -2 * weight / d + 1
number_of_divisions = n_choose_k(d, weight)
weight_order = bit_string_index(element)
# if weight_order >= number_of_divisions / 2:
# com_key = compliment(element)
# weight_order_temp = bit_string_index(com_key)
# weight_order = np.floor(
# number_of_divisions / 2) + weight_order_temp + 1
angle = weight_order * 2 * np.pi / number_of_divisions
xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle)
yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle)
ax.plot([xvalue], [yvalue], [zvalue],
markerfacecolor=(.5, .5, .5),
markeredgecolor=(.5, .5, .5),
marker='o', markersize=10, alpha=1)
# get prob and angle - prob will be shade and angle color
prob = np.real(np.dot(state[i], state[i].conj()))
colorstate = phase_to_color_wheel(state[i])
a = Arrow3D([0, xvalue], [0, yvalue], [0, zvalue],
mutation_scale=20, alpha=prob, arrowstyle="-",
color=colorstate, lw=10)
ax.add_artist(a)
# add weight lines
for weight in range(d + 1):
theta = np.linspace(-2 * np.pi, 2 * np.pi, 100)
z = -2 * weight / d + 1
r = np.sqrt(1 - z**2)
x = r * np.cos(theta)
y = r * np.sin(theta)
ax.plot(x, y, z, color=(.5, .5, .5))
# add center point
ax.plot([0], [0], [0], markerfacecolor=(.5, .5, .5),
markeredgecolor=(.5, .5, .5), marker='o', markersize=10,
alpha=1)
if filename:
plt.savefig(filename)
else:
plt.show()
we[prob_location] = 0
else:
break
def plot_state(quantum_state, method='city', filename=None):
"""Plot the quantum state.
Args:
quantum_state (ndarray): statevector or density matrix
representation of a quantum state.
method (str): Plotting method to use.
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window. If
`bloch` method is used a `-n` will be added to the filename before
the extension for each qubit.
Raises:
VisualizationError: if the input is not a statevector or density
matrix, or if the state is not an multi-qubit quantum state.
"""
# Check if input is a statevector, and convert to density matrix
rho = np.array(quantum_state)
if rho.ndim == 1:
rho = np.outer(rho, np.conj(rho))
# Check the shape of the input is a square matrix
shape = np.shape(rho)
if len(shape) != 2 or shape[0] != shape[1]:
raise VisualizationError("Input is not a valid quantum state.")
# Check state is an n-qubit state
num = int(np.log2(len(rho)))
if 2 ** num != len(rho):
raise VisualizationError("Input is not a multi-qubit quantum state.")
if method == 'city':
plot_state_city(rho, filename=filename)
elif method == "paulivec":
plot_state_paulivec(rho, filename=filename)
elif method == "qsphere":
plot_state_qsphere(rho, filename=filename)
elif method == "bloch":
orig_filename = filename
for i in range(num):
if orig_filename:
filename_parts = orig_filename.split('.')
filename_parts[-2] += '-%d' % i
filename = '.'.join(filename_parts)
print(filename)
bloch_state = list(
map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_singles(i, num)))
plot_bloch_vector(bloch_state, "qubit " + str(i), filename=filename)
elif method == "wigner":
plot_wigner_function(rho, filename=filename)
###############################################################
# Plotting Wigner functions
###############################################################
def plot_wigner_function(state, res=100, filename=None):
"""Plot the equal angle slice spin Wigner function of an arbitrary
quantum state.
Args:
state (np.matrix[[complex]]):
- Matrix of 2**n x 2**n complex numbers
- State Vector of 2**n x 1 complex numbers
res (int) : number of theta and phi values in meshgrid
on sphere (creates a res x res grid of points)
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
References:
[1] T. Tilma, M. J. Everitt, J. H. Samson, W. J. Munro,
and K. Nemoto, Phys. Rev. Lett. 117, 180401 (2016).
[2] R. P. Rundle, P. W. Mills, T. Tilma, J. H. Samson, and
M. J. Everitt, Phys. Rev. A 96, 022117 (2017).
"""
state = np.array(state)
if state.ndim == 1:
state = np.outer(state,
state) # turns state vector to a density matrix
state = np.matrix(state)
num = int(np.log2(len(state))) # number of qubits
phi_vals = np.linspace(0, np.pi, num=res,
dtype=np.complex_)
theta_vals = np.linspace(0, 0.5*np.pi, num=res,
dtype=np.complex_) # phi and theta values for WF
w = np.empty([res, res])
harr = np.sqrt(3)
delta_su2 = np.zeros((2, 2), dtype=np.complex_)
# create the spin Wigner function
for theta in range(res):
costheta = harr*np.cos(2*theta_vals[theta])
sintheta = harr*np.sin(2*theta_vals[theta])
for phi in range(res):
delta_su2[0, 0] = 0.5*(1+costheta)
delta_su2[0, 1] = -0.5*(np.exp(2j*phi_vals[phi])*sintheta)
delta_su2[1, 0] = -0.5*(np.exp(-2j*phi_vals[phi])*sintheta)
delta_su2[1, 1] = 0.5*(1-costheta)
kernel = 1
for _ in range(num):
kernel = np.kron(kernel,
delta_su2) # creates phase point kernel
w[phi, theta] = np.real(np.trace(state*kernel)) # Wigner function
# Plot a sphere (x,y,z) with Wigner function facecolor data stored in Wc
fig = plt.figure(figsize=(11, 9))
ax = fig.gca(projection='3d')
w_max = np.amax(w)
# Color data for plotting
w_c = cm.seismic_r((w+w_max)/(2*w_max)) # color data for sphere
w_c2 = cm.seismic_r((w[0:res, int(res/2):res]+w_max)/(2*w_max)) # bottom
w_c3 = cm.seismic_r((w[int(res/4):int(3*res/4), 0:res]+w_max) /
(2*w_max)) # side
w_c4 = cm.seismic_r((w[int(res/2):res, 0:res]+w_max)/(2*w_max)) # back
u = np.linspace(0, 2 * np.pi, res)
v = np.linspace(0, np.pi, res)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones(np.size(u)), np.cos(v)) # creates a sphere mesh
ax.plot_surface(x, y, z, facecolors=w_c,
vmin=-w_max, vmax=w_max,
rcount=res, ccount=res,
linewidth=0, zorder=0.5,
antialiased=False) # plots Wigner Bloch sphere
ax.plot_surface(x[0:res, int(res/2):res],
y[0:res, int(res/2):res],
-1.5*np.ones((res, int(res/2))),
facecolors=w_c2,
vmin=-w_max, vmax=w_max,
rcount=res/2, ccount=res/2,
linewidth=0, zorder=0.5,
antialiased=False) # plots bottom reflection
ax.plot_surface(-1.5*np.ones((int(res/2), res)),
y[int(res/4):int(3*res/4), 0:res],
z[int(res/4):int(3*res/4), 0:res],
facecolors=w_c3,
vmin=-w_max, vmax=w_max,
rcount=res/2, ccount=res/2,
linewidth=0, zorder=0.5,
antialiased=False) # plots side reflection
ax.plot_surface(x[int(res/2):res, 0:res],
1.5*np.ones((int(res/2), res)),
z[int(res/2):res, 0:res],
facecolors=w_c4,
vmin=-w_max, vmax=w_max,
rcount=res/2, ccount=res/2,
linewidth=0, zorder=0.5,
antialiased=False) # plots back reflection
ax.w_xaxis.set_pane_color((0.4, 0.4, 0.4, 1.0))
ax.w_yaxis.set_pane_color((0.4, 0.4, 0.4, 1.0))
ax.w_zaxis.set_pane_color((0.4, 0.4, 0.4, 1.0))
ax.set_xticks([], [])
ax.set_yticks([], [])
ax.set_zticks([], [])
ax.grid(False)
ax.xaxis.pane.set_edgecolor('black')
ax.yaxis.pane.set_edgecolor('black')
ax.zaxis.pane.set_edgecolor('black')
ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_zlim(-1.5, 1.5)
m = cm.ScalarMappable(cmap=cm.seismic_r)
m.set_array([-w_max, w_max])
plt.colorbar(m, shrink=0.5, aspect=10)
if filename:
plt.savefig(filename)
else:
plt.show()
def plot_wigner_curve(wigner_data, xaxis=None, filename=None):
"""Plots a curve for points in phase space of the spin Wigner function.
Args:
wigner_data(np.array): an array of points to plot as a 2d curve
xaxis (np.array): the range of the x axis
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
"""
if not xaxis:
xaxis = np.linspace(0, len(wigner_data)-1, num=len(wigner_data))
plt.plot(xaxis, wigner_data)
if filename:
plt.savefig(filename)
else:
plt.show()
def plot_wigner_plaquette(wigner_data, max_wigner='local', filename=None):
"""Plots plaquette of wigner function data, the plaquette will
consist of cicles each colored to match the value of the Wigner
function at the given point in phase space.
Args:
wigner_data (matrix): array of Wigner function data where the
rows are plotted along the x axis and the
columns are plotted along the y axis
max_wigner (str or float):
- 'local' puts the maximum value to maximum of the points
- 'unit' sets maximum to 1
- float for a custom maximum.
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
"""
wigner_data = np.matrix(wigner_data)
dim = wigner_data.shape
if max_wigner == 'local':
w_max = np.amax(wigner_data)
elif max_wigner == 'unit':
w_max = 1
else:
w_max = max_wigner # For a float input
w_max = float(w_max)
cmap = plt.cm.get_cmap('seismic_r')
xax = dim[1]-0.5
yax = dim[0]-0.5
norm = np.amax(dim)
fig = plt.figure(figsize=((xax+0.5)*6/norm, (yax+0.5)*6/norm))
ax = fig.gca()
for x in range(int(dim[1])):
for y in range(int(dim[0])):
circle = plt.Circle(
(x, y), 0.49, color=cmap((wigner_data[y, x]+w_max)/(2*w_max)))
ax.add_artist(circle)
ax.set_xlim(-1, xax+0.5)
ax.set_ylim(-1, yax+0.5)
ax.set_xticks([], [])
ax.set_yticks([], [])
m = cm.ScalarMappable(cmap=cm.seismic_r)
m.set_array([-w_max, w_max])
plt.colorbar(m, shrink=0.5, aspect=10)
if filename:
plt.savefig(filename)
else:
plt.show()
def plot_wigner_data(wigner_data, phis=None, method=None, filename=None):
"""Plots Wigner results in appropriate format.
Args:
wigner_data (numpy.array): Output returned from the wigner_data
function
phis (numpy.array): Values of phi
method (str or None): how the data is to be plotted, methods are:
point: a single point in phase space
curve: a two dimensional curve
plaquette: points plotted as circles
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
"""
if not method:
wig_dim = len(np.shape(wigner_data))
if wig_dim == 1:
if np.shape(wigner_data) == 1:
method = 'point'
else:
method = 'curve'
elif wig_dim == 2:
method = 'plaquette'
if method == 'curve':
plot_wigner_curve(wigner_data, xaxis=phis, filename=filename)
elif method == 'plaquette':
plot_wigner_plaquette(wigner_data, filename=filename)
elif method == 'state':
plot_wigner_function(wigner_data, filename=filename)
elif method == 'point':
plot_wigner_plaquette(wigner_data, filename=filename)
print('point in phase space is '+str(wigner_data))
else:
print("No method given")
<|code_end|>
|
Barrier when reversebits circuit drawer
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**:
- **Python version**:
- **Operating system**:
### What is the current behavior?
I saw two problems when using barriers in the latex drawer.
1. When using `'reversebits': True` in the style, the barriers get messed up. The following should have barriers on quantum registers q and v:

2. The style `'plotbarrier': False` is introduced by the mpl drawer, but the latex drawer ignores it. It would be nice if this style affected both drawers.
### Steps to reproduce the problem
```
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.tools.visualization import circuit_drawer
q = QuantumRegister(3, 'q')
v = QuantumRegister(2, 'v')
c = ClassicalRegister(4, 'c')
d = ClassicalRegister(3, 'd')
circ = QuantumCircuit(q, v, c, d)
circ.x(q[0])
circ.x(q[2])
circ.x(v[1])
circ.barrier(q)
circ.barrier(v)
circ.measure(q[0], c[1])
circ.measure(q[2], d[2])
circ.measure(v[1], c[0])
circuit_drawer(circ, output='latex', scale=0.5, style={'reversebits': True, 'plotbarrier': False})
```
### What is the expected behavior?
Barrier on registers `q` and `v`
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import json
import logging
import operator
import os
import re
import subprocess
import tempfile
from collections import namedtuple, OrderedDict
from fractions import Fraction
from io import StringIO
from itertools import groupby, zip_longest
from math import fmod, isclose, ceil
import warnings
import numpy as np
from PIL import Image, ImageChops
from matplotlib import get_backend as get_matplotlib_backend, \
patches as patches, pyplot as plt
from qiskit._qiskiterror import QISKitError
from qiskit.wrapper import load_qasm_file
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization._error import VisualizationError
from qiskit.transpiler import transpile
from .text import TextDrawing
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art string
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
output (str): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if one
is not specified it will use latex and if that fails fallback to
mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect
line_length (int): sets the length of the lines generated by `text`
Returns:
PIL.Image: (outputs `latex` and `python`) an in-memory representation of
the circuit diagram.
String: (outputs `text` and `latex_source`). The ascii art or the LaTeX
source code.
Raises:
VisualizationError: when an invalid output method is selected
"""
im = None
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'"text" by default', DeprecationWarning)
try:
im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError, FileNotFoundError):
im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
else:
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename, basis=basis,
line_length=line_length)
elif output == 'latex':
im = _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
elif output == 'latex_source':
return _generate_latex_source(circuit, basis=basis,
filename=filename, scale=scale,
style=style)
elif output == 'mpl':
im = _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
else:
raise VisualizationError('Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if im and interactive:
im.show()
return im
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
class QCStyle:
def __init__(self):
self.tc = '#000000'
self.sc = '#000000'
self.lc = '#000000'
self.cc = '#778899'
self.gc = '#ffffff'
self.gt = '#000000'
self.bc = '#bdbdbd'
self.bg = '#ffffff'
self.fs = 13
self.sfs = 8
self.disptex = {
'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'
}
self.dispcol = {
'id': '#ffffff',
'u0': '#ffffff',
'u1': '#ffffff',
'u2': '#ffffff',
'u3': '#ffffff',
'x': '#ffffff',
'y': '#ffffff',
'z': '#ffffff',
'h': '#ffffff',
's': '#ffffff',
'sdg': '#ffffff',
't': '#ffffff',
'tdg': '#ffffff',
'rx': '#ffffff',
'ry': '#ffffff',
'rz': '#ffffff',
'reset': '#ffffff',
'target': '#ffffff',
'meas': '#ffffff'
}
self.latexmode = True
self.pimode = False
self.fold = 20
self.bundle = False
self.barrier = False
self.index = False
self.compress = True
self.figwidth = -1
self.dpi = 150
self.margin = [2.0, 0.0, 0.0, 0.3]
self.cline = 'doublet'
self.reverse = False
def set_style(self, dic):
self.tc = dic.get('textcolor', self.tc)
self.sc = dic.get('subtextcolor', self.sc)
self.lc = dic.get('linecolor', self.lc)
self.cc = dic.get('creglinecolor', self.cc)
self.gt = dic.get('gatetextcolor', self.tc)
self.gc = dic.get('gatefacecolor', self.gc)
self.bc = dic.get('barrierfacecolor', self.bc)
self.bg = dic.get('backgroundcolor', self.bg)
self.fs = dic.get('fontsize', self.fs)
self.sfs = dic.get('subfontsize', self.sfs)
self.disptex = dic.get('displaytext', self.disptex)
for key in self.dispcol.keys():
self.dispcol[key] = self.gc
self.dispcol = dic.get('displaycolor', self.dispcol)
self.latexmode = dic.get('latexdrawerstyle', self.latexmode)
self.pimode = dic.get('usepiformat', self.pimode)
self.fold = dic.get('fold', self.fold)
if self.fold < 2:
self.fold = -1
self.bundle = dic.get('cregbundle', self.bundle)
self.barrier = dic.get('plotbarrier', self.barrier)
self.index = dic.get('showindex', self.index)
self.compress = dic.get('compress', self.compress)
self.figwidth = dic.get('figwidth', self.figwidth)
self.dpi = dic.get('dpi', self.dpi)
self.margin = dic.get('margin', self.margin)
self.cline = dic.get('creglinestyle', self.cline)
self.reverse = dic.get('reversebits', self.reverse)
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap", line_length=None):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
basis (str): Optional. Comma-separated list of gate names
line_length (int): Optional. Sometimes, your console is too small of the drawing. Give me
you maximum line length your console supports.
Returns:
String: The drawing in a loooong string.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
text = "\n".join(TextDrawing(json_circuit).lines(line_length))
if filename:
with open(filename, mode='w', encoding="utf8") as text_file:
text_file.write(text)
return text
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to complile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def _trim(im):
"""Trim image and remove white space
"""
bg = Image.new(im.mode, im.size, im.getpixel((0, 0)))
diff = ImageChops.difference(im, bg)
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
im = im.crop(bbox)
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename, basis=basis,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
qcimg = QCircuitImage(json_circuit, scale, style=style)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, circuit, scale, style=None):
"""
Args:
circuit (dict): compiled_circuit from qobj
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
"""
# style sheet
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.circuit = circuit
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
#################################
self.header = self.circuit['header']
self.qregs = OrderedDict(_get_register_specs(
self.header['qubit_labels']))
self.qubit_list = []
for qr in self.qregs:
for i in range(self.qregs[qr]):
self.qubit_list.append((qr, i))
self.cregs = OrderedDict()
if 'clbit_labels' in self.header:
for item in self.header['clbit_labels']:
self.cregs[item[0]] = item[1]
self.clbit_list = []
cregs = self.cregs
if self._style.reverse:
self.orig_cregs = self.cregs
cregs = reversed(self.cregs)
for cr in cregs:
for i in range(self.cregs[cr]):
self.clbit_list.append((cr, i))
self.ordered_regs = [(item[0], item[1]) for
item in self.header['qubit_labels']]
if self._style.reverse:
reg_size = []
reg_labels = []
new_ordered_regs = []
for regs in self.ordered_regs:
if regs[0] in reg_labels:
continue
reg_labels.append(regs[0])
reg_size.append(len(
[x for x in self.ordered_regs if x[0] == regs[0]]))
index = 0
for size in reg_size:
new_index = index + size
for i in range(new_index - 1, index - 1, -1):
new_ordered_regs.append(self.ordered_regs[i])
index = new_index
self.ordered_regs = new_ordered_regs
if 'clbit_labels' in self.header:
for clabel in self.header['clbit_labels']:
if self._style.reverse:
for cind in reversed(range(clabel[1])):
self.ordered_regs.append((clabel[0], cind))
else:
for cind in range(clabel[1]):
self.ordered_regs.append((clabel[0], cind))
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\' + '\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
QISKitError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.circuit['instructions']:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's', 'sdg',
't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy', 'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['texparams']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, arg)
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
assert len(op['clbits']) == 1 and len(op['qubits']) == 1
if 'conditional' in op:
raise QISKitError('conditional measures currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise QISKitError('conditional reset currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
assert False, "bad node data"
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns + 1, ceil(sum_column_widths) + 4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above example,
index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _convert_mask(self, mask):
orig_clbit_list = []
for cr in self.orig_cregs:
for i in range(self.orig_cregs[cr]):
orig_clbit_list.append((cr, i))
bit_list = [(mask >> bit) & 1 for bit in range(
len(orig_clbit_list) - 1, -1, -1)]
converted_mask_list = [None] * len(bit_list)
converted_mask = 0
for pos, bit in enumerate(reversed(bit_list)):
new_pos = self.clbit_list.index(orig_clbit_list[pos])
converted_mask_list[new_pos] = bit
if None in converted_mask_list:
raise VisualizationError('Reverse mask creation failed')
converted_mask_list = list(reversed(converted_mask_list))
for bit in converted_mask_list:
converted_mask = (converted_mask << 1) | bit
return converted_mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.circuit['instructions']):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier']:
nm = op['name']
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1],
op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1],
op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
elif nm == "reset":
self._latex[pos_1][columns] = \
"\\push{\\rule{.6em}{0em}\\ket{0}\\rule{.2em}{0em}} \\qw"
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1],
op["texparams"][2])
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace('\\barrier{', '\\barrier[-0.65em]{')
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace('\\barrier{', '\\barrier[-0.65em]{')
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
assert len(op['clbits']) == 1 and \
len(op['qubits']) == 1 and \
'params' not in op, "bad operation record"
if 'conditional' in op:
assert False, "If controlled measures currently not supported."
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[item][columns - 1] = \
prev_entry.replace('\\barrier{', '\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise QISKitError('Error during Latex building: %s' %
str(e))
elif op['name'] == "barrier":
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qubits']) - 1
self._latex[start][columns] += " \\barrier{" + str(span) + "}"
else:
assert False, "bad node data"
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
if self._style.reverse:
return origin + 1
return origin - 1
def _get_register_specs(bit_labels):
"""
Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,'
'ry,rz,cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,'
'cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = MatplotlibDrawer(basis=basis, scale=scale, style=style)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
Register = namedtuple('Register', 'name index')
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=1.0, style=None):
self._ast = None
self._basis = basis
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = OrderedDict()
self._creg_dict = OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False, labelleft=False, labelright=False)
def load_qasm_file(self, filename):
circuit = load_qasm_file(filename, name='draw', basis_gates=self._basis)
self.parse_circuit(circuit)
def parse_circuit(self, circuit):
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
self._ast = transpile(dag_circuit, basis_gates=self._basis, format='json')
self._registers()
self._ops = self._ast['instructions']
def _registers(self):
# NOTE: formats of clbit and qubit are different!
header = self._ast['header']
self._creg = []
for e in header['clbit_labels']:
for i in range(e[1]):
self._creg.append(Register(name=e[0], index=i))
assert len(self._creg) == header['number_of_clbits']
self._qreg = []
for e in header['qubit_labels']:
self._qreg.append(Register(name=e[0], index=e[1]))
assert len(self._qreg) == header['number_of_qubits']
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.sc,
clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7, height=HIG * 0.7,
theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID], [qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy + 0.35 * WID], lc=self._style.cc, ls=self._style.cline)
arrowhead = patches.Polygon(((cx - 0.20 * WID, cy + 0.35 * WID),
(cx + 0.20 * WID, cy + 0.35 * WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'], ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if get_matplotlib_backend() == 'module://ipykernel.pylab.backend_inline':
# returns None when matplotlib is inline mode to prevent Jupyter
# with matplotlib inlining enabled to draw the diagram twice.
im = None
else:
# when matplotlib is not inline mode,
# self.figure.savefig is called twice because...
# ... this is needed to get the in-memory representation
with tempfile.TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, 'circuit.png')
self.figure.savefig(tmpfile, dpi=self._style.dpi,
bbox_inches='tight')
im = Image.open(tmpfile)
_trim(im)
os.remove(tmpfile)
# ... and this is needed to delegate in matplotlib the generation of
# the proper format.
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
return im
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index, 'group': reg.name}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(zip_longest(self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
self._cond['n_lines'] += 1
idx += 1
# reverse bit order
if self._style.reverse:
self._reverse_bits(self._qreg_dict)
self._reverse_bits(self._creg_dict)
def _reverse_bits(self, target_dict):
coord = {}
# grouping
for dict_ in target_dict.values():
if dict_['group'] not in coord:
coord[dict_['group']] = [dict_['y']]
else:
coord[dict_['group']].insert(0, dict_['y'])
# reverse bit order
for key in target_dict.keys():
target_dict[key]['y'] = coord[target_dict[key]['group']].pop(0)
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc, ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qubits' in op.keys():
q_idxs = op['qubits']
else:
q_idxs = []
# get creg index
if 'clbits' in op.keys():
c_idxs = op['clbits']
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied), max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] == 'barrier' and not self._style.barrier:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg corrdinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc, ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] == 'barrier':
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self._style.barrier:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise QISKitError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if isclose(fmod(abs_val, 1.0), 0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
elif 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return Fraction(i, j)
return None
<|code_end|>
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import json
import logging
import operator
import os
import re
import subprocess
import tempfile
from collections import namedtuple, OrderedDict
from fractions import Fraction
from io import StringIO
from itertools import groupby, zip_longest
from math import fmod, isclose, ceil
import warnings
import numpy as np
from PIL import Image, ImageChops
from matplotlib import get_backend as get_matplotlib_backend, \
patches as patches, pyplot as plt
from qiskit._qiskiterror import QISKitError
from qiskit.wrapper import load_qasm_file
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization._error import VisualizationError
from qiskit.transpiler import transpile
from .text import TextDrawing
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art string
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
output (str): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if one
is not specified it will use latex and if that fails fallback to
mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect
line_length (int): sets the length of the lines generated by `text`
Returns:
PIL.Image: (outputs `latex` and `python`) an in-memory representation of
the circuit diagram.
String: (outputs `text` and `latex_source`). The ascii art or the LaTeX
source code.
Raises:
VisualizationError: when an invalid output method is selected
"""
im = None
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'"text" by default', DeprecationWarning)
try:
im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError, FileNotFoundError):
im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
else:
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename, basis=basis,
line_length=line_length)
elif output == 'latex':
im = _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
elif output == 'latex_source':
return _generate_latex_source(circuit, basis=basis,
filename=filename, scale=scale,
style=style)
elif output == 'mpl':
im = _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
else:
raise VisualizationError('Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if im and interactive:
im.show()
return im
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
class QCStyle:
def __init__(self):
self.tc = '#000000'
self.sc = '#000000'
self.lc = '#000000'
self.cc = '#778899'
self.gc = '#ffffff'
self.gt = '#000000'
self.bc = '#bdbdbd'
self.bg = '#ffffff'
self.fs = 13
self.sfs = 8
self.disptex = {
'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'
}
self.dispcol = {
'id': '#ffffff',
'u0': '#ffffff',
'u1': '#ffffff',
'u2': '#ffffff',
'u3': '#ffffff',
'x': '#ffffff',
'y': '#ffffff',
'z': '#ffffff',
'h': '#ffffff',
's': '#ffffff',
'sdg': '#ffffff',
't': '#ffffff',
'tdg': '#ffffff',
'rx': '#ffffff',
'ry': '#ffffff',
'rz': '#ffffff',
'reset': '#ffffff',
'target': '#ffffff',
'meas': '#ffffff'
}
self.latexmode = True
self.pimode = False
self.fold = 20
self.bundle = False
self.barrier = False
self.index = False
self.compress = True
self.figwidth = -1
self.dpi = 150
self.margin = [2.0, 0.0, 0.0, 0.3]
self.cline = 'doublet'
self.reverse = False
def set_style(self, dic):
self.tc = dic.get('textcolor', self.tc)
self.sc = dic.get('subtextcolor', self.sc)
self.lc = dic.get('linecolor', self.lc)
self.cc = dic.get('creglinecolor', self.cc)
self.gt = dic.get('gatetextcolor', self.tc)
self.gc = dic.get('gatefacecolor', self.gc)
self.bc = dic.get('barrierfacecolor', self.bc)
self.bg = dic.get('backgroundcolor', self.bg)
self.fs = dic.get('fontsize', self.fs)
self.sfs = dic.get('subfontsize', self.sfs)
self.disptex = dic.get('displaytext', self.disptex)
for key in self.dispcol.keys():
self.dispcol[key] = self.gc
self.dispcol = dic.get('displaycolor', self.dispcol)
self.latexmode = dic.get('latexdrawerstyle', self.latexmode)
self.pimode = dic.get('usepiformat', self.pimode)
self.fold = dic.get('fold', self.fold)
if self.fold < 2:
self.fold = -1
self.bundle = dic.get('cregbundle', self.bundle)
self.barrier = dic.get('plotbarrier', self.barrier)
self.index = dic.get('showindex', self.index)
self.compress = dic.get('compress', self.compress)
self.figwidth = dic.get('figwidth', self.figwidth)
self.dpi = dic.get('dpi', self.dpi)
self.margin = dic.get('margin', self.margin)
self.cline = dic.get('creglinestyle', self.cline)
self.reverse = dic.get('reversebits', self.reverse)
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap", line_length=None):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
basis (str): Optional. Comma-separated list of gate names
line_length (int): Optional. Sometimes, your console is too small of the drawing. Give me
you maximum line length your console supports.
Returns:
String: The drawing in a loooong string.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
text = "\n".join(TextDrawing(json_circuit).lines(line_length))
if filename:
with open(filename, mode='w', encoding="utf8") as text_file:
text_file.write(text)
return text
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to complile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def _trim(im):
"""Trim image and remove white space
"""
bg = Image.new(im.mode, im.size, im.getpixel((0, 0)))
diff = ImageChops.difference(im, bg)
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
im = im.crop(bbox)
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename, basis=basis,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
qcimg = QCircuitImage(json_circuit, scale, style=style)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, circuit, scale, style=None):
"""
Args:
circuit (dict): compiled_circuit from qobj
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
"""
# style sheet
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.circuit = circuit
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
#################################
self.header = self.circuit['header']
self.qregs = OrderedDict(_get_register_specs(
self.header['qubit_labels']))
self.qubit_list = []
for qr in self.qregs:
for i in range(self.qregs[qr]):
self.qubit_list.append((qr, i))
self.cregs = OrderedDict()
if 'clbit_labels' in self.header:
for item in self.header['clbit_labels']:
self.cregs[item[0]] = item[1]
self.clbit_list = []
cregs = self.cregs
if self._style.reverse:
self.orig_cregs = self.cregs
cregs = reversed(self.cregs)
for cr in cregs:
for i in range(self.cregs[cr]):
self.clbit_list.append((cr, i))
self.ordered_regs = [(item[0], item[1]) for
item in self.header['qubit_labels']]
if self._style.reverse:
reg_size = []
reg_labels = []
new_ordered_regs = []
for regs in self.ordered_regs:
if regs[0] in reg_labels:
continue
reg_labels.append(regs[0])
reg_size.append(len(
[x for x in self.ordered_regs if x[0] == regs[0]]))
index = 0
for size in reg_size:
new_index = index + size
for i in range(new_index - 1, index - 1, -1):
new_ordered_regs.append(self.ordered_regs[i])
index = new_index
self.ordered_regs = new_ordered_regs
if 'clbit_labels' in self.header:
for clabel in self.header['clbit_labels']:
if self._style.reverse:
for cind in reversed(range(clabel[1])):
self.ordered_regs.append((clabel[0], cind))
else:
for cind in range(clabel[1]):
self.ordered_regs.append((clabel[0], cind))
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\' + '\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
QISKitError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.circuit['instructions']:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's', 'sdg',
't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy', 'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['texparams']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, arg)
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
assert len(op['clbits']) == 1 and len(op['qubits']) == 1
if 'conditional' in op:
raise QISKitError('conditional measures currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise QISKitError('conditional reset currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
assert False, "bad node data"
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns + 1, ceil(sum_column_widths) + 4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above example,
index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _convert_mask(self, mask):
orig_clbit_list = []
for cr in self.orig_cregs:
for i in range(self.orig_cregs[cr]):
orig_clbit_list.append((cr, i))
bit_list = [(mask >> bit) & 1 for bit in range(
len(orig_clbit_list) - 1, -1, -1)]
converted_mask_list = [None] * len(bit_list)
converted_mask = 0
for pos, bit in enumerate(reversed(bit_list)):
new_pos = self.clbit_list.index(orig_clbit_list[pos])
converted_mask_list[new_pos] = bit
if None in converted_mask_list:
raise VisualizationError('Reverse mask creation failed')
converted_mask_list = list(reversed(converted_mask_list))
for bit in converted_mask_list:
converted_mask = (converted_mask << 1) | bit
return converted_mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.circuit['instructions']):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier']:
nm = op['name']
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1],
op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1],
op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
elif nm == "reset":
self._latex[pos_1][columns] = \
"\\push{\\rule{.6em}{0em}\\ket{0}\\rule{.2em}{0em}} \\qw"
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1],
op["texparams"][2])
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace('\\barrier{', '\\barrier[-0.65em]{')
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace('\\barrier{', '\\barrier[-0.65em]{')
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
assert len(op['clbits']) == 1 and \
len(op['qubits']) == 1 and \
'params' not in op, "bad operation record"
if 'conditional' in op:
assert False, "If controlled measures currently not supported."
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[item][columns - 1] = \
prev_entry.replace('\\barrier{', '\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise QISKitError('Error during Latex building: %s' %
str(e))
elif op['name'] == "barrier":
qarglist = [self.qubit_list[i] for i in op['qubits']]
if self._style.reverse:
qarglist = list(reversed(qarglist))
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qubits']) - 1
self._latex[start][columns] += " \\barrier{" + str(span) + "}"
else:
assert False, "bad node data"
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
if self._style.reverse:
return origin + 1
return origin - 1
def _get_register_specs(bit_labels):
"""
Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,'
'ry,rz,cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,'
'cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = MatplotlibDrawer(basis=basis, scale=scale, style=style)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
Register = namedtuple('Register', 'name index')
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=1.0, style=None):
self._ast = None
self._basis = basis
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = OrderedDict()
self._creg_dict = OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False, labelleft=False, labelright=False)
def load_qasm_file(self, filename):
circuit = load_qasm_file(filename, name='draw', basis_gates=self._basis)
self.parse_circuit(circuit)
def parse_circuit(self, circuit):
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
self._ast = transpile(dag_circuit, basis_gates=self._basis, format='json')
self._registers()
self._ops = self._ast['instructions']
def _registers(self):
# NOTE: formats of clbit and qubit are different!
header = self._ast['header']
self._creg = []
for e in header['clbit_labels']:
for i in range(e[1]):
self._creg.append(Register(name=e[0], index=i))
assert len(self._creg) == header['number_of_clbits']
self._qreg = []
for e in header['qubit_labels']:
self._qreg.append(Register(name=e[0], index=e[1]))
assert len(self._qreg) == header['number_of_qubits']
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.sc,
clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7, height=HIG * 0.7,
theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID], [qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy + 0.35 * WID], lc=self._style.cc, ls=self._style.cline)
arrowhead = patches.Polygon(((cx - 0.20 * WID, cy + 0.35 * WID),
(cx + 0.20 * WID, cy + 0.35 * WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'], ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID], [ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if get_matplotlib_backend() == 'module://ipykernel.pylab.backend_inline':
# returns None when matplotlib is inline mode to prevent Jupyter
# with matplotlib inlining enabled to draw the diagram twice.
im = None
else:
# when matplotlib is not inline mode,
# self.figure.savefig is called twice because...
# ... this is needed to get the in-memory representation
with tempfile.TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, 'circuit.png')
self.figure.savefig(tmpfile, dpi=self._style.dpi,
bbox_inches='tight')
im = Image.open(tmpfile)
_trim(im)
os.remove(tmpfile)
# ... and this is needed to delegate in matplotlib the generation of
# the proper format.
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
return im
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index, 'group': reg.name}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(zip_longest(self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {'y': pos, 'label': label, 'index': reg.index,
'group': reg.name}
self._cond['n_lines'] += 1
idx += 1
# reverse bit order
if self._style.reverse:
self._reverse_bits(self._qreg_dict)
self._reverse_bits(self._creg_dict)
def _reverse_bits(self, target_dict):
coord = {}
# grouping
for dict_ in target_dict.values():
if dict_['group'] not in coord:
coord[dict_['group']] = [dict_['y']]
else:
coord[dict_['group']].insert(0, dict_['y'])
# reverse bit order
for key in target_dict.keys():
target_dict[key]['y'] = coord[target_dict[key]['group']].pop(0)
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc, ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qubits' in op.keys():
q_idxs = op['qubits']
else:
q_idxs = []
# get creg index
if 'clbits' in op.keys():
c_idxs = op['clbits']
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied), max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] == 'barrier' and not self._style.barrier:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg corrdinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc, ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] == 'barrier':
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self._style.barrier:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp, subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise QISKitError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center', va='center',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if isclose(fmod(abs_val, 1.0), 0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
elif 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return Fraction(i, j)
return None
<|code_end|>
|
Split Circuit Visualization Backends into separate modules
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
Right now we have one giant module `qiskit.tools.visualization._circuit_visualization` which contains both the public methods and the implementations for 2 different backends (mpl and latex). As part of the circuit visualization cleanup we should create a separate module for each backend `qiskit.tools.visualization._latex` and `qiskit.tools.visualization._matplotlib`. This is how we set up the text/ascii backend already. After this happens we'll just have the public interfaces (mainly circuit_drawer() and it's helper functions) living in `qiskit.tools.visualization._circuit_visualization`.
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import json
import logging
import operator
import os
import re
import subprocess
import tempfile
from collections import OrderedDict
from io import StringIO
from itertools import groupby
from math import ceil
import warnings
import numpy as np
from PIL import Image
from qiskit._qiskiterror import QISKitError
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization._error import VisualizationError
from qiskit.tools.visualization import _matplotlib
from qiskit.tools.visualization import _qcstyle
from qiskit.tools.visualization import _utils
from qiskit.transpiler import transpile
from .text import TextDrawing
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art string
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (str): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if
one is not specified it will use latex and if that fails fallback
to mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect
line_length (int): sets the length of the lines generated by `text`
Returns:
PIL.Image: (outputs `latex` and `python`) an in-memory representation of
the circuit diagram.
String: (outputs `text` and `latex_source`). The ascii art or the LaTeX
source code.
Raises:
VisualizationError: when an invalid output method is selected
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defatuls to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'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'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
plotbarrier (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
reversebits (bool): When set to True reverse the bit order inside
registers for the output visualization.
"""
im = None
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'"text" by default', DeprecationWarning)
try:
im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError, FileNotFoundError):
im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
else:
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename, basis=basis,
line_length=line_length)
elif output == 'latex':
im = _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
elif output == 'latex_source':
return _generate_latex_source(circuit, basis=basis,
filename=filename, scale=scale,
style=style)
elif output == 'mpl':
im = _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
else:
raise VisualizationError('Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if im and interactive:
im.show()
return im
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap", line_length=None):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
basis (str): Optional. Comma-separated list of gate names
line_length (int): Optional. Sometimes, your console is too small of the drawing. Give me
you maximum line length your console supports.
Returns:
String: The drawing in a loooong string.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
text = "\n".join(TextDrawing(json_circuit).lines(line_length))
if filename:
with open(filename, mode='w', encoding="utf8") as text_file:
text_file.write(text)
return text
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to complile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _utils._trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename, basis=basis,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
qcimg = QCircuitImage(json_circuit, scale, style=style)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, circuit, scale, style=None):
"""
Args:
circuit (dict): compiled_circuit from qobj
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
"""
# style sheet
self._style = _qcstyle.QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.circuit = circuit
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
#################################
self.header = self.circuit['header']
self.qregs = OrderedDict(_get_register_specs(
self.header['qubit_labels']))
self.qubit_list = []
for qr in self.qregs:
for i in range(self.qregs[qr]):
self.qubit_list.append((qr, i))
self.cregs = OrderedDict()
if 'clbit_labels' in self.header:
for item in self.header['clbit_labels']:
self.cregs[item[0]] = item[1]
self.clbit_list = []
cregs = self.cregs
if self._style.reverse:
self.orig_cregs = self.cregs
cregs = reversed(self.cregs)
for cr in cregs:
for i in range(self.cregs[cr]):
self.clbit_list.append((cr, i))
self.ordered_regs = [(item[0], item[1]) for
item in self.header['qubit_labels']]
if self._style.reverse:
reg_size = []
reg_labels = []
new_ordered_regs = []
for regs in self.ordered_regs:
if regs[0] in reg_labels:
continue
reg_labels.append(regs[0])
reg_size.append(len(
[x for x in self.ordered_regs if x[0] == regs[0]]))
index = 0
for size in reg_size:
new_index = index + size
for i in range(new_index - 1, index - 1, -1):
new_ordered_regs.append(self.ordered_regs[i])
index = new_index
self.ordered_regs = new_ordered_regs
if 'clbit_labels' in self.header:
for clabel in self.header['clbit_labels']:
if self._style.reverse:
for cind in reversed(range(clabel[1])):
self.ordered_regs.append((clabel[0], cind))
else:
for cind in range(clabel[1]):
self.ordered_regs.append((clabel[0], cind))
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\' + '\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
QISKitError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.circuit['instructions']:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's', 'sdg',
't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy', 'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['texparams']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}', _truncate_float, arg)
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
assert len(op['clbits']) == 1 and len(op['qubits']) == 1
if 'conditional' in op:
raise QISKitError('conditional measures currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise QISKitError('conditional reset currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
assert False, "bad node data"
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns + 1, ceil(sum_column_widths) + 4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above example,
index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _convert_mask(self, mask):
orig_clbit_list = []
for cr in self.orig_cregs:
for i in range(self.orig_cregs[cr]):
orig_clbit_list.append((cr, i))
bit_list = [(mask >> bit) & 1 for bit in range(
len(orig_clbit_list) - 1, -1, -1)]
converted_mask_list = [None] * len(bit_list)
converted_mask = 0
for pos, bit in enumerate(reversed(bit_list)):
new_pos = self.clbit_list.index(orig_clbit_list[pos])
converted_mask_list[new_pos] = bit
if None in converted_mask_list:
raise VisualizationError('Reverse mask creation failed')
converted_mask_list = list(reversed(converted_mask_list))
for bit in converted_mask_list:
converted_mask = (converted_mask << 1) | bit
return converted_mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.circuit['instructions']):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier']:
nm = op['name']
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1],
op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1],
op["texparams"][2])
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
elif nm == "reset":
self._latex[pos_1][columns] = \
"\\push{\\rule{.6em}{0em}\\ket{0}\\rule{.2em}{0em}} \\qw"
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{U_3(%s,%s,%s)}" \
% (op["texparams"][0], op["texparams"][1],
op["texparams"][2])
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace('\\barrier{', '\\barrier[-0.65em]{')
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace('\\barrier{', '\\barrier[-0.65em]{')
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
assert len(op['clbits']) == 1 and \
len(op['qubits']) == 1 and \
'params' not in op, "bad operation record"
if 'conditional' in op:
assert False, "If controlled measures currently not supported."
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[item][columns - 1] = \
prev_entry.replace('\\barrier{', '\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise QISKitError('Error during Latex building: %s' %
str(e))
elif op['name'] == "barrier":
if self._style.barrier:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if self._style.reverse:
qarglist = list(reversed(qarglist))
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qubits']) - 1
self._latex[start][columns] += " \\barrier{" + str(span) + "}"
else:
assert False, "bad node data"
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
if self._style.reverse:
return origin + 1
return origin - 1
def _get_register_specs(bit_labels):
"""
Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,'
'ry,rz,cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,'
'cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = _matplotlib.MatplotlibDrawer(basis=basis, scale=scale, style=style)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
<|code_end|>
qiskit/tools/visualization/_latex.py
<|code_start|><|code_end|>
qiskit/tools/visualization/text.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A module for drawing circuits in ascii art or some other text representation
"""
class DrawElement():
""" An element is an instruction or an operation that need to be drawn."""
def __init__(self, label=None):
self._width = None
self.label = self.mid_content = label
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = self.bot_connect = " "
self.top_pad = self._mid_padding = self.bot_pad = " "
self.bot_connector = {}
self.top_connector = {}
self.right_fill = self.left_fill = 0
@property
def top(self):
""" Constructs the top line of the element"""
ret = self.top_format % self.top_connect.center(
self.width - self.left_fill - self.right_fill, self.top_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.top_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.top_pad)
return ret
@property
def mid(self):
""" Constructs the middle line of the element"""
ret = self.mid_format % self.mid_content.center(
self.width - self.left_fill - self.right_fill, self._mid_padding)
if self.right_fill:
ret = ret.ljust(self.right_fill, self._mid_padding)
if self.left_fill:
ret = ret.rjust(self.left_fill, self._mid_padding)
return ret
@property
def bot(self):
""" Constructs the bottom line of the element"""
ret = self.bot_format % self.bot_connect.center(
self.width - self.left_fill - self.right_fill, self.bot_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.bot_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.bot_pad)
return ret
@property
def length(self):
""" Returns the length of the element, including the box around."""
return max(len(self.top), len(self.mid), len(self.bot))
@length.setter
def length(self, value):
""" Adjusts width so the length fits."""
self.width = value - max(
[len(getattr(self, i) % '') for i in ["bot_format", "mid_format", "top_format"]])
@property
def width(self):
""" Returns the width of the label, including padding"""
if self._width:
return self._width
return len(self.mid_content)
@width.setter
def width(self, value):
self._width = value
def connect(self, wire_char, where, label=None):
"""
Connects boxes and elements using wire_char and setting proper connectors.
Args:
wire_char (char): For example '║' or '│'.
where (list["top", "bot"]): Where the connector should be set.
label (string): Some connectors have a label (see cu1, for example).
"""
if 'top' in where:
self.top_connect = self.top_connector[
wire_char] if wire_char in self.top_connector else wire_char
if 'bot' in where:
self.bot_connect = self.bot_connector[
wire_char] if wire_char in self.bot_connector else wire_char
if label:
self.top_format = self.top_format[:-1] + (label if label else "")
class BoxOnClWire(DrawElement):
""" Draws a box on the classical wire
top: ┌───┐ ┌───────┐
mid: ╡ A ╞ ╡ A ╞
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "╡ %s ╞"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
class BoxOnQuWire(DrawElement):
""" Draws a box on the quantum wire
top: ┌───┐ ┌───────┐
mid: ┤ A ├ ┤ A ├
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "┤ %s ├"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
self.top_connector = {"│": '┴'}
self.bot_connector = {"│": '┬'}
class MeasureTo(DrawElement):
""" The element on the classic wire to which the measure is performed
top: ║ ║
mid: ═╩═ ═══╩═══
bot:
"""
def __init__(self):
super().__init__()
self.top_connect = " ║ "
self.mid_content = "═╩═"
self.bot_connect = " "
self._mid_padding = "═"
class MeasureFrom(BoxOnQuWire):
""" The element on the quantum wire in which the measure is performed
top: ┌─┐ ┌─┐
mid: ┤M├ ───┤M├───
bot: └╥┘ └╥┘
"""
def __init__(self):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = "┌─┐"
self.mid_content = "┤M├"
self.bot_connect = "└╥┘"
class MultiBox(DrawElement):
"""Elements that is draw on over multiple wires."""
def center_label(self, input_length, order):
"""
In multi-bit elements, the label is centered vertically.
Args:
input_length (int): Rhe amount of wires affected.
order (int): Which middle element is this one?
"""
location_in_the_box = '*'.center(input_length * 2 - 1).index('*') + 1
top_limit = (order - 1) * 2 + 2
bot_limit = top_limit + 2
if top_limit <= location_in_the_box < bot_limit:
if location_in_the_box == top_limit:
self.top_connect = self.label
elif location_in_the_box == top_limit + 1:
self.mid_content = self.label
else:
self.bot_connect = self.label
class BoxOnQuWireTop(MultiBox, BoxOnQuWire):
""" Draws the top part of a box that affects more than one quantum wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnQuWireMid(MultiBox, BoxOnQuWire):
""" Draws the middle part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.center_label(input_length, order)
class BoxOnQuWireBot(MultiBox, BoxOnQuWire):
""" Draws the bottom part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length):
super().__init__(label)
self.top_format = "│ %s │"
self.mid_content = self.bot_connect = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class BoxOnClWireTop(MultiBox, BoxOnClWire):
""" Draws the top part of a conditional box that affects more than one classical wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnClWireMid(MultiBox, BoxOnClWire):
""" Draws the middle part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.mid_content = label
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.top_pad = self.bot_pad = ' '
self.top_connect = self.bot_connect = self.mid_content = ''
self.center_label(input_length, order)
class BoxOnClWireBot(MultiBox, BoxOnClWire):
""" Draws the bottom part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, bot_connect='─'):
super().__init__(label)
self.top_format = "│ %s │"
self.top_pad = " "
self.bot_connect = bot_connect
self.mid_content = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class DirectOnQuWire(DrawElement):
"""
Element to the wire (without the box).
"""
def __init__(self, label=""):
super().__init__(label)
self.top_format = ' %s '
self.mid_format = '─%s─'
self.bot_format = ' %s '
self._mid_padding = '─'
class Barrier(DirectOnQuWire):
""" Draws a barrier.
top: ░ ░
mid: ─░─ ───░───
bot: ░ ░
"""
def __init__(self, label=""):
super().__init__("░")
self.top_connect = "░"
self.bot_connect = "░"
class Ex(DirectOnQuWire):
""" Draws an X (usually with a connector). E.g. the top part of a swap gate
top:
mid: ─X─ ───X───
bot: │ │
"""
def __init__(self, bot_connect=" ", top_connect=" "):
super().__init__("X")
self.bot_connect = bot_connect
self.top_connect = top_connect
class Reset(DirectOnQuWire):
""" Draws a reset gate"""
def __init__(self):
super().__init__("|0>")
class Bullet(DirectOnQuWire):
""" Draws a bullet (usuallly with a connector). E.g. the top part of a CX gate.
top:
mid: ─■─ ───■───
bot: │ │
"""
def __init__(self, top_connect=" ", bot_connect=" "):
super().__init__('■')
self.top_connect = top_connect
self.bot_connect = bot_connect
class EmptyWire(DrawElement):
""" This element is just the wire, with no instructions nor operations."""
def __init__(self, wire):
super().__init__(wire)
self._mid_padding = wire
@staticmethod
def fillup_layer(layer, first_clbit):
"""
Given a layer, replace the Nones in it with EmptyWire elements.
Args:
layer (list): The layer that contains Nones.
first_clbit (int): The first wire that is classic.
Returns:
list: The new layer, with no Nones.
"""
for nones in [i for i, x in enumerate(layer) if x is None]:
layer[nones] = EmptyWire('═') if nones >= first_clbit else EmptyWire('─')
return layer
class BreakWire(DrawElement):
""" This element is used to break the drawing in several pages."""
def __init__(self, arrow_char):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = arrow_char
self.mid_content = arrow_char
self.bot_connect = arrow_char
@staticmethod
def fillup_layer(layer_length, arrow_char):
"""
Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer.
"""
breakwire_layer = []
for _ in range(layer_length):
breakwire_layer.append(BreakWire(arrow_char))
return breakwire_layer
class InputWire(DrawElement):
""" This element is the label and the initial value of a wire."""
def __init__(self, label):
super().__init__(label)
@staticmethod
def fillup_layer(names): # pylint: disable=arguments-differ
"""
Creates a layer with InputWire elements.
Args:
names (list): List of names for the wires.
Returns:
list: The new layer
"""
longest = max([len(name) for name in names])
inputs_wires = []
for name in names:
inputs_wires.append(InputWire(name.rjust(longest)))
return inputs_wires
class TextDrawing():
""" The text drawing"""
def __init__(self, json_circuit):
self.json_circuit = json_circuit
def lines(self, line_length=None):
"""
Generates a list with lines. These lines form the text drawing.
Args:
line_length (int): Optional. When given, breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console.
Returns:
list: A list of lines with the text drawing.
"""
noqubits = self.json_circuit['header']['number_of_qubits']
layers = self.build_layers()
# TODO compress layers
# -| H |----------
# --------| H |---
# should be
# -| H |---
# -| H |---
layer_groups = [[]]
rest_of_the_line = line_length
for layerno, layer in enumerate(layers):
# Replace the Nones with EmptyWire
layers[layerno] = EmptyWire.fillup_layer(layer, noqubits)
TextDrawing.normalize_width(layer)
if line_length is None:
# does not page
layer_groups[-1].append(layer)
continue
# chop the layer to the line_length (pager)
layer_length = layers[layerno][0].length
if layer_length < rest_of_the_line:
layer_groups[-1].append(layer)
rest_of_the_line -= layer_length
else:
layer_groups[-1].append(BreakWire.fillup_layer(len(layer), '»'))
# New group
layer_groups.append([BreakWire.fillup_layer(len(layer), '«')])
rest_of_the_line = line_length - layer_groups[-1][-1][0].length
layer_groups[-1].append(
InputWire.fillup_layer(self.wire_names(with_initial_value=False)))
rest_of_the_line -= layer_groups[-1][-1][0].length
layer_groups[-1].append(layer)
rest_of_the_line -= layer_groups[-1][-1][0].length
lines = []
for layer_group in layer_groups:
wires = [i for i in zip(*layer_group)]
lines += TextDrawing.draw_wires(wires)
return lines
def wire_names(self, with_initial_value=True):
"""
Returns a list of names for each wire.
Args:
with_initial_value (bool): Optional (Default: True). If true, adds the initial value to
the name.
Returns:
List: The list of wire names.
"""
ret = []
if with_initial_value:
initial_value = {'qubit': '|0>', 'clbit': '0 '}
else:
initial_value = {'qubit': '', 'clbit': ''}
header = self.json_circuit['header']
for qubit in header['qubit_labels']:
ret.append("%s_%s: %s" % (qubit[0], qubit[1], initial_value['qubit']))
for creg in header['clbit_labels']:
for clbit in range(creg[1]):
ret.append("%s_%s: %s" % (creg[0], clbit, initial_value['clbit']))
return ret
@staticmethod
def draw_wires(wires):
"""
Given a list of wires, creates a list of lines with the text drawing.
Args:
wires (list): A list of wires with instructions.
Returns:
list: A list of lines with the text drawing.
"""
lines = []
bot_line = None
for wire in wires:
# TOP
top_line = ""
for instruction in wire:
top_line += instruction.top
if bot_line is None:
lines.append(top_line)
else:
lines.append(TextDrawing.merge_lines(lines.pop(), top_line))
# MID
mid_line = ""
for instruction in wire:
mid_line += instruction.mid
lines.append(TextDrawing.merge_lines(lines[-1], mid_line, icod="bot"))
# BOT
bot_line = ""
for instruction in wire:
bot_line += instruction.bot
lines.append(TextDrawing.merge_lines(lines[-1], bot_line, icod="bot"))
return lines
@staticmethod
def label_for_conditional(instruction):
""" Creates the label for a conditional instruction."""
return "%s %s" % ('=', instruction['conditional']['val'])
@staticmethod
def params_for_label(instruction):
"""Get the params and format them to add them to a label. None of there is no param."""
if 'params' in instruction and instruction['params']:
return ['%.5g' % i for i in instruction['params']]
return None
@staticmethod
def label_for_box(instruction):
""" Creates the label for a box."""
label = instruction['name'].capitalize()
params = TextDrawing.params_for_label(instruction)
if params:
label += "(%s)" % ','.join(params)
return label
@staticmethod
def merge_lines(top, bot, icod="top"):
"""
Merges two lines (top and bot) in the way that the overlapping make senses.
Args:
top (str): the top line
bot (str): the bottom line
icod (top or bot): in case of doubt, which line should have priority? Default: "top".
Returns:
str: The merge of both lines.
"""
ret = ""
for topc, botc in zip(top, bot):
if topc == botc:
ret += topc
elif topc in '┼╪' and botc == " ":
ret += "│"
elif topc == " ":
ret += botc
elif topc in '┬╥' and botc in " ║│":
ret += topc
elif topc in '┬│' and botc == "═":
ret += '╪'
elif topc in '┬│' and botc == "─":
ret += '┼'
elif topc in '└┘║│░' and botc == " ":
ret += topc
elif topc in '─═' and botc == " " and icod == "top":
ret += topc
elif topc in '─═' and botc == " " and icod == "bot":
ret += botc
elif topc in "║╥" and botc in "═":
ret += "╬"
elif topc in "║╥" and botc in "─":
ret += "╫"
elif topc in '╫╬' and botc in " ":
ret += "║"
elif topc == '└' and botc == "┌":
ret += "├"
elif topc == '┘' and botc == "┐":
ret += "┤"
else:
ret += botc
return ret
def clbit_index_from_mask(self, mask):
"""
Given a mask, returns a list of classical indexes affected by that mask.
Args:
mask (int): The mask.
Returns:
list: A list of indexes affected by the mask.
"""
clbit_len = self.json_circuit['header']['number_of_clbits']
bit_mask = [bool(mask & (1 << n)) for n in range(clbit_len)]
return [i for i, x in enumerate(bit_mask) if x]
@staticmethod
def normalize_width(layer):
"""
When the elements of the layer have different widths, sets the width to the max elements.
Args:
layer (list): A list of elements.
"""
instructions = [instruction for instruction in filter(lambda x: x is not None, layer)]
longest = max([instruction.length for instruction in instructions])
for instruction in instructions:
instruction.length = longest
def build_layers(self):
"""
Constructs layers.
Returns:
list: List of DrawElements.
Raises:
Exception: When the drawing is, for some reason, impossible to be drawn.
"""
layers = []
noqubits = self.json_circuit['header']['number_of_qubits']
noclbits = self.json_circuit['header']['number_of_clbits']
layers.append(InputWire.fillup_layer(self.wire_names(with_initial_value=True)))
for instruction in self.json_circuit['instructions']:
layer = Layer(noqubits, noclbits)
if instruction['name'] == 'measure':
layer.set_qubit(instruction['qubits'][0], MeasureFrom())
layer.set_clbit(instruction['clbits'][0], MeasureTo())
elif instruction['name'] == 'barrier':
# barrier
for qubit in instruction['qubits']:
layer.qubit_layer[qubit] = Barrier()
elif instruction['name'] == 'swap':
# swap
for qubit in instruction['qubits']:
layer.qubit_layer[qubit] = Ex()
layer.connect_with("│")
elif instruction['name'] == 'cswap':
# cswap
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Ex())
layer.set_qubit(instruction['qubits'][2], Ex())
layer.connect_with("│")
elif instruction['name'] == 'reset':
layer.set_qubit(instruction['qubits'][0], Reset())
elif 'conditional' in instruction:
# conditional
clbits = self.clbit_index_from_mask(int(instruction['conditional']['mask'], 16))
cllabel = TextDrawing.label_for_conditional(instruction)
qulabel = TextDrawing.label_for_box(instruction)
layer.set_cl_multibox(clbits, cllabel, top_connect='┴')
layer.set_qubit(instruction['qubits'][0], BoxOnQuWire(qulabel, bot_connect='┬'))
elif instruction['name'] in ['cx', 'CX', 'ccx']:
# cx/ccx
for qubit in [qubit for qubit in instruction['qubits'][:-1]]:
layer.set_qubit(qubit, Bullet())
layer.set_qubit(instruction['qubits'][-1], BoxOnQuWire('X'))
layer.connect_with("│")
elif instruction['name'] == 'cy':
# cy
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], BoxOnQuWire('Y'))
layer.connect_with("│")
elif instruction['name'] == 'cz':
# cz
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Bullet())
layer.connect_with("│")
elif instruction['name'] == 'ch':
# ch
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], BoxOnQuWire('H'))
layer.connect_with("│")
elif instruction['name'] == 'cu1':
# cu1
label = TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Bullet())
layer.connect_with("│", label)
elif instruction['name'] == 'cu3':
# cu3
params = TextDrawing.params_for_label(instruction)
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1],
BoxOnQuWire("U3(%s)" % ','.join(params)))
layer.connect_with("│")
elif instruction['name'] == 'crz':
# crz
label = "Rz(%s)" % TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1],
BoxOnQuWire(label))
layer.connect_with("│")
elif len(instruction['qubits']) == 1 and 'clbits' not in instruction:
# unitary gate
layer.set_qubit(instruction['qubits'][0],
BoxOnQuWire(TextDrawing.label_for_box(instruction)))
elif len(instruction['qubits']) >= 2 and 'clbits' not in instruction:
# multiple qubit gate
layer.set_qu_multibox(instruction['qubits'], TextDrawing.label_for_box(instruction))
else:
raise Exception("I don't know how to handle this instruction", instruction)
layers.append(layer.full_layer)
return layers
class Layer:
""" A layer is the "column" of the circuit. """
def __init__(self, noqubits, noclbits):
self.qubit_layer = [None] * noqubits
self.clbit_layer = [None] * noclbits
@property
def full_layer(self):
"""
Returns the composition of qubits and classic wires.
Returns:
String: self.qubit_layer + self.clbit_layer
"""
return self.qubit_layer + self.clbit_layer
def set_qubit(self, qubit, element):
"""
Sets the qubit to the element
Args:
qubit (int): Qubit index.
element (DrawElement): Element to set in the qubit
"""
self.qubit_layer[qubit] = element
def set_clbit(self, clbit, element):
"""
Sets the clbit to the element
Args:
clbit (int): Clbit index.
element (DrawElement): Element to set in the clbit
"""
self.clbit_layer[clbit] = element
def _set_multibox(self, wire_type, bits, label, top_connect=None):
# pylint: disable=invalid-name
bits = sorted(bits)
if wire_type == "cl":
set_bit = self.set_clbit
BoxOnWire = BoxOnClWire
BoxOnWireTop = BoxOnClWireTop
BoxOnWireMid = BoxOnClWireMid
BoxOnWireBot = BoxOnClWireBot
elif wire_type == "qu":
set_bit = self.set_qubit
BoxOnWire = BoxOnQuWire
BoxOnWireTop = BoxOnQuWireTop
BoxOnWireMid = BoxOnQuWireMid
BoxOnWireBot = BoxOnQuWireBot
# Checks if qubits are consecutive
if bits != [i for i in range(bits[0], bits[-1] + 1)]:
raise Exception("I don't know how to build a gate with multiple bits when"
"they are not adjacent to each other")
if len(bits) == 1:
set_bit(bits[0], BoxOnWire(label, top_connect=top_connect))
else:
set_bit(bits[0], BoxOnWireTop(label, top_connect=top_connect))
for order, bit in enumerate(bits[1:-1], 1):
set_bit(bit, BoxOnWireMid(label, len(bits), order))
set_bit(bits[-1], BoxOnWireBot(label, len(bits)))
def set_cl_multibox(self, bits, label, top_connect='┴'):
"""
Sets the multi clbit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi clbit box.
top_connect (char): The char to connect the box on the top.
"""
self._set_multibox("cl", bits, label, top_connect=top_connect)
def set_qu_multibox(self, bits, label):
"""
Sets the multi qubit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi qubit box.
"""
self._set_multibox("qu", bits, label)
def connect_with(self, wire_char, label=None):
"""
Connects the elements in the layer using wire_char.
Args:
wire_char (char): For example '║' or '│'.
label (string): Some connectors have a label (see cu1, for example).
"""
affected_bits = [bit for bit in self.full_layer if bit is not None]
affected_bits[0].connect(wire_char, ['bot'])
for affected_bit in affected_bits[1:-1]:
affected_bit.connect(wire_char, ['bot', 'top'])
affected_bits[-1].connect(wire_char, ['top'], label)
if label:
for affected_bit in affected_bits:
affected_bit.right_fill = len(label) + len(affected_bit.mid)
<|code_end|>
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import logging
import os
import subprocess
import tempfile
import warnings
from PIL import Image
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization._error import VisualizationError
from qiskit.tools.visualization import _latex
from qiskit.tools.visualization import _matplotlib
from qiskit.tools.visualization import _text
from qiskit.tools.visualization import _utils
from qiskit.transpiler import transpile
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art string
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (str): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if
one is not specified it will use latex and if that fails fallback
to mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect
line_length (int): sets the length of the lines generated by `text`
Returns:
PIL.Image: (outputs `latex` and `python`) an in-memory representation of
the circuit diagram.
String: (outputs `text` and `latex_source`). The ascii art or the LaTeX
source code.
Raises:
VisualizationError: when an invalid output method is selected
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defatuls to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'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'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
plotbarrier (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
reversebits (bool): When set to True reverse the bit order inside
registers for the output visualization.
"""
im = None
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'"text" by default', DeprecationWarning)
try:
im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError, FileNotFoundError):
im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
else:
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename, basis=basis,
line_length=line_length)
elif output == 'latex':
im = _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
elif output == 'latex_source':
return _generate_latex_source(circuit, basis=basis,
filename=filename, scale=scale,
style=style)
elif output == 'mpl':
im = _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
else:
raise VisualizationError('Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if im and interactive:
im.show()
return im
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap", line_length=None):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
basis (str): Optional. Comma-separated list of gate names
line_length (int): Optional. Sometimes, your console is too small of the drawing. Give me
you maximum line length your console supports.
Returns:
String: The drawing in a loooong string.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
text = "\n".join(_text.TextDrawing(json_circuit).lines(line_length))
if filename:
with open(filename, mode='w', encoding="utf8") as text_file:
text_file.write(text)
return text
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to complile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _utils._trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename, basis=basis,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile(dag_circuit, basis_gates=basis, format='json')
qcimg = _latex.QCircuitImage(json_circuit, scale, style=style)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,'
'ry,rz,cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,'
'cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = _matplotlib.MatplotlibDrawer(basis=basis, scale=scale, style=style)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
<|code_end|>
qiskit/tools/visualization/_latex.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""latex circuit visualization backends."""
import collections
import io
import itertools
import json
import math
import operator
import re
import numpy as np
from qiskit import _qiskiterror
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _qcstyle
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, circuit, scale, style=None):
"""
Args:
circuit (dict): compiled_circuit from qobj
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
"""
# style sheet
self._style = _qcstyle.QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.circuit = circuit
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
#################################
self.header = self.circuit['header']
self.qregs = collections.OrderedDict(_get_register_specs(
self.header['qubit_labels']))
self.qubit_list = []
for qr in self.qregs:
for i in range(self.qregs[qr]):
self.qubit_list.append((qr, i))
self.cregs = collections.OrderedDict()
if 'clbit_labels' in self.header:
for item in self.header['clbit_labels']:
self.cregs[item[0]] = item[1]
self.clbit_list = []
cregs = self.cregs
if self._style.reverse:
self.orig_cregs = self.cregs
cregs = reversed(self.cregs)
for cr in cregs:
for i in range(self.cregs[cr]):
self.clbit_list.append((cr, i))
self.ordered_regs = [(item[0], item[1]) for
item in self.header['qubit_labels']]
if self._style.reverse:
reg_size = []
reg_labels = []
new_ordered_regs = []
for regs in self.ordered_regs:
if regs[0] in reg_labels:
continue
reg_labels.append(regs[0])
reg_size.append(len(
[x for x in self.ordered_regs if x[0] == regs[0]]))
index = 0
for size in reg_size:
new_index = index + size
for i in range(new_index - 1, index - 1, -1):
new_ordered_regs.append(self.ordered_regs[i])
index = new_index
self.ordered_regs = new_ordered_regs
if 'clbit_labels' in self.header:
for clabel in self.header['clbit_labels']:
if self._style.reverse:
for cind in reversed(range(clabel[1])):
self.ordered_regs.append((clabel[0], cind))
else:
for cind in range(clabel[1]):
self.ordered_regs.append((clabel[0], cind))
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = io.StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\' + '\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
QISKitError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.circuit['instructions']:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's',
'sdg', 't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy',
'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image
# scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['texparams']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float, arg)
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
assert len(op['clbits']) == 1 and len(op['qubits']) == 1
if 'conditional' in op:
raise _qiskiterror.QISKitError(
'conditional measures currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise _qiskiterror.QISKitError(
'conditional reset currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
assert False, "bad node data"
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns + 1, math.ceil(sum_column_widths) + 4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet
# (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above
example, index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _convert_mask(self, mask):
orig_clbit_list = []
for cr in self.orig_cregs:
for i in range(self.orig_cregs[cr]):
orig_clbit_list.append((cr, i))
bit_list = [(mask >> bit) & 1 for bit in range(
len(orig_clbit_list) - 1, -1, -1)]
converted_mask_list = [None] * len(bit_list)
converted_mask = 0
for pos, bit in enumerate(reversed(bit_list)):
new_pos = self.clbit_list.index(orig_clbit_list[pos])
converted_mask_list[new_pos] = bit
if None in converted_mask_list:
raise _error.VisualizationError('Reverse mask creation failed')
converted_mask_list = list(reversed(converted_mask_list))
for bit in converted_mask_list:
converted_mask = (converted_mask << 1) | bit
return converted_mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.circuit['instructions']):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier']:
nm = op['name']
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self._style.reverse:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = (
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2]))
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = (
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2]))
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
elif nm == "reset":
self._latex[pos_1][columns] = (
"\\push{\\rule{.6em}{0em}\\ket{0}\\"
"rule{.2em}{0em}} \\qw")
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = (
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2]))
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-0.65em]{')
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(
pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-0.65em]{')
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(
pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
assert len(op['clbits']) == 1 and \
len(op['qubits']) == 1 and \
'params' not in op, "bad operation record"
if 'conditional' in op:
assert False, "If controlled measures currently not supported."
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise _qiskiterror.QISKitError(
'Error during Latex building: %s' % str(e))
elif op['name'] == "barrier":
if self._style.barrier:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if self._style.reverse:
qarglist = list(reversed(qarglist))
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qubits']) - 1
self._latex[start][columns] += " \\barrier{" + str(
span) + "}"
else:
assert False, "bad node data"
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
if self._style.reverse:
return origin + 1
return origin - 1
def _get_register_specs(bit_labels):
"""Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = itertools.groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
<|code_end|>
qiskit/tools/visualization/_text.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A module for drawing circuits in ascii art or some other text representation
"""
class DrawElement():
""" An element is an instruction or an operation that need to be drawn."""
def __init__(self, label=None):
self._width = None
self.label = self.mid_content = label
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = self.bot_connect = " "
self.top_pad = self._mid_padding = self.bot_pad = " "
self.bot_connector = {}
self.top_connector = {}
self.right_fill = self.left_fill = 0
@property
def top(self):
""" Constructs the top line of the element"""
ret = self.top_format % self.top_connect.center(
self.width - self.left_fill - self.right_fill, self.top_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.top_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.top_pad)
return ret
@property
def mid(self):
""" Constructs the middle line of the element"""
ret = self.mid_format % self.mid_content.center(
self.width - self.left_fill - self.right_fill, self._mid_padding)
if self.right_fill:
ret = ret.ljust(self.right_fill, self._mid_padding)
if self.left_fill:
ret = ret.rjust(self.left_fill, self._mid_padding)
return ret
@property
def bot(self):
""" Constructs the bottom line of the element"""
ret = self.bot_format % self.bot_connect.center(
self.width - self.left_fill - self.right_fill, self.bot_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.bot_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.bot_pad)
return ret
@property
def length(self):
""" Returns the length of the element, including the box around."""
return max(len(self.top), len(self.mid), len(self.bot))
@length.setter
def length(self, value):
""" Adjusts width so the length fits."""
self.width = value - max(
[len(getattr(self, i) % '') for i in ["bot_format", "mid_format", "top_format"]])
@property
def width(self):
""" Returns the width of the label, including padding"""
if self._width:
return self._width
return len(self.mid_content)
@width.setter
def width(self, value):
self._width = value
def connect(self, wire_char, where, label=None):
"""
Connects boxes and elements using wire_char and setting proper connectors.
Args:
wire_char (char): For example '║' or '│'.
where (list["top", "bot"]): Where the connector should be set.
label (string): Some connectors have a label (see cu1, for example).
"""
if 'top' in where:
self.top_connect = self.top_connector[
wire_char] if wire_char in self.top_connector else wire_char
if 'bot' in where:
self.bot_connect = self.bot_connector[
wire_char] if wire_char in self.bot_connector else wire_char
if label:
self.top_format = self.top_format[:-1] + (label if label else "")
class BoxOnClWire(DrawElement):
""" Draws a box on the classical wire
top: ┌───┐ ┌───────┐
mid: ╡ A ╞ ╡ A ╞
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "╡ %s ╞"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
class BoxOnQuWire(DrawElement):
""" Draws a box on the quantum wire
top: ┌───┐ ┌───────┐
mid: ┤ A ├ ┤ A ├
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "┤ %s ├"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
self.top_connector = {"│": '┴'}
self.bot_connector = {"│": '┬'}
class MeasureTo(DrawElement):
""" The element on the classic wire to which the measure is performed
top: ║ ║
mid: ═╩═ ═══╩═══
bot:
"""
def __init__(self):
super().__init__()
self.top_connect = " ║ "
self.mid_content = "═╩═"
self.bot_connect = " "
self._mid_padding = "═"
class MeasureFrom(BoxOnQuWire):
""" The element on the quantum wire in which the measure is performed
top: ┌─┐ ┌─┐
mid: ┤M├ ───┤M├───
bot: └╥┘ └╥┘
"""
def __init__(self):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = "┌─┐"
self.mid_content = "┤M├"
self.bot_connect = "└╥┘"
class MultiBox(DrawElement):
"""Elements that is draw on over multiple wires."""
def center_label(self, input_length, order):
"""
In multi-bit elements, the label is centered vertically.
Args:
input_length (int): Rhe amount of wires affected.
order (int): Which middle element is this one?
"""
location_in_the_box = '*'.center(input_length * 2 - 1).index('*') + 1
top_limit = (order - 1) * 2 + 2
bot_limit = top_limit + 2
if top_limit <= location_in_the_box < bot_limit:
if location_in_the_box == top_limit:
self.top_connect = self.label
elif location_in_the_box == top_limit + 1:
self.mid_content = self.label
else:
self.bot_connect = self.label
class BoxOnQuWireTop(MultiBox, BoxOnQuWire):
""" Draws the top part of a box that affects more than one quantum wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnQuWireMid(MultiBox, BoxOnQuWire):
""" Draws the middle part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.center_label(input_length, order)
class BoxOnQuWireBot(MultiBox, BoxOnQuWire):
""" Draws the bottom part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length):
super().__init__(label)
self.top_format = "│ %s │"
self.mid_content = self.bot_connect = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class BoxOnClWireTop(MultiBox, BoxOnClWire):
""" Draws the top part of a conditional box that affects more than one classical wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnClWireMid(MultiBox, BoxOnClWire):
""" Draws the middle part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.mid_content = label
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.top_pad = self.bot_pad = ' '
self.top_connect = self.bot_connect = self.mid_content = ''
self.center_label(input_length, order)
class BoxOnClWireBot(MultiBox, BoxOnClWire):
""" Draws the bottom part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, bot_connect='─'):
super().__init__(label)
self.top_format = "│ %s │"
self.top_pad = " "
self.bot_connect = bot_connect
self.mid_content = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class DirectOnQuWire(DrawElement):
"""
Element to the wire (without the box).
"""
def __init__(self, label=""):
super().__init__(label)
self.top_format = ' %s '
self.mid_format = '─%s─'
self.bot_format = ' %s '
self._mid_padding = '─'
class Barrier(DirectOnQuWire):
""" Draws a barrier.
top: ░ ░
mid: ─░─ ───░───
bot: ░ ░
"""
def __init__(self, label=""):
super().__init__("░")
self.top_connect = "░"
self.bot_connect = "░"
class Ex(DirectOnQuWire):
""" Draws an X (usually with a connector). E.g. the top part of a swap gate
top:
mid: ─X─ ───X───
bot: │ │
"""
def __init__(self, bot_connect=" ", top_connect=" "):
super().__init__("X")
self.bot_connect = bot_connect
self.top_connect = top_connect
class Reset(DirectOnQuWire):
""" Draws a reset gate"""
def __init__(self):
super().__init__("|0>")
class Bullet(DirectOnQuWire):
""" Draws a bullet (usuallly with a connector). E.g. the top part of a CX gate.
top:
mid: ─■─ ───■───
bot: │ │
"""
def __init__(self, top_connect=" ", bot_connect=" "):
super().__init__('■')
self.top_connect = top_connect
self.bot_connect = bot_connect
class EmptyWire(DrawElement):
""" This element is just the wire, with no instructions nor operations."""
def __init__(self, wire):
super().__init__(wire)
self._mid_padding = wire
@staticmethod
def fillup_layer(layer, first_clbit):
"""
Given a layer, replace the Nones in it with EmptyWire elements.
Args:
layer (list): The layer that contains Nones.
first_clbit (int): The first wire that is classic.
Returns:
list: The new layer, with no Nones.
"""
for nones in [i for i, x in enumerate(layer) if x is None]:
layer[nones] = EmptyWire('═') if nones >= first_clbit else EmptyWire('─')
return layer
class BreakWire(DrawElement):
""" This element is used to break the drawing in several pages."""
def __init__(self, arrow_char):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = arrow_char
self.mid_content = arrow_char
self.bot_connect = arrow_char
@staticmethod
def fillup_layer(layer_length, arrow_char):
"""
Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer.
"""
breakwire_layer = []
for _ in range(layer_length):
breakwire_layer.append(BreakWire(arrow_char))
return breakwire_layer
class InputWire(DrawElement):
""" This element is the label and the initial value of a wire."""
def __init__(self, label):
super().__init__(label)
@staticmethod
def fillup_layer(names): # pylint: disable=arguments-differ
"""
Creates a layer with InputWire elements.
Args:
names (list): List of names for the wires.
Returns:
list: The new layer
"""
longest = max([len(name) for name in names])
inputs_wires = []
for name in names:
inputs_wires.append(InputWire(name.rjust(longest)))
return inputs_wires
class TextDrawing():
""" The text drawing"""
def __init__(self, json_circuit):
self.json_circuit = json_circuit
def lines(self, line_length=None):
"""
Generates a list with lines. These lines form the text drawing.
Args:
line_length (int): Optional. When given, breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console.
Returns:
list: A list of lines with the text drawing.
"""
noqubits = self.json_circuit['header']['number_of_qubits']
layers = self.build_layers()
# TODO compress layers
# -| H |----------
# --------| H |---
# should be
# -| H |---
# -| H |---
layer_groups = [[]]
rest_of_the_line = line_length
for layerno, layer in enumerate(layers):
# Replace the Nones with EmptyWire
layers[layerno] = EmptyWire.fillup_layer(layer, noqubits)
TextDrawing.normalize_width(layer)
if line_length is None:
# does not page
layer_groups[-1].append(layer)
continue
# chop the layer to the line_length (pager)
layer_length = layers[layerno][0].length
if layer_length < rest_of_the_line:
layer_groups[-1].append(layer)
rest_of_the_line -= layer_length
else:
layer_groups[-1].append(BreakWire.fillup_layer(len(layer), '»'))
# New group
layer_groups.append([BreakWire.fillup_layer(len(layer), '«')])
rest_of_the_line = line_length - layer_groups[-1][-1][0].length
layer_groups[-1].append(
InputWire.fillup_layer(self.wire_names(with_initial_value=False)))
rest_of_the_line -= layer_groups[-1][-1][0].length
layer_groups[-1].append(layer)
rest_of_the_line -= layer_groups[-1][-1][0].length
lines = []
for layer_group in layer_groups:
wires = [i for i in zip(*layer_group)]
lines += TextDrawing.draw_wires(wires)
return lines
def wire_names(self, with_initial_value=True):
"""
Returns a list of names for each wire.
Args:
with_initial_value (bool): Optional (Default: True). If true, adds the initial value to
the name.
Returns:
List: The list of wire names.
"""
ret = []
if with_initial_value:
initial_value = {'qubit': '|0>', 'clbit': '0 '}
else:
initial_value = {'qubit': '', 'clbit': ''}
header = self.json_circuit['header']
for qubit in header['qubit_labels']:
ret.append("%s_%s: %s" % (qubit[0], qubit[1], initial_value['qubit']))
for creg in header['clbit_labels']:
for clbit in range(creg[1]):
ret.append("%s_%s: %s" % (creg[0], clbit, initial_value['clbit']))
return ret
@staticmethod
def draw_wires(wires):
"""
Given a list of wires, creates a list of lines with the text drawing.
Args:
wires (list): A list of wires with instructions.
Returns:
list: A list of lines with the text drawing.
"""
lines = []
bot_line = None
for wire in wires:
# TOP
top_line = ""
for instruction in wire:
top_line += instruction.top
if bot_line is None:
lines.append(top_line)
else:
lines.append(TextDrawing.merge_lines(lines.pop(), top_line))
# MID
mid_line = ""
for instruction in wire:
mid_line += instruction.mid
lines.append(TextDrawing.merge_lines(lines[-1], mid_line, icod="bot"))
# BOT
bot_line = ""
for instruction in wire:
bot_line += instruction.bot
lines.append(TextDrawing.merge_lines(lines[-1], bot_line, icod="bot"))
return lines
@staticmethod
def label_for_conditional(instruction):
""" Creates the label for a conditional instruction."""
return "%s %s" % ('=', instruction['conditional']['val'])
@staticmethod
def params_for_label(instruction):
"""Get the params and format them to add them to a label. None of there is no param."""
if 'params' in instruction and instruction['params']:
return ['%.5g' % i for i in instruction['params']]
return None
@staticmethod
def label_for_box(instruction):
""" Creates the label for a box."""
label = instruction['name'].capitalize()
params = TextDrawing.params_for_label(instruction)
if params:
label += "(%s)" % ','.join(params)
return label
@staticmethod
def merge_lines(top, bot, icod="top"):
"""
Merges two lines (top and bot) in the way that the overlapping make senses.
Args:
top (str): the top line
bot (str): the bottom line
icod (top or bot): in case of doubt, which line should have priority? Default: "top".
Returns:
str: The merge of both lines.
"""
ret = ""
for topc, botc in zip(top, bot):
if topc == botc:
ret += topc
elif topc in '┼╪' and botc == " ":
ret += "│"
elif topc == " ":
ret += botc
elif topc in '┬╥' and botc in " ║│":
ret += topc
elif topc in '┬│' and botc == "═":
ret += '╪'
elif topc in '┬│' and botc == "─":
ret += '┼'
elif topc in '└┘║│░' and botc == " ":
ret += topc
elif topc in '─═' and botc == " " and icod == "top":
ret += topc
elif topc in '─═' and botc == " " and icod == "bot":
ret += botc
elif topc in "║╥" and botc in "═":
ret += "╬"
elif topc in "║╥" and botc in "─":
ret += "╫"
elif topc in '╫╬' and botc in " ":
ret += "║"
elif topc == '└' and botc == "┌":
ret += "├"
elif topc == '┘' and botc == "┐":
ret += "┤"
else:
ret += botc
return ret
def clbit_index_from_mask(self, mask):
"""
Given a mask, returns a list of classical indexes affected by that mask.
Args:
mask (int): The mask.
Returns:
list: A list of indexes affected by the mask.
"""
clbit_len = self.json_circuit['header']['number_of_clbits']
bit_mask = [bool(mask & (1 << n)) for n in range(clbit_len)]
return [i for i, x in enumerate(bit_mask) if x]
@staticmethod
def normalize_width(layer):
"""
When the elements of the layer have different widths, sets the width to the max elements.
Args:
layer (list): A list of elements.
"""
instructions = [instruction for instruction in filter(lambda x: x is not None, layer)]
longest = max([instruction.length for instruction in instructions])
for instruction in instructions:
instruction.length = longest
def build_layers(self):
"""
Constructs layers.
Returns:
list: List of DrawElements.
Raises:
Exception: When the drawing is, for some reason, impossible to be drawn.
"""
layers = []
noqubits = self.json_circuit['header']['number_of_qubits']
noclbits = self.json_circuit['header']['number_of_clbits']
layers.append(InputWire.fillup_layer(self.wire_names(with_initial_value=True)))
for instruction in self.json_circuit['instructions']:
layer = Layer(noqubits, noclbits)
if instruction['name'] == 'measure':
layer.set_qubit(instruction['qubits'][0], MeasureFrom())
layer.set_clbit(instruction['clbits'][0], MeasureTo())
elif instruction['name'] == 'barrier':
# barrier
for qubit in instruction['qubits']:
layer.qubit_layer[qubit] = Barrier()
elif instruction['name'] == 'swap':
# swap
for qubit in instruction['qubits']:
layer.qubit_layer[qubit] = Ex()
layer.connect_with("│")
elif instruction['name'] == 'cswap':
# cswap
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Ex())
layer.set_qubit(instruction['qubits'][2], Ex())
layer.connect_with("│")
elif instruction['name'] == 'reset':
layer.set_qubit(instruction['qubits'][0], Reset())
elif 'conditional' in instruction:
# conditional
clbits = self.clbit_index_from_mask(int(instruction['conditional']['mask'], 16))
cllabel = TextDrawing.label_for_conditional(instruction)
qulabel = TextDrawing.label_for_box(instruction)
layer.set_cl_multibox(clbits, cllabel, top_connect='┴')
layer.set_qubit(instruction['qubits'][0], BoxOnQuWire(qulabel, bot_connect='┬'))
elif instruction['name'] in ['cx', 'CX', 'ccx']:
# cx/ccx
for qubit in [qubit for qubit in instruction['qubits'][:-1]]:
layer.set_qubit(qubit, Bullet())
layer.set_qubit(instruction['qubits'][-1], BoxOnQuWire('X'))
layer.connect_with("│")
elif instruction['name'] == 'cy':
# cy
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], BoxOnQuWire('Y'))
layer.connect_with("│")
elif instruction['name'] == 'cz':
# cz
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Bullet())
layer.connect_with("│")
elif instruction['name'] == 'ch':
# ch
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], BoxOnQuWire('H'))
layer.connect_with("│")
elif instruction['name'] == 'cu1':
# cu1
label = TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Bullet())
layer.connect_with("│", label)
elif instruction['name'] == 'cu3':
# cu3
params = TextDrawing.params_for_label(instruction)
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1],
BoxOnQuWire("U3(%s)" % ','.join(params)))
layer.connect_with("│")
elif instruction['name'] == 'crz':
# crz
label = "Rz(%s)" % TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1],
BoxOnQuWire(label))
layer.connect_with("│")
elif len(instruction['qubits']) == 1 and 'clbits' not in instruction:
# unitary gate
layer.set_qubit(instruction['qubits'][0],
BoxOnQuWire(TextDrawing.label_for_box(instruction)))
elif len(instruction['qubits']) >= 2 and 'clbits' not in instruction:
# multiple qubit gate
layer.set_qu_multibox(instruction['qubits'], TextDrawing.label_for_box(instruction))
else:
raise Exception("I don't know how to handle this instruction", instruction)
layers.append(layer.full_layer)
return layers
class Layer:
""" A layer is the "column" of the circuit. """
def __init__(self, noqubits, noclbits):
self.qubit_layer = [None] * noqubits
self.clbit_layer = [None] * noclbits
@property
def full_layer(self):
"""
Returns the composition of qubits and classic wires.
Returns:
String: self.qubit_layer + self.clbit_layer
"""
return self.qubit_layer + self.clbit_layer
def set_qubit(self, qubit, element):
"""
Sets the qubit to the element
Args:
qubit (int): Qubit index.
element (DrawElement): Element to set in the qubit
"""
self.qubit_layer[qubit] = element
def set_clbit(self, clbit, element):
"""
Sets the clbit to the element
Args:
clbit (int): Clbit index.
element (DrawElement): Element to set in the clbit
"""
self.clbit_layer[clbit] = element
def _set_multibox(self, wire_type, bits, label, top_connect=None):
# pylint: disable=invalid-name
bits = sorted(bits)
if wire_type == "cl":
set_bit = self.set_clbit
BoxOnWire = BoxOnClWire
BoxOnWireTop = BoxOnClWireTop
BoxOnWireMid = BoxOnClWireMid
BoxOnWireBot = BoxOnClWireBot
elif wire_type == "qu":
set_bit = self.set_qubit
BoxOnWire = BoxOnQuWire
BoxOnWireTop = BoxOnQuWireTop
BoxOnWireMid = BoxOnQuWireMid
BoxOnWireBot = BoxOnQuWireBot
# Checks if qubits are consecutive
if bits != [i for i in range(bits[0], bits[-1] + 1)]:
raise Exception("I don't know how to build a gate with multiple bits when"
"they are not adjacent to each other")
if len(bits) == 1:
set_bit(bits[0], BoxOnWire(label, top_connect=top_connect))
else:
set_bit(bits[0], BoxOnWireTop(label, top_connect=top_connect))
for order, bit in enumerate(bits[1:-1], 1):
set_bit(bit, BoxOnWireMid(label, len(bits), order))
set_bit(bits[-1], BoxOnWireBot(label, len(bits)))
def set_cl_multibox(self, bits, label, top_connect='┴'):
"""
Sets the multi clbit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi clbit box.
top_connect (char): The char to connect the box on the top.
"""
self._set_multibox("cl", bits, label, top_connect=top_connect)
def set_qu_multibox(self, bits, label):
"""
Sets the multi qubit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi qubit box.
"""
self._set_multibox("qu", bits, label)
def connect_with(self, wire_char, label=None):
"""
Connects the elements in the layer using wire_char.
Args:
wire_char (char): For example '║' or '│'.
label (string): Some connectors have a label (see cu1, for example).
"""
affected_bits = [bit for bit in self.full_layer if bit is not None]
affected_bits[0].connect(wire_char, ['bot'])
for affected_bit in affected_bits[1:-1]:
affected_bit.connect(wire_char, ['bot', 'top'])
affected_bits[-1].connect(wire_char, ['top'], label)
if label:
for affected_bit in affected_bits:
affected_bit.right_fill = len(label) + len(affected_bit.mid)
<|code_end|>
|
Text circuit output doesn't understand plotbarriers or reversebits style arguments
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: Latest master
- **Python version**: 3.7
- **Operating system**: linux
### What is the current behavior?
When calling circuit_drawer(output='text') the style kwarg isn't used at all. So even common arguments that aren't matplotlib specific are not understood. These include the 'reversebits' and 'plotbarriers' options which should be implementable on the text drawer too.
### Steps to reproduce the problem
Call circuit_drawer() with the style kwarg and that input has 'reversebits' and/or 'plotbarriers' set.
### What is the expected behavior?
The output circuit ascii art circuit will have reversed bit and/or no barriers drawn.
### Suggested solutions
There are 2 things here, first we need to add an option to reverse the bits and not draw barriers to the text drawer. Then we need to pass that option to the text drawer.
However after writing #1108 I think we should just move plotbarriers and reversebits to kwargs for circuit_drawer() as they should be common options for all backends. The rest of the style dict is just for the matplotlib backend, so I feel we should make all the arguments from the style dict which are used by >=2 backends a top level kwarg.
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import logging
import os
import subprocess
import tempfile
import warnings
from PIL import Image
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization._error import VisualizationError
from qiskit.tools.visualization import _latex
from qiskit.tools.visualization import _matplotlib
from qiskit.tools.visualization import _text
from qiskit.tools.visualization import _utils
from qiskit.transpiler import transpile_dag
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis=None,
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art string
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing. Defaults to
`"id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,cx,cy,cz,ch,crz,cu1,
cu3,swap,ccx,cswap"` This option is deprecated and will be removed
in the future.
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (str): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if
one is not specified it will use latex and if that fails fallback
to mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect
line_length (int): sets the length of the lines generated by `text`
Returns:
PIL.Image: (outputs `latex` and `python`) an in-memory representation of
the circuit diagram.
String: (outputs `text` and `latex_source`). The ascii art or the LaTeX
source code.
Raises:
VisualizationError: when an invalid output method is selected
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defaults to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'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'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
plotbarrier (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
reversebits (bool): When set to True reverse the bit order inside
registers for the output visualization.
"""
if basis is None:
basis = ("id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap")
else:
warnings.warn('The basis kwarg is deprecated and the circuit drawer '
'function will not be able to adjust basis gates itself '
'in a future release', DeprecationWarning)
im = None
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'"text" by default', DeprecationWarning)
try:
im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError, FileNotFoundError):
im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
else:
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename, basis=basis,
line_length=line_length)
elif output == 'latex':
im = _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
elif output == 'latex_source':
return _generate_latex_source(circuit, basis=basis,
filename=filename, scale=scale,
style=style)
elif output == 'mpl':
im = _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
else:
raise VisualizationError('Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if im and interactive:
im.show()
return im
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap", line_length=None):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
basis (str): Optional. Comma-separated list of gate names
line_length (int): Optional. Sometimes, your console is too small of the drawing. Give me
you maximum line length your console supports.
Returns:
String: The drawing in a loooong string.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
text = "\n".join(_text.TextDrawing(json_circuit).lines(line_length))
if filename:
with open(filename, mode='w', encoding="utf8") as text_file:
text_file.write(text)
return text
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to compile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _utils._trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename, basis=basis,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
qcimg = _latex.QCircuitImage(json_circuit, scale, style=style)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,'
'ry,rz,cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,'
'cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = _matplotlib.MatplotlibDrawer(basis=basis, scale=scale, style=style)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
<|code_end|>
qiskit/tools/visualization/_text.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A module for drawing circuits in ascii art or some other text representation
"""
class DrawElement():
""" An element is an instruction or an operation that need to be drawn."""
def __init__(self, label=None):
self._width = None
self.label = self.mid_content = label
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = self.bot_connect = " "
self.top_pad = self._mid_padding = self.bot_pad = " "
self.bot_connector = {}
self.top_connector = {}
self.right_fill = self.left_fill = 0
@property
def top(self):
""" Constructs the top line of the element"""
ret = self.top_format % self.top_connect.center(
self.width - self.left_fill - self.right_fill, self.top_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.top_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.top_pad)
return ret
@property
def mid(self):
""" Constructs the middle line of the element"""
ret = self.mid_format % self.mid_content.center(
self.width - self.left_fill - self.right_fill, self._mid_padding)
if self.right_fill:
ret = ret.ljust(self.right_fill, self._mid_padding)
if self.left_fill:
ret = ret.rjust(self.left_fill, self._mid_padding)
return ret
@property
def bot(self):
""" Constructs the bottom line of the element"""
ret = self.bot_format % self.bot_connect.center(
self.width - self.left_fill - self.right_fill, self.bot_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.bot_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.bot_pad)
return ret
@property
def length(self):
""" Returns the length of the element, including the box around."""
return max(len(self.top), len(self.mid), len(self.bot))
@length.setter
def length(self, value):
""" Adjusts width so the length fits."""
self.width = value - max(
[len(getattr(self, i) % '') for i in ["bot_format", "mid_format", "top_format"]])
@property
def width(self):
""" Returns the width of the label, including padding"""
if self._width:
return self._width
return len(self.mid_content)
@width.setter
def width(self, value):
self._width = value
def connect(self, wire_char, where, label=None):
"""
Connects boxes and elements using wire_char and setting proper connectors.
Args:
wire_char (char): For example '║' or '│'.
where (list["top", "bot"]): Where the connector should be set.
label (string): Some connectors have a label (see cu1, for example).
"""
if 'top' in where:
self.top_connect = self.top_connector[
wire_char] if wire_char in self.top_connector else wire_char
if 'bot' in where:
self.bot_connect = self.bot_connector[
wire_char] if wire_char in self.bot_connector else wire_char
if label:
self.top_format = self.top_format[:-1] + (label if label else "")
class BoxOnClWire(DrawElement):
""" Draws a box on the classical wire
top: ┌───┐ ┌───────┐
mid: ╡ A ╞ ╡ A ╞
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "╡ %s ╞"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
class BoxOnQuWire(DrawElement):
""" Draws a box on the quantum wire
top: ┌───┐ ┌───────┐
mid: ┤ A ├ ┤ A ├
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "┤ %s ├"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
self.top_connector = {"│": '┴'}
self.bot_connector = {"│": '┬'}
class MeasureTo(DrawElement):
""" The element on the classic wire to which the measure is performed
top: ║ ║
mid: ═╩═ ═══╩═══
bot:
"""
def __init__(self):
super().__init__()
self.top_connect = " ║ "
self.mid_content = "═╩═"
self.bot_connect = " "
self._mid_padding = "═"
class MeasureFrom(BoxOnQuWire):
""" The element on the quantum wire in which the measure is performed
top: ┌─┐ ┌─┐
mid: ┤M├ ───┤M├───
bot: └╥┘ └╥┘
"""
def __init__(self):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = "┌─┐"
self.mid_content = "┤M├"
self.bot_connect = "└╥┘"
class MultiBox(DrawElement):
"""Elements that is draw on over multiple wires."""
def center_label(self, input_length, order):
"""
In multi-bit elements, the label is centered vertically.
Args:
input_length (int): Rhe amount of wires affected.
order (int): Which middle element is this one?
"""
location_in_the_box = '*'.center(input_length * 2 - 1).index('*') + 1
top_limit = (order - 1) * 2 + 2
bot_limit = top_limit + 2
if top_limit <= location_in_the_box < bot_limit:
if location_in_the_box == top_limit:
self.top_connect = self.label
elif location_in_the_box == top_limit + 1:
self.mid_content = self.label
else:
self.bot_connect = self.label
class BoxOnQuWireTop(MultiBox, BoxOnQuWire):
""" Draws the top part of a box that affects more than one quantum wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnQuWireMid(MultiBox, BoxOnQuWire):
""" Draws the middle part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.center_label(input_length, order)
class BoxOnQuWireBot(MultiBox, BoxOnQuWire):
""" Draws the bottom part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length):
super().__init__(label)
self.top_format = "│ %s │"
self.mid_content = self.bot_connect = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class BoxOnClWireTop(MultiBox, BoxOnClWire):
""" Draws the top part of a conditional box that affects more than one classical wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnClWireMid(MultiBox, BoxOnClWire):
""" Draws the middle part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.mid_content = label
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.top_pad = self.bot_pad = ' '
self.top_connect = self.bot_connect = self.mid_content = ''
self.center_label(input_length, order)
class BoxOnClWireBot(MultiBox, BoxOnClWire):
""" Draws the bottom part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, bot_connect='─'):
super().__init__(label)
self.top_format = "│ %s │"
self.top_pad = " "
self.bot_connect = bot_connect
self.mid_content = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class DirectOnQuWire(DrawElement):
"""
Element to the wire (without the box).
"""
def __init__(self, label=""):
super().__init__(label)
self.top_format = ' %s '
self.mid_format = '─%s─'
self.bot_format = ' %s '
self._mid_padding = '─'
class Barrier(DirectOnQuWire):
""" Draws a barrier.
top: ░ ░
mid: ─░─ ───░───
bot: ░ ░
"""
def __init__(self, label=""):
super().__init__("░")
self.top_connect = "░"
self.bot_connect = "░"
class Ex(DirectOnQuWire):
""" Draws an X (usually with a connector). E.g. the top part of a swap gate
top:
mid: ─X─ ───X───
bot: │ │
"""
def __init__(self, bot_connect=" ", top_connect=" "):
super().__init__("X")
self.bot_connect = bot_connect
self.top_connect = top_connect
class Reset(DirectOnQuWire):
""" Draws a reset gate"""
def __init__(self):
super().__init__("|0>")
class Bullet(DirectOnQuWire):
""" Draws a bullet (usually with a connector). E.g. the top part of a CX gate.
top:
mid: ─■─ ───■───
bot: │ │
"""
def __init__(self, top_connect=" ", bot_connect=" "):
super().__init__('■')
self.top_connect = top_connect
self.bot_connect = bot_connect
class EmptyWire(DrawElement):
""" This element is just the wire, with no instructions nor operations."""
def __init__(self, wire):
super().__init__(wire)
self._mid_padding = wire
@staticmethod
def fillup_layer(layer, first_clbit):
"""
Given a layer, replace the Nones in it with EmptyWire elements.
Args:
layer (list): The layer that contains Nones.
first_clbit (int): The first wire that is classic.
Returns:
list: The new layer, with no Nones.
"""
for nones in [i for i, x in enumerate(layer) if x is None]:
layer[nones] = EmptyWire('═') if nones >= first_clbit else EmptyWire('─')
return layer
class BreakWire(DrawElement):
""" This element is used to break the drawing in several pages."""
def __init__(self, arrow_char):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = arrow_char
self.mid_content = arrow_char
self.bot_connect = arrow_char
@staticmethod
def fillup_layer(layer_length, arrow_char):
"""
Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer.
"""
breakwire_layer = []
for _ in range(layer_length):
breakwire_layer.append(BreakWire(arrow_char))
return breakwire_layer
class InputWire(DrawElement):
""" This element is the label and the initial value of a wire."""
def __init__(self, label):
super().__init__(label)
@staticmethod
def fillup_layer(names): # pylint: disable=arguments-differ
"""
Creates a layer with InputWire elements.
Args:
names (list): List of names for the wires.
Returns:
list: The new layer
"""
longest = max([len(name) for name in names])
inputs_wires = []
for name in names:
inputs_wires.append(InputWire(name.rjust(longest)))
return inputs_wires
class TextDrawing():
""" The text drawing"""
def __init__(self, json_circuit):
self.json_circuit = json_circuit
def lines(self, line_length=None):
"""
Generates a list with lines. These lines form the text drawing.
Args:
line_length (int): Optional. When given, breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console.
Returns:
list: A list of lines with the text drawing.
"""
noqubits = self.json_circuit['header']['number_of_qubits']
layers = self.build_layers()
# TODO compress layers
# -| H |----------
# --------| H |---
# should be
# -| H |---
# -| H |---
layer_groups = [[]]
rest_of_the_line = line_length
for layerno, layer in enumerate(layers):
# Replace the Nones with EmptyWire
layers[layerno] = EmptyWire.fillup_layer(layer, noqubits)
TextDrawing.normalize_width(layer)
if line_length is None:
# does not page
layer_groups[-1].append(layer)
continue
# chop the layer to the line_length (pager)
layer_length = layers[layerno][0].length
if layer_length < rest_of_the_line:
layer_groups[-1].append(layer)
rest_of_the_line -= layer_length
else:
layer_groups[-1].append(BreakWire.fillup_layer(len(layer), '»'))
# New group
layer_groups.append([BreakWire.fillup_layer(len(layer), '«')])
rest_of_the_line = line_length - layer_groups[-1][-1][0].length
layer_groups[-1].append(
InputWire.fillup_layer(self.wire_names(with_initial_value=False)))
rest_of_the_line -= layer_groups[-1][-1][0].length
layer_groups[-1].append(layer)
rest_of_the_line -= layer_groups[-1][-1][0].length
lines = []
for layer_group in layer_groups:
wires = [i for i in zip(*layer_group)]
lines += TextDrawing.draw_wires(wires)
return lines
def wire_names(self, with_initial_value=True):
"""
Returns a list of names for each wire.
Args:
with_initial_value (bool): Optional (Default: True). If true, adds the initial value to
the name.
Returns:
List: The list of wire names.
"""
ret = []
if with_initial_value:
initial_value = {'qubit': '|0>', 'clbit': '0 '}
else:
initial_value = {'qubit': '', 'clbit': ''}
header = self.json_circuit['header']
for qubit in header['qubit_labels']:
ret.append("%s_%s: %s" % (qubit[0], qubit[1], initial_value['qubit']))
for creg in header['clbit_labels']:
for clbit in range(creg[1]):
ret.append("%s_%s: %s" % (creg[0], clbit, initial_value['clbit']))
return ret
@staticmethod
def draw_wires(wires):
"""
Given a list of wires, creates a list of lines with the text drawing.
Args:
wires (list): A list of wires with instructions.
Returns:
list: A list of lines with the text drawing.
"""
lines = []
bot_line = None
for wire in wires:
# TOP
top_line = ""
for instruction in wire:
top_line += instruction.top
if bot_line is None:
lines.append(top_line)
else:
lines.append(TextDrawing.merge_lines(lines.pop(), top_line))
# MID
mid_line = ""
for instruction in wire:
mid_line += instruction.mid
lines.append(TextDrawing.merge_lines(lines[-1], mid_line, icod="bot"))
# BOT
bot_line = ""
for instruction in wire:
bot_line += instruction.bot
lines.append(TextDrawing.merge_lines(lines[-1], bot_line, icod="bot"))
return lines
@staticmethod
def label_for_conditional(instruction):
""" Creates the label for a conditional instruction."""
return "%s %s" % ('=', instruction['conditional']['val'])
@staticmethod
def params_for_label(instruction):
"""Get the params and format them to add them to a label. None of there is no param."""
if 'params' in instruction and instruction['params']:
return ['%.5g' % i for i in instruction['params']]
return None
@staticmethod
def label_for_box(instruction):
""" Creates the label for a box."""
label = instruction['name'].capitalize()
params = TextDrawing.params_for_label(instruction)
if params:
label += "(%s)" % ','.join(params)
return label
@staticmethod
def merge_lines(top, bot, icod="top"):
"""
Merges two lines (top and bot) in the way that the overlapping make senses.
Args:
top (str): the top line
bot (str): the bottom line
icod (top or bot): in case of doubt, which line should have priority? Default: "top".
Returns:
str: The merge of both lines.
"""
ret = ""
for topc, botc in zip(top, bot):
if topc == botc:
ret += topc
elif topc in '┼╪' and botc == " ":
ret += "│"
elif topc == " ":
ret += botc
elif topc in '┬╥' and botc in " ║│":
ret += topc
elif topc in '┬│' and botc == "═":
ret += '╪'
elif topc in '┬│' and botc == "─":
ret += '┼'
elif topc in '└┘║│░' and botc == " ":
ret += topc
elif topc in '─═' and botc == " " and icod == "top":
ret += topc
elif topc in '─═' and botc == " " and icod == "bot":
ret += botc
elif topc in "║╥" and botc in "═":
ret += "╬"
elif topc in "║╥" and botc in "─":
ret += "╫"
elif topc in '╫╬' and botc in " ":
ret += "║"
elif topc == '└' and botc == "┌":
ret += "├"
elif topc == '┘' and botc == "┐":
ret += "┤"
else:
ret += botc
return ret
def clbit_index_from_mask(self, mask):
"""
Given a mask, returns a list of classical indexes affected by that mask.
Args:
mask (int): The mask.
Returns:
list: A list of indexes affected by the mask.
"""
clbit_len = self.json_circuit['header']['number_of_clbits']
bit_mask = [bool(mask & (1 << n)) for n in range(clbit_len)]
return [i for i, x in enumerate(bit_mask) if x]
@staticmethod
def normalize_width(layer):
"""
When the elements of the layer have different widths, sets the width to the max elements.
Args:
layer (list): A list of elements.
"""
instructions = [instruction for instruction in filter(lambda x: x is not None, layer)]
longest = max([instruction.length for instruction in instructions])
for instruction in instructions:
instruction.length = longest
def build_layers(self):
"""
Constructs layers.
Returns:
list: List of DrawElements.
Raises:
Exception: When the drawing is, for some reason, impossible to be drawn.
"""
layers = []
noqubits = self.json_circuit['header']['number_of_qubits']
noclbits = self.json_circuit['header']['number_of_clbits']
layers.append(InputWire.fillup_layer(self.wire_names(with_initial_value=True)))
for instruction in self.json_circuit['instructions']:
layer = Layer(noqubits, noclbits)
if instruction['name'] == 'measure':
layer.set_qubit(instruction['qubits'][0], MeasureFrom())
layer.set_clbit(instruction['clbits'][0], MeasureTo())
elif instruction['name'] == 'barrier':
# barrier
for qubit in instruction['qubits']:
layer.qubit_layer[qubit] = Barrier()
elif instruction['name'] == 'swap':
# swap
for qubit in instruction['qubits']:
layer.qubit_layer[qubit] = Ex()
layer.connect_with("│")
elif instruction['name'] == 'cswap':
# cswap
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Ex())
layer.set_qubit(instruction['qubits'][2], Ex())
layer.connect_with("│")
elif instruction['name'] == 'reset':
layer.set_qubit(instruction['qubits'][0], Reset())
elif 'conditional' in instruction:
# conditional
clbits = self.clbit_index_from_mask(int(instruction['conditional']['mask'], 16))
cllabel = TextDrawing.label_for_conditional(instruction)
qulabel = TextDrawing.label_for_box(instruction)
layer.set_cl_multibox(clbits, cllabel, top_connect='┴')
layer.set_qubit(instruction['qubits'][0], BoxOnQuWire(qulabel, bot_connect='┬'))
elif instruction['name'] in ['cx', 'CX', 'ccx']:
# cx/ccx
for qubit in [qubit for qubit in instruction['qubits'][:-1]]:
layer.set_qubit(qubit, Bullet())
layer.set_qubit(instruction['qubits'][-1], BoxOnQuWire('X'))
layer.connect_with("│")
elif instruction['name'] == 'cy':
# cy
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], BoxOnQuWire('Y'))
layer.connect_with("│")
elif instruction['name'] == 'cz':
# cz
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Bullet())
layer.connect_with("│")
elif instruction['name'] == 'ch':
# ch
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], BoxOnQuWire('H'))
layer.connect_with("│")
elif instruction['name'] == 'cu1':
# cu1
label = TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Bullet())
layer.connect_with("│", label)
elif instruction['name'] == 'cu3':
# cu3
params = TextDrawing.params_for_label(instruction)
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1],
BoxOnQuWire("U3(%s)" % ','.join(params)))
layer.connect_with("│")
elif instruction['name'] == 'crz':
# crz
label = "Rz(%s)" % TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1],
BoxOnQuWire(label))
layer.connect_with("│")
elif len(instruction['qubits']) == 1 and 'clbits' not in instruction:
# unitary gate
layer.set_qubit(instruction['qubits'][0],
BoxOnQuWire(TextDrawing.label_for_box(instruction)))
elif len(instruction['qubits']) >= 2 and 'clbits' not in instruction:
# multiple qubit gate
layer.set_qu_multibox(instruction['qubits'], TextDrawing.label_for_box(instruction))
else:
raise Exception("I don't know how to handle this instruction", instruction)
layers.append(layer.full_layer)
return layers
class Layer:
""" A layer is the "column" of the circuit. """
def __init__(self, noqubits, noclbits):
self.qubit_layer = [None] * noqubits
self.clbit_layer = [None] * noclbits
@property
def full_layer(self):
"""
Returns the composition of qubits and classic wires.
Returns:
String: self.qubit_layer + self.clbit_layer
"""
return self.qubit_layer + self.clbit_layer
def set_qubit(self, qubit, element):
"""
Sets the qubit to the element
Args:
qubit (int): Qubit index.
element (DrawElement): Element to set in the qubit
"""
self.qubit_layer[qubit] = element
def set_clbit(self, clbit, element):
"""
Sets the clbit to the element
Args:
clbit (int): Clbit index.
element (DrawElement): Element to set in the clbit
"""
self.clbit_layer[clbit] = element
def _set_multibox(self, wire_type, bits, label, top_connect=None):
# pylint: disable=invalid-name
bits = sorted(bits)
if wire_type == "cl":
set_bit = self.set_clbit
BoxOnWire = BoxOnClWire
BoxOnWireTop = BoxOnClWireTop
BoxOnWireMid = BoxOnClWireMid
BoxOnWireBot = BoxOnClWireBot
elif wire_type == "qu":
set_bit = self.set_qubit
BoxOnWire = BoxOnQuWire
BoxOnWireTop = BoxOnQuWireTop
BoxOnWireMid = BoxOnQuWireMid
BoxOnWireBot = BoxOnQuWireBot
# Checks if qubits are consecutive
if bits != [i for i in range(bits[0], bits[-1] + 1)]:
raise Exception("I don't know how to build a gate with multiple bits when"
"they are not adjacent to each other")
if len(bits) == 1:
set_bit(bits[0], BoxOnWire(label, top_connect=top_connect))
else:
set_bit(bits[0], BoxOnWireTop(label, top_connect=top_connect))
for order, bit in enumerate(bits[1:-1], 1):
set_bit(bit, BoxOnWireMid(label, len(bits), order))
set_bit(bits[-1], BoxOnWireBot(label, len(bits)))
def set_cl_multibox(self, bits, label, top_connect='┴'):
"""
Sets the multi clbit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi clbit box.
top_connect (char): The char to connect the box on the top.
"""
self._set_multibox("cl", bits, label, top_connect=top_connect)
def set_qu_multibox(self, bits, label):
"""
Sets the multi qubit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi qubit box.
"""
self._set_multibox("qu", bits, label)
def connect_with(self, wire_char, label=None):
"""
Connects the elements in the layer using wire_char.
Args:
wire_char (char): For example '║' or '│'.
label (string): Some connectors have a label (see cu1, for example).
"""
affected_bits = [bit for bit in self.full_layer if bit is not None]
affected_bits[0].connect(wire_char, ['bot'])
for affected_bit in affected_bits[1:-1]:
affected_bit.connect(wire_char, ['bot', 'top'])
affected_bits[-1].connect(wire_char, ['top'], label)
if label:
for affected_bit in affected_bits:
affected_bit.right_fill = len(label) + len(affected_bit.mid)
<|code_end|>
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import logging
import os
import subprocess
import tempfile
import warnings
from PIL import Image
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization._error import VisualizationError
from qiskit.tools.visualization import _latex
from qiskit.tools.visualization import _matplotlib
from qiskit.tools.visualization import _text
from qiskit.tools.visualization import _utils
from qiskit.transpiler import transpile_dag
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis=None,
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art string
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing. Defaults to
`"id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,cx,cy,cz,ch,crz,cu1,
cu3,swap,ccx,cswap"` This option is deprecated and will be removed
in the future.
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (str): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if
one is not specified it will use latex and if that fails fallback
to mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect
line_length (int): sets the length of the lines generated by `text`
Returns:
PIL.Image: (outputs `latex` and `python`) an in-memory representation of
the circuit diagram.
String: (outputs `text` and `latex_source`). The ascii art or the LaTeX
source code.
Raises:
VisualizationError: when an invalid output method is selected
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defaults to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'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'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
plotbarrier (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
reversebits (bool): When set to True reverse the bit order inside
registers for the output visualization.
"""
if basis is None:
basis = ("id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap")
else:
warnings.warn('The basis kwarg is deprecated and the circuit drawer '
'function will not be able to adjust basis gates itself '
'in a future release', DeprecationWarning)
im = None
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'"text" by default', DeprecationWarning)
try:
im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError, FileNotFoundError):
im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
else:
if output == 'text':
reversebits = style['reversebits'] if style and 'reversebits' in style else False
plotbarriers = style['plotbarriers'] if style and 'plotbarriers' in style else True
return _text_circuit_drawer(circuit, filename=filename, basis=basis,
line_length=line_length,
reversebits=reversebits, plotbarriers=plotbarriers)
elif output == 'latex':
im = _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
elif output == 'latex_source':
return _generate_latex_source(circuit, basis=basis,
filename=filename, scale=scale,
style=style)
elif output == 'mpl':
im = _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
else:
raise VisualizationError('Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if im and interactive:
im.show()
return im
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap", line_length=None,
reversebits=False, plotbarriers=True):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
basis (str): Optional. Comma-separated list of gate names
line_length (int): Optional. Sometimes, your console is too small of the drawing. Give me
you maximum line length your console supports.
reversebits (bool): Rearrange the bits in reverse order.
plotbarriers (bool): Draws the barriers when they are there.
Returns:
String: The drawing in a loooong string.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
text = "\n".join(
_text.TextDrawing(json_circuit, reversebits=reversebits, plotbarriers=plotbarriers).lines(
line_length))
if filename:
with open(filename, mode='w', encoding="utf8") as text_file:
text_file.write(text)
return text
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to compile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _utils._trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename, basis=basis,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
qcimg = _latex.QCircuitImage(json_circuit, scale, style=style)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,'
'ry,rz,cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,'
'cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = _matplotlib.MatplotlibDrawer(basis=basis, scale=scale, style=style)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
<|code_end|>
qiskit/tools/visualization/_text.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A module for drawing circuits in ascii art or some other text representation
"""
from itertools import groupby
class DrawElement():
""" An element is an instruction or an operation that need to be drawn."""
def __init__(self, label=None):
self._width = None
self.label = self.mid_content = label
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = self.bot_connect = " "
self.top_pad = self._mid_padding = self.bot_pad = " "
self.bot_connector = {}
self.top_connector = {}
self.right_fill = self.left_fill = 0
@property
def top(self):
""" Constructs the top line of the element"""
ret = self.top_format % self.top_connect.center(
self.width - self.left_fill - self.right_fill, self.top_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.top_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.top_pad)
return ret
@property
def mid(self):
""" Constructs the middle line of the element"""
ret = self.mid_format % self.mid_content.center(
self.width - self.left_fill - self.right_fill, self._mid_padding)
if self.right_fill:
ret = ret.ljust(self.right_fill, self._mid_padding)
if self.left_fill:
ret = ret.rjust(self.left_fill, self._mid_padding)
return ret
@property
def bot(self):
""" Constructs the bottom line of the element"""
ret = self.bot_format % self.bot_connect.center(
self.width - self.left_fill - self.right_fill, self.bot_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.bot_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.bot_pad)
return ret
@property
def length(self):
""" Returns the length of the element, including the box around."""
return max(len(self.top), len(self.mid), len(self.bot))
@length.setter
def length(self, value):
""" Adjusts width so the length fits."""
self.width = value - max(
[len(getattr(self, i) % '') for i in ["bot_format", "mid_format", "top_format"]])
@property
def width(self):
""" Returns the width of the label, including padding"""
if self._width:
return self._width
return len(self.mid_content)
@width.setter
def width(self, value):
self._width = value
def connect(self, wire_char, where, label=None):
"""
Connects boxes and elements using wire_char and setting proper connectors.
Args:
wire_char (char): For example '║' or '│'.
where (list["top", "bot"]): Where the connector should be set.
label (string): Some connectors have a label (see cu1, for example).
"""
if 'top' in where and self.top_connector:
self.top_connect = self.top_connector[wire_char]
if 'bot' in where and self.bot_connector:
self.bot_connect = self.bot_connector[wire_char]
if label:
self.top_format = self.top_format[:-1] + (label if label else "")
class BoxOnClWire(DrawElement):
""" Draws a box on the classical wire
top: ┌───┐ ┌───────┐
mid: ╡ A ╞ ╡ A ╞
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "╡ %s ╞"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
class BoxOnQuWire(DrawElement):
""" Draws a box on the quantum wire
top: ┌───┐ ┌───────┐
mid: ┤ A ├ ┤ A ├
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "┤ %s ├"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
self.top_connector = {"│": '┴'}
self.bot_connector = {"│": '┬'}
class MeasureTo(DrawElement):
""" The element on the classic wire to which the measure is performed
top: ║ ║
mid: ═╩═ ═══╩═══
bot:
"""
def __init__(self):
super().__init__()
self.top_connect = " ║ "
self.mid_content = "═╩═"
self.bot_connect = " "
self._mid_padding = "═"
class MeasureFrom(BoxOnQuWire):
""" The element on the quantum wire in which the measure is performed
top: ┌─┐ ┌─┐
mid: ┤M├ ───┤M├───
bot: └╥┘ └╥┘
"""
def __init__(self):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = "┌─┐"
self.mid_content = "┤M├"
self.bot_connect = "└╥┘"
class MultiBox(DrawElement):
"""Elements that is draw on over multiple wires."""
def center_label(self, input_length, order):
"""
In multi-bit elements, the label is centered vertically.
Args:
input_length (int): Rhe amount of wires affected.
order (int): Which middle element is this one?
"""
location_in_the_box = '*'.center(input_length * 2 - 1).index('*') + 1
top_limit = (order - 1) * 2 + 2
bot_limit = top_limit + 2
if top_limit <= location_in_the_box < bot_limit:
if location_in_the_box == top_limit:
self.top_connect = self.label
elif location_in_the_box == top_limit + 1:
self.mid_content = self.label
else:
self.bot_connect = self.label
class BoxOnQuWireTop(MultiBox, BoxOnQuWire):
""" Draws the top part of a box that affects more than one quantum wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnQuWireMid(MultiBox, BoxOnQuWire):
""" Draws the middle part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.center_label(input_length, order)
class BoxOnQuWireBot(MultiBox, BoxOnQuWire):
""" Draws the bottom part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length):
super().__init__(label)
self.top_format = "│ %s │"
self.mid_content = self.bot_connect = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class BoxOnClWireTop(MultiBox, BoxOnClWire):
""" Draws the top part of a conditional box that affects more than one classical wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnClWireMid(MultiBox, BoxOnClWire):
""" Draws the middle part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.mid_content = label
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.top_pad = self.bot_pad = ' '
self.top_connect = self.bot_connect = self.mid_content = ''
self.center_label(input_length, order)
class BoxOnClWireBot(MultiBox, BoxOnClWire):
""" Draws the bottom part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, bot_connect='─'):
super().__init__(label)
self.top_format = "│ %s │"
self.top_pad = " "
self.bot_connect = bot_connect
self.mid_content = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class DirectOnQuWire(DrawElement):
"""
Element to the wire (without the box).
"""
def __init__(self, label=""):
super().__init__(label)
self.top_format = ' %s '
self.mid_format = '─%s─'
self.bot_format = ' %s '
self._mid_padding = '─'
self.top_connector = {"│": '│'}
self.bot_connector = {"│": '│'}
class Barrier(DirectOnQuWire):
""" Draws a barrier.
top: ░ ░
mid: ─░─ ───░───
bot: ░ ░
"""
def __init__(self, label=""):
super().__init__("░")
self.top_connect = "░"
self.bot_connect = "░"
self.top_connector = {}
self.bot_connector = {}
class Ex(DirectOnQuWire):
""" Draws an X (usually with a connector). E.g. the top part of a swap gate
top:
mid: ─X─ ───X───
bot: │ │
"""
def __init__(self, bot_connect=" ", top_connect=" "):
super().__init__("X")
self.bot_connect = bot_connect
self.top_connect = top_connect
class Reset(DirectOnQuWire):
""" Draws a reset gate"""
def __init__(self):
super().__init__("|0>")
class Bullet(DirectOnQuWire):
""" Draws a bullet (usually with a connector). E.g. the top part of a CX gate.
top:
mid: ─■─ ───■───
bot: │ │
"""
def __init__(self, top_connect=" ", bot_connect=" "):
super().__init__('■')
self.top_connect = top_connect
self.bot_connect = bot_connect
class EmptyWire(DrawElement):
""" This element is just the wire, with no instructions nor operations."""
def __init__(self, wire):
super().__init__(wire)
self._mid_padding = wire
@staticmethod
def fillup_layer(layer, first_clbit):
"""
Given a layer, replace the Nones in it with EmptyWire elements.
Args:
layer (list): The layer that contains Nones.
first_clbit (int): The first wire that is classic.
Returns:
list: The new layer, with no Nones.
"""
for nones in [i for i, x in enumerate(layer) if x is None]:
layer[nones] = EmptyWire('═') if nones >= first_clbit else EmptyWire('─')
return layer
class BreakWire(DrawElement):
""" This element is used to break the drawing in several pages."""
def __init__(self, arrow_char):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = arrow_char
self.mid_content = arrow_char
self.bot_connect = arrow_char
@staticmethod
def fillup_layer(layer_length, arrow_char):
"""
Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer.
"""
breakwire_layer = []
for _ in range(layer_length):
breakwire_layer.append(BreakWire(arrow_char))
return breakwire_layer
class InputWire(DrawElement):
""" This element is the label and the initial value of a wire."""
def __init__(self, label):
super().__init__(label)
@staticmethod
def fillup_layer(names): # pylint: disable=arguments-differ
"""
Creates a layer with InputWire elements.
Args:
names (list): List of names for the wires.
Returns:
list: The new layer
"""
longest = max([len(name) for name in names])
inputs_wires = []
for name in names:
inputs_wires.append(InputWire(name.rjust(longest)))
return inputs_wires
class TextDrawing():
""" The text drawing"""
def __init__(self, json_circuit, reversebits=False, plotbarriers=True):
self.json_circuit = json_circuit
self.reversebits = reversebits
self.plotbarriers = plotbarriers
self.qubitorder = self._get_qubitorder()
self.clbitorder = self._get_clbitorder()
def _get_qubit_labels(self):
qubits = []
for qubit in self.json_circuit['header']['qubit_labels']:
qubits.append("%s_%s" % (qubit[0], qubit[1]))
return qubits
def _get_clbit_labels(self):
clbits = []
for creg in self.json_circuit['header']['clbit_labels']:
for clbit in range(creg[1]):
clbits.append("%s_%s" % (creg[0], clbit))
return clbits
def _get_qubitorder(self):
header = self.json_circuit['header']
if not self.reversebits:
return [qub for qub in range(header['number_of_qubits'])]
qreg_dest_order = []
for _, qubits in groupby(header['qubit_labels'], lambda x: x[0]):
qubits = [qubit for qubit in qubits]
qubits.reverse()
for qubit in qubits:
qreg_dest_order.append("%s_%s" % (qubit[0], qubit[1]))
return [qreg_dest_order.index(ind) for ind in self._get_qubit_labels()]
def _get_clbitorder(self):
header = self.json_circuit['header']
if not self.reversebits:
return [clb for clb in range(header['number_of_clbits'])]
creg_dest_order = []
for creg in self.json_circuit['header']['clbit_labels']:
bit_nos = [bit for bit in range(creg[1])]
bit_nos.reverse()
for clbit in bit_nos:
creg_dest_order.append("%s_%s" % (creg[0], clbit))
return [creg_dest_order.index(ind) for ind in self._get_clbit_labels()]
def lines(self, line_length=None):
"""
Generates a list with lines. These lines form the text drawing.
Args:
line_length (int): Optional. When given, breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console.
Returns:
list: A list of lines with the text drawing.
"""
noqubits = self.json_circuit['header']['number_of_qubits']
layers = self.build_layers()
# TODO compress layers
# -| H |----------
# --------| H |---
# should be
# -| H |---
# -| H |---
layer_groups = [[]]
rest_of_the_line = line_length
for layerno, layer in enumerate(layers):
# Replace the Nones with EmptyWire
layers[layerno] = EmptyWire.fillup_layer(layer, noqubits)
TextDrawing.normalize_width(layer)
if line_length is None:
# does not page
layer_groups[-1].append(layer)
continue
# chop the layer to the line_length (pager)
layer_length = layers[layerno][0].length
if layer_length < rest_of_the_line:
layer_groups[-1].append(layer)
rest_of_the_line -= layer_length
else:
layer_groups[-1].append(BreakWire.fillup_layer(len(layer), '»'))
# New group
layer_groups.append([BreakWire.fillup_layer(len(layer), '«')])
rest_of_the_line = line_length - layer_groups[-1][-1][0].length
layer_groups[-1].append(
InputWire.fillup_layer(self.wire_names(with_initial_value=False)))
rest_of_the_line -= layer_groups[-1][-1][0].length
layer_groups[-1].append(layer)
rest_of_the_line -= layer_groups[-1][-1][0].length
lines = []
for layer_group in layer_groups:
wires = [i for i in zip(*layer_group)]
lines += TextDrawing.draw_wires(wires)
return lines
def wire_names(self, with_initial_value=True):
"""
Returns a list of names for each wire.
Args:
with_initial_value (bool): Optional (Default: True). If true, adds the initial value to
the name.
Returns:
List: The list of wire names.
"""
qubit_labels = self._get_qubit_labels()
clbit_labels = self._get_clbit_labels()
if with_initial_value:
qubit_labels = ['%s: |0>' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: 0 ' % clbit for clbit in clbit_labels]
else:
qubit_labels = ['%s: ' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: ' % clbit for clbit in clbit_labels]
qubit_wires = [None] * self.json_circuit['header']['number_of_qubits']
clbit_wires = [None] * self.json_circuit['header']['number_of_clbits']
for order, label in enumerate(qubit_labels):
qubit_wires[self.qubitorder[order]] = label
for order, label in enumerate(clbit_labels):
clbit_wires[self.clbitorder[order]] = label
return qubit_wires + clbit_wires
@staticmethod
def draw_wires(wires):
"""
Given a list of wires, creates a list of lines with the text drawing.
Args:
wires (list): A list of wires with instructions.
Returns:
list: A list of lines with the text drawing.
"""
lines = []
bot_line = None
for wire in wires:
# TOP
top_line = ""
for instruction in wire:
top_line += instruction.top
if bot_line is None:
lines.append(top_line)
else:
lines.append(TextDrawing.merge_lines(lines.pop(), top_line))
# MID
mid_line = ""
for instruction in wire:
mid_line += instruction.mid
lines.append(TextDrawing.merge_lines(lines[-1], mid_line, icod="bot"))
# BOT
bot_line = ""
for instruction in wire:
bot_line += instruction.bot
lines.append(TextDrawing.merge_lines(lines[-1], bot_line, icod="bot"))
return lines
@staticmethod
def label_for_conditional(instruction):
""" Creates the label for a conditional instruction."""
return "%s %s" % ('=', instruction['conditional']['val'])
@staticmethod
def params_for_label(instruction):
"""Get the params and format them to add them to a label. None of there is no param."""
if 'params' in instruction and instruction['params']:
return ['%.5g' % i for i in instruction['params']]
return None
@staticmethod
def label_for_box(instruction):
""" Creates the label for a box."""
label = instruction['name'].capitalize()
params = TextDrawing.params_for_label(instruction)
if params:
label += "(%s)" % ','.join(params)
return label
@staticmethod
def merge_lines(top, bot, icod="top"):
"""
Merges two lines (top and bot) in the way that the overlapping make senses.
Args:
top (str): the top line
bot (str): the bottom line
icod (top or bot): in case of doubt, which line should have priority? Default: "top".
Returns:
str: The merge of both lines.
"""
ret = ""
for topc, botc in zip(top, bot):
if topc == botc:
ret += topc
elif topc in '┼╪' and botc == " ":
ret += "│"
elif topc == " ":
ret += botc
elif topc in '┬╥' and botc in " ║│":
ret += topc
elif topc in '┬│' and botc == "═":
ret += '╪'
elif topc in '┬│' and botc == "─":
ret += '┼'
elif topc in '└┘║│░' and botc == " ":
ret += topc
elif topc in '─═' and botc == " " and icod == "top":
ret += topc
elif topc in '─═' and botc == " " and icod == "bot":
ret += botc
elif topc in "║╥" and botc in "═":
ret += "╬"
elif topc in "║╥" and botc in "─":
ret += "╫"
elif topc in '╫╬' and botc in " ":
ret += "║"
elif topc == '└' and botc == "┌":
ret += "├"
elif topc == '┘' and botc == "┐":
ret += "┤"
else:
ret += botc
return ret
def clbit_index_from_mask(self, mask):
"""
Given a mask, returns a list of classical indexes affected by that mask.
Args:
mask (int): The mask.
Returns:
list: A list of indexes affected by the mask.
"""
clbit_len = self.json_circuit['header']['number_of_clbits']
bit_mask = [bool(mask & (1 << n)) for n in range(clbit_len)]
return [i for i, x in enumerate(bit_mask) if x]
@staticmethod
def normalize_width(layer):
"""
When the elements of the layer have different widths, sets the width to the max elements.
Args:
layer (list): A list of elements.
"""
instructions = [instruction for instruction in filter(lambda x: x is not None, layer)]
longest = max([instruction.length for instruction in instructions])
for instruction in instructions:
instruction.length = longest
def build_layers(self):
"""
Constructs layers.
Returns:
list: List of DrawElements.
Raises:
Exception: When the drawing is, for some reason, impossible to be drawn.
"""
layers = []
layers.append(InputWire.fillup_layer(self.wire_names(with_initial_value=True)))
for instruction in self.json_circuit['instructions']:
layer = Layer(self.qubitorder, self.clbitorder)
connector_label = None
if instruction['name'] == 'measure':
layer.set_qubit(instruction['qubits'][0], MeasureFrom())
layer.set_clbit(instruction['clbits'][0], MeasureTo())
elif instruction['name'] == 'barrier':
# barrier
if not self.plotbarriers:
continue
for qubit in instruction['qubits']:
layer.set_qubit(qubit, Barrier())
elif instruction['name'] == 'swap':
# swap
for qubit in instruction['qubits']:
layer.set_qubit(qubit, Ex())
elif instruction['name'] == 'cswap':
# cswap
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Ex())
layer.set_qubit(instruction['qubits'][2], Ex())
elif instruction['name'] == 'reset':
layer.set_qubit(instruction['qubits'][0], Reset())
elif 'conditional' in instruction:
# conditional
clbits = self.clbit_index_from_mask(int(instruction['conditional']['mask'], 16))
cllabel = TextDrawing.label_for_conditional(instruction)
qulabel = TextDrawing.label_for_box(instruction)
layer.set_cl_multibox(clbits, cllabel, top_connect='┴')
layer.set_qubit(instruction['qubits'][0], BoxOnQuWire(qulabel, bot_connect='┬'))
elif instruction['name'] in ['cx', 'CX', 'ccx']:
# cx/ccx
for qubit in [qubit for qubit in instruction['qubits'][:-1]]:
layer.set_qubit(qubit, Bullet())
layer.set_qubit(instruction['qubits'][-1], BoxOnQuWire('X'))
elif instruction['name'] == 'cy':
# cy
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], BoxOnQuWire('Y'))
elif instruction['name'] == 'cz':
# cz
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Bullet())
elif instruction['name'] == 'ch':
# ch
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], BoxOnQuWire('H'))
elif instruction['name'] == 'cu1':
# cu1
connector_label = TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Bullet())
elif instruction['name'] == 'cu3':
# cu3
params = TextDrawing.params_for_label(instruction)
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1],
BoxOnQuWire("U3(%s)" % ','.join(params)))
elif instruction['name'] == 'crz':
# crz
label = "Rz(%s)" % TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1],
BoxOnQuWire(label))
elif len(instruction['qubits']) == 1 and 'clbits' not in instruction:
# unitary gate
layer.set_qubit(instruction['qubits'][0],
BoxOnQuWire(TextDrawing.label_for_box(instruction)))
elif len(instruction['qubits']) >= 2 and 'clbits' not in instruction:
# multiple qubit gate
layer.set_qu_multibox(instruction['qubits'], TextDrawing.label_for_box(instruction))
else:
raise Exception("I don't know how to handle this instruction", instruction)
layer.connect_with("│", connector_label)
layers.append(layer.full_layer)
return layers
class Layer:
""" A layer is the "column" of the circuit. """
def __init__(self, qubitorder, clbitorder):
self.qubitorder = qubitorder
self.clbitorder = clbitorder
self.qubit_layer = [None] * len(qubitorder)
self.clbit_layer = [None] * len(clbitorder)
@property
def full_layer(self):
"""
Returns the composition of qubits and classic wires.
Returns:
String: self.qubit_layer + self.clbit_layer
"""
return self.qubit_layer + self.clbit_layer
def set_qubit(self, qubit, element):
"""
Sets the qubit to the element
Args:
qubit (int): Qubit index.
element (DrawElement): Element to set in the qubit
"""
self.qubit_layer[self.qubitorder[qubit]] = element
def set_clbit(self, clbit, element):
"""
Sets the clbit to the element
Args:
clbit (int): Clbit index.
element (DrawElement): Element to set in the clbit
"""
self.clbit_layer[self.clbitorder[clbit]] = element
def _set_multibox(self, wire_type, bits, label, top_connect=None):
# pylint: disable=invalid-name
bits = sorted(bits)
if wire_type == "cl":
set_bit = self.set_clbit
BoxOnWire = BoxOnClWire
BoxOnWireTop = BoxOnClWireTop
BoxOnWireMid = BoxOnClWireMid
BoxOnWireBot = BoxOnClWireBot
elif wire_type == "qu":
set_bit = self.set_qubit
BoxOnWire = BoxOnQuWire
BoxOnWireTop = BoxOnQuWireTop
BoxOnWireMid = BoxOnQuWireMid
BoxOnWireBot = BoxOnQuWireBot
# Checks if qubits are consecutive
if bits != [i for i in range(bits[0], bits[-1] + 1)]:
raise Exception("I don't know how to build a gate with multiple bits when"
"they are not adjacent to each other")
if len(bits) == 1:
set_bit(bits[0], BoxOnWire(label, top_connect=top_connect))
else:
set_bit(bits[0], BoxOnWireTop(label, top_connect=top_connect))
for order, bit in enumerate(bits[1:-1], 1):
set_bit(bit, BoxOnWireMid(label, len(bits), order))
set_bit(bits[-1], BoxOnWireBot(label, len(bits)))
def set_cl_multibox(self, bits, label, top_connect='┴'):
"""
Sets the multi clbit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi clbit box.
top_connect (char): The char to connect the box on the top.
"""
self._set_multibox("cl", bits, label, top_connect=top_connect)
def set_qu_multibox(self, bits, label):
"""
Sets the multi qubit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi qubit box.
"""
self._set_multibox("qu", bits, label)
def connect_with(self, wire_char, label=None):
"""
Connects the elements in the layer using wire_char.
Args:
wire_char (char): For example '║' or '│'.
label (string): Some connectors have a label (see cu1, for example).
"""
affected_bits = [bit for bit in self.full_layer if bit is not None]
if len([qbit for qbit in self.qubit_layer if qbit is not None]) == 1:
# Nothing to connect
return
affected_bits[0].connect(wire_char, ['bot'])
for affected_bit in affected_bits[1:-1]:
affected_bit.connect(wire_char, ['bot', 'top'])
affected_bits[-1].connect(wire_char, ['top'], label)
if label:
for affected_bit in affected_bits:
affected_bit.right_fill = len(label) + len(affected_bit.mid)
<|code_end|>
|
Can not combine the Result object from the same backend (statevector)
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: the master branch
- **Python version**: 3.6.5
- **Operating system**: macOS 10.13
### What is the current behavior?
raise error
```
Traceback (most recent call last):
File "/Users/rchen/Developer/Quantum/qiskit-terra/qiskit/result/_result.py", line 125, in __add__
copy_of_self += other
File "/Users/rchen/Developer/Quantum/qiskit-terra/qiskit/result/_result.py", line 108, in __iadd__
raise QISKitError('Result objects from different backends cannot be combined.')
qiskit._qiskiterror.QISKitError: 'Result objects from different backends cannot be combined.'
```
### Steps to reproduce the problem
Code
```python
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
import qiskit as qk
import numpy as np
num_qubits = 2
q = QuantumRegister(num_qubits, name='q')
c = ClassicalRegister(num_qubits, name='c')
circuits = QuantumCircuit(q, c)
param_idx = 0
for qubit in range(num_qubits):
circuits.u3(0.0, 0.0, 0.0, q[qubit])
circuits.u1(3.0, q[qubit])
# circuits.measure(q, c)
my_backend = qk.Aer.get_backend('statevector_simulator')
qobj = qk.compile(circuits=circuits, backend=my_backend)
job = my_backend.run(qobj)
result_a = job.result()
qobj = qk.compile(circuits=circuits, backend=my_backend)
job = my_backend.run(qobj)
result_b = job.result()
result = result_a + result_b
```
### What is the expected behavior?
Result objects are combined without error
### Suggested solutions
None
Note: If I change the backend to `qasm_simulator`, there is no error.
|
qiskit/backends/aer/statevector_simulator.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""
Interface to C++ quantum circuit simulator with realistic noise.
"""
import logging
import uuid
from qiskit.qobj import QobjInstruction
from .qasm_simulator import QasmSimulator
from ._simulatorerror import SimulatorError
from .aerjob import AerJob
logger = logging.getLogger(__name__)
class StatevectorSimulator(QasmSimulator):
"""C++ statevector simulator"""
DEFAULT_CONFIGURATION = {
'name': 'statevector_simulator',
'url': 'https://github.com/QISKit/qiskit-terra/src/qasm-simulator-cpp',
'simulator': True,
'local': True,
'description': 'A C++ statevector simulator for qobj files',
'coupling_map': 'all-to-all',
'basis_gates': 'u1,u2,u3,cx,cz,id,x,y,z,h,s,sdg,t,tdg,rzz,load,save,snapshot'
}
def __init__(self, configuration=None, provider=None):
super().__init__(configuration=configuration or self.DEFAULT_CONFIGURATION.copy(),
provider=provider)
def run(self, qobj):
"""Run a qobj on the the backend."""
job_id = str(uuid.uuid4())
aer_job = AerJob(self, job_id, self._run_job, qobj)
aer_job.submit()
return aer_job
def _run_job(self, job_id, qobj):
"""Run a Qobj on the backend."""
self._validate(qobj)
final_state_key = 32767 # Internal key for final state snapshot
# Add final snapshots to circuits
for experiment in qobj.experiments:
experiment.instructions.append(
QobjInstruction(name='snapshot', params=[final_state_key])
)
result = super()._run_job(job_id, qobj)
# Replace backend name with current backend
result.backend_name = self.name
# Extract final state snapshot and move to 'statevector' data field
for experiment_result in result.results.values():
snapshots = experiment_result.snapshots
if str(final_state_key) in snapshots:
final_state_key = str(final_state_key)
# Pop off final snapshot added above
final_state = snapshots.pop(final_state_key, None)
final_state = final_state['statevector'][0]
# Add final state to results data
experiment_result.data['statevector'] = final_state
# Remove snapshot dict if empty
if snapshots == {}:
experiment_result.data.pop('snapshots', None)
return result
def _validate(self, qobj):
"""Semantic validations of the qobj which cannot be done via schemas.
Some of these may later move to backend schemas.
1. No shots
2. No measurements in the middle
"""
if qobj.config.shots != 1:
logger.info("statevector simulator only supports 1 shot. "
"Setting shots=1.")
qobj.config.shots = 1
for experiment in qobj.experiments:
if getattr(experiment.config, 'shots', 1) != 1:
logger.info("statevector simulator only supports 1 shot. "
"Setting shots=1 for circuit %s.", experiment.name)
experiment.config.shots = 1
for op in experiment.instructions:
if op.name in ['measure', 'reset']:
raise SimulatorError(
"In circuit {}: statevector simulator does not support "
"measure or reset.".format(experiment.header.name))
<|code_end|>
qiskit/backends/aer/statevector_simulator_py.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""Contains a (slow) python statevector simulator.
It simulates the statevector through a quantum circuit. It is exponential in
the number of qubits.
We advise using the c++ simulator or online simulator for larger size systems.
The input is a qobj dictionary and the output is a Result object.
The input qobj to this simulator has no shots, no measures, no reset, no noise.
"""
import logging
import uuid
from qiskit.backends.aer.aerjob import AerJob
from qiskit.backends.aer._simulatorerror import SimulatorError
from qiskit.qobj import QobjInstruction
from .qasm_simulator_py import QasmSimulatorPy
logger = logging.getLogger(__name__)
class StatevectorSimulatorPy(QasmSimulatorPy):
"""Python statevector simulator."""
DEFAULT_CONFIGURATION = {
'name': 'statevector_simulator_py',
'url': 'https://github.com/QISKit/qiskit-terra',
'simulator': True,
'local': True,
'description': 'A Python statevector simulator for qobj files',
'coupling_map': 'all-to-all',
'basis_gates': 'u1,u2,u3,cx,id,snapshot'
}
def __init__(self, configuration=None, provider=None):
super().__init__(configuration=configuration or self.DEFAULT_CONFIGURATION.copy(),
provider=provider)
def run(self, qobj):
"""Run qobj asynchronously.
Args:
qobj (dict): job description
Returns:
AerJob: derived from BaseJob
"""
job_id = str(uuid.uuid4())
aer_job = AerJob(self, job_id, self._run_job, qobj)
aer_job.submit()
return aer_job
def _run_job(self, job_id, qobj):
"""Run a Qobj on the backend."""
self._validate(qobj)
final_state_key = 32767 # Internal key for final state snapshot
# Add final snapshots to circuits
for experiment in qobj.experiments:
experiment.instructions.append(
QobjInstruction(name='snapshot', params=[final_state_key])
)
result = super()._run_job(job_id, qobj)
# Replace backend name with current backend
result.backend_name = self.name
# Extract final state snapshot and move to 'statevector' data field
for experiment_result in result.results.values():
snapshots = experiment_result.snapshots
if str(final_state_key) in snapshots:
final_state_key = str(final_state_key)
# Pop off final snapshot added above
final_state = snapshots.pop(final_state_key, None)
final_state = final_state['statevector'][0]
# Add final state to results data
experiment_result.data['statevector'] = final_state
# Remove snapshot dict if empty
if snapshots == {}:
experiment_result.data.pop('snapshots', None)
return result
def _validate(self, qobj):
"""Semantic validations of the qobj which cannot be done via schemas.
Some of these may later move to backend schemas.
1. No shots
2. No measurements in the middle
"""
if qobj.config.shots != 1:
logger.info("statevector simulator only supports 1 shot. "
"Setting shots=1.")
qobj.config.shots = 1
for experiment in qobj.experiments:
if getattr(experiment.config, 'shots', 1) != 1:
logger.info("statevector simulator only supports 1 shot. "
"Setting shots=1 for circuit %s.", experiment.name)
experiment.config.shots = 1
for op in experiment.instructions:
if op.name in ['measure', 'reset']:
raise SimulatorError(
"In circuit {}: statevector simulator does not support "
"measure or reset.".format(experiment.header.name))
<|code_end|>
|
qiskit/backends/aer/statevector_simulator.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""
Interface to C++ quantum circuit simulator with realistic noise.
"""
import logging
import uuid
from qiskit.qobj import QobjInstruction
from .qasm_simulator import QasmSimulator
from ._simulatorerror import SimulatorError
from .aerjob import AerJob
logger = logging.getLogger(__name__)
class StatevectorSimulator(QasmSimulator):
"""C++ statevector simulator"""
DEFAULT_CONFIGURATION = {
'name': 'statevector_simulator',
'url': 'https://github.com/QISKit/qiskit-terra/src/qasm-simulator-cpp',
'simulator': True,
'local': True,
'description': 'A C++ statevector simulator for qobj files',
'coupling_map': 'all-to-all',
'basis_gates': 'u1,u2,u3,cx,cz,id,x,y,z,h,s,sdg,t,tdg,rzz,load,save,snapshot'
}
def __init__(self, configuration=None, provider=None):
super().__init__(configuration=configuration or self.DEFAULT_CONFIGURATION.copy(),
provider=provider)
def run(self, qobj):
"""Run a qobj on the the backend."""
job_id = str(uuid.uuid4())
aer_job = AerJob(self, job_id, self._run_job, qobj)
aer_job.submit()
return aer_job
def _run_job(self, job_id, qobj):
"""Run a Qobj on the backend."""
self._validate(qobj)
final_state_key = 32767 # Internal key for final state snapshot
# Add final snapshots to circuits
for experiment in qobj.experiments:
experiment.instructions.append(
QobjInstruction(name='snapshot', params=[final_state_key])
)
result = super()._run_job(job_id, qobj)
# Extract final state snapshot and move to 'statevector' data field
for experiment_result in result.results.values():
snapshots = experiment_result.snapshots
if str(final_state_key) in snapshots:
final_state_key = str(final_state_key)
# Pop off final snapshot added above
final_state = snapshots.pop(final_state_key, None)
final_state = final_state['statevector'][0]
# Add final state to results data
experiment_result.data['statevector'] = final_state
# Remove snapshot dict if empty
if snapshots == {}:
experiment_result.data.pop('snapshots', None)
return result
def _validate(self, qobj):
"""Semantic validations of the qobj which cannot be done via schemas.
Some of these may later move to backend schemas.
1. No shots
2. No measurements in the middle
"""
if qobj.config.shots != 1:
logger.info("statevector simulator only supports 1 shot. "
"Setting shots=1.")
qobj.config.shots = 1
for experiment in qobj.experiments:
if getattr(experiment.config, 'shots', 1) != 1:
logger.info("statevector simulator only supports 1 shot. "
"Setting shots=1 for circuit %s.", experiment.name)
experiment.config.shots = 1
for op in experiment.instructions:
if op.name in ['measure', 'reset']:
raise SimulatorError(
"In circuit {}: statevector simulator does not support "
"measure or reset.".format(experiment.header.name))
<|code_end|>
qiskit/backends/aer/statevector_simulator_py.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""Contains a (slow) python statevector simulator.
It simulates the statevector through a quantum circuit. It is exponential in
the number of qubits.
We advise using the c++ simulator or online simulator for larger size systems.
The input is a qobj dictionary and the output is a Result object.
The input qobj to this simulator has no shots, no measures, no reset, no noise.
"""
import logging
import uuid
from qiskit.backends.aer.aerjob import AerJob
from qiskit.backends.aer._simulatorerror import SimulatorError
from qiskit.qobj import QobjInstruction
from .qasm_simulator_py import QasmSimulatorPy
logger = logging.getLogger(__name__)
class StatevectorSimulatorPy(QasmSimulatorPy):
"""Python statevector simulator."""
DEFAULT_CONFIGURATION = {
'name': 'statevector_simulator_py',
'url': 'https://github.com/QISKit/qiskit-terra',
'simulator': True,
'local': True,
'description': 'A Python statevector simulator for qobj files',
'coupling_map': 'all-to-all',
'basis_gates': 'u1,u2,u3,cx,id,snapshot'
}
def __init__(self, configuration=None, provider=None):
super().__init__(configuration=configuration or self.DEFAULT_CONFIGURATION.copy(),
provider=provider)
def run(self, qobj):
"""Run qobj asynchronously.
Args:
qobj (dict): job description
Returns:
AerJob: derived from BaseJob
"""
job_id = str(uuid.uuid4())
aer_job = AerJob(self, job_id, self._run_job, qobj)
aer_job.submit()
return aer_job
def _run_job(self, job_id, qobj):
"""Run a Qobj on the backend."""
self._validate(qobj)
final_state_key = 32767 # Internal key for final state snapshot
# Add final snapshots to circuits
for experiment in qobj.experiments:
experiment.instructions.append(
QobjInstruction(name='snapshot', params=[final_state_key])
)
result = super()._run_job(job_id, qobj)
# Extract final state snapshot and move to 'statevector' data field
for experiment_result in result.results.values():
snapshots = experiment_result.snapshots
if str(final_state_key) in snapshots:
final_state_key = str(final_state_key)
# Pop off final snapshot added above
final_state = snapshots.pop(final_state_key, None)
final_state = final_state['statevector'][0]
# Add final state to results data
experiment_result.data['statevector'] = final_state
# Remove snapshot dict if empty
if snapshots == {}:
experiment_result.data.pop('snapshots', None)
return result
def _validate(self, qobj):
"""Semantic validations of the qobj which cannot be done via schemas.
Some of these may later move to backend schemas.
1. No shots
2. No measurements in the middle
"""
if qobj.config.shots != 1:
logger.info("statevector simulator only supports 1 shot. "
"Setting shots=1.")
qobj.config.shots = 1
for experiment in qobj.experiments:
if getattr(experiment.config, 'shots', 1) != 1:
logger.info("statevector simulator only supports 1 shot. "
"Setting shots=1 for circuit %s.", experiment.name)
experiment.config.shots = 1
for op in experiment.instructions:
if op.name in ['measure', 'reset']:
raise SimulatorError(
"In circuit {}: statevector simulator does not support "
"measure or reset.".format(experiment.header.name))
<|code_end|>
|
Clifford simulator result() fails on any circuit
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: Latest master
- **Python version**: 3.7
- **Operating system**: Linux
### What is the current behavior?
When attempting to call execute() with the backend being the clifford simulator it always fails.
This was hit in trying to add some new tests that ran on all backends:
https://travis-ci.org/Qiskit/qiskit-terra/jobs/442859915#L1694
```
1: concurrent.futures.process._RemoteTraceback:
1: """
1: Traceback (most recent call last):
1: File "/opt/python/3.5.6/lib/python3.5/concurrent/futures/process.py", line 175, in _process_worker
1: r = call_item.fn(*call_item.args, **call_item.kwargs)
1: File "/home/travis/build/Qiskit/qiskit-terra/qiskit/backends/aer/qasm_simulator.py", line 151, in _run_job
1: if 'config' in qobj:
1: TypeError: argument of type 'Qobj' is not iterable
1: """
1:
1: The above exception was the direct cause of the following exception:
1:
1: Traceback (most recent call last):
1: File "/home/travis/build/Qiskit/qiskit-terra/test/python/test_result.py", line 136, in test_add_aer
1: result_a = qiskit.execute(qc1, backend).result()
1: File "/home/travis/build/Qiskit/qiskit-terra/qiskit/backends/aer/aerjob.py", line 37, in _wrapper
1: return func(self, *args, **kwargs)
1: File "/home/travis/build/Qiskit/qiskit-terra/qiskit/backends/aer/aerjob.py", line 92, in result
1: return self._future.result(timeout=timeout)
1: File "/opt/python/3.5.6/lib/python3.5/concurrent/futures/_base.py", line 405, in result
1: return self.__get_result()
1: File "/opt/python/3.5.6/lib/python3.5/concurrent/futures/_base.py", line 357, in __get_result
1: raise self._exception
1: TypeError: argument of type 'Qobj' is not iterable
```
### Steps to reproduce the problem
Build any circuit and run execute() and result() on it with the clifford simulator backend. For example:
```
import qiskit
qr = qiskit.QuantumRegister(2)
cr = qiskit.ClassicalRegister(2)
qc = qiskit.QuantumCircuit(qr, cr)
qc.h(qr[0])
qc.measure(qr, cr)
qiskit.execute(qc, 'clifford_simulator').result()
```
### What is the expected behavior?
The circuit runs on the simulator.
### Suggested solutions
Fix the underlying issue
|
qiskit/backends/aer/qasm_simulator.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Interface to C++ quantum circuit simulator with realistic noise.
"""
import uuid
import json
import logging
import os
import subprocess
from subprocess import PIPE
import platform
import numpy as np
from qiskit.result._utils import copy_qasm_from_qobj_into_result, result_from_old_style_dict
from qiskit.backends import BaseBackend
from qiskit.backends.aer.aerjob import AerJob
from qiskit.qobj import qobj_to_dict
logger = logging.getLogger(__name__)
EXTENSION = '.exe' if platform.system() == 'Windows' else ''
# Add path to compiled qasm simulator
DEFAULT_SIMULATOR_PATHS = [
# This is the path where Makefile creates the simulator by default
os.path.abspath(os.path.join(os.path.dirname(__file__),
'../../../out/src/qasm-simulator-cpp/qasm_simulator_cpp'
+ EXTENSION)),
# This is the path where PIP installs the simulator
os.path.abspath(os.path.join(os.path.dirname(__file__),
'qasm_simulator_cpp' + EXTENSION)),
]
class QasmSimulator(BaseBackend):
"""C++ quantum circuit simulator with realistic noise"""
DEFAULT_CONFIGURATION = {
'name': 'qasm_simulator',
'url': 'https://github.com/QISKit/qiskit-terra/src/qasm-simulator-cpp',
'simulator': True,
'local': True,
'description': 'A C++ realistic noise simulator for qobj files',
'coupling_map': 'all-to-all',
"basis_gates": 'u0,u1,u2,u3,cx,cz,id,x,y,z,h,s,sdg,t,tdg,rzz,' +
'snapshot,wait,noise,save,load'
}
def __init__(self, configuration=None, provider=None):
super().__init__(configuration=configuration or self.DEFAULT_CONFIGURATION.copy(),
provider=provider)
# Try to use the default executable if not specified.
if self._configuration.get('exe'):
paths = [self._configuration.get('exe')]
else:
paths = DEFAULT_SIMULATOR_PATHS
# Ensure that the executable is available.
try:
self._configuration['exe'] = next(
path for path in paths if (os.path.exists(path) and
os.path.getsize(path) > 100))
except StopIteration:
raise FileNotFoundError('Simulator executable not found (using %s)' %
self._configuration.get('exe', 'default locations'))
def run(self, qobj):
"""Run a qobj on the backend."""
job_id = str(uuid.uuid4())
aer_job = AerJob(self, job_id, self._run_job, qobj)
aer_job.submit()
return aer_job
def _run_job(self, job_id, qobj):
self._validate(qobj)
result = run(qobj, self._configuration['exe'])
result['job_id'] = job_id
copy_qasm_from_qobj_into_result(qobj, result)
return result_from_old_style_dict(
result, [circuit.header.name for circuit in qobj.experiments])
def _validate(self, qobj):
for experiment in qobj.experiments:
if 'measure' not in [op.name for
op in experiment.instructions]:
logger.warning("no measurements in circuit '%s', "
"classical register will remain all zeros.",
experiment.header.name)
class CliffordSimulator(BaseBackend):
""""C++ Clifford circuit simulator with realistic noise."""
DEFAULT_CONFIGURATION = {
'name': 'clifford_simulator',
'url': 'https://github.com/QISKit/qiskit-terra/src/qasm-simulator',
'simulator': True,
'local': True,
'description': 'A C++ Clifford simulator with approximate noise',
'coupling_map': 'all-to-all',
'basis_gates': 'cx,id,x,y,z,h,s,sdg,snapshot,wait,noise,save,load'
}
def __init__(self, configuration=None, provider=None):
super().__init__(configuration=configuration or self.DEFAULT_CONFIGURATION.copy(),
provider=provider)
# Try to use the default executable if not specified.
if self._configuration.get('exe'):
paths = [self._configuration.get('exe')]
else:
paths = DEFAULT_SIMULATOR_PATHS
# Ensure that the executable is available.
try:
self._configuration['exe'] = next(
path for path in paths if (os.path.exists(path) and
os.path.getsize(path) > 100))
except StopIteration:
raise FileNotFoundError('Simulator executable not found (using %s)' %
self._configuration.get('exe', 'default locations'))
def run(self, qobj):
"""Run a Qobj on the backend.
Args:
qobj (dict): job description
Returns:
AerJob: derived from BaseJob
"""
job_id = str(uuid.uuid4())
aer_job = AerJob(self, job_id, self._run_job, qobj)
aer_job.submit()
return aer_job
def _run_job(self, job_id, qobj):
self._validate()
# set backend to Clifford simulator
if 'config' in qobj:
qobj['config']['simulator'] = 'clifford'
else:
qobj['config'] = {'simulator': 'clifford'}
result = run(qobj, self._configuration['exe'])
result['job_id'] = job_id
return result_from_old_style_dict(
result, [circuit.header.name for circuit in qobj.experiments])
def _validate(self):
return
class QASMSimulatorEncoder(json.JSONEncoder):
"""
JSON encoder for NumPy arrays and complex numbers.
This functions as the standard JSON Encoder but adds support
for encoding:
* complex numbers z as lists [z.real, z.imag]
* ndarrays as nested lists.
"""
# pylint: disable=method-hidden,arguments-differ
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, complex):
return [obj.real, obj.imag]
return json.JSONEncoder.default(self, obj)
class QASMSimulatorDecoder(json.JSONDecoder):
"""
JSON decoder for the output from C++ qasm_simulator.
This converts complex vectors and matrices into numpy arrays
for the following keys.
"""
def __init__(self, *args, **kwargs):
json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)
# pylint: disable=method-hidden
def object_hook(self, obj):
"""Special decoding rules for simulator output."""
for key in ['U_error', 'density_matrix']:
# JSON is a complex matrix
if key in obj and isinstance(obj[key], list):
tmp = np.array(obj[key])
obj[key] = tmp[::, ::, 0] + 1j * tmp[::, ::, 1]
for key in ['statevector', 'inner_products']:
# JSON is a list of complex vectors
if key in obj:
for j in range(len(obj[key])):
if isinstance(obj[key][j], list):
tmp = np.array(obj[key][j])
obj[key][j] = tmp[::, 0] + 1j * tmp[::, 1]
return obj
def run(qobj, executable):
"""
Run simulation on C++ simulator inside a subprocess.
Args:
qobj (Qobj): qobj dictionary defining the simulation to run
executable (string): filename (with path) of the simulator executable
Returns:
dict: A dict of simulation results
"""
# Open subprocess and execute external command
try:
with subprocess.Popen([executable, '-'],
stdin=PIPE, stdout=PIPE, stderr=PIPE) as proc:
cin = json.dumps(qobj_to_dict(qobj, version='0.0.1'),
cls=QASMSimulatorEncoder).encode()
cout, cerr = proc.communicate(cin)
if cerr:
logger.error('ERROR: Simulator encountered a runtime error: %s',
cerr.decode())
sim_output = cout.decode()
return json.loads(sim_output, cls=QASMSimulatorDecoder)
except FileNotFoundError:
msg = "ERROR: Simulator exe not found at: %s" % executable
logger.error(msg)
return {"status": msg, "success": False}
def cx_error_matrix(cal_error, zz_error):
"""
Return the coherent error matrix for CR error model of a CNOT gate.
Args:
cal_error (double): calibration error of rotation
zz_error (double): ZZ interaction term error
Returns:
numpy.ndarray: A coherent error matrix U_error for the CNOT gate.
Details:
The ideal cross-resonsance (CR) gate corresponds to a 2-qubit rotation
U_CR_ideal = exp(-1j * (pi/2) * XZ/2)
where qubit-0 is the control, and qubit-1 is the target. This can be
converted to a CNOT gate by single-qubit rotations::
U_CX = U_L * U_CR_ideal * U_R
The noisy rotation is implemented as
U_CR_noise = exp(-1j * (pi/2 + cal_error) * (XZ + zz_error ZZ)/2)
The retured error matrix is given by
U_error = U_L * U_CR_noise * U_R * U_CX^dagger
"""
# pylint: disable=invalid-name
if cal_error == 0 and zz_error == 0:
return np.eye(4)
cx_ideal = np.array([[1, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 0]])
b = np.sqrt(1.0 + zz_error * zz_error)
a = b * (np.pi / 2.0 + cal_error) / 2.0
sp = (1.0 + 1j * zz_error) * np.sin(a) / b
sm = (1.0 - 1j * zz_error) * np.sin(a) / b
c = np.cos(a)
cx_noise = np.array([[c + sm, 0, -1j * (c - sm), 0],
[0, 1j * (c - sm), 0, c + sm],
[-1j * (c - sp), 0, c + sp, 0],
[0, c + sp, 0, 1j * (c - sp)]]) / np.sqrt(2)
return cx_noise.dot(cx_ideal.conj().T)
def x90_error_matrix(cal_error, detuning_error):
"""
Return the coherent error matrix for a X90 rotation gate.
Args:
cal_error (double): calibration error of rotation
detuning_error (double): detuning amount for rotation axis error
Returns:
numpy.ndarray: A coherent error matrix U_error for the X90 gate.
Details:
The ideal X90 rotation is a pi/2 rotation about the X-axis:
U_X90_ideal = exp(-1j (pi/2) X/2)
The noisy rotation is implemented as
U_X90_noise = exp(-1j (pi/2 + cal_error) (cos(d) X + sin(d) Y)/2)
where d is the detuning_error.
The retured error matrix is given by
U_error = U_X90_noise * U_X90_ideal^dagger
"""
# pylint: disable=invalid-name
if cal_error == 0 and detuning_error == 0:
return np.eye(2)
else:
x90_ideal = np.array([[1., -1.j], [-1.j, 1]]) / np.sqrt(2)
c = np.cos(0.5 * cal_error)
s = np.sin(0.5 * cal_error)
gamma = np.exp(-1j * detuning_error)
x90_noise = np.array([[c - s, -1j * (c + s) * gamma],
[-1j * (c + s) * np.conj(gamma), c - s]]) / np.sqrt(2)
return x90_noise.dot(x90_ideal.conj().T)
def _generate_coherent_error_matrix(config):
"""
Generate U_error matrix for CX and X90 gates.
Args:
config (dict): the config of a qobj circuit
This parses the config for the following noise parameter keys and returns a
coherent error matrix for simulation coherent noise::
* 'CX' gate: 'calibration_error', 'zz_error'
* 'X90' gate: 'calibration_error', 'detuning_error'
"""
# pylint: disable=invalid-name
if 'noise_params' in config:
# Check for CR coherent error parameters
if 'CX' in config['noise_params']:
noise_cx = config['noise_params']['CX']
cal_error = noise_cx.pop('calibration_error', 0)
zz_error = noise_cx.pop('zz_error', 0)
# Add to current coherent error matrix
if not cal_error == 0 or not zz_error == 0:
u_error = noise_cx.get('U_error', np.eye(4))
u_error = u_error.dot(cx_error_matrix(cal_error, zz_error))
config['noise_params']['CX']['U_error'] = u_error
# Check for X90 coherent error parameters
if 'X90' in config['noise_params']:
noise_x90 = config['noise_params']['X90']
cal_error = noise_x90.pop('calibration_error', 0)
detuning_error = noise_x90.pop('detuning_error', 0)
# Add to current coherent error matrix
if not cal_error == 0 or not detuning_error == 0:
u_error = noise_x90.get('U_error', np.eye(2))
u_error = u_error.dot(x90_error_matrix(cal_error,
detuning_error))
config['noise_params']['X90']['U_error'] = u_error
<|code_end|>
|
qiskit/backends/aer/qasm_simulator.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Interface to C++ quantum circuit simulator with realistic noise.
"""
import uuid
import json
import logging
import os
import subprocess
from subprocess import PIPE
import platform
import numpy as np
from qiskit.result._utils import copy_qasm_from_qobj_into_result, result_from_old_style_dict
from qiskit.backends import BaseBackend
from qiskit.backends.aer.aerjob import AerJob
from qiskit.qobj import Qobj
from qiskit.qobj import qobj_to_dict
logger = logging.getLogger(__name__)
EXTENSION = '.exe' if platform.system() == 'Windows' else ''
# Add path to compiled qasm simulator
DEFAULT_SIMULATOR_PATHS = [
# This is the path where Makefile creates the simulator by default
os.path.abspath(os.path.join(os.path.dirname(__file__),
'../../../out/src/qasm-simulator-cpp/qasm_simulator_cpp'
+ EXTENSION)),
# This is the path where PIP installs the simulator
os.path.abspath(os.path.join(os.path.dirname(__file__),
'qasm_simulator_cpp' + EXTENSION)),
]
class QasmSimulator(BaseBackend):
"""C++ quantum circuit simulator with realistic noise"""
DEFAULT_CONFIGURATION = {
'name': 'qasm_simulator',
'url': 'https://github.com/QISKit/qiskit-terra/src/qasm-simulator-cpp',
'simulator': True,
'local': True,
'description': 'A C++ realistic noise simulator for qobj files',
'coupling_map': 'all-to-all',
"basis_gates": 'u0,u1,u2,u3,cx,cz,id,x,y,z,h,s,sdg,t,tdg,rzz,' +
'snapshot,wait,noise,save,load'
}
def __init__(self, configuration=None, provider=None):
super().__init__(configuration=configuration or self.DEFAULT_CONFIGURATION.copy(),
provider=provider)
# Try to use the default executable if not specified.
if self._configuration.get('exe'):
paths = [self._configuration.get('exe')]
else:
paths = DEFAULT_SIMULATOR_PATHS
# Ensure that the executable is available.
try:
self._configuration['exe'] = next(
path for path in paths if (os.path.exists(path) and
os.path.getsize(path) > 100))
except StopIteration:
raise FileNotFoundError('Simulator executable not found (using %s)' %
self._configuration.get('exe', 'default locations'))
def run(self, qobj):
"""Run a qobj on the backend."""
job_id = str(uuid.uuid4())
aer_job = AerJob(self, job_id, self._run_job, qobj)
aer_job.submit()
return aer_job
def _run_job(self, job_id, qobj):
self._validate(qobj)
result = run(qobj, self._configuration['exe'])
result['job_id'] = job_id
copy_qasm_from_qobj_into_result(qobj, result)
return result_from_old_style_dict(
result, [circuit.header.name for circuit in qobj.experiments])
def _validate(self, qobj):
for experiment in qobj.experiments:
if 'measure' not in [op.name for
op in experiment.instructions]:
logger.warning("no measurements in circuit '%s', "
"classical register will remain all zeros.",
experiment.header.name)
class CliffordSimulator(BaseBackend):
""""C++ Clifford circuit simulator with realistic noise."""
DEFAULT_CONFIGURATION = {
'name': 'clifford_simulator',
'url': 'https://github.com/QISKit/qiskit-terra/src/qasm-simulator',
'simulator': True,
'local': True,
'description': 'A C++ Clifford simulator with approximate noise',
'coupling_map': 'all-to-all',
'basis_gates': 'cx,id,x,y,z,h,s,sdg,snapshot,wait,noise,save,load'
}
def __init__(self, configuration=None, provider=None):
super().__init__(configuration=configuration or self.DEFAULT_CONFIGURATION.copy(),
provider=provider)
# Try to use the default executable if not specified.
if self._configuration.get('exe'):
paths = [self._configuration.get('exe')]
else:
paths = DEFAULT_SIMULATOR_PATHS
# Ensure that the executable is available.
try:
self._configuration['exe'] = next(
path for path in paths if (os.path.exists(path) and
os.path.getsize(path) > 100))
except StopIteration:
raise FileNotFoundError('Simulator executable not found (using %s)' %
self._configuration.get('exe', 'default locations'))
def run(self, qobj):
"""Run a Qobj on the backend.
Args:
qobj (dict): job description
Returns:
AerJob: derived from BaseJob
"""
job_id = str(uuid.uuid4())
aer_job = AerJob(self, job_id, self._run_job, qobj)
aer_job.submit()
return aer_job
def _run_job(self, job_id, qobj):
if isinstance(qobj, Qobj):
qobj_dict = qobj.as_dict()
else:
qobj_dict = qobj
self._validate()
# set backend to Clifford simulator
if 'config' in qobj_dict:
qobj_dict['config']['simulator'] = 'clifford'
else:
qobj_dict['config'] = {'simulator': 'clifford'}
qobj = Qobj.from_dict(qobj_dict)
result = run(qobj, self._configuration['exe'])
result['job_id'] = job_id
return result_from_old_style_dict(
result, [circuit.header.name for circuit in qobj.experiments])
def _validate(self):
return
class QASMSimulatorEncoder(json.JSONEncoder):
"""
JSON encoder for NumPy arrays and complex numbers.
This functions as the standard JSON Encoder but adds support
for encoding:
* complex numbers z as lists [z.real, z.imag]
* ndarrays as nested lists.
"""
# pylint: disable=method-hidden,arguments-differ
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, complex):
return [obj.real, obj.imag]
return json.JSONEncoder.default(self, obj)
class QASMSimulatorDecoder(json.JSONDecoder):
"""
JSON decoder for the output from C++ qasm_simulator.
This converts complex vectors and matrices into numpy arrays
for the following keys.
"""
def __init__(self, *args, **kwargs):
json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)
# pylint: disable=method-hidden
def object_hook(self, obj):
"""Special decoding rules for simulator output."""
for key in ['U_error', 'density_matrix']:
# JSON is a complex matrix
if key in obj and isinstance(obj[key], list):
tmp = np.array(obj[key])
obj[key] = tmp[::, ::, 0] + 1j * tmp[::, ::, 1]
for key in ['statevector', 'inner_products']:
# JSON is a list of complex vectors
if key in obj:
for j in range(len(obj[key])):
if isinstance(obj[key][j], list):
tmp = np.array(obj[key][j])
obj[key][j] = tmp[::, 0] + 1j * tmp[::, 1]
return obj
def run(qobj, executable):
"""
Run simulation on C++ simulator inside a subprocess.
Args:
qobj (Qobj): qobj dictionary defining the simulation to run
executable (string): filename (with path) of the simulator executable
Returns:
dict: A dict of simulation results
"""
# Open subprocess and execute external command
try:
with subprocess.Popen([executable, '-'],
stdin=PIPE, stdout=PIPE, stderr=PIPE) as proc:
cin = json.dumps(qobj_to_dict(qobj, version='0.0.1'),
cls=QASMSimulatorEncoder).encode()
cout, cerr = proc.communicate(cin)
if cerr:
logger.error('ERROR: Simulator encountered a runtime error: %s',
cerr.decode())
sim_output = cout.decode()
return json.loads(sim_output, cls=QASMSimulatorDecoder)
except FileNotFoundError:
msg = "ERROR: Simulator exe not found at: %s" % executable
logger.error(msg)
return {"status": msg, "success": False}
def cx_error_matrix(cal_error, zz_error):
"""
Return the coherent error matrix for CR error model of a CNOT gate.
Args:
cal_error (double): calibration error of rotation
zz_error (double): ZZ interaction term error
Returns:
numpy.ndarray: A coherent error matrix U_error for the CNOT gate.
Details:
The ideal cross-resonsance (CR) gate corresponds to a 2-qubit rotation
U_CR_ideal = exp(-1j * (pi/2) * XZ/2)
where qubit-0 is the control, and qubit-1 is the target. This can be
converted to a CNOT gate by single-qubit rotations::
U_CX = U_L * U_CR_ideal * U_R
The noisy rotation is implemented as
U_CR_noise = exp(-1j * (pi/2 + cal_error) * (XZ + zz_error ZZ)/2)
The retured error matrix is given by
U_error = U_L * U_CR_noise * U_R * U_CX^dagger
"""
# pylint: disable=invalid-name
if cal_error == 0 and zz_error == 0:
return np.eye(4)
cx_ideal = np.array([[1, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 0]])
b = np.sqrt(1.0 + zz_error * zz_error)
a = b * (np.pi / 2.0 + cal_error) / 2.0
sp = (1.0 + 1j * zz_error) * np.sin(a) / b
sm = (1.0 - 1j * zz_error) * np.sin(a) / b
c = np.cos(a)
cx_noise = np.array([[c + sm, 0, -1j * (c - sm), 0],
[0, 1j * (c - sm), 0, c + sm],
[-1j * (c - sp), 0, c + sp, 0],
[0, c + sp, 0, 1j * (c - sp)]]) / np.sqrt(2)
return cx_noise.dot(cx_ideal.conj().T)
def x90_error_matrix(cal_error, detuning_error):
"""
Return the coherent error matrix for a X90 rotation gate.
Args:
cal_error (double): calibration error of rotation
detuning_error (double): detuning amount for rotation axis error
Returns:
numpy.ndarray: A coherent error matrix U_error for the X90 gate.
Details:
The ideal X90 rotation is a pi/2 rotation about the X-axis:
U_X90_ideal = exp(-1j (pi/2) X/2)
The noisy rotation is implemented as
U_X90_noise = exp(-1j (pi/2 + cal_error) (cos(d) X + sin(d) Y)/2)
where d is the detuning_error.
The retured error matrix is given by
U_error = U_X90_noise * U_X90_ideal^dagger
"""
# pylint: disable=invalid-name
if cal_error == 0 and detuning_error == 0:
return np.eye(2)
else:
x90_ideal = np.array([[1., -1.j], [-1.j, 1]]) / np.sqrt(2)
c = np.cos(0.5 * cal_error)
s = np.sin(0.5 * cal_error)
gamma = np.exp(-1j * detuning_error)
x90_noise = np.array([[c - s, -1j * (c + s) * gamma],
[-1j * (c + s) * np.conj(gamma), c - s]]) / np.sqrt(2)
return x90_noise.dot(x90_ideal.conj().T)
def _generate_coherent_error_matrix(config):
"""
Generate U_error matrix for CX and X90 gates.
Args:
config (dict): the config of a qobj circuit
This parses the config for the following noise parameter keys and returns a
coherent error matrix for simulation coherent noise::
* 'CX' gate: 'calibration_error', 'zz_error'
* 'X90' gate: 'calibration_error', 'detuning_error'
"""
# pylint: disable=invalid-name
if 'noise_params' in config:
# Check for CR coherent error parameters
if 'CX' in config['noise_params']:
noise_cx = config['noise_params']['CX']
cal_error = noise_cx.pop('calibration_error', 0)
zz_error = noise_cx.pop('zz_error', 0)
# Add to current coherent error matrix
if not cal_error == 0 or not zz_error == 0:
u_error = noise_cx.get('U_error', np.eye(4))
u_error = u_error.dot(cx_error_matrix(cal_error, zz_error))
config['noise_params']['CX']['U_error'] = u_error
# Check for X90 coherent error parameters
if 'X90' in config['noise_params']:
noise_x90 = config['noise_params']['X90']
cal_error = noise_x90.pop('calibration_error', 0)
detuning_error = noise_x90.pop('detuning_error', 0)
# Add to current coherent error matrix
if not cal_error == 0 or not detuning_error == 0:
u_error = noise_x90.get('U_error', np.eye(2))
u_error = u_error.dot(x90_error_matrix(cal_error,
detuning_error))
config['noise_params']['X90']['U_error'] = u_error
<|code_end|>
|
improve the speed of sgn_prod in pauli.py
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
Speed improvement.
Since current Pauli class use int or float vector to present `v` and `w` vector, it is inefficient if we would like to check it is X, Y, Z, or I (we need to compare `v` and `w` with 1 and 0.)
If we support native boolean representation, it will be faster.
Nonetheless, I do not have a good idea to change whole `Pauli` class to boolean representation while supports backward-compatibility.
Thus, a workaround to improve the speed of `sgn_prod` only, we can internally convert it to boolean and then use boolean to track the phase, and then convert `v` and `w` back to int or float.
here is the prototype of my implementation on `sgn_prod`:
```python
def sgn_prod(P1, P2):
"""Multiply two Paulis P1*P2 and track the sign.
P3 = P1*P2: X*Y
"""
if P1.numberofqubits != P2.numberofqubits:
print('Paulis cannot be multiplied - different number of qubits')
p1_v = P1.v.astype(np.bool)
p1_w = P1.w.astype(np.bool)
p2_v = P2.v.astype(np.bool)
p2_w = P2.w.astype(np.bool)
v_new = np.logical_xor(p1_v, p2_v).astype(np.int)
w_new = np.logical_xor(p1_w, p2_w).astype(np.int)
paulinew = Pauli(v_new, w_new)
phase = 0 # 1
for v1, w1, v2, w2 in zip(p1_v, p1_w, p2_v, p2_w):
if v1 and not w1: # Z
if w2:
phase = phase - 1 if v2 else phase + 1
elif not v1 and w1: # X
if v2:
phase = phase + 1 if w2 else phase - 1
elif v1 and w1: # Y
if not v2 and w2: # X
phase -= 1 # -1j * phase
elif v2 and not w2: # Z
phase += 1 # 1j * phase
phase = (1j) ** (phase % 4)
return paulinew, phase
```
and this is my test case:
```python
from qiskit.tools.qi.pauli import sgn_prod, Pauli, label_to_pauli
import itertools
import time
num_qubits = 5
# generate 2^num_qubits paulis
paulis = []
for pauli_label in itertools.product('IXYZ', repeat=num_qubits):
pauli_term = label_to_pauli(pauli_label)
paulis.append(pauli_term)
print("number of paulis: {}".format(len(paulis)))
start = time.time()
for pauli_a in paulis:
for pauli_b in paulis:
a, sign = sgn_prod(pauli_a, pauli_b)
end = time.time()
print(end-start)
```
Here is some benchmark on macOS 10.13, python 3.6
```
num_qubit=4
new implementation: 0.477 seconds
old implementation: 1.189 seconds
```
```
num_qubit=5
new implementation: 7.593 seconds
old implementation: 21.895 seconds
```
```
num_qubit=6
new implementation: 129.231 seconds
old implementation: 403.953 seconds
```
|
qiskit/tools/qi/pauli.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""
Tools for working with Pauli Operators.
A simple pauli class and some tools.
"""
import random
import numpy as np
from scipy import sparse
class Pauli:
"""A simple class representing Pauli Operators.
The form is P = (-i)^dot(v,w) Z^v X^w where v and w are elements of Z_2^n.
That is, there are 4^n elements (no phases in this group).
For example, for 1 qubit
P_00 = Z^0 X^0 = I
P_01 = X
P_10 = Z
P_11 = -iZX = (-i) iY = Y
Multiplication is P1*P2 = (-i)^dot(v1+v2,w1+w2) Z^(v1+v2) X^(w1+w2)
where the sums are taken modulo 2.
Pauli vectors v and w are supposed to be defined as numpy arrays.
Ref.
Jeroen Dehaene and Bart De Moor
Clifford group, stabilizer states, and linear and quadratic operations
over GF(2)
Phys. Rev. A 68, 042318 – Published 20 October 2003
"""
def __init__(self, v, w):
"""Make the Pauli class."""
self.numberofqubits = len(v)
self.v = v
self.w = w
def __str__(self):
"""Output the Pauli as first row v and second row w."""
stemp = 'v = '
for i in self.v:
stemp += str(i) + '\t'
stemp = stemp + '\nw = '
for j in self.w:
stemp += str(j) + '\t'
return stemp
def __eq__(self, other):
"""Return True if all Pauli terms are equal."""
bres = False
if self.numberofqubits == other.numberofqubits:
if np.all(self.v == other.v) and np.all(self.w == other.w):
bres = True
return bres
def __mul__(self, other):
"""Multiply two Paulis."""
if self.numberofqubits != other.numberofqubits:
print('These Paulis cannot be multiplied - different number '
'of qubits')
v_new = (self.v + other.v) % 2
w_new = (self.w + other.w) % 2
pauli_new = Pauli(v_new, w_new)
return pauli_new
def to_label(self):
"""Print out the labels in X, Y, Z format.
Returns:
str: pauli label
"""
p_label = ''
for j_index in range(self.numberofqubits):
if self.v[j_index] == 0 and self.w[j_index] == 0:
p_label += 'I'
elif self.v[j_index] == 0 and self.w[j_index] == 1:
p_label += 'X'
elif self.v[j_index] == 1 and self.w[j_index] == 1:
p_label += 'Y'
elif self.v[j_index] == 1 and self.w[j_index] == 0:
p_label += 'Z'
return p_label
def to_matrix(self):
"""Convert Pauli to a matrix representation.
Order is q_n x q_{n-1} .... q_0
Returns:
numpy.array: a matrix that represnets the pauli.
"""
x = np.array([[0, 1], [1, 0]], dtype=complex)
y = np.array([[0, -1j], [1j, 0]], dtype=complex)
z = np.array([[1, 0], [0, -1]], dtype=complex)
id_ = np.array([[1, 0], [0, 1]], dtype=complex)
matrix = 1
for k in range(self.numberofqubits):
if self.v[k] == 0 and self.w[k] == 0:
new = id_
elif self.v[k] == 1 and self.w[k] == 0:
new = z
elif self.v[k] == 0 and self.w[k] == 1:
new = x
elif self.v[k] == 1 and self.w[k] == 1:
new = y
else:
print('the string is not of the form 0 and 1')
matrix = np.kron(new, matrix)
return matrix
def to_spmatrix(self):
"""Convert Pauli to a sparse matrix representation (CSR format).
Order is q_n x q_{n-1} .... q_0
Returns:
scipy.sparse.csr_matrix: a sparse matrix with CSR format that
represnets the pauli.
"""
x = sparse.csr_matrix(np.array([[0, 1], [1, 0]], dtype=complex))
y = sparse.csr_matrix(np.array([[0, -1j], [1j, 0]], dtype=complex))
z = sparse.csr_matrix(np.array([[1, 0], [0, -1]], dtype=complex))
id_ = sparse.csr_matrix(np.array([[1, 0], [0, 1]], dtype=complex))
matrix = 1
for k in range(self.numberofqubits):
if self.v[k] == 0 and self.w[k] == 0:
new = id_
elif self.v[k] == 1 and self.w[k] == 0:
new = z
elif self.v[k] == 0 and self.w[k] == 1:
new = x
elif self.v[k] == 1 and self.w[k] == 1:
new = y
else:
print('the string is not of the form 0 and 1')
matrix = sparse.kron(new, matrix, 'csr')
return matrix
def random_pauli(number_qubits):
"""Return a random Pauli on numberofqubits."""
v = np.array(list(bin(random.getrandbits(number_qubits))
[2:].zfill(number_qubits))).astype(np.int)
w = np.array(list(bin(random.getrandbits(number_qubits))
[2:].zfill(number_qubits))).astype(np.int)
return Pauli(v, w)
def sgn_prod(P1, P2):
"""Multiply two Paulis P1*P2 and track the sign.
P3 = P1*P2: X*Y
"""
if P1.numberofqubits != P2.numberofqubits:
print('Paulis cannot be multiplied - different number of qubits')
v_new = (P1.v + P2.v) % 2
w_new = (P1.w + P2.w) % 2
paulinew = Pauli(v_new, w_new)
phase = 1
for i in range(len(P1.v)):
if P1.v[i] == 1 and P1.w[i] == 0 and P2.v[i] == 0 and P2.w[i] == 1:
# Z*X
phase = 1j * phase
elif P1.v[i] == 0 and P1.w[i] == 1 and P2.v[i] == 1 and P2.w[i] == 0:
# X*Z
phase = -1j * phase
elif P1.v[i] == 0 and P1.w[i] == 1 and P2.v[i] == 1 and P2.w[i] == 1:
# X*Y
phase = 1j * phase
elif P1.v[i] == 1 and P1.w[i] == 1 and P2.v[i] == 0 and P2.w[i] == 1:
# Y*X
phase = -1j * phase
elif P1.v[i] == 1 and P1.w[i] == 1 and P2.v[i] == 1 and P2.w[i] == 0:
# Y*Z
phase = 1j * phase
elif P1.v[i] == 1 and P1.w[i] == 0 and P2.v[i] == 1 and P2.w[i] == 1:
# Z*Y
phase = -1j * phase
return paulinew, phase
def inverse_pauli(other):
"""Return the inverse of a Pauli."""
v = other.v
w = other.w
return Pauli(v, w)
def label_to_pauli(label):
"""Return the pauli of a string ."""
v = np.zeros(len(label))
w = np.zeros(len(label))
for j, _ in enumerate(label):
if label[j] == 'I':
v[j] = 0
w[j] = 0
elif label[j] == 'Z':
v[j] = 1
w[j] = 0
elif label[j] == 'Y':
v[j] = 1
w[j] = 1
elif label[j] == 'X':
v[j] = 0
w[j] = 1
else:
print('something went wrong')
return -1
return Pauli(v, w)
def pauli_group(number_of_qubits, case=0):
"""Return the Pauli group with 4^n elements.
The phases have been removed.
case 0 is ordered by Pauli weights and
case 1 is ordered by I,X,Y,Z counting last qubit fastest.
Args:
number_of_qubits (int): number of qubits
case (int): determines ordering of group elements (0=weight, 1=tensor)
Returns:
list: list of Pauli objects
Note:
WARNING THIS IS EXPONENTIAL
"""
if number_of_qubits < 5:
temp_set = []
if case == 0:
tmp = pauli_group(number_of_qubits, case=1)
# sort on the weight of the Pauli operator
return sorted(tmp, key=lambda x: -np.count_nonzero(
np.array(x.to_label(), 'c') == b'I'))
elif case == 1:
# the Pauli set is in tensor order II IX IY IZ XI ...
for k_index in range(4 ** number_of_qubits):
v = np.zeros(number_of_qubits)
w = np.zeros(number_of_qubits)
# looping over all the qubits
for j_index in range(number_of_qubits):
# making the Pauli for each kindex i fill it in from the
# end first
element = int((k_index) / (4 ** (j_index))) % 4
if element == 0:
v[j_index] = 0
w[j_index] = 0
elif element == 1:
v[j_index] = 0
w[j_index] = 1
elif element == 2:
v[j_index] = 1
w[j_index] = 1
elif element == 3:
v[j_index] = 1
w[j_index] = 0
temp_set.append(Pauli(v, w))
return temp_set
print('please set the number of qubits to less than 5')
return -1
def pauli_singles(j_index, number_qubits):
"""Return the single qubit pauli in number_qubits."""
# looping over all the qubits
tempset = []
v = np.zeros(number_qubits)
w = np.zeros(number_qubits)
v[j_index] = 0
w[j_index] = 1
tempset.append(Pauli(v, w))
v = np.zeros(number_qubits)
w = np.zeros(number_qubits)
v[j_index] = 1
w[j_index] = 1
tempset.append(Pauli(v, w))
v = np.zeros(number_qubits)
w = np.zeros(number_qubits)
v[j_index] = 1
w[j_index] = 0
tempset.append(Pauli(v, w))
return tempset
<|code_end|>
|
qiskit/tools/qi/pauli.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""
Tools for working with Pauli Operators.
A simple pauli class and some tools.
"""
import random
import numpy as np
from scipy import sparse
class Pauli:
"""A simple class representing Pauli Operators.
The form is P = (-i)^dot(v,w) Z^v X^w where v and w are elements of Z_2^n.
That is, there are 4^n elements (no phases in this group).
For example, for 1 qubit
P_00 = Z^0 X^0 = I
P_01 = X
P_10 = Z
P_11 = -iZX = (-i) iY = Y
Multiplication is P1*P2 = (-i)^dot(v1+v2,w1+w2) Z^(v1+v2) X^(w1+w2)
where the sums are taken modulo 2.
Pauli vectors v and w are supposed to be defined as numpy arrays.
Ref.
Jeroen Dehaene and Bart De Moor
Clifford group, stabilizer states, and linear and quadratic operations
over GF(2)
Phys. Rev. A 68, 042318 – Published 20 October 2003
"""
def __init__(self, v, w):
"""Make the Pauli class."""
self.numberofqubits = len(v)
self.v = v
self.w = w
def __str__(self):
"""Output the Pauli as first row v and second row w."""
stemp = 'v = '
for i in self.v:
stemp += str(i) + '\t'
stemp = stemp + '\nw = '
for j in self.w:
stemp += str(j) + '\t'
return stemp
def __eq__(self, other):
"""Return True if all Pauli terms are equal."""
bres = False
if self.numberofqubits == other.numberofqubits:
if np.all(self.v == other.v) and np.all(self.w == other.w):
bres = True
return bres
def __mul__(self, other):
"""Multiply two Paulis."""
if self.numberofqubits != other.numberofqubits:
print('These Paulis cannot be multiplied - different number '
'of qubits')
v_new = (self.v + other.v) % 2
w_new = (self.w + other.w) % 2
pauli_new = Pauli(v_new, w_new)
return pauli_new
def to_label(self):
"""Print out the labels in X, Y, Z format.
Returns:
str: pauli label
"""
p_label = ''
for j_index in range(self.numberofqubits):
if self.v[j_index] == 0 and self.w[j_index] == 0:
p_label += 'I'
elif self.v[j_index] == 0 and self.w[j_index] == 1:
p_label += 'X'
elif self.v[j_index] == 1 and self.w[j_index] == 1:
p_label += 'Y'
elif self.v[j_index] == 1 and self.w[j_index] == 0:
p_label += 'Z'
return p_label
def to_matrix(self):
"""Convert Pauli to a matrix representation.
Order is q_n x q_{n-1} .... q_0
Returns:
numpy.array: a matrix that represnets the pauli.
"""
x = np.array([[0, 1], [1, 0]], dtype=complex)
y = np.array([[0, -1j], [1j, 0]], dtype=complex)
z = np.array([[1, 0], [0, -1]], dtype=complex)
id_ = np.array([[1, 0], [0, 1]], dtype=complex)
matrix = 1
for k in range(self.numberofqubits):
if self.v[k] == 0 and self.w[k] == 0:
new = id_
elif self.v[k] == 1 and self.w[k] == 0:
new = z
elif self.v[k] == 0 and self.w[k] == 1:
new = x
elif self.v[k] == 1 and self.w[k] == 1:
new = y
else:
print('the string is not of the form 0 and 1')
matrix = np.kron(new, matrix)
return matrix
def to_spmatrix(self):
"""Convert Pauli to a sparse matrix representation (CSR format).
Order is q_n x q_{n-1} .... q_0
Returns:
scipy.sparse.csr_matrix: a sparse matrix with CSR format that
represnets the pauli.
"""
x = sparse.csr_matrix(np.array([[0, 1], [1, 0]], dtype=complex))
y = sparse.csr_matrix(np.array([[0, -1j], [1j, 0]], dtype=complex))
z = sparse.csr_matrix(np.array([[1, 0], [0, -1]], dtype=complex))
id_ = sparse.csr_matrix(np.array([[1, 0], [0, 1]], dtype=complex))
matrix = 1
for k in range(self.numberofqubits):
if self.v[k] == 0 and self.w[k] == 0:
new = id_
elif self.v[k] == 1 and self.w[k] == 0:
new = z
elif self.v[k] == 0 and self.w[k] == 1:
new = x
elif self.v[k] == 1 and self.w[k] == 1:
new = y
else:
print('the string is not of the form 0 and 1')
matrix = sparse.kron(new, matrix, 'csr')
return matrix
def random_pauli(number_qubits):
"""Return a random Pauli on numberofqubits."""
v = np.array(list(bin(random.getrandbits(number_qubits))
[2:].zfill(number_qubits))).astype(np.int)
w = np.array(list(bin(random.getrandbits(number_qubits))
[2:].zfill(number_qubits))).astype(np.int)
return Pauli(v, w)
def sgn_prod(P1, P2):
"""Multiply two Paulis P1*P2 and track the sign.
P3 = P1*P2: X*Y
"""
if P1.numberofqubits != P2.numberofqubits:
print('Paulis cannot be multiplied - different number of qubits')
p1_v = P1.v.astype(np.bool)
p1_w = P1.w.astype(np.bool)
p2_v = P2.v.astype(np.bool)
p2_w = P2.w.astype(np.bool)
v_new = np.logical_xor(p1_v, p2_v).astype(np.int)
w_new = np.logical_xor(p1_w, p2_w).astype(np.int)
paulinew = Pauli(v_new, w_new)
phase_changes = 0
for v1, w1, v2, w2 in zip(p1_v, p1_w, p2_v, p2_w):
if v1 and not w1: # Z
if w2:
phase_changes = phase_changes - 1 if v2 else phase_changes + 1
elif not v1 and w1: # X
if v2:
phase_changes = phase_changes + 1 if w2 else phase_changes - 1
elif v1 and w1: # Y
if not v2 and w2: # X
phase_changes -= 1
elif v2 and not w2: # Z
phase_changes += 1
phase = (1j) ** (phase_changes % 4)
return paulinew, phase
def inverse_pauli(other):
"""Return the inverse of a Pauli."""
v = other.v
w = other.w
return Pauli(v, w)
def label_to_pauli(label):
"""Return the pauli of a string ."""
v = np.zeros(len(label))
w = np.zeros(len(label))
for j, _ in enumerate(label):
if label[j] == 'I':
v[j] = 0
w[j] = 0
elif label[j] == 'Z':
v[j] = 1
w[j] = 0
elif label[j] == 'Y':
v[j] = 1
w[j] = 1
elif label[j] == 'X':
v[j] = 0
w[j] = 1
else:
print('something went wrong')
return -1
return Pauli(v, w)
def pauli_group(number_of_qubits, case=0):
"""Return the Pauli group with 4^n elements.
The phases have been removed.
case 0 is ordered by Pauli weights and
case 1 is ordered by I,X,Y,Z counting last qubit fastest.
Args:
number_of_qubits (int): number of qubits
case (int): determines ordering of group elements (0=weight, 1=tensor)
Returns:
list: list of Pauli objects
Note:
WARNING THIS IS EXPONENTIAL
"""
if number_of_qubits < 5:
temp_set = []
if case == 0:
tmp = pauli_group(number_of_qubits, case=1)
# sort on the weight of the Pauli operator
return sorted(tmp, key=lambda x: -np.count_nonzero(
np.array(x.to_label(), 'c') == b'I'))
elif case == 1:
# the Pauli set is in tensor order II IX IY IZ XI ...
for k_index in range(4 ** number_of_qubits):
v = np.zeros(number_of_qubits)
w = np.zeros(number_of_qubits)
# looping over all the qubits
for j_index in range(number_of_qubits):
# making the Pauli for each kindex i fill it in from the
# end first
element = int((k_index) / (4 ** (j_index))) % 4
if element == 0:
v[j_index] = 0
w[j_index] = 0
elif element == 1:
v[j_index] = 0
w[j_index] = 1
elif element == 2:
v[j_index] = 1
w[j_index] = 1
elif element == 3:
v[j_index] = 1
w[j_index] = 0
temp_set.append(Pauli(v, w))
return temp_set
print('please set the number of qubits to less than 5')
return -1
def pauli_singles(j_index, number_qubits):
"""Return the single qubit pauli in number_qubits."""
# looping over all the qubits
tempset = []
v = np.zeros(number_qubits)
w = np.zeros(number_qubits)
v[j_index] = 0
w[j_index] = 1
tempset.append(Pauli(v, w))
v = np.zeros(number_qubits)
w = np.zeros(number_qubits)
v[j_index] = 1
w[j_index] = 1
tempset.append(Pauli(v, w))
v = np.zeros(number_qubits)
w = np.zeros(number_qubits)
v[j_index] = 1
w[j_index] = 0
tempset.append(Pauli(v, w))
return tempset
<|code_end|>
|
Running on statevector_simulator alters the qobj
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**:
- **Python version**:
- **Operating system**:
### What is the current behavior?
When a qobj is run on a statevector_simulator, it implicitly inserts a snapshot at the end, sets `shots=1`, then runs it on the qasm_simulator.
The added instruction makes the qobj not pass validation if run again.
```python
statevector_simulator = Aer.get_backend('statevector_simulator')
qobj = compile(circ, statevector_simulator, shots=1)
statevector_simulator.run(qobj).result().get_statevector() # this works fine
statevector_simulator.run(qobj).result().get_statevector() # the second time, SchemaValidationError is raised
```
### Suggested solution:
Move this logic to the transpiler, and make Qobj immutable.
|
qiskit/backends/aer/statevector_simulator.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""
Interface to C++ quantum circuit simulator with realistic noise.
"""
import logging
import uuid
from qiskit.qobj import QobjInstruction
from .qasm_simulator import QasmSimulator
from ._simulatorerror import SimulatorError
from .aerjob import AerJob
logger = logging.getLogger(__name__)
class StatevectorSimulator(QasmSimulator):
"""C++ statevector simulator"""
DEFAULT_CONFIGURATION = {
'name': 'statevector_simulator',
'url': 'https://github.com/QISKit/qiskit-terra/src/qasm-simulator-cpp',
'simulator': True,
'local': True,
'description': 'A C++ statevector simulator for qobj files',
'coupling_map': 'all-to-all',
'basis_gates': 'u1,u2,u3,cx,cz,id,x,y,z,h,s,sdg,t,tdg,rzz,load,save,snapshot'
}
def __init__(self, configuration=None, provider=None):
super().__init__(configuration=configuration or self.DEFAULT_CONFIGURATION.copy(),
provider=provider)
def run(self, qobj):
"""Run a qobj on the the backend."""
job_id = str(uuid.uuid4())
aer_job = AerJob(self, job_id, self._run_job, qobj)
aer_job.submit()
return aer_job
def _run_job(self, job_id, qobj):
"""Run a Qobj on the backend."""
self._validate(qobj)
final_state_key = 32767 # Internal key for final state snapshot
# Add final snapshots to circuits
for experiment in qobj.experiments:
experiment.instructions.append(
QobjInstruction(name='snapshot', params=[final_state_key],
label='MISSING', type='MISSING')
)
result = super()._run_job(job_id, qobj)
# Extract final state snapshot and move to 'statevector' data field
for experiment_result in result.results.values():
snapshots = experiment_result.snapshots
if str(final_state_key) in snapshots:
final_state_key = str(final_state_key)
# Pop off final snapshot added above
final_state = snapshots.pop(final_state_key, None)
final_state = final_state['statevector'][0]
# Add final state to results data
experiment_result.data['statevector'] = final_state
# Remove snapshot dict if empty
if snapshots == {}:
experiment_result.data.pop('snapshots', None)
return result
def _validate(self, qobj):
"""Semantic validations of the qobj which cannot be done via schemas.
Some of these may later move to backend schemas.
1. No shots
2. No measurements in the middle
"""
if qobj.config.shots != 1:
logger.info("statevector simulator only supports 1 shot. "
"Setting shots=1.")
qobj.config.shots = 1
for experiment in qobj.experiments:
if getattr(experiment.config, 'shots', 1) != 1:
logger.info("statevector simulator only supports 1 shot. "
"Setting shots=1 for circuit %s.", experiment.name)
experiment.config.shots = 1
for op in experiment.instructions:
if op.name in ['measure', 'reset']:
raise SimulatorError(
"In circuit {}: statevector simulator does not support "
"measure or reset.".format(experiment.header.name))
<|code_end|>
qiskit/backends/aer/statevector_simulator_py.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""Contains a (slow) python statevector simulator.
It simulates the statevector through a quantum circuit. It is exponential in
the number of qubits.
We advise using the c++ simulator or online simulator for larger size systems.
The input is a qobj dictionary and the output is a Result object.
The input qobj to this simulator has no shots, no measures, no reset, no noise.
"""
import logging
import uuid
from qiskit.backends.aer.aerjob import AerJob
from qiskit.backends.aer._simulatorerror import SimulatorError
from qiskit.qobj import QobjInstruction
from .qasm_simulator_py import QasmSimulatorPy
logger = logging.getLogger(__name__)
class StatevectorSimulatorPy(QasmSimulatorPy):
"""Python statevector simulator."""
DEFAULT_CONFIGURATION = {
'name': 'statevector_simulator_py',
'url': 'https://github.com/QISKit/qiskit-terra',
'simulator': True,
'local': True,
'description': 'A Python statevector simulator for qobj files',
'coupling_map': 'all-to-all',
'basis_gates': 'u1,u2,u3,cx,id,snapshot'
}
def __init__(self, configuration=None, provider=None):
super().__init__(configuration=configuration or self.DEFAULT_CONFIGURATION.copy(),
provider=provider)
def run(self, qobj):
"""Run qobj asynchronously.
Args:
qobj (dict): job description
Returns:
AerJob: derived from BaseJob
"""
job_id = str(uuid.uuid4())
aer_job = AerJob(self, job_id, self._run_job, qobj)
aer_job.submit()
return aer_job
def _run_job(self, job_id, qobj):
"""Run a Qobj on the backend."""
self._validate(qobj)
final_state_key = 32767 # Internal key for final state snapshot
# Add final snapshots to circuits
for experiment in qobj.experiments:
experiment.instructions.append(
QobjInstruction(name='snapshot', params=[final_state_key],
label='MISSING', type='MISSING')
)
result = super()._run_job(job_id, qobj)
# Extract final state snapshot and move to 'statevector' data field
for experiment_result in result.results.values():
snapshots = experiment_result.snapshots
if str(final_state_key) in snapshots:
final_state_key = str(final_state_key)
# Pop off final snapshot added above
final_state = snapshots.pop(final_state_key, None)
final_state = final_state['statevector'][0]
# Add final state to results data
experiment_result.data['statevector'] = final_state
# Remove snapshot dict if empty
if snapshots == {}:
experiment_result.data.pop('snapshots', None)
return result
def _validate(self, qobj):
"""Semantic validations of the qobj which cannot be done via schemas.
Some of these may later move to backend schemas.
1. No shots
2. No measurements in the middle
"""
if qobj.config.shots != 1:
logger.info("statevector simulator only supports 1 shot. "
"Setting shots=1.")
qobj.config.shots = 1
for experiment in qobj.experiments:
if getattr(experiment.config, 'shots', 1) != 1:
logger.info("statevector simulator only supports 1 shot. "
"Setting shots=1 for circuit %s.", experiment.name)
experiment.config.shots = 1
for op in experiment.instructions:
if op.name in ['measure', 'reset']:
raise SimulatorError(
"In circuit {}: statevector simulator does not support "
"measure or reset.".format(experiment.header.name))
<|code_end|>
|
qiskit/backends/aer/statevector_simulator.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""
Interface to C++ quantum circuit simulator with realistic noise.
"""
import logging
import uuid
from qiskit.qobj import QobjInstruction
from .qasm_simulator import QasmSimulator
from ._simulatorerror import SimulatorError
from .aerjob import AerJob
logger = logging.getLogger(__name__)
class StatevectorSimulator(QasmSimulator):
"""C++ statevector simulator"""
DEFAULT_CONFIGURATION = {
'name': 'statevector_simulator',
'url': 'https://github.com/QISKit/qiskit-terra/src/qasm-simulator-cpp',
'simulator': True,
'local': True,
'description': 'A C++ statevector simulator for qobj files',
'coupling_map': 'all-to-all',
'basis_gates': 'u1,u2,u3,cx,cz,id,x,y,z,h,s,sdg,t,tdg,rzz,load,save,snapshot'
}
def __init__(self, configuration=None, provider=None):
super().__init__(configuration=configuration or self.DEFAULT_CONFIGURATION.copy(),
provider=provider)
def run(self, qobj):
"""Run a qobj on the the backend."""
job_id = str(uuid.uuid4())
aer_job = AerJob(self, job_id, self._run_job, qobj)
aer_job.submit()
return aer_job
def _run_job(self, job_id, qobj):
"""Run a Qobj on the backend."""
self._validate(qobj)
final_state_key = 32767 # Internal key for final state snapshot
# Add final snapshots to circuits
for experiment in qobj.experiments:
experiment.instructions.append(
QobjInstruction(name='snapshot', params=[final_state_key],
label='MISSING', type='MISSING')
)
result = super()._run_job(job_id, qobj)
# Remove added snapshot from qobj
for experiment in qobj.experiments:
del experiment.instructions[-1]
# Extract final state snapshot and move to 'statevector' data field
for experiment_result in result.results.values():
snapshots = experiment_result.snapshots
if str(final_state_key) in snapshots:
final_state_key = str(final_state_key)
# Pop off final snapshot added above
final_state = snapshots.pop(final_state_key, None)
final_state = final_state['statevector'][0]
# Add final state to results data
experiment_result.data['statevector'] = final_state
# Remove snapshot dict if empty
if snapshots == {}:
experiment_result.data.pop('snapshots', None)
return result
def _validate(self, qobj):
"""Semantic validations of the qobj which cannot be done via schemas.
Some of these may later move to backend schemas.
1. No shots
2. No measurements in the middle
"""
if qobj.config.shots != 1:
logger.info("statevector simulator only supports 1 shot. "
"Setting shots=1.")
qobj.config.shots = 1
for experiment in qobj.experiments:
if getattr(experiment.config, 'shots', 1) != 1:
logger.info("statevector simulator only supports 1 shot. "
"Setting shots=1 for circuit %s.", experiment.name)
experiment.config.shots = 1
for op in experiment.instructions:
if op.name in ['measure', 'reset']:
raise SimulatorError(
"In circuit {}: statevector simulator does not support "
"measure or reset.".format(experiment.header.name))
<|code_end|>
qiskit/backends/aer/statevector_simulator_py.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""Contains a (slow) python statevector simulator.
It simulates the statevector through a quantum circuit. It is exponential in
the number of qubits.
We advise using the c++ simulator or online simulator for larger size systems.
The input is a qobj dictionary and the output is a Result object.
The input qobj to this simulator has no shots, no measures, no reset, no noise.
"""
import logging
import uuid
from qiskit.backends.aer.aerjob import AerJob
from qiskit.backends.aer._simulatorerror import SimulatorError
from qiskit.qobj import QobjInstruction
from .qasm_simulator_py import QasmSimulatorPy
logger = logging.getLogger(__name__)
class StatevectorSimulatorPy(QasmSimulatorPy):
"""Python statevector simulator."""
DEFAULT_CONFIGURATION = {
'name': 'statevector_simulator_py',
'url': 'https://github.com/QISKit/qiskit-terra',
'simulator': True,
'local': True,
'description': 'A Python statevector simulator for qobj files',
'coupling_map': 'all-to-all',
'basis_gates': 'u1,u2,u3,cx,id,snapshot'
}
def __init__(self, configuration=None, provider=None):
super().__init__(configuration=configuration or self.DEFAULT_CONFIGURATION.copy(),
provider=provider)
def run(self, qobj):
"""Run qobj asynchronously.
Args:
qobj (dict): job description
Returns:
AerJob: derived from BaseJob
"""
job_id = str(uuid.uuid4())
aer_job = AerJob(self, job_id, self._run_job, qobj)
aer_job.submit()
return aer_job
def _run_job(self, job_id, qobj):
"""Run a Qobj on the backend."""
self._validate(qobj)
final_state_key = 32767 # Internal key for final state snapshot
# Add final snapshots to circuits
for experiment in qobj.experiments:
experiment.instructions.append(
QobjInstruction(name='snapshot', params=[final_state_key],
label='MISSING', type='MISSING')
)
result = super()._run_job(job_id, qobj)
# Remove added snapshot from qobj
for experiment in qobj.experiments:
del experiment.instructions[-1]
# Extract final state snapshot and move to 'statevector' data field
for experiment_result in result.results.values():
snapshots = experiment_result.snapshots
if str(final_state_key) in snapshots:
final_state_key = str(final_state_key)
# Pop off final snapshot added above
final_state = snapshots.pop(final_state_key, None)
final_state = final_state['statevector'][0]
# Add final state to results data
experiment_result.data['statevector'] = final_state
# Remove snapshot dict if empty
if snapshots == {}:
experiment_result.data.pop('snapshots', None)
return result
def _validate(self, qobj):
"""Semantic validations of the qobj which cannot be done via schemas.
Some of these may later move to backend schemas.
1. No shots
2. No measurements in the middle
"""
if qobj.config.shots != 1:
logger.info("statevector simulator only supports 1 shot. "
"Setting shots=1.")
qobj.config.shots = 1
for experiment in qobj.experiments:
if getattr(experiment.config, 'shots', 1) != 1:
logger.info("statevector simulator only supports 1 shot. "
"Setting shots=1 for circuit %s.", experiment.name)
experiment.config.shots = 1
for op in experiment.instructions:
if op.name in ['measure', 'reset']:
raise SimulatorError(
"In circuit {}: statevector simulator does not support "
"measure or reset.".format(experiment.header.name))
<|code_end|>
|
load_qasm_file and load_qasm_string should be part of circuits
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected behavior?
The load_qasm_* should be part of the circuit object and not in the wrapper
```circuit(qasm_file)```
or
```circuit.load(qasm_file)```
|
qiskit/_quantumcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Quantum circuit object.
"""
import itertools
from collections import OrderedDict
from ._qiskiterror import QISKitError
from ._register import Register
from ._quantumregister import QuantumRegister
from ._classicalregister import ClassicalRegister
class QuantumCircuit(object):
"""Quantum circuit."""
instances = 0
prefix = 'circuit'
# Class variable OPENQASM header
header = "OPENQASM 2.0;"
# Class variable with gate definitions
# This is a dict whose values are dicts with the
# following keys:
# "print" = True or False
# "opaque" = True or False
# "n_args" = number of real parameters
# "n_bits" = number of qubits
# "args" = list of parameter names
# "bits" = list of qubit names
# "body" = GateBody AST node
definitions = OrderedDict()
def __init__(self, *regs, name=None):
"""Create a new circuit.
A circuit is a list of instructions bound to some registers.
Args:
*regs (Registers): registers to include in the circuit.
name (str or None): the name of the quantum circuit. If
None, an automatically generated string will be assigned.
Raises:
QISKitError: if the circuit name, if given, is not valid.
"""
if name is None:
name = self.cls_prefix() + str(self.cls_instances())
self._increment_instances()
if not isinstance(name, str):
raise QISKitError("The circuit name should be a string "
"(or None to auto-generate a name).")
self.name = name
# Data contains a list of instructions in the order they were applied.
self.data = []
# This is a map of registers bound to this circuit, by name.
self.regs = OrderedDict()
self.add(*regs)
@classmethod
def _increment_instances(cls):
cls.instances += 1
@classmethod
def cls_instances(cls):
"""Return the current number of instances of this class,
useful for auto naming."""
return cls.instances
@classmethod
def cls_prefix(cls):
"""Return the prefix to use for auto naming."""
return cls.prefix
def has_register(self, register):
"""
Test if this circuit has the register r.
Args:
register (Register): a quantum or classical register.
Returns:
bool: True if the register is contained in this circuit.
"""
if register.name in self.regs:
registers = self.regs[register.name]
if registers.size == register.size:
if ((isinstance(register, QuantumRegister) and
isinstance(registers, QuantumRegister)) or
(isinstance(register, ClassicalRegister) and
isinstance(registers, ClassicalRegister))):
return True
return False
def get_qregs(self):
"""Get the qregs of the circuit."""
qregs = OrderedDict()
for name, register in self.regs.items():
if isinstance(register, QuantumRegister):
qregs[name] = register
return qregs
def get_cregs(self):
"""Get the cregs of the circuit."""
cregs = OrderedDict()
for name, register in self.regs.items():
if isinstance(register, ClassicalRegister):
cregs[name] = register
return cregs
def combine(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Return self + rhs as a new object.
"""
combined_registers = []
# Check registers in LHS are compatible with RHS
for name, register in self.regs.items():
if name in rhs.regs and register != rhs.regs[name]:
raise QISKitError("circuits are not compatible")
else:
combined_registers.append(register)
# Add registers in RHS not in LHS
complement_registers = set(rhs.regs) - set(self.regs)
for name in complement_registers:
combined_registers.append(rhs.regs[name])
# Make new circuit with combined registers
circuit = QuantumCircuit(*combined_registers)
for gate in itertools.chain(self.data, rhs.data):
gate.reapply(circuit)
return circuit
def extend(self, rhs):
"""
Append rhs to self if self if it contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Modify and return self.
"""
# Check compatibility and add new registers
for name, register in rhs.regs.items():
if name not in self.regs:
self.add(register)
elif name in self.regs and register != self.regs[name]:
raise QISKitError("circuits are not compatible")
# Add new gates
for gate in rhs.data:
gate.reapply(self)
return self
def __add__(self, rhs):
"""Overload + to implement self.concatenate."""
return self.combine(rhs)
def __iadd__(self, rhs):
"""Overload += to implement self.extend."""
return self.extend(rhs)
def __len__(self):
"""Return number of operations in circuit."""
return len(self.data)
def __getitem__(self, item):
"""Return indexed operation."""
return self.data[item]
def _attach(self, instruction):
"""Attach an instruction."""
self.data.append(instruction)
return instruction
def add(self, *regs):
"""Add registers."""
for register in regs:
if not isinstance(register, Register):
raise QISKitError("expected a register")
if register.name not in self.regs:
self.regs[register.name] = register
else:
raise QISKitError("register name \"%s\" already exists"
% register.name)
def _check_qreg(self, register):
"""Raise exception if r is not in this circuit or not qreg."""
if not isinstance(register, QuantumRegister):
raise QISKitError("expected quantum register")
if not self.has_register(register):
raise QISKitError(
"register '%s' not in this circuit" %
register.name)
def _check_qubit(self, qubit):
"""Raise exception if qubit is not in this circuit or bad format."""
if not isinstance(qubit, tuple):
raise QISKitError("%s is not a tuple."
"A qubit should be formated as a tuple." % str(qubit))
if not len(qubit) == 2:
raise QISKitError("%s is not a tuple with two elements, but %i instead" % len(qubit))
if not isinstance(qubit[1], int):
raise QISKitError("The second element of a tuple defining a qubit should be an int:"
"%s was found instead" % type(qubit[1]).__name__)
self._check_qreg(qubit[0])
qubit[0].check_range(qubit[1])
def _check_creg(self, register):
"""Raise exception if r is not in this circuit or not creg."""
if not isinstance(register, ClassicalRegister):
raise QISKitError("expected classical register")
if not self.has_register(register):
raise QISKitError(
"register '%s' not in this circuit" %
register.name)
def _check_dups(self, qubits):
"""Raise exception if list of qubits contains duplicates."""
squbits = set(qubits)
if len(squbits) != len(qubits):
raise QISKitError("duplicate qubit arguments")
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.definitions[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.definitions[name]["n_args"] > 0:
out += "(" + ",".join(self.definitions[name]["args"]) + ")"
out += " " + ",".join(self.definitions[name]["bits"])
if self.definitions[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.definitions[name]["body"].qasm() + "}\n"
return out
def qasm(self):
"""Return OPENQASM string."""
string_temp = self.header + "\n"
for gate_name in self.definitions:
if self.definitions[gate_name]["print"]:
string_temp += self._gate_string(gate_name)
for register in self.regs.values():
string_temp += register.qasm() + "\n"
for instruction in self.data:
string_temp += instruction.qasm() + "\n"
return string_temp
<|code_end|>
qiskit/unrollers/_circuitbackend.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Backend for the unroller that produces a QuantumCircuit.
"""
from qiskit import QuantumCircuit
from ._backenderror import BackendError
from ._unrollerbackend import UnrollerBackend
class CircuitBackend(UnrollerBackend):
"""Backend for the unroller that produces a QuantumCircuit.
By default, basis gates are the QX gates.
"""
def __init__(self, basis=None):
"""Setup this backend.
basis is a list of operation name strings.
"""
super().__init__(basis)
self.creg = None
self.cval = None
if basis:
self.basis = basis.copy()
else:
self.basis = ["cx", "u1", "u2", "u3"]
self.gates = {}
self.listen = True
self.in_gate = ""
self.circuit = QuantumCircuit()
def set_basis(self, basis):
"""Declare the set of user-defined gates to emit.
basis is a list of operation name strings.
"""
self.basis = basis.copy()
def version(self, version):
"""Ignore the version string.
v is a version number.
"""
pass
def new_qreg(self, qreg):
"""Create a new quantum register.
qreg = QuantumRegister object
"""
self.circuit.add(qreg)
def new_creg(self, creg):
"""Create a new classical register.
creg = ClassicalRegister object
"""
self.circuit.add(creg)
def define_gate(self, name, gatedata):
"""Define a new quantum gate.
We don't check that the definition and name agree.
name is a string.
gatedata is the AST node for the gate.
"""
self.gates[name] = gatedata
def _map_qubit(self, qubit):
"""Map qubit tuple (regname, index) to (QuantumRegister, index)."""
qregs = self.circuit.get_qregs()
if qubit[0] not in qregs:
raise BackendError("qreg %s does not exist" % qubit[0])
return (qregs[qubit[0]], qubit[1])
def _map_bit(self, bit):
"""Map bit tuple (regname, index) to (ClassicalRegister, index)."""
cregs = self.circuit.get_cregs()
if bit[0] not in cregs:
raise BackendError("creg %s does not exist" % bit[0])
return (cregs[bit[0]], bit[1])
def _map_creg(self, creg):
"""Map creg name to ClassicalRegister."""
cregs = self.circuit.get_cregs()
if creg not in cregs:
raise BackendError("creg %s does not exist" % creg)
return cregs[creg]
def u(self, arg, qubit, nested_scope=None):
"""Fundamental single qubit gate.
arg is 3-tuple of Node expression objects.
qubit is (regname,idx) tuple.
nested_scope is a list of dictionaries mapping expression variables
to Node expression objects in order of increasing nesting depth.
"""
if self.listen:
if "U" not in self.basis:
self.basis.append("U")
(theta, phi, lam) = list(map(lambda x: x.sym(nested_scope), arg))
this_gate = self.circuit.u_base(theta, phi, lam,
self._map_qubit(qubit))
if self.creg is not None:
this_gate.c_if(self._map_creg(self.creg), self.cval)
def cx(self, qubit0, qubit1):
"""Fundamental two qubit gate.
qubit0 is (regname,idx) tuple for the control qubit.
qubit1 is (regname,idx) tuple for the target qubit.
"""
if self.listen:
if "CX" not in self.basis:
self.basis.append("CX")
this_gate = self.circuit.cx_base(self._map_qubit(qubit0),
self._map_qubit(qubit1))
if self.creg is not None:
this_gate.c_if(self._map_creg(self.creg), self.cval)
def measure(self, qubit, bit):
"""Measurement operation.
qubit is (regname, idx) tuple for the input qubit.
bit is (regname, idx) tuple for the output bit.
"""
if "measure" not in self.basis:
self.basis.append("measure")
this_op = self.circuit.measure(self._map_qubit(qubit),
self._map_bit(bit))
if self.creg is not None:
this_op.c_if(self._map_creg(self.creg), self.cval)
def barrier(self, qubitlists):
"""Barrier instruction.
qubitlists is a list of lists of (regname, idx) tuples.
"""
if self.listen:
if "barrier" not in self.basis:
self.basis.append("barrier")
flatlist = map(self._map_qubit,
[qubit for qubitlist in qubitlists
for qubit in qubitlist])
self.circuit.barrier(*list(flatlist))
def reset(self, qubit):
"""Reset instruction.
qubit is a (regname, idx) tuple.
"""
if "reset" not in self.basis:
self.basis.append("reset")
this_op = self.circuit.reset(self._map_qubit(qubit))
if self.creg is not None:
this_op.c_if(self._map_creg(self.creg), self.cval)
def set_condition(self, creg, cval):
"""Attach a current condition.
creg is a name string.
cval is the integer value for the test.
"""
self.creg = creg
self.cval = cval
def drop_condition(self):
"""Drop the current condition."""
self.creg = None
self.cval = None
def start_gate(self, name, args, qubits, nested_scope=None, extra_fields=None):
"""Begin a custom gate.
name is name string.
args is list of Node expression objects.
qubits is list of (regname, idx) tuples.
nested_scope is a list of dictionaries mapping expression variables
to Node expression objects in order of increasing nesting depth.
"""
if self.listen and name not in self.basis \
and self.gates[name]["opaque"]:
raise BackendError("opaque gate %s not in basis" % name)
if self.listen and name in self.basis:
self.in_gate = name
self.listen = False
# Gate names mapped to number of arguments and qubits
# and method to invoke on [args, qubits]
lut = {"ccx": [(0, 3),
lambda x: self.circuit.ccx(x[1][0], x[1][1],
x[1][2])],
"ch": [(0, 2),
lambda x: self.circuit.ch(x[1][0], x[1][1])],
"crz": [(1, 2),
lambda x: self.circuit.crz(x[0][0], x[1][0],
x[1][1])],
"cswap": [(0, 3),
lambda x: self.circuit.cswap(x[1][0],
x[1][1],
x[1][2])],
"cu1": [(1, 2),
lambda x: self.circuit.cu1(x[0][0], x[1][0],
x[1][1])],
"cu3": [(3, 2), lambda x: self.circuit.cu3(x[0][0],
x[0][1],
x[0][2],
x[1][0],
x[1][1])],
"cx": [(0, 2), lambda x: self.circuit.cx(x[1][0], x[1][1])],
"cy": [(0, 2), lambda x: self.circuit.cy(x[1][0], x[1][1])],
"cz": [(0, 2), lambda x: self.circuit.cz(x[1][0], x[1][1])],
"swap": [(0, 2), lambda x: self.circuit.swap(x[1][0], x[1][1])],
"h": [(0, 1), lambda x: self.circuit.h(x[1][0])],
"id": [(0, 1), lambda x: self.circuit.iden(x[1][0])],
"rx": [(1, 1), lambda x: self.circuit.rx(x[0][0], x[1][0])],
"ry": [(1, 1), lambda x: self.circuit.ry(x[0][0], x[1][0])],
"rz": [(1, 1), lambda x: self.circuit.rz(x[0][0], x[1][0])],
"s": [(0, 1), lambda x: self.circuit.s(x[1][0])],
"sdg": [(0, 1), lambda x: self.circuit.s(x[1][0]).inverse()],
"t": [(0, 1), lambda x: self.circuit.t(x[1][0])],
"tdg": [(0, 1), lambda x: self.circuit.t(x[1][0]).inverse()],
"u1": [(1, 1), lambda x: self.circuit.u1(x[0][0], x[1][0])],
"u2": [(2, 1), lambda x: self.circuit.u2(x[0][0], x[0][1],
x[1][0])],
"u3": [(3, 1), lambda x: self.circuit.u3(x[0][0], x[0][1],
x[0][2], x[1][0])],
"x": [(0, 1), lambda x: self.circuit.x(x[1][0])],
"y": [(0, 1), lambda x: self.circuit.y(x[1][0])],
"z": [(0, 1), lambda x: self.circuit.z(x[1][0])]}
if name not in lut:
raise BackendError("gate %s not in standard extensions" %
name)
gate_data = lut[name]
if gate_data[0] != (len(args), len(qubits)):
raise BackendError("gate %s signature (%d, %d) is " %
(name, len(args), len(qubits)) +
"incompatible with the standard " +
"extensions")
this_gate = gate_data[1]([list(map(lambda x:
x.sym(nested_scope), args)),
list(map(self._map_qubit, qubits))])
if self.creg is not None:
this_gate.c_if(self._map_creg(self.creg), self.cval)
def end_gate(self, name, args, qubits, nested_scope=None):
"""End a custom gate.
name is name string.
args is list of Node expression objects.
qubits is list of (regname, idx) tuples.
nested_scope is a list of dictionaries mapping expression variables
to Node expression objects in order of increasing nesting depth.
"""
if name == self.in_gate:
self.in_gate = ""
self.listen = True
def get_output(self):
"""Return the QuantumCircuit object."""
return self.circuit
<|code_end|>
qiskit/wrapper/_wrapper.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Helper module for simplified QISKit usage."""
import logging
from ._circuittoolkit import circuit_from_qasm_file, circuit_from_qasm_string
logger = logging.getLogger(__name__)
# Functions for importing qasm
def load_qasm_string(qasm_string, name=None,
basis_gates="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap"):
"""Construct a quantum circuit from a qasm representation (string).
Args:
qasm_string (str): a string of qasm, or a filename containing qasm.
basis_gates (str): basis gates for the quantum circuit.
name (str or None): the name of the quantum circuit after loading qasm
text into it. If no name given, assign automatically.
Returns:
QuantumCircuit: circuit constructed from qasm.
Raises:
QISKitError: if the string is not valid QASM
"""
return circuit_from_qasm_string(qasm_string, name, basis_gates)
def load_qasm_file(qasm_file, name=None,
basis_gates="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap"):
"""Construct a quantum circuit from a qasm representation (file).
Args:
qasm_file (str): a string for the filename including its location.
name (str or None): the name of the quantum circuit after
loading qasm text into it. If no name is give the name is of
the text file.
basis_gates (str): basis gates for the quantum circuit.
Returns:
QuantumCircuit: circuit constructed from qasm.
Raises:
QISKitError: if the file cannot be read.
"""
return circuit_from_qasm_file(qasm_file, name, basis_gates)
def qobj_to_circuits(qobj):
"""Return a list of QuantumCircuit object(s) from a qobj
Args:
qobj (Qobj): The Qobj object to convert to QuantumCircuits
Returns:
list: A list of QuantumCircuit objects from the qobj
"""
if qobj.experiments:
circuits = []
for x in qobj.experiments:
if hasattr(x.header, 'compiled_circuit_qasm'):
circuits.append(
load_qasm_string(x.header.compiled_circuit_qasm))
return circuits
# TODO(mtreinish): add support for converting a qobj if the qasm isn't
# embedded in the header
return None
<|code_end|>
|
qiskit/_quantumcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=cyclic-import
"""
Quantum circuit object.
"""
import itertools
from collections import OrderedDict
from qiskit.qasm import _qasm
from qiskit.unrollers import _unroller
from qiskit.unrollers import _circuitbackend
from ._qiskiterror import QISKitError
from ._register import Register
from ._quantumregister import QuantumRegister
from ._classicalregister import ClassicalRegister
def _circuit_from_qasm(qasm, basis=None):
default_basis = ["id", "u0", "u1", "u2", "u3", "x", "y", "z", "h", "s",
"sdg", "t", "tdg", "rx", "ry", "rz", "cx", "cy", "cz",
"ch", "crz", "cu1", "cu3", "swap", "ccx", "cswap"]
if not basis:
basis = default_basis
ast = qasm.parse()
unroll = _unroller.Unroller(
ast, _circuitbackend.CircuitBackend(basis))
circuit = unroll.execute()
return circuit
class QuantumCircuit(object):
"""Quantum circuit."""
instances = 0
prefix = 'circuit'
# Class variable OPENQASM header
header = "OPENQASM 2.0;"
# Class variable with gate definitions
# This is a dict whose values are dicts with the
# following keys:
# "print" = True or False
# "opaque" = True or False
# "n_args" = number of real parameters
# "n_bits" = number of qubits
# "args" = list of parameter names
# "bits" = list of qubit names
# "body" = GateBody AST node
definitions = OrderedDict()
@staticmethod
def from_qasm_file(path):
"""Take in a QASM file and generate a QuantumCircuit object.
Args:
path (str): Path to the file for a QASM program
Return:
QuantumCircuit: The QuantumCircuit object for the input QASM
"""
qasm = _qasm.Qasm(filename=path)
return _circuit_from_qasm(qasm)
@staticmethod
def from_qasm_str(qasm_str):
"""Take in a QASM string and generate a QuantumCircuit object.
Args:
qasm_str (str): A QASM program string
Return:
QuantumCircuit: The QuantumCircuit object for the input QASM
"""
qasm = _qasm.Qasm(data=qasm_str)
return _circuit_from_qasm(qasm)
def __init__(self, *regs, name=None):
"""Create a new circuit.
A circuit is a list of instructions bound to some registers.
Args:
*regs (Registers): registers to include in the circuit.
name (str or None): the name of the quantum circuit. If
None, an automatically generated string will be assigned.
Raises:
QISKitError: if the circuit name, if given, is not valid.
"""
if name is None:
name = self.cls_prefix() + str(self.cls_instances())
self._increment_instances()
if not isinstance(name, str):
raise QISKitError("The circuit name should be a string "
"(or None to auto-generate a name).")
self.name = name
# Data contains a list of instructions in the order they were applied.
self.data = []
# This is a map of registers bound to this circuit, by name.
self.regs = OrderedDict()
self.add(*regs)
@classmethod
def _increment_instances(cls):
cls.instances += 1
@classmethod
def cls_instances(cls):
"""Return the current number of instances of this class,
useful for auto naming."""
return cls.instances
@classmethod
def cls_prefix(cls):
"""Return the prefix to use for auto naming."""
return cls.prefix
def has_register(self, register):
"""
Test if this circuit has the register r.
Args:
register (Register): a quantum or classical register.
Returns:
bool: True if the register is contained in this circuit.
"""
if register.name in self.regs:
registers = self.regs[register.name]
if registers.size == register.size:
if ((isinstance(register, QuantumRegister) and
isinstance(registers, QuantumRegister)) or
(isinstance(register, ClassicalRegister) and
isinstance(registers, ClassicalRegister))):
return True
return False
def get_qregs(self):
"""Get the qregs of the circuit."""
qregs = OrderedDict()
for name, register in self.regs.items():
if isinstance(register, QuantumRegister):
qregs[name] = register
return qregs
def get_cregs(self):
"""Get the cregs of the circuit."""
cregs = OrderedDict()
for name, register in self.regs.items():
if isinstance(register, ClassicalRegister):
cregs[name] = register
return cregs
def combine(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Return self + rhs as a new object.
"""
combined_registers = []
# Check registers in LHS are compatible with RHS
for name, register in self.regs.items():
if name in rhs.regs and register != rhs.regs[name]:
raise QISKitError("circuits are not compatible")
else:
combined_registers.append(register)
# Add registers in RHS not in LHS
complement_registers = set(rhs.regs) - set(self.regs)
for name in complement_registers:
combined_registers.append(rhs.regs[name])
# Make new circuit with combined registers
circuit = QuantumCircuit(*combined_registers)
for gate in itertools.chain(self.data, rhs.data):
gate.reapply(circuit)
return circuit
def extend(self, rhs):
"""
Append rhs to self if self if it contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Modify and return self.
"""
# Check compatibility and add new registers
for name, register in rhs.regs.items():
if name not in self.regs:
self.add(register)
elif name in self.regs and register != self.regs[name]:
raise QISKitError("circuits are not compatible")
# Add new gates
for gate in rhs.data:
gate.reapply(self)
return self
def __add__(self, rhs):
"""Overload + to implement self.concatenate."""
return self.combine(rhs)
def __iadd__(self, rhs):
"""Overload += to implement self.extend."""
return self.extend(rhs)
def __len__(self):
"""Return number of operations in circuit."""
return len(self.data)
def __getitem__(self, item):
"""Return indexed operation."""
return self.data[item]
def _attach(self, instruction):
"""Attach an instruction."""
self.data.append(instruction)
return instruction
def add(self, *regs):
"""Add registers."""
for register in regs:
if not isinstance(register, Register):
raise QISKitError("expected a register")
if register.name not in self.regs:
self.regs[register.name] = register
else:
raise QISKitError("register name \"%s\" already exists"
% register.name)
def _check_qreg(self, register):
"""Raise exception if r is not in this circuit or not qreg."""
if not isinstance(register, QuantumRegister):
raise QISKitError("expected quantum register")
if not self.has_register(register):
raise QISKitError(
"register '%s' not in this circuit" %
register.name)
def _check_qubit(self, qubit):
"""Raise exception if qubit is not in this circuit or bad format."""
if not isinstance(qubit, tuple):
raise QISKitError("%s is not a tuple."
"A qubit should be formated as a tuple." % str(qubit))
if not len(qubit) == 2:
raise QISKitError("%s is not a tuple with two elements, but %i instead" % len(qubit))
if not isinstance(qubit[1], int):
raise QISKitError("The second element of a tuple defining a qubit should be an int:"
"%s was found instead" % type(qubit[1]).__name__)
self._check_qreg(qubit[0])
qubit[0].check_range(qubit[1])
def _check_creg(self, register):
"""Raise exception if r is not in this circuit or not creg."""
if not isinstance(register, ClassicalRegister):
raise QISKitError("expected classical register")
if not self.has_register(register):
raise QISKitError(
"register '%s' not in this circuit" %
register.name)
def _check_dups(self, qubits):
"""Raise exception if list of qubits contains duplicates."""
squbits = set(qubits)
if len(squbits) != len(qubits):
raise QISKitError("duplicate qubit arguments")
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.definitions[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.definitions[name]["n_args"] > 0:
out += "(" + ",".join(self.definitions[name]["args"]) + ")"
out += " " + ",".join(self.definitions[name]["bits"])
if self.definitions[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.definitions[name]["body"].qasm() + "}\n"
return out
def qasm(self):
"""Return OPENQASM string."""
string_temp = self.header + "\n"
for gate_name in self.definitions:
if self.definitions[gate_name]["print"]:
string_temp += self._gate_string(gate_name)
for register in self.regs.values():
string_temp += register.qasm() + "\n"
for instruction in self.data:
string_temp += instruction.qasm() + "\n"
return string_temp
<|code_end|>
qiskit/unrollers/_circuitbackend.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Backend for the unroller that produces a QuantumCircuit.
"""
from qiskit import _quantumcircuit
from qiskit.unrollers import _backenderror
from qiskit.unrollers import _unrollerbackend
class CircuitBackend(_unrollerbackend.UnrollerBackend):
"""Backend for the unroller that produces a QuantumCircuit.
By default, basis gates are the QX gates.
"""
def __init__(self, basis=None):
"""Setup this backend.
basis is a list of operation name strings.
"""
super().__init__(basis)
self.creg = None
self.cval = None
if basis:
self.basis = basis.copy()
else:
self.basis = ["cx", "u1", "u2", "u3"]
self.gates = {}
self.listen = True
self.in_gate = ""
self.circuit = _quantumcircuit.QuantumCircuit()
def set_basis(self, basis):
"""Declare the set of user-defined gates to emit.
basis is a list of operation name strings.
"""
self.basis = basis.copy()
def version(self, version):
"""Ignore the version string.
v is a version number.
"""
pass
def new_qreg(self, qreg):
"""Create a new quantum register.
qreg = QuantumRegister object
"""
self.circuit.add(qreg)
def new_creg(self, creg):
"""Create a new classical register.
creg = ClassicalRegister object
"""
self.circuit.add(creg)
def define_gate(self, name, gatedata):
"""Define a new quantum gate.
We don't check that the definition and name agree.
name is a string.
gatedata is the AST node for the gate.
"""
self.gates[name] = gatedata
def _map_qubit(self, qubit):
"""Map qubit tuple (regname, index) to (QuantumRegister, index)."""
qregs = self.circuit.get_qregs()
if qubit[0] not in qregs:
raise _backenderror.BackendError(
"qreg %s does not exist" % qubit[0])
return (qregs[qubit[0]], qubit[1])
def _map_bit(self, bit):
"""Map bit tuple (regname, index) to (ClassicalRegister, index)."""
cregs = self.circuit.get_cregs()
if bit[0] not in cregs:
raise _backenderror.BackendError(
"creg %s does not exist" % bit[0])
return (cregs[bit[0]], bit[1])
def _map_creg(self, creg):
"""Map creg name to ClassicalRegister."""
cregs = self.circuit.get_cregs()
if creg not in cregs:
raise _backenderror.BackendError("creg %s does not exist" % creg)
return cregs[creg]
def u(self, arg, qubit, nested_scope=None):
"""Fundamental single qubit gate.
arg is 3-tuple of Node expression objects.
qubit is (regname,idx) tuple.
nested_scope is a list of dictionaries mapping expression variables
to Node expression objects in order of increasing nesting depth.
"""
if self.listen:
if "U" not in self.basis:
self.basis.append("U")
(theta, phi, lam) = list(map(lambda x: x.sym(nested_scope), arg))
this_gate = self.circuit.u_base(theta, phi, lam,
self._map_qubit(qubit))
if self.creg is not None:
this_gate.c_if(self._map_creg(self.creg), self.cval)
def cx(self, qubit0, qubit1):
"""Fundamental two qubit gate.
qubit0 is (regname,idx) tuple for the control qubit.
qubit1 is (regname,idx) tuple for the target qubit.
"""
if self.listen:
if "CX" not in self.basis:
self.basis.append("CX")
this_gate = self.circuit.cx_base(self._map_qubit(qubit0),
self._map_qubit(qubit1))
if self.creg is not None:
this_gate.c_if(self._map_creg(self.creg), self.cval)
def measure(self, qubit, bit):
"""Measurement operation.
qubit is (regname, idx) tuple for the input qubit.
bit is (regname, idx) tuple for the output bit.
"""
if "measure" not in self.basis:
self.basis.append("measure")
this_op = self.circuit.measure(self._map_qubit(qubit),
self._map_bit(bit))
if self.creg is not None:
this_op.c_if(self._map_creg(self.creg), self.cval)
def barrier(self, qubitlists):
"""Barrier instruction.
qubitlists is a list of lists of (regname, idx) tuples.
"""
if self.listen:
if "barrier" not in self.basis:
self.basis.append("barrier")
flatlist = map(self._map_qubit,
[qubit for qubitlist in qubitlists
for qubit in qubitlist])
self.circuit.barrier(*list(flatlist))
def reset(self, qubit):
"""Reset instruction.
qubit is a (regname, idx) tuple.
"""
if "reset" not in self.basis:
self.basis.append("reset")
this_op = self.circuit.reset(self._map_qubit(qubit))
if self.creg is not None:
this_op.c_if(self._map_creg(self.creg), self.cval)
def set_condition(self, creg, cval):
"""Attach a current condition.
creg is a name string.
cval is the integer value for the test.
"""
self.creg = creg
self.cval = cval
def drop_condition(self):
"""Drop the current condition."""
self.creg = None
self.cval = None
def start_gate(self, name, args, qubits, nested_scope=None, extra_fields=None):
"""Begin a custom gate.
name is name string.
args is list of Node expression objects.
qubits is list of (regname, idx) tuples.
nested_scope is a list of dictionaries mapping expression variables
to Node expression objects in order of increasing nesting depth.
"""
if self.listen and name not in self.basis \
and self.gates[name]["opaque"]:
raise _backenderror.BackendError(
"opaque gate %s not in basis" % name)
if self.listen and name in self.basis:
self.in_gate = name
self.listen = False
# Gate names mapped to number of arguments and qubits
# and method to invoke on [args, qubits]
lut = {"ccx": [(0, 3),
lambda x: self.circuit.ccx(x[1][0], x[1][1],
x[1][2])],
"ch": [(0, 2),
lambda x: self.circuit.ch(x[1][0], x[1][1])],
"crz": [(1, 2),
lambda x: self.circuit.crz(x[0][0], x[1][0],
x[1][1])],
"cswap": [(0, 3),
lambda x: self.circuit.cswap(x[1][0],
x[1][1],
x[1][2])],
"cu1": [(1, 2),
lambda x: self.circuit.cu1(x[0][0], x[1][0],
x[1][1])],
"cu3": [(3, 2), lambda x: self.circuit.cu3(x[0][0],
x[0][1],
x[0][2],
x[1][0],
x[1][1])],
"cx": [(0, 2), lambda x: self.circuit.cx(x[1][0], x[1][1])],
"cy": [(0, 2), lambda x: self.circuit.cy(x[1][0], x[1][1])],
"cz": [(0, 2), lambda x: self.circuit.cz(x[1][0], x[1][1])],
"swap": [(0, 2), lambda x: self.circuit.swap(x[1][0], x[1][1])],
"h": [(0, 1), lambda x: self.circuit.h(x[1][0])],
"id": [(0, 1), lambda x: self.circuit.iden(x[1][0])],
"rx": [(1, 1), lambda x: self.circuit.rx(x[0][0], x[1][0])],
"ry": [(1, 1), lambda x: self.circuit.ry(x[0][0], x[1][0])],
"rz": [(1, 1), lambda x: self.circuit.rz(x[0][0], x[1][0])],
"s": [(0, 1), lambda x: self.circuit.s(x[1][0])],
"sdg": [(0, 1), lambda x: self.circuit.s(x[1][0]).inverse()],
"t": [(0, 1), lambda x: self.circuit.t(x[1][0])],
"tdg": [(0, 1), lambda x: self.circuit.t(x[1][0]).inverse()],
"u1": [(1, 1), lambda x: self.circuit.u1(x[0][0], x[1][0])],
"u2": [(2, 1), lambda x: self.circuit.u2(x[0][0], x[0][1],
x[1][0])],
"u3": [(3, 1), lambda x: self.circuit.u3(x[0][0], x[0][1],
x[0][2], x[1][0])],
"x": [(0, 1), lambda x: self.circuit.x(x[1][0])],
"y": [(0, 1), lambda x: self.circuit.y(x[1][0])],
"z": [(0, 1), lambda x: self.circuit.z(x[1][0])]}
if name not in lut:
raise _backenderror.BackendError(
"gate %s not in standard extensions" % name)
gate_data = lut[name]
if gate_data[0] != (len(args), len(qubits)):
raise _backenderror.BackendError(
"gate %s signature (%d, %d) is " %
(name, len(args), len(qubits)) +
"incompatible with the standard " +
"extensions")
this_gate = gate_data[1]([list(map(lambda x:
x.sym(nested_scope), args)),
list(map(self._map_qubit, qubits))])
if self.creg is not None:
this_gate.c_if(self._map_creg(self.creg), self.cval)
def end_gate(self, name, args, qubits, nested_scope=None):
"""End a custom gate.
name is name string.
args is list of Node expression objects.
qubits is list of (regname, idx) tuples.
nested_scope is a list of dictionaries mapping expression variables
to Node expression objects in order of increasing nesting depth.
"""
if name == self.in_gate:
self.in_gate = ""
self.listen = True
def get_output(self):
"""Return the QuantumCircuit object."""
return self.circuit
<|code_end|>
qiskit/wrapper/_wrapper.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Helper module for simplified QISKit usage."""
import logging
import warnings
from ._circuittoolkit import circuit_from_qasm_file, circuit_from_qasm_string
logger = logging.getLogger(__name__)
# Functions for importing qasm
def load_qasm_string(qasm_string, name=None,
basis_gates="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap"):
"""Construct a quantum circuit from a qasm representation (string).
Args:
qasm_string (str): a string of qasm, or a filename containing qasm.
basis_gates (str): basis gates for the quantum circuit.
name (str or None): the name of the quantum circuit after loading qasm
text into it. If no name given, assign automatically.
Returns:
QuantumCircuit: circuit constructed from qasm.
Raises:
QISKitError: if the string is not valid QASM
"""
warnings.warn('The load_qasm_string() function is deprecated and will be '
'removed in a future release. Instead use '
'QuantumCircuit.from_qasm_str().', DeprecationWarning)
return circuit_from_qasm_string(qasm_string, name, basis_gates)
def load_qasm_file(qasm_file, name=None,
basis_gates="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap"):
"""Construct a quantum circuit from a qasm representation (file).
Args:
qasm_file (str): a string for the filename including its location.
name (str or None): the name of the quantum circuit after
loading qasm text into it. If no name is give the name is of
the text file.
basis_gates (str): basis gates for the quantum circuit.
Returns:
QuantumCircuit: circuit constructed from qasm.
Raises:
QISKitError: if the file cannot be read.
"""
warnings.warn('The load_qasm_file() function is deprecated and will be '
'removed in a future release. Instead use '
'QuantumCircuit.from_qasm_file().', DeprecationWarning)
return circuit_from_qasm_file(qasm_file, name, basis_gates)
def qobj_to_circuits(qobj):
"""Return a list of QuantumCircuit object(s) from a qobj
Args:
qobj (Qobj): The Qobj object to convert to QuantumCircuits
Returns:
list: A list of QuantumCircuit objects from the qobj
"""
if qobj.experiments:
circuits = []
for x in qobj.experiments:
if hasattr(x.header, 'compiled_circuit_qasm'):
circuits.append(
load_qasm_string(x.header.compiled_circuit_qasm))
return circuits
# TODO(mtreinish): add support for converting a qobj if the qasm isn't
# embedded in the header
return None
<|code_end|>
|
Text-based circuit drawer output is scrambled in notebook unless print is called.
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**:
- **Python version**:
- **Operating system**:
### What is the current behavior?
```python
from qiskit import *
from qiskit.tools.visualization import circuit_drawer
q = QuantumRegister(5)
qc = QuantumCircuit(q)
qc.ccx(q[1], q[2], q[3])
qc.ccx(q[0], q[2], q[4])
qc.x(q[4])
qc.x(q[3])
circuit_drawer(qc, output='text')
```
' \nq1_0: |0>────────────■───────\n │ \nq1_1: |0>──■─────────┼───────\n │ │ \nq1_2: |0>──■─────────■───────\n ┌─┴─┐┌───┐ │ \nq1_3: |0>┤ X ├┤ X ├──┼───────\n └───┘└───┘┌─┴─┐┌───┐\nq1_4: |0>──────────┤ X ├┤ X ├\n └───┘└───┘'
### Steps to reproduce the problem
The output is messed up unless calling `print(circuit_drawer(qc, output='text'))`. Therefore it is not a drop in replacement for the other methods which work fine in a notebook.
### What is the expected behavior?
### Suggested solutions
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import logging
import os
import subprocess
import tempfile
import warnings
from PIL import Image
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _latex
from qiskit.tools.visualization import _matplotlib
from qiskit.tools.visualization import _text
from qiskit.tools.visualization import _utils
from qiskit.transpiler import transpile_dag
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis=None,
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art string
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing. Defaults to
`"id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,cx,cy,cz,ch,crz,cu1,
cu3,swap,ccx,cswap"` This option is deprecated and will be removed
in the future.
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (str): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if
one is not specified it will use latex and if that fails fallback
to mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect.
line_length (int): Sets the length of the lines generated by `text`
output type. This useful when the drawing does not fit in the
console. If None (default), it will try to guess the console width
using shutil.get_terminal_size(). If you don't want pagination at
all, set `line_length=-1`.
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: (outputs `latex` and `python`) an in-memory representation of
the circuit diagram.
String: (outputs `text` and `latex_source`). The ascii art or the LaTeX
source code.
Raises:
VisualizationError: when an invalid output method is selected
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defaults to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'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'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
plotbarrier (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True. This is deprecated in the style dict
and will be removed in a future release. Use the `plot_barriers`
kwarg instead.
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
reversebits (bool): When set to True reverse the bit order inside
registers for the output visualization. This is deprecated in the
style dict and will be removed in a future release use the
`reverse_bits` kwarg instead.
"""
if basis is None:
basis = ("id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap")
else:
warnings.warn('The basis kwarg is deprecated and the circuit drawer '
'function will not be able to adjust basis gates itself '
'in a future release', DeprecationWarning)
im = None
if style:
if 'reversebits' in style:
warnings.warn('The reversebits key in style is deprecated and will'
'not work in the future. Instead use the '
'``reverse_bits`` kwarg.', DeprecationWarning)
reverse_bits = style.get('reversebits')
if 'plotbarrier' in style:
warnings.warn('The plotbarrier key in style is deprecated and will'
'not work in the future. Instead use the '
'``plot_barriers`` kwarg.', DeprecationWarning)
plot_barriers = style.get('plotbarrier')
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'"text" by default', DeprecationWarning)
try:
im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError, FileNotFoundError):
im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
else:
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename, basis=basis,
line_length=line_length,
reversebits=reverse_bits,
plotbarriers=plot_barriers)
elif output == 'latex':
im = _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'latex_source':
return _generate_latex_source(circuit, basis=basis,
filename=filename, scale=scale,
style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'mpl':
im = _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
else:
raise _error.VisualizationError(
'Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if im and interactive:
im.show()
return im
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap", line_length=None,
reversebits=False, plotbarriers=True):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
basis (str): Optional. Comma-separated list of gate names
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
reversebits (bool): Rearrange the bits in reverse order.
plotbarriers (bool): Draws the barriers when they are there.
Returns:
String: The drawing in a loooong string.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
text = "\n".join(
_text.TextDrawing(json_circuit, reversebits=reversebits, plotbarriers=plotbarriers).lines(
line_length))
if filename:
with open(filename, mode='w', encoding="utf8") as text_file:
text_file.write(text)
return text
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to compile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _utils._trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename, basis=basis,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None, reverse_bits=False,
plot_barriers=True):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
qcimg = _latex.QCircuitImage(json_circuit, scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,'
'ry,rz,cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,'
'cswap',
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = _matplotlib.MatplotlibDrawer(basis=basis, scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
<|code_end|>
qiskit/tools/visualization/_text.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A module for drawing circuits in ascii art or some other text representation
"""
from itertools import groupby
from shutil import get_terminal_size
from ._error import VisualizationError
class DrawElement():
""" An element is an instruction or an operation that need to be drawn."""
def __init__(self, label=None):
self._width = None
self.label = self.mid_content = label
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = self.bot_connect = " "
self.top_pad = self._mid_padding = self.bot_pad = " "
self.bot_connector = {}
self.top_connector = {}
self.right_fill = self.left_fill = 0
@property
def top(self):
""" Constructs the top line of the element"""
ret = self.top_format % self.top_connect.center(
self.width - self.left_fill - self.right_fill, self.top_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.top_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.top_pad)
return ret
@property
def mid(self):
""" Constructs the middle line of the element"""
ret = self.mid_format % self.mid_content.center(
self.width - self.left_fill - self.right_fill, self._mid_padding)
if self.right_fill:
ret = ret.ljust(self.right_fill, self._mid_padding)
if self.left_fill:
ret = ret.rjust(self.left_fill, self._mid_padding)
return ret
@property
def bot(self):
""" Constructs the bottom line of the element"""
ret = self.bot_format % self.bot_connect.center(
self.width - self.left_fill - self.right_fill, self.bot_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.bot_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.bot_pad)
return ret
@property
def length(self):
""" Returns the length of the element, including the box around."""
return max(len(self.top), len(self.mid), len(self.bot))
@length.setter
def length(self, value):
""" Adjusts width so the length fits."""
self.width = value - max(
[len(getattr(self, i) % '') for i in ["bot_format", "mid_format", "top_format"]])
@property
def width(self):
""" Returns the width of the label, including padding"""
if self._width:
return self._width
return len(self.mid_content)
@width.setter
def width(self, value):
self._width = value
def connect(self, wire_char, where, label=None):
"""
Connects boxes and elements using wire_char and setting proper connectors.
Args:
wire_char (char): For example '║' or '│'.
where (list["top", "bot"]): Where the connector should be set.
label (string): Some connectors have a label (see cu1, for example).
"""
if 'top' in where and self.top_connector:
self.top_connect = self.top_connector[wire_char]
if 'bot' in where and self.bot_connector:
self.bot_connect = self.bot_connector[wire_char]
if label:
self.top_format = self.top_format[:-1] + (label if label else "")
class BoxOnClWire(DrawElement):
""" Draws a box on the classical wire
top: ┌───┐ ┌───────┐
mid: ╡ A ╞ ╡ A ╞
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "╡ %s ╞"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
class BoxOnQuWire(DrawElement):
""" Draws a box on the quantum wire
top: ┌───┐ ┌───────┐
mid: ┤ A ├ ┤ A ├
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "┤ %s ├"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
self.top_connector = {"│": '┴'}
self.bot_connector = {"│": '┬'}
class MeasureTo(DrawElement):
""" The element on the classic wire to which the measure is performed
top: ║ ║
mid: ═╩═ ═══╩═══
bot:
"""
def __init__(self):
super().__init__()
self.top_connect = " ║ "
self.mid_content = "═╩═"
self.bot_connect = " "
self._mid_padding = "═"
class MeasureFrom(BoxOnQuWire):
""" The element on the quantum wire in which the measure is performed
top: ┌─┐ ┌─┐
mid: ┤M├ ───┤M├───
bot: └╥┘ └╥┘
"""
def __init__(self):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = "┌─┐"
self.mid_content = "┤M├"
self.bot_connect = "└╥┘"
class MultiBox(DrawElement):
"""Elements that is draw on over multiple wires."""
def center_label(self, input_length, order):
"""
In multi-bit elements, the label is centered vertically.
Args:
input_length (int): Rhe amount of wires affected.
order (int): Which middle element is this one?
"""
location_in_the_box = '*'.center(input_length * 2 - 1).index('*') + 1
top_limit = (order - 1) * 2 + 2
bot_limit = top_limit + 2
if top_limit <= location_in_the_box < bot_limit:
if location_in_the_box == top_limit:
self.top_connect = self.label
elif location_in_the_box == top_limit + 1:
self.mid_content = self.label
else:
self.bot_connect = self.label
class BoxOnQuWireTop(MultiBox, BoxOnQuWire):
""" Draws the top part of a box that affects more than one quantum wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnQuWireMid(MultiBox, BoxOnQuWire):
""" Draws the middle part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.center_label(input_length, order)
class BoxOnQuWireBot(MultiBox, BoxOnQuWire):
""" Draws the bottom part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length):
super().__init__(label)
self.top_format = "│ %s │"
self.mid_content = self.bot_connect = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class BoxOnClWireTop(MultiBox, BoxOnClWire):
""" Draws the top part of a conditional box that affects more than one classical wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnClWireMid(MultiBox, BoxOnClWire):
""" Draws the middle part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.mid_content = label
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.top_pad = self.bot_pad = ' '
self.top_connect = self.bot_connect = self.mid_content = ''
self.center_label(input_length, order)
class BoxOnClWireBot(MultiBox, BoxOnClWire):
""" Draws the bottom part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, bot_connect='─'):
super().__init__(label)
self.top_format = "│ %s │"
self.top_pad = " "
self.bot_connect = bot_connect
self.mid_content = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class DirectOnQuWire(DrawElement):
"""
Element to the wire (without the box).
"""
def __init__(self, label=""):
super().__init__(label)
self.top_format = ' %s '
self.mid_format = '─%s─'
self.bot_format = ' %s '
self._mid_padding = '─'
self.top_connector = {"│": '│'}
self.bot_connector = {"│": '│'}
class Barrier(DirectOnQuWire):
""" Draws a barrier.
top: ░ ░
mid: ─░─ ───░───
bot: ░ ░
"""
def __init__(self, label=""):
super().__init__("░")
self.top_connect = "░"
self.bot_connect = "░"
self.top_connector = {}
self.bot_connector = {}
class Ex(DirectOnQuWire):
""" Draws an X (usually with a connector). E.g. the top part of a swap gate
top:
mid: ─X─ ───X───
bot: │ │
"""
def __init__(self, bot_connect=" ", top_connect=" "):
super().__init__("X")
self.bot_connect = bot_connect
self.top_connect = top_connect
class Reset(DirectOnQuWire):
""" Draws a reset gate"""
def __init__(self):
super().__init__("|0>")
class Bullet(DirectOnQuWire):
""" Draws a bullet (usually with a connector). E.g. the top part of a CX gate.
top:
mid: ─■─ ───■───
bot: │ │
"""
def __init__(self, top_connect=" ", bot_connect=" "):
super().__init__('■')
self.top_connect = top_connect
self.bot_connect = bot_connect
class EmptyWire(DrawElement):
""" This element is just the wire, with no instructions nor operations."""
def __init__(self, wire):
super().__init__(wire)
self._mid_padding = wire
@staticmethod
def fillup_layer(layer, first_clbit):
"""
Given a layer, replace the Nones in it with EmptyWire elements.
Args:
layer (list): The layer that contains Nones.
first_clbit (int): The first wire that is classic.
Returns:
list: The new layer, with no Nones.
"""
for nones in [i for i, x in enumerate(layer) if x is None]:
layer[nones] = EmptyWire('═') if nones >= first_clbit else EmptyWire('─')
return layer
class BreakWire(DrawElement):
""" This element is used to break the drawing in several pages."""
def __init__(self, arrow_char):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = arrow_char
self.mid_content = arrow_char
self.bot_connect = arrow_char
@staticmethod
def fillup_layer(layer_length, arrow_char):
"""
Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer.
"""
breakwire_layer = []
for _ in range(layer_length):
breakwire_layer.append(BreakWire(arrow_char))
return breakwire_layer
class InputWire(DrawElement):
""" This element is the label and the initial value of a wire."""
def __init__(self, label):
super().__init__(label)
@staticmethod
def fillup_layer(names): # pylint: disable=arguments-differ
"""
Creates a layer with InputWire elements.
Args:
names (list): List of names for the wires.
Returns:
list: The new layer
"""
longest = max([len(name) for name in names])
inputs_wires = []
for name in names:
inputs_wires.append(InputWire(name.rjust(longest)))
return inputs_wires
class TextDrawing():
""" The text drawing"""
def __init__(self, json_circuit, reversebits=False, plotbarriers=True):
self.json_circuit = json_circuit
self.reversebits = reversebits
self.plotbarriers = plotbarriers
self.qubitorder = self._get_qubitorder()
self.clbitorder = self._get_clbitorder()
def _get_qubit_labels(self):
qubits = []
for qubit in self.json_circuit['header']['qubit_labels']:
qubits.append("%s_%s" % (qubit[0], qubit[1]))
return qubits
def _get_clbit_labels(self):
clbits = []
for creg in self.json_circuit['header']['clbit_labels']:
for clbit in range(creg[1]):
clbits.append("%s_%s" % (creg[0], clbit))
return clbits
def _get_qubitorder(self):
header = self.json_circuit['header']
if not self.reversebits:
return [qub for qub in range(header['number_of_qubits'])]
qreg_dest_order = []
for _, qubits in groupby(header['qubit_labels'], lambda x: x[0]):
qubits = [qubit for qubit in qubits]
qubits.reverse()
for qubit in qubits:
qreg_dest_order.append("%s_%s" % (qubit[0], qubit[1]))
return [qreg_dest_order.index(ind) for ind in self._get_qubit_labels()]
def _get_clbitorder(self):
header = self.json_circuit['header']
if not self.reversebits:
return [clb for clb in range(header['number_of_clbits'])]
creg_dest_order = []
for creg in self.json_circuit['header']['clbit_labels']:
bit_nos = [bit for bit in range(creg[1])]
bit_nos.reverse()
for clbit in bit_nos:
creg_dest_order.append("%s_%s" % (creg[0], clbit))
return [creg_dest_order.index(ind) for ind in self._get_clbit_labels()]
def lines(self, line_length=None):
"""
Generates a list with lines. These lines form the text drawing.
Args:
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
Returns:
list: A list of lines with the text drawing.
"""
if line_length is None:
line_length, _ = get_terminal_size()
noqubits = self.json_circuit['header']['number_of_qubits']
layers = self.build_layers()
# TODO compress layers
# -| H |----------
# --------| H |---
# should be
# -| H |---
# -| H |---
layer_groups = [[]]
rest_of_the_line = line_length
for layerno, layer in enumerate(layers):
# Replace the Nones with EmptyWire
layers[layerno] = EmptyWire.fillup_layer(layer, noqubits)
TextDrawing.normalize_width(layer)
if line_length == -1:
# Do not use pagination (aka line breaking. aka ignore line_length).
layer_groups[-1].append(layer)
continue
# chop the layer to the line_length (pager)
layer_length = layers[layerno][0].length
if layer_length < rest_of_the_line:
layer_groups[-1].append(layer)
rest_of_the_line -= layer_length
else:
layer_groups[-1].append(BreakWire.fillup_layer(len(layer), '»'))
# New group
layer_groups.append([BreakWire.fillup_layer(len(layer), '«')])
rest_of_the_line = line_length - layer_groups[-1][-1][0].length
layer_groups[-1].append(
InputWire.fillup_layer(self.wire_names(with_initial_value=False)))
rest_of_the_line -= layer_groups[-1][-1][0].length
layer_groups[-1].append(layer)
rest_of_the_line -= layer_groups[-1][-1][0].length
lines = []
for layer_group in layer_groups:
wires = [i for i in zip(*layer_group)]
lines += TextDrawing.draw_wires(wires)
return lines
def wire_names(self, with_initial_value=True):
"""
Returns a list of names for each wire.
Args:
with_initial_value (bool): Optional (Default: True). If true, adds the initial value to
the name.
Returns:
List: The list of wire names.
"""
qubit_labels = self._get_qubit_labels()
clbit_labels = self._get_clbit_labels()
if with_initial_value:
qubit_labels = ['%s: |0>' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: 0 ' % clbit for clbit in clbit_labels]
else:
qubit_labels = ['%s: ' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: ' % clbit for clbit in clbit_labels]
qubit_wires = [None] * self.json_circuit['header']['number_of_qubits']
clbit_wires = [None] * self.json_circuit['header']['number_of_clbits']
for order, label in enumerate(qubit_labels):
qubit_wires[self.qubitorder[order]] = label
for order, label in enumerate(clbit_labels):
clbit_wires[self.clbitorder[order]] = label
return qubit_wires + clbit_wires
@staticmethod
def draw_wires(wires):
"""
Given a list of wires, creates a list of lines with the text drawing.
Args:
wires (list): A list of wires with instructions.
Returns:
list: A list of lines with the text drawing.
"""
lines = []
bot_line = None
for wire in wires:
# TOP
top_line = ""
for instruction in wire:
top_line += instruction.top
if bot_line is None:
lines.append(top_line)
else:
lines.append(TextDrawing.merge_lines(lines.pop(), top_line))
# MID
mid_line = ""
for instruction in wire:
mid_line += instruction.mid
lines.append(TextDrawing.merge_lines(lines[-1], mid_line, icod="bot"))
# BOT
bot_line = ""
for instruction in wire:
bot_line += instruction.bot
lines.append(TextDrawing.merge_lines(lines[-1], bot_line, icod="bot"))
return lines
@staticmethod
def label_for_conditional(instruction):
""" Creates the label for a conditional instruction."""
return "%s %s" % ('=', instruction['conditional']['val'])
@staticmethod
def params_for_label(instruction):
"""Get the params and format them to add them to a label. None of there is no param."""
if 'params' in instruction and instruction['params']:
return ['%.5g' % i for i in instruction['params']]
return None
@staticmethod
def label_for_box(instruction):
""" Creates the label for a box."""
label = instruction['name'].capitalize()
params = TextDrawing.params_for_label(instruction)
if params:
label += "(%s)" % ','.join(params)
return label
@staticmethod
def merge_lines(top, bot, icod="top"):
"""
Merges two lines (top and bot) in the way that the overlapping make senses.
Args:
top (str): the top line
bot (str): the bottom line
icod (top or bot): in case of doubt, which line should have priority? Default: "top".
Returns:
str: The merge of both lines.
"""
ret = ""
for topc, botc in zip(top, bot):
if topc == botc:
ret += topc
elif topc in '┼╪' and botc == " ":
ret += "│"
elif topc == " ":
ret += botc
elif topc in '┬╥' and botc in " ║│":
ret += topc
elif topc in '┬│' and botc == "═":
ret += '╪'
elif topc in '┬│' and botc == "─":
ret += '┼'
elif topc in '└┘║│░' and botc == " ":
ret += topc
elif topc in '─═' and botc == " " and icod == "top":
ret += topc
elif topc in '─═' and botc == " " and icod == "bot":
ret += botc
elif topc in "║╥" and botc in "═":
ret += "╬"
elif topc in "║╥" and botc in "─":
ret += "╫"
elif topc in '╫╬' and botc in " ":
ret += "║"
elif topc == '└' and botc == "┌":
ret += "├"
elif topc == '┘' and botc == "┐":
ret += "┤"
else:
ret += botc
return ret
def clbit_index_from_mask(self, mask):
"""
Given a mask, returns a list of classical indexes affected by that mask.
Args:
mask (int): The mask.
Returns:
list: A list of indexes affected by the mask.
"""
clbit_len = self.json_circuit['header']['number_of_clbits']
bit_mask = [bool(mask & (1 << n)) for n in range(clbit_len)]
return [i for i, x in enumerate(bit_mask) if x]
@staticmethod
def normalize_width(layer):
"""
When the elements of the layer have different widths, sets the width to the max elements.
Args:
layer (list): A list of elements.
"""
instructions = [instruction for instruction in filter(lambda x: x is not None, layer)]
longest = max([instruction.length for instruction in instructions])
for instruction in instructions:
instruction.length = longest
def build_layers(self):
"""
Constructs layers.
Returns:
list: List of DrawElements.
Raises:
VisualizationError: When the drawing is, for some reason, impossible to be drawn.
"""
layers = []
layers.append(InputWire.fillup_layer(self.wire_names(with_initial_value=True)))
for instruction in self.json_circuit['instructions']:
layer = Layer(self.qubitorder, self.clbitorder)
connector_label = None
if instruction['name'] == 'measure':
layer.set_qubit(instruction['qubits'][0], MeasureFrom())
layer.set_clbit(instruction['clbits'][0], MeasureTo())
elif instruction['name'] == 'barrier':
# barrier
if not self.plotbarriers:
continue
for qubit in instruction['qubits']:
layer.set_qubit(qubit, Barrier())
elif instruction['name'] == 'swap':
# swap
for qubit in instruction['qubits']:
layer.set_qubit(qubit, Ex())
elif instruction['name'] == 'cswap':
# cswap
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Ex())
layer.set_qubit(instruction['qubits'][2], Ex())
elif instruction['name'] == 'reset':
layer.set_qubit(instruction['qubits'][0], Reset())
elif 'conditional' in instruction:
# conditional
clbits = self.clbit_index_from_mask(int(instruction['conditional']['mask'], 16))
cllabel = TextDrawing.label_for_conditional(instruction)
qulabel = TextDrawing.label_for_box(instruction)
layer.set_cl_multibox(clbits, cllabel, top_connect='┴')
layer.set_qubit(instruction['qubits'][0], BoxOnQuWire(qulabel, bot_connect='┬'))
elif instruction['name'] in ['cx', 'CX', 'ccx']:
# cx/ccx
for qubit in [qubit for qubit in instruction['qubits'][:-1]]:
layer.set_qubit(qubit, Bullet())
layer.set_qubit(instruction['qubits'][-1], BoxOnQuWire('X'))
elif instruction['name'] == 'cy':
# cy
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], BoxOnQuWire('Y'))
elif instruction['name'] == 'cz':
# cz
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Bullet())
elif instruction['name'] == 'ch':
# ch
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], BoxOnQuWire('H'))
elif instruction['name'] == 'cu1':
# cu1
connector_label = TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Bullet())
elif instruction['name'] == 'cu3':
# cu3
params = TextDrawing.params_for_label(instruction)
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1],
BoxOnQuWire("U3(%s)" % ','.join(params)))
elif instruction['name'] == 'crz':
# crz
label = "Rz(%s)" % TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1],
BoxOnQuWire(label))
elif len(instruction['qubits']) == 1 and 'clbits' not in instruction:
# unitary gate
layer.set_qubit(instruction['qubits'][0],
BoxOnQuWire(TextDrawing.label_for_box(instruction)))
elif len(instruction['qubits']) >= 2 and 'clbits' not in instruction:
# multiple qubit gate
layer.set_qu_multibox(instruction['qubits'], TextDrawing.label_for_box(instruction))
else:
raise VisualizationError(
"Text visualizer does not know how to handle this instruction", instruction)
layer.connect_with("│", connector_label)
layers.append(layer.full_layer)
return layers
class Layer:
""" A layer is the "column" of the circuit. """
def __init__(self, qubitorder, clbitorder):
self.qubitorder = qubitorder
self.clbitorder = clbitorder
self.qubit_layer = [None] * len(qubitorder)
self.clbit_layer = [None] * len(clbitorder)
@property
def full_layer(self):
"""
Returns the composition of qubits and classic wires.
Returns:
String: self.qubit_layer + self.clbit_layer
"""
return self.qubit_layer + self.clbit_layer
def set_qubit(self, qubit, element):
"""
Sets the qubit to the element
Args:
qubit (int): Qubit index.
element (DrawElement): Element to set in the qubit
"""
self.qubit_layer[self.qubitorder[qubit]] = element
def set_clbit(self, clbit, element):
"""
Sets the clbit to the element
Args:
clbit (int): Clbit index.
element (DrawElement): Element to set in the clbit
"""
self.clbit_layer[self.clbitorder[clbit]] = element
def _set_multibox(self, wire_type, bits, label, top_connect=None):
# pylint: disable=invalid-name
bits = sorted(bits)
if wire_type == "cl":
set_bit = self.set_clbit
BoxOnWire = BoxOnClWire
BoxOnWireTop = BoxOnClWireTop
BoxOnWireMid = BoxOnClWireMid
BoxOnWireBot = BoxOnClWireBot
elif wire_type == "qu":
set_bit = self.set_qubit
BoxOnWire = BoxOnQuWire
BoxOnWireTop = BoxOnQuWireTop
BoxOnWireMid = BoxOnQuWireMid
BoxOnWireBot = BoxOnQuWireBot
# Checks if qubits are consecutive
if bits != [i for i in range(bits[0], bits[-1] + 1)]:
raise VisualizationError("Text visualizaer does know how to build a gate with multiple"
"bits when they are not adjacent to each other")
if len(bits) == 1:
set_bit(bits[0], BoxOnWire(label, top_connect=top_connect))
else:
set_bit(bits[0], BoxOnWireTop(label, top_connect=top_connect))
for order, bit in enumerate(bits[1:-1], 1):
set_bit(bit, BoxOnWireMid(label, len(bits), order))
set_bit(bits[-1], BoxOnWireBot(label, len(bits)))
def set_cl_multibox(self, bits, label, top_connect='┴'):
"""
Sets the multi clbit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi clbit box.
top_connect (char): The char to connect the box on the top.
"""
self._set_multibox("cl", bits, label, top_connect=top_connect)
def set_qu_multibox(self, bits, label):
"""
Sets the multi qubit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi qubit box.
"""
self._set_multibox("qu", bits, label)
def connect_with(self, wire_char, label=None):
"""
Connects the elements in the layer using wire_char.
Args:
wire_char (char): For example '║' or '│'.
label (string): Some connectors have a label (see cu1, for example).
"""
affected_bits = [bit for bit in self.full_layer if bit is not None]
if len([qbit for qbit in self.qubit_layer if qbit is not None]) == 1:
# Nothing to connect
return
affected_bits[0].connect(wire_char, ['bot'])
for affected_bit in affected_bits[1:-1]:
affected_bit.connect(wire_char, ['bot', 'top'])
affected_bits[-1].connect(wire_char, ['top'], label)
if label:
for affected_bit in affected_bits:
affected_bit.right_fill = len(label) + len(affected_bit.mid)
<|code_end|>
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import logging
import os
import subprocess
import tempfile
import warnings
from PIL import Image
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _latex
from qiskit.tools.visualization import _matplotlib
from qiskit.tools.visualization import _text
from qiskit.tools.visualization import _utils
from qiskit.transpiler import transpile_dag
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis=None,
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art TextDrawing that can be printed in the console.
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing. Defaults to
`"id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,cx,cy,cz,ch,crz,cu1,
cu3,swap,ccx,cswap"` This option is deprecated and will be removed
in the future.
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (TextDrawing): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if
one is not specified it will use latex and if that fails fallback
to mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect.
line_length (int): Sets the length of the lines generated by `text`
output type. This useful when the drawing does not fit in the
console. If None (default), it will try to guess the console width
using shutil.get_terminal_size(). If you don't want pagination at
all, set `line_length=-1`.
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: (outputs `latex` and `python`) an in-memory representation of
the circuit diagram.
String: (output `latex_source`). The LaTeX source code.
TextDrawing: (output `text`). A drawing that can be printed as ascii art
Raises:
VisualizationError: when an invalid output method is selected
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defaults to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'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'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
plotbarrier (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True. This is deprecated in the style dict
and will be removed in a future release. Use the `plot_barriers`
kwarg instead.
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
reversebits (bool): When set to True reverse the bit order inside
registers for the output visualization. This is deprecated in the
style dict and will be removed in a future release use the
`reverse_bits` kwarg instead.
"""
if basis is None:
basis = ("id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap")
else:
warnings.warn('The basis kwarg is deprecated and the circuit drawer '
'function will not be able to adjust basis gates itself '
'in a future release', DeprecationWarning)
im = None
if style:
if 'reversebits' in style:
warnings.warn('The reversebits key in style is deprecated and will'
'not work in the future. Instead use the '
'``reverse_bits`` kwarg.', DeprecationWarning)
reverse_bits = style.get('reversebits')
if 'plotbarrier' in style:
warnings.warn('The plotbarrier key in style is deprecated and will'
'not work in the future. Instead use the '
'``plot_barriers`` kwarg.', DeprecationWarning)
plot_barriers = style.get('plotbarrier')
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'"text" by default', DeprecationWarning)
try:
im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError, FileNotFoundError):
im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
else:
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename, basis=basis,
line_length=line_length,
reversebits=reverse_bits,
plotbarriers=plot_barriers)
elif output == 'latex':
im = _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'latex_source':
return _generate_latex_source(circuit, basis=basis,
filename=filename, scale=scale,
style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'mpl':
im = _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
else:
raise _error.VisualizationError(
'Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if im and interactive:
im.show()
return im
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap", line_length=None,
reversebits=False, plotbarriers=True):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
basis (str): Optional. Comma-separated list of gate names
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
reversebits (bool): Rearrange the bits in reverse order.
plotbarriers (bool): Draws the barriers when they are there.
Returns:
TextDrawing: An instances that, when printed, draws the circuit in ascii art.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
text_drawing = _text.TextDrawing(json_circuit, reversebits=reversebits)
text_drawing.plotbarriers = plotbarriers
text_drawing.line_length = line_length
if filename:
text_drawing.dump(filename)
return text_drawing
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to compile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _utils._trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename, basis=basis,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None, reverse_bits=False,
plot_barriers=True):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
qcimg = _latex.QCircuitImage(json_circuit, scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,'
'ry,rz,cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,'
'cswap',
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = _matplotlib.MatplotlibDrawer(basis=basis, scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
<|code_end|>
qiskit/tools/visualization/_text.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A module for drawing circuits in ascii art or some other text representation
"""
from itertools import groupby
from shutil import get_terminal_size
from ._error import VisualizationError
class DrawElement():
""" An element is an instruction or an operation that need to be drawn."""
def __init__(self, label=None):
self._width = None
self.label = self.mid_content = label
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = self.bot_connect = " "
self.top_pad = self._mid_padding = self.bot_pad = " "
self.bot_connector = {}
self.top_connector = {}
self.right_fill = self.left_fill = 0
@property
def top(self):
""" Constructs the top line of the element"""
ret = self.top_format % self.top_connect.center(
self.width - self.left_fill - self.right_fill, self.top_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.top_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.top_pad)
return ret
@property
def mid(self):
""" Constructs the middle line of the element"""
ret = self.mid_format % self.mid_content.center(
self.width - self.left_fill - self.right_fill, self._mid_padding)
if self.right_fill:
ret = ret.ljust(self.right_fill, self._mid_padding)
if self.left_fill:
ret = ret.rjust(self.left_fill, self._mid_padding)
return ret
@property
def bot(self):
""" Constructs the bottom line of the element"""
ret = self.bot_format % self.bot_connect.center(
self.width - self.left_fill - self.right_fill, self.bot_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.bot_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.bot_pad)
return ret
@property
def length(self):
""" Returns the length of the element, including the box around."""
return max(len(self.top), len(self.mid), len(self.bot))
@length.setter
def length(self, value):
""" Adjusts width so the length fits."""
self.width = value - max(
[len(getattr(self, i) % '') for i in ["bot_format", "mid_format", "top_format"]])
@property
def width(self):
""" Returns the width of the label, including padding"""
if self._width:
return self._width
return len(self.mid_content)
@width.setter
def width(self, value):
self._width = value
def connect(self, wire_char, where, label=None):
"""
Connects boxes and elements using wire_char and setting proper connectors.
Args:
wire_char (char): For example '║' or '│'.
where (list["top", "bot"]): Where the connector should be set.
label (string): Some connectors have a label (see cu1, for example).
"""
if 'top' in where and self.top_connector:
self.top_connect = self.top_connector[wire_char]
if 'bot' in where and self.bot_connector:
self.bot_connect = self.bot_connector[wire_char]
if label:
self.top_format = self.top_format[:-1] + (label if label else "")
class BoxOnClWire(DrawElement):
""" Draws a box on the classical wire
top: ┌───┐ ┌───────┐
mid: ╡ A ╞ ╡ A ╞
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "╡ %s ╞"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
class BoxOnQuWire(DrawElement):
""" Draws a box on the quantum wire
top: ┌───┐ ┌───────┐
mid: ┤ A ├ ┤ A ├
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "┤ %s ├"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
self.top_connector = {"│": '┴'}
self.bot_connector = {"│": '┬'}
class MeasureTo(DrawElement):
""" The element on the classic wire to which the measure is performed
top: ║ ║
mid: ═╩═ ═══╩═══
bot:
"""
def __init__(self):
super().__init__()
self.top_connect = " ║ "
self.mid_content = "═╩═"
self.bot_connect = " "
self._mid_padding = "═"
class MeasureFrom(BoxOnQuWire):
""" The element on the quantum wire in which the measure is performed
top: ┌─┐ ┌─┐
mid: ┤M├ ───┤M├───
bot: └╥┘ └╥┘
"""
def __init__(self):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = "┌─┐"
self.mid_content = "┤M├"
self.bot_connect = "└╥┘"
class MultiBox(DrawElement):
"""Elements that is draw on over multiple wires."""
def center_label(self, input_length, order):
"""
In multi-bit elements, the label is centered vertically.
Args:
input_length (int): Rhe amount of wires affected.
order (int): Which middle element is this one?
"""
location_in_the_box = '*'.center(input_length * 2 - 1).index('*') + 1
top_limit = (order - 1) * 2 + 2
bot_limit = top_limit + 2
if top_limit <= location_in_the_box < bot_limit:
if location_in_the_box == top_limit:
self.top_connect = self.label
elif location_in_the_box == top_limit + 1:
self.mid_content = self.label
else:
self.bot_connect = self.label
class BoxOnQuWireTop(MultiBox, BoxOnQuWire):
""" Draws the top part of a box that affects more than one quantum wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnQuWireMid(MultiBox, BoxOnQuWire):
""" Draws the middle part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.center_label(input_length, order)
class BoxOnQuWireBot(MultiBox, BoxOnQuWire):
""" Draws the bottom part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length):
super().__init__(label)
self.top_format = "│ %s │"
self.mid_content = self.bot_connect = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class BoxOnClWireTop(MultiBox, BoxOnClWire):
""" Draws the top part of a conditional box that affects more than one classical wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnClWireMid(MultiBox, BoxOnClWire):
""" Draws the middle part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.mid_content = label
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.top_pad = self.bot_pad = ' '
self.top_connect = self.bot_connect = self.mid_content = ''
self.center_label(input_length, order)
class BoxOnClWireBot(MultiBox, BoxOnClWire):
""" Draws the bottom part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, bot_connect='─'):
super().__init__(label)
self.top_format = "│ %s │"
self.top_pad = " "
self.bot_connect = bot_connect
self.mid_content = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class DirectOnQuWire(DrawElement):
"""
Element to the wire (without the box).
"""
def __init__(self, label=""):
super().__init__(label)
self.top_format = ' %s '
self.mid_format = '─%s─'
self.bot_format = ' %s '
self._mid_padding = '─'
self.top_connector = {"│": '│'}
self.bot_connector = {"│": '│'}
class Barrier(DirectOnQuWire):
""" Draws a barrier.
top: ░ ░
mid: ─░─ ───░───
bot: ░ ░
"""
def __init__(self, label=""):
super().__init__("░")
self.top_connect = "░"
self.bot_connect = "░"
self.top_connector = {}
self.bot_connector = {}
class Ex(DirectOnQuWire):
""" Draws an X (usually with a connector). E.g. the top part of a swap gate
top:
mid: ─X─ ───X───
bot: │ │
"""
def __init__(self, bot_connect=" ", top_connect=" "):
super().__init__("X")
self.bot_connect = bot_connect
self.top_connect = top_connect
class Reset(DirectOnQuWire):
""" Draws a reset gate"""
def __init__(self):
super().__init__("|0>")
class Bullet(DirectOnQuWire):
""" Draws a bullet (usually with a connector). E.g. the top part of a CX gate.
top:
mid: ─■─ ───■───
bot: │ │
"""
def __init__(self, top_connect=" ", bot_connect=" "):
super().__init__('■')
self.top_connect = top_connect
self.bot_connect = bot_connect
class EmptyWire(DrawElement):
""" This element is just the wire, with no instructions nor operations."""
def __init__(self, wire):
super().__init__(wire)
self._mid_padding = wire
@staticmethod
def fillup_layer(layer, first_clbit):
"""
Given a layer, replace the Nones in it with EmptyWire elements.
Args:
layer (list): The layer that contains Nones.
first_clbit (int): The first wire that is classic.
Returns:
list: The new layer, with no Nones.
"""
for nones in [i for i, x in enumerate(layer) if x is None]:
layer[nones] = EmptyWire('═') if nones >= first_clbit else EmptyWire('─')
return layer
class BreakWire(DrawElement):
""" This element is used to break the drawing in several pages."""
def __init__(self, arrow_char):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = arrow_char
self.mid_content = arrow_char
self.bot_connect = arrow_char
@staticmethod
def fillup_layer(layer_length, arrow_char):
"""
Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer.
"""
breakwire_layer = []
for _ in range(layer_length):
breakwire_layer.append(BreakWire(arrow_char))
return breakwire_layer
class InputWire(DrawElement):
""" This element is the label and the initial value of a wire."""
def __init__(self, label):
super().__init__(label)
@staticmethod
def fillup_layer(names): # pylint: disable=arguments-differ
"""
Creates a layer with InputWire elements.
Args:
names (list): List of names for the wires.
Returns:
list: The new layer
"""
longest = max([len(name) for name in names])
inputs_wires = []
for name in names:
inputs_wires.append(InputWire(name.rjust(longest)))
return inputs_wires
class TextDrawing():
""" The text drawing"""
def __init__(self, json_circuit, reversebits=False, plotbarriers=True, line_length=None):
self.json_circuit = json_circuit
self.reversebits = reversebits
self.plotbarriers = plotbarriers
self.line_length = line_length
self.qubitorder = self._get_qubitorder()
self.clbitorder = self._get_clbitorder()
def __str__(self):
return self.single_string()
def _repr_html_(self):
return '<pre style="line-height: 15px;">%s</pre>' % self.single_string()
def _get_qubit_labels(self):
qubits = []
for qubit in self.json_circuit['header']['qubit_labels']:
qubits.append("%s_%s" % (qubit[0], qubit[1]))
return qubits
def _get_clbit_labels(self):
clbits = []
for creg in self.json_circuit['header']['clbit_labels']:
for clbit in range(creg[1]):
clbits.append("%s_%s" % (creg[0], clbit))
return clbits
def _get_qubitorder(self):
header = self.json_circuit['header']
if not self.reversebits:
return [qub for qub in range(header['number_of_qubits'])]
qreg_dest_order = []
for _, qubits in groupby(header['qubit_labels'], lambda x: x[0]):
qubits = [qubit for qubit in qubits]
qubits.reverse()
for qubit in qubits:
qreg_dest_order.append("%s_%s" % (qubit[0], qubit[1]))
return [qreg_dest_order.index(ind) for ind in self._get_qubit_labels()]
def _get_clbitorder(self):
header = self.json_circuit['header']
if not self.reversebits:
return [clb for clb in range(header['number_of_clbits'])]
creg_dest_order = []
for creg in self.json_circuit['header']['clbit_labels']:
bit_nos = [bit for bit in range(creg[1])]
bit_nos.reverse()
for clbit in bit_nos:
creg_dest_order.append("%s_%s" % (creg[0], clbit))
return [creg_dest_order.index(ind) for ind in self._get_clbit_labels()]
def single_string(self):
"""
Creates a loong string with the ascii art
Returns:
str: The lines joined by '\n'
"""
return "\n".join(self.lines())
def dump(self, filename, encoding="utf8"):
"""
Dumps the ascii art in the file.
Args:
filename (str): File to dump the ascii art.
encoding (str): Optional. Default "utf-8".
"""
with open(filename, mode='w', encoding=encoding) as text_file:
text_file.write(self.single_string())
def lines(self, line_length=None):
"""
Generates a list with lines. These lines form the text drawing.
Args:
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
Returns:
list: A list of lines with the text drawing.
"""
if line_length is None:
line_length = self.line_length
if line_length is None:
line_length, _ = get_terminal_size()
noqubits = self.json_circuit['header']['number_of_qubits']
layers = self.build_layers()
# TODO compress layers
# -| H |----------
# --------| H |---
# should be
# -| H |---
# -| H |---
if not line_length:
line_length = self.line_length
layer_groups = [[]]
rest_of_the_line = line_length
for layerno, layer in enumerate(layers):
# Replace the Nones with EmptyWire
layers[layerno] = EmptyWire.fillup_layer(layer, noqubits)
TextDrawing.normalize_width(layer)
if line_length == -1:
# Do not use pagination (aka line breaking. aka ignore line_length).
layer_groups[-1].append(layer)
continue
# chop the layer to the line_length (pager)
layer_length = layers[layerno][0].length
if layer_length < rest_of_the_line:
layer_groups[-1].append(layer)
rest_of_the_line -= layer_length
else:
layer_groups[-1].append(BreakWire.fillup_layer(len(layer), '»'))
# New group
layer_groups.append([BreakWire.fillup_layer(len(layer), '«')])
rest_of_the_line = line_length - layer_groups[-1][-1][0].length
layer_groups[-1].append(
InputWire.fillup_layer(self.wire_names(with_initial_value=False)))
rest_of_the_line -= layer_groups[-1][-1][0].length
layer_groups[-1].append(layer)
rest_of_the_line -= layer_groups[-1][-1][0].length
lines = []
for layer_group in layer_groups:
wires = [i for i in zip(*layer_group)]
lines += TextDrawing.draw_wires(wires)
return lines
def wire_names(self, with_initial_value=True):
"""
Returns a list of names for each wire.
Args:
with_initial_value (bool): Optional (Default: True). If true, adds the initial value to
the name.
Returns:
List: The list of wire names.
"""
qubit_labels = self._get_qubit_labels()
clbit_labels = self._get_clbit_labels()
if with_initial_value:
qubit_labels = ['%s: |0>' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: 0 ' % clbit for clbit in clbit_labels]
else:
qubit_labels = ['%s: ' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: ' % clbit for clbit in clbit_labels]
qubit_wires = [None] * self.json_circuit['header']['number_of_qubits']
clbit_wires = [None] * self.json_circuit['header']['number_of_clbits']
for order, label in enumerate(qubit_labels):
qubit_wires[self.qubitorder[order]] = label
for order, label in enumerate(clbit_labels):
clbit_wires[self.clbitorder[order]] = label
return qubit_wires + clbit_wires
@staticmethod
def draw_wires(wires):
"""
Given a list of wires, creates a list of lines with the text drawing.
Args:
wires (list): A list of wires with instructions.
Returns:
list: A list of lines with the text drawing.
"""
lines = []
bot_line = None
for wire in wires:
# TOP
top_line = ""
for instruction in wire:
top_line += instruction.top
if bot_line is None:
lines.append(top_line)
else:
lines.append(TextDrawing.merge_lines(lines.pop(), top_line))
# MID
mid_line = ""
for instruction in wire:
mid_line += instruction.mid
lines.append(TextDrawing.merge_lines(lines[-1], mid_line, icod="bot"))
# BOT
bot_line = ""
for instruction in wire:
bot_line += instruction.bot
lines.append(TextDrawing.merge_lines(lines[-1], bot_line, icod="bot"))
return lines
@staticmethod
def label_for_conditional(instruction):
""" Creates the label for a conditional instruction."""
return "%s %s" % ('=', instruction['conditional']['val'])
@staticmethod
def params_for_label(instruction):
"""Get the params and format them to add them to a label. None of there is no param."""
if 'params' in instruction and instruction['params']:
return ['%.5g' % i for i in instruction['params']]
return None
@staticmethod
def label_for_box(instruction):
""" Creates the label for a box."""
label = instruction['name'].capitalize()
params = TextDrawing.params_for_label(instruction)
if params:
label += "(%s)" % ','.join(params)
return label
@staticmethod
def merge_lines(top, bot, icod="top"):
"""
Merges two lines (top and bot) in the way that the overlapping make senses.
Args:
top (str): the top line
bot (str): the bottom line
icod (top or bot): in case of doubt, which line should have priority? Default: "top".
Returns:
str: The merge of both lines.
"""
ret = ""
for topc, botc in zip(top, bot):
if topc == botc:
ret += topc
elif topc in '┼╪' and botc == " ":
ret += "│"
elif topc == " ":
ret += botc
elif topc in '┬╥' and botc in " ║│":
ret += topc
elif topc in '┬│' and botc == "═":
ret += '╪'
elif topc in '┬│' and botc == "─":
ret += '┼'
elif topc in '└┘║│░' and botc == " ":
ret += topc
elif topc in '─═' and botc == " " and icod == "top":
ret += topc
elif topc in '─═' and botc == " " and icod == "bot":
ret += botc
elif topc in "║╥" and botc in "═":
ret += "╬"
elif topc in "║╥" and botc in "─":
ret += "╫"
elif topc in '╫╬' and botc in " ":
ret += "║"
elif topc == '└' and botc == "┌":
ret += "├"
elif topc == '┘' and botc == "┐":
ret += "┤"
else:
ret += botc
return ret
def clbit_index_from_mask(self, mask):
"""
Given a mask, returns a list of classical indexes affected by that mask.
Args:
mask (int): The mask.
Returns:
list: A list of indexes affected by the mask.
"""
clbit_len = self.json_circuit['header']['number_of_clbits']
bit_mask = [bool(mask & (1 << n)) for n in range(clbit_len)]
return [i for i, x in enumerate(bit_mask) if x]
@staticmethod
def normalize_width(layer):
"""
When the elements of the layer have different widths, sets the width to the max elements.
Args:
layer (list): A list of elements.
"""
instructions = [instruction for instruction in filter(lambda x: x is not None, layer)]
longest = max([instruction.length for instruction in instructions])
for instruction in instructions:
instruction.length = longest
def build_layers(self):
"""
Constructs layers.
Returns:
list: List of DrawElements.
Raises:
VisualizationError: When the drawing is, for some reason, impossible to be drawn.
"""
layers = []
layers.append(InputWire.fillup_layer(self.wire_names(with_initial_value=True)))
for instruction in self.json_circuit['instructions']:
layer = Layer(self.qubitorder, self.clbitorder)
connector_label = None
if instruction['name'] == 'measure':
layer.set_qubit(instruction['qubits'][0], MeasureFrom())
layer.set_clbit(instruction['clbits'][0], MeasureTo())
elif instruction['name'] == 'barrier':
# barrier
if not self.plotbarriers:
continue
for qubit in instruction['qubits']:
layer.set_qubit(qubit, Barrier())
elif instruction['name'] == 'swap':
# swap
for qubit in instruction['qubits']:
layer.set_qubit(qubit, Ex())
elif instruction['name'] == 'cswap':
# cswap
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Ex())
layer.set_qubit(instruction['qubits'][2], Ex())
elif instruction['name'] == 'reset':
layer.set_qubit(instruction['qubits'][0], Reset())
elif 'conditional' in instruction:
# conditional
clbits = self.clbit_index_from_mask(int(instruction['conditional']['mask'], 16))
cllabel = TextDrawing.label_for_conditional(instruction)
qulabel = TextDrawing.label_for_box(instruction)
layer.set_cl_multibox(clbits, cllabel, top_connect='┴')
layer.set_qubit(instruction['qubits'][0], BoxOnQuWire(qulabel, bot_connect='┬'))
elif instruction['name'] in ['cx', 'CX', 'ccx']:
# cx/ccx
for qubit in [qubit for qubit in instruction['qubits'][:-1]]:
layer.set_qubit(qubit, Bullet())
layer.set_qubit(instruction['qubits'][-1], BoxOnQuWire('X'))
elif instruction['name'] == 'cy':
# cy
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], BoxOnQuWire('Y'))
elif instruction['name'] == 'cz':
# cz
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Bullet())
elif instruction['name'] == 'ch':
# ch
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], BoxOnQuWire('H'))
elif instruction['name'] == 'cu1':
# cu1
connector_label = TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Bullet())
elif instruction['name'] == 'cu3':
# cu3
params = TextDrawing.params_for_label(instruction)
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1],
BoxOnQuWire("U3(%s)" % ','.join(params)))
elif instruction['name'] == 'crz':
# crz
label = "Rz(%s)" % TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1],
BoxOnQuWire(label))
elif len(instruction['qubits']) == 1 and 'clbits' not in instruction:
# unitary gate
layer.set_qubit(instruction['qubits'][0],
BoxOnQuWire(TextDrawing.label_for_box(instruction)))
elif len(instruction['qubits']) >= 2 and 'clbits' not in instruction:
# multiple qubit gate
layer.set_qu_multibox(instruction['qubits'], TextDrawing.label_for_box(instruction))
else:
raise VisualizationError(
"Text visualizer does not know how to handle this instruction", instruction)
layer.connect_with("│", connector_label)
layers.append(layer.full_layer)
return layers
class Layer:
""" A layer is the "column" of the circuit. """
def __init__(self, qubitorder, clbitorder):
self.qubitorder = qubitorder
self.clbitorder = clbitorder
self.qubit_layer = [None] * len(qubitorder)
self.clbit_layer = [None] * len(clbitorder)
@property
def full_layer(self):
"""
Returns the composition of qubits and classic wires.
Returns:
String: self.qubit_layer + self.clbit_layer
"""
return self.qubit_layer + self.clbit_layer
def set_qubit(self, qubit, element):
"""
Sets the qubit to the element
Args:
qubit (int): Qubit index.
element (DrawElement): Element to set in the qubit
"""
self.qubit_layer[self.qubitorder[qubit]] = element
def set_clbit(self, clbit, element):
"""
Sets the clbit to the element
Args:
clbit (int): Clbit index.
element (DrawElement): Element to set in the clbit
"""
self.clbit_layer[self.clbitorder[clbit]] = element
def _set_multibox(self, wire_type, bits, label, top_connect=None):
# pylint: disable=invalid-name
bits = sorted(bits)
if wire_type == "cl":
set_bit = self.set_clbit
BoxOnWire = BoxOnClWire
BoxOnWireTop = BoxOnClWireTop
BoxOnWireMid = BoxOnClWireMid
BoxOnWireBot = BoxOnClWireBot
elif wire_type == "qu":
set_bit = self.set_qubit
BoxOnWire = BoxOnQuWire
BoxOnWireTop = BoxOnQuWireTop
BoxOnWireMid = BoxOnQuWireMid
BoxOnWireBot = BoxOnQuWireBot
# Checks if qubits are consecutive
if bits != [i for i in range(bits[0], bits[-1] + 1)]:
raise VisualizationError("Text visualizaer does know how to build a gate with multiple"
"bits when they are not adjacent to each other")
if len(bits) == 1:
set_bit(bits[0], BoxOnWire(label, top_connect=top_connect))
else:
set_bit(bits[0], BoxOnWireTop(label, top_connect=top_connect))
for order, bit in enumerate(bits[1:-1], 1):
set_bit(bit, BoxOnWireMid(label, len(bits), order))
set_bit(bits[-1], BoxOnWireBot(label, len(bits)))
def set_cl_multibox(self, bits, label, top_connect='┴'):
"""
Sets the multi clbit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi clbit box.
top_connect (char): The char to connect the box on the top.
"""
self._set_multibox("cl", bits, label, top_connect=top_connect)
def set_qu_multibox(self, bits, label):
"""
Sets the multi qubit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi qubit box.
"""
self._set_multibox("qu", bits, label)
def connect_with(self, wire_char, label=None):
"""
Connects the elements in the layer using wire_char.
Args:
wire_char (char): For example '║' or '│'.
label (string): Some connectors have a label (see cu1, for example).
"""
affected_bits = [bit for bit in self.full_layer if bit is not None]
if len([qbit for qbit in self.qubit_layer if qbit is not None]) == 1:
# Nothing to connect
return
affected_bits[0].connect(wire_char, ['bot'])
for affected_bit in affected_bits[1:-1]:
affected_bit.connect(wire_char, ['bot', 'top'])
affected_bits[-1].connect(wire_char, ['top'], label)
if label:
for affected_bit in affected_bits:
affected_bit.right_fill = len(label) + len(affected_bit.mid)
<|code_end|>
|
removing tools/apps
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
I am going to try the issues first approach :-)
I will work on a pull request to remove the openquantumcompiler and the tools/apps. This is low priority and is not in the main updates for next release so we dont need to track
I will do these as two seperate pull requests.
|
qiskit/tools/apps/__init__.py
<|code_start|><|code_end|>
qiskit/tools/apps/fermion.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A set of functions to map fermionic Hamiltonians to qubit Hamiltonians.
References:
- E. Wigner and P. Jordan., Über das Paulische Äguivalenzverbot,
Z. Phys., 47:631 (1928).
- S. Bravyi and A. Kitaev. Fermionic quantum computation,
Ann. of Phys., 298(1):210–226 (2002).
- A. Tranter, S. Sofia, J. Seeley, M. Kaicher, J. McClean, R. Babbush,
P. Coveney, F. Mintert, F. Wilhelm, and P. Love. The Bravyi–Kitaev
transformation: Properties and applications. Int. Journal of Quantum
Chemistry, 115(19):1431–1441 (2015).
- S. Bravyi, J. M. Gambetta, A. Mezzacapo, and K. Temme,
arXiv e-print arXiv:1701.08213 (2017).
"""
import numpy as np
from qiskit.tools.apps.optimization import Hamiltonian_from_file
from qiskit.tools.qi.pauli import Pauli, sgn_prod
def parity_set(j, n):
"""Computes the parity set of the j-th orbital in n modes
Args:
j (int) : the orbital index
n (int) : the total number of modes
Returns:
numpy.array: Array of mode indexes
"""
indexes = np.array([])
if n % 2 == 0:
if j < n / 2:
indexes = np.append(indexes, parity_set(j, n / 2))
else:
indexes = np.append(indexes, np.append(
parity_set(j - n / 2, n / 2) + n / 2, n / 2 - 1))
return indexes
def update_set(j, n):
"""Computes the update set of the j-th orbital in n modes
Args:
j (int) : the orbital index
n (int) : the total number of modes
Returns:
numpy.array: Array of mode indexes
"""
indexes = np.array([])
if n % 2 == 0:
if j < n / 2:
indexes = np.append(indexes, np.append(
n - 1, update_set(j, n / 2)))
else:
indexes = np.append(indexes, update_set(j - n / 2, n / 2) + n / 2)
return indexes
def flip_set(j, n):
"""Computes the flip set of the j-th orbital in n modes
Args:
j (int) : the orbital index
n (int) : the total number of modes
Returns:
numpy.array: Array of mode indexes
"""
indexes = np.array([])
if n % 2 == 0:
if j < n / 2:
indexes = np.append(indexes, flip_set(j, n / 2))
elif j >= n / 2 and j < n - 1:
indexes = np.append(indexes, flip_set(j - n / 2, n / 2) + n / 2)
else:
indexes = np.append(np.append(indexes, flip_set(
j - n / 2, n / 2) + n / 2), n / 2 - 1)
return indexes
def pauli_term_append(pauli_term, pauli_list, threshold):
"""Appends a Pauli term to a Pauli list
If pauli_term is already present in the list adjusts the coefficient
of the existing pauli. If the new coefficient is less than
threshold the pauli term is deleted from the list
Args:
pauli_term (list): list of [coeff, pauli]
pauli_list (list): a list of pauli_terms
threshold (float): simplification threshold
Returns:
list: an updated pauli_list
"""
found = False
if np.absolute(pauli_term[0]) > threshold:
if pauli_list: # if the list is not empty
for i, _ in enumerate(pauli_list):
# check if the new pauli belongs to the list
if pauli_list[i][1] == pauli_term[1]:
# if found renormalize the coefficient of existent pauli
pauli_list[i][0] += pauli_term[0]
# remove the element if coeff. value is now less than
# threshold
if np.absolute(pauli_list[i][0]) < threshold:
del pauli_list[i]
found = True
break
if found is False: # if not found add the new pauli
pauli_list.append(pauli_term)
else:
# if list is empty add the new pauli
pauli_list.append(pauli_term)
return pauli_list
def fermionic_maps(h1, h2, map_type, out_file=None, threshold=0.000000000001):
"""Creates a list of Paulis with coefficients from fermionic one and
two-body operator.
Args:
h1 (list): second-quantized fermionic one-body operator
h2 (list): second-quantized fermionic two-body operator
map_type (str): "JORDAN_WIGNER", "PARITY", "BINARY_TREE"
out_file (str): name of the optional file to write the Pauli list on
threshold (float): threshold for Pauli simplification
Returns:
list: A list of Paulis with coefficients
"""
# pylint: disable=invalid-name
####################################################################
# ########### DEFINING MAPPED FERMIONIC OPERATORS #############
####################################################################
pauli_list = []
n = len(h1) # number of fermionic modes / qubits
a = []
if map_type == 'JORDAN_WIGNER':
for i in range(n):
xv = np.append(np.append(np.ones(i), 0), np.zeros(n - i - 1))
xw = np.append(np.append(np.zeros(i), 1), np.zeros(n - i - 1))
yv = np.append(np.append(np.ones(i), 1), np.zeros(n - i - 1))
yw = np.append(np.append(np.zeros(i), 1), np.zeros(n - i - 1))
# defines the two mapped Pauli components of a_i and a_i^\dag,
# according to a_i -> (a[i][0]+i*a[i][1])/2,
# a_i^\dag -> (a_[i][0]-i*a[i][1])/2
a.append((Pauli(xv, xw), Pauli(yv, yw)))
if map_type == 'PARITY':
for i in range(n):
if i > 1:
Xv = np.append(np.append(np.zeros(i - 1),
[1, 0]), np.zeros(n - i - 1))
Xw = np.append(np.append(np.zeros(i - 1),
[0, 1]), np.ones(n - i - 1))
Yv = np.append(np.append(np.zeros(i - 1),
[0, 1]), np.zeros(n - i - 1))
Yw = np.append(np.append(np.zeros(i - 1),
[0, 1]), np.ones(n - i - 1))
elif i > 0:
Xv = np.append((1, 0), np.zeros(n - i - 1))
Xw = np.append([0, 1], np.ones(n - i - 1))
Yv = np.append([0, 1], np.zeros(n - i - 1))
Yw = np.append([0, 1], np.ones(n - i - 1))
else:
Xv = np.append(0, np.zeros(n - i - 1))
Xw = np.append(1, np.ones(n - i - 1))
Yv = np.append(1, np.zeros(n - i - 1))
Yw = np.append(1, np.ones(n - i - 1))
# defines the two mapped Pauli components of a_i and a_i^\dag,
# according to a_i -> (a[i][0]+i*a[i][1])/2,
# a_i^\dag -> (a_[i][0]-i*a[i][1])/2
a.append((Pauli(Xv, Xw), Pauli(Yv, Yw)))
if map_type == 'BINARY_TREE':
# FIND BINARY SUPERSET SIZE
bin_sup = 1
while n > np.power(2, bin_sup):
bin_sup += 1
# DEFINE INDEX SETS FOR EVERY FERMIONIC MODE
update_sets = []
update_pauli = []
parity_sets = []
parity_pauli = []
flip_sets = []
remainder_sets = []
remainder_pauli = []
for j in range(n):
update_sets.append(update_set(j, np.power(2, bin_sup)))
update_sets[j] = update_sets[j][update_sets[j] < n]
parity_sets.append(parity_set(j, np.power(2, bin_sup)))
parity_sets[j] = parity_sets[j][parity_sets[j] < n]
flip_sets.append(flip_set(j, np.power(2, bin_sup)))
flip_sets[j] = flip_sets[j][flip_sets[j] < n]
remainder_sets.append(np.setdiff1d(parity_sets[j], flip_sets[j]))
update_pauli.append(Pauli(np.zeros(n), np.zeros(n)))
parity_pauli.append(Pauli(np.zeros(n), np.zeros(n)))
remainder_pauli.append(Pauli(np.zeros(n), np.zeros(n)))
for k in range(n):
if np.in1d(k, update_sets[j]):
update_pauli[j].w[k] = 1
if np.in1d(k, parity_sets[j]):
parity_pauli[j].v[k] = 1
if np.in1d(k, remainder_sets[j]):
remainder_pauli[j].v[k] = 1
x_j = Pauli(np.zeros(n), np.zeros(n))
x_j.w[j] = 1
y_j = Pauli(np.zeros(n), np.zeros(n))
y_j.v[j] = 1
y_j.w[j] = 1
# defines the two mapped Pauli components of a_i and a_i^\dag,
# according to a_i -> (a[i][0]+i*a[i][1])/2, a_i^\dag ->
# (a_[i][0]-i*a[i][1])/2
a.append((update_pauli[j] * x_j * parity_pauli[j],
update_pauli[j] * y_j * remainder_pauli[j]))
####################################################################
# ########### BUILDING THE MAPPED HAMILTONIAN ###############
####################################################################
# ###################### One-body #############################
for i in range(n):
for j in range(n):
if h1[i, j] != 0:
for alpha in range(2):
for beta in range(2):
pauli_prod = sgn_prod(a[i][alpha], a[j][beta])
pauli_term = [h1[i, j] * 1 / 4 * pauli_prod[1] *
np.power(-1j, alpha) *
np.power(1j, beta),
pauli_prod[0]]
pauli_list = pauli_term_append(
pauli_term, pauli_list, threshold)
# ###################### Two-body ############################
for i in range(n):
for j in range(n):
for k in range(n):
for m in range(n):
if h2[i, j, k, m] != 0:
for alpha in range(2):
for beta in range(2):
for gamma in range(2):
for delta in range(2):
# Note: chemists' notation for the
# labeling,
# h2(i,j,k,m) adag_i adag_k a_m a_j
pauli_prod_1 = sgn_prod(
a[i][alpha], a[k][beta])
pauli_prod_2 = sgn_prod(
pauli_prod_1[0], a[m][gamma])
pauli_prod_3 = sgn_prod(
pauli_prod_2[0], a[j][delta])
phase1 = pauli_prod_1[1] *\
pauli_prod_2[1] * pauli_prod_3[1]
phase2 = np.power(-1j, alpha + beta) *\
np.power(1j, gamma + delta)
pauli_term = [
h2[i, j, k, m] * 1 / 16 * phase1 *
phase2, pauli_prod_3[0]]
pauli_list = pauli_term_append(
pauli_term, pauli_list, threshold)
####################################################################
# ################ WRITE TO FILE ##################
####################################################################
if out_file is not None:
out_stream = open(out_file, 'w')
for pauli_term in pauli_list:
out_stream.write(pauli_term[1].to_label() + '\n')
out_stream.write('%.15f' % pauli_term[0].real + '\n')
out_stream.close()
return pauli_list
def two_qubit_reduction(ham_in, m, out_file=None, threshold=0.000000000001):
"""
Eliminates the central and last qubit in a list of Pauli that has
diagonal operators (Z,I) at those positions.abs
It can be used to taper two qubits in parity and binary-tree mapped
fermionic Hamiltonians when the spin orbitals are ordered in two spin
sectors, according to the number of particles in the system.
Args:
ham_in (list): a list of Paulis representing the mapped fermionic
Hamiltonian
m (int): number of fermionic particles
out_file (string or None): name of the optional file to write the Pauli
list on
threshold (float): threshold for Pauli simplification
Returns:
list: A tapered Hamiltonian in the form of list of Paulis with
coefficients
"""
ham_out = []
if m % 4 == 0:
par_1 = 1
par_2 = 1
elif m % 4 == 1:
par_1 = -1
par_2 = -1 # could be also +1, +1/-1 are spin-parity sectors
elif m % 4 == 2:
par_1 = 1
par_2 = -1
else:
par_1 = -1
par_2 = -1 # could be also +1, +1/-1 are spin-parity sectors
if isinstance(ham_in, str):
# conversion from Hamiltonian text file to pauli_list
ham_in = Hamiltonian_from_file(ham_in)
# number of qubits
n = len(ham_in[0][1].v)
for pauli_term in ham_in: # loop over Pauli terms
coeff_out = pauli_term[0]
# Z operator encountered at qubit n/2-1
if pauli_term[1].v[n // 2 -
1] == 1 and pauli_term[1].w[n // 2 - 1] == 0:
coeff_out = par_2 * coeff_out
# Z operator encountered at qubit n-1
if pauli_term[1].v[n - 1] == 1 and pauli_term[1].w[n - 1] == 0:
coeff_out = par_1 * coeff_out
v_temp = []
w_temp = []
for j in range(n):
if j != n // 2 - 1 and j != n - 1:
v_temp.append(pauli_term[1].v[j])
w_temp.append(pauli_term[1].w[j])
pauli_term_out = [coeff_out, Pauli(v_temp, w_temp)]
ham_out = pauli_term_append(pauli_term_out, ham_out, threshold)
####################################################################
# ################ WRITE TO FILE ##################
####################################################################
if out_file is not None:
out_stream = open(out_file, 'w')
for pauli_term in ham_out:
out_stream.write(pauli_term[1].to_label() + '\n')
out_stream.write('%.15f' % pauli_term[0].real + '\n')
out_stream.close()
return ham_out
<|code_end|>
qiskit/tools/apps/optimization.py
<|code_start|># -*- coding: utf-8 -*-
# pylint: disable=unused-import,invalid-name
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
These are tools that are used in the classical optimization and chemistry
tutorials
"""
import copy
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import execute
from qiskit.extensions.standard import h, ry, barrier, cz, x, y, z
from qiskit.tools.qi.pauli import Pauli, label_to_pauli
def SPSA_optimization(obj_fun, initial_theta, SPSA_parameters, max_trials,
save_steps=1, last_avg=1):
"""Minimizes obj_fun(theta) with a simultaneous perturbation stochastic
approximation algorithm.
Args:
obj_fun (callable): the function to minimize
initial_theta (numpy.array): initial value for the variables of
obj_fun
SPSA_parameters (list[float]) : the parameters of the SPSA
optimization routine
max_trials (int) : the maximum number of trial steps ( = function
calls/2) in the optimization
save_steps (int) : stores optimization outcomes each 'save_steps'
trial steps
last_avg (int) : number of last updates of the variables to average
on for the final obj_fun
Returns:
list: a list with the following elements:
cost_final : final optimized value for obj_fun
theta_best : final values of the variables corresponding to
cost_final
cost_plus_save : array of stored values for obj_fun along the
optimization in the + direction
cost_minus_save : array of stored values for obj_fun along the
optimization in the - direction
theta_plus_save : array of stored variables of obj_fun along the
optimization in the + direction
theta_minus_save : array of stored variables of obj_fun along the
optimization in the - direction
list[QuantumCircuit]: the circuits used in optimization
"""
theta_plus_save = []
theta_minus_save = []
cost_plus_save = []
cost_minus_save = []
theta = initial_theta
theta_best = np.zeros(initial_theta.shape)
circuits = []
for k in range(max_trials):
# SPSA Parameters
a_spsa = float(SPSA_parameters[0]) / np.power(k + 1 +
SPSA_parameters[4],
SPSA_parameters[2])
c_spsa = float(SPSA_parameters[1]) / np.power(k + 1,
SPSA_parameters[3])
delta = 2 * np.random.randint(2, size=np.shape(initial_theta)[0]) - 1
# plus and minus directions
theta_plus = theta + c_spsa * delta
theta_minus = theta - c_spsa * delta
# cost fuction for the two directions
cost_plus, circuits_plus = obj_fun(theta_plus)
cost_minus, circuits_minus = obj_fun(theta_minus)
# derivative estimate
g_spsa = (cost_plus - cost_minus) * delta / (2.0 * c_spsa)
# updated theta
theta = theta - a_spsa * g_spsa
# saving
if k % save_steps == 0:
print('objective function at theta+ for step # ' + str(k))
print("%.7f" % cost_plus)
print(('objective function at theta- for step # ' + str(k)))
print("%.7f" % cost_minus)
theta_plus_save.append(theta_plus)
theta_minus_save.append(theta_minus)
cost_plus_save.append(cost_plus)
cost_minus_save.append(cost_minus)
# record circuits ran
circuits += circuits_plus
circuits += circuits_minus
if k >= max_trials - last_avg:
theta_best += theta / last_avg
# final cost update
cost_final, circuits_final = obj_fun(theta_best)
circuits += circuits_final
print('Final objective function is: %.7f' % cost_final)
return [cost_final, theta_best, cost_plus_save, cost_minus_save,
theta_plus_save, theta_minus_save], circuits
def SPSA_calibration(obj_fun, initial_theta, initial_c, target_update, stat):
"""Calibrates and returns the SPSA parameters.
Args:
obj_fun (callable): the function to minimize.
initial_theta (numpy.array): initial value for the variables of
obj_fun.
initial_c (float) : first perturbation of intitial_theta.
target_update (float) : the aimed update of variables on the first
trial step.
stat (int) : number of random gradient directions to average on in
the calibration.
Returns:
numpy.array: An array of 5 SPSA_parameters to use in the optimization.
list[QuantumCircuit]: the circuits used in calibration
"""
SPSA_parameters = np.zeros((5))
SPSA_parameters[1] = initial_c
SPSA_parameters[2] = 0.602
SPSA_parameters[3] = 0.101
SPSA_parameters[4] = 0
delta_obj = 0
circuits = []
for i in range(stat):
if i % 5 == 0:
print('calibration step # ' + str(i) + ' of ' + str(stat))
delta = 2 * np.random.randint(2, size=np.shape(initial_theta)[0]) - 1
obj_plus, circuits_plus = obj_fun(initial_theta + initial_c * delta)
obj_minus, circuits_minus = obj_fun(initial_theta - initial_c * delta)
delta_obj += np.absolute(obj_plus - obj_minus) / stat
circuits += circuits_plus
circuits += circuits_minus
SPSA_parameters[0] = target_update * 2 / delta_obj \
* SPSA_parameters[1] * (SPSA_parameters[4] + 1)
print('calibrated SPSA_parameters[0] is %.7f' % SPSA_parameters[0])
return SPSA_parameters, circuits
def measure_pauli_z(data, pauli):
"""Compute the expectation value of Z.
Z is represented by Z^v where v has length number of qubits and is 1
if Z is present and 0 otherwise.
Args:
data (dict): a dictionary of the form data = {'00000': 10}
pauli (Pauli): a Pauli object
Returns:
float: Expected value of pauli given data
"""
observable = 0
tot = sum(data.values())
for key in data:
value = 1
for j in range(pauli.numberofqubits):
if ((pauli.v[j] == 1 or pauli.w[j] == 1) and
key[pauli.numberofqubits - j - 1] == '1'):
value = -value
observable = observable + value * data[key] / tot
return observable
def Energy_Estimate(data, pauli_list):
"""Compute expectation value of a list of diagonal Paulis with
coefficients given measurement data. If somePaulis are non-diagonal
appropriate post-rotations had to be performed in the collection of data
Args:
data (dict): output of the execution of a quantum program
pauli_list (list): list of [coeff, Pauli]
Returns:
float: The expectation value
"""
energy = 0
if np.ndim(pauli_list) == 1:
energy = pauli_list[0] * measure_pauli_z(data, pauli_list[1])
else:
for p in pauli_list:
energy += p[0] * measure_pauli_z(data, p[1])
return energy
def index_2_bit(state_index, num_bits):
"""Returns bit string corresponding to quantum state index
Args:
state_index (int): basis index of a quantum state
num_bits (int): the number of bits in the returned string
Returns:
numpy.array: A integer array with the binary representation of
state_index
"""
return np.array([int(c) for c
in np.binary_repr(state_index, num_bits)[::-1]],
dtype=np.uint8)
def group_paulis(pauli_list):
"""
Groups a list of (coeff,Pauli) tuples into tensor product basis (tpb) sets
Args:
pauli_list (list): a list of (coeff, Pauli object) tuples.
Returns:
list: A list of tpb sets, each one being a list of (coeff, Pauli
object) tuples.
"""
n = len(pauli_list[0][1].v)
pauli_list_grouped = []
pauli_list_sorted = []
for p_1 in pauli_list:
if p_1 not in pauli_list_sorted:
pauli_list_temp = []
# pauli_list_temp.extend(p_1) # this is going to signal the total
# post-rotations of the set (set master)
pauli_list_temp.append(list(p_1))
pauli_list_temp.append(copy.deepcopy(list(p_1)))
pauli_list_temp[0][0] = 0
for p_2 in pauli_list:
if p_2 not in pauli_list_sorted and p_1[1] != p_2[1]:
j = 0
for i in range(n):
if not ((p_2[1].v[i] == 0 and p_2[1].w[i] == 0) or
(p_1[1].v[i] == 0 and p_1[1].w[i] == 0) or
(p_2[1].v[i] == p_1[1].v[i] and
p_2[1].w[i] == p_1[1].w[i])):
break
else:
# update master
if p_2[1].v[i] == 1 or p_2[1].w[i] == 1:
pauli_list_temp[0][1].v[i] = p_2[1].v[i]
pauli_list_temp[0][1].w[i] = p_2[1].w[i]
j += 1
if j == n:
pauli_list_temp.append(p_2)
pauli_list_sorted.append(p_2)
pauli_list_grouped.append(pauli_list_temp)
return pauli_list_grouped
def print_pauli_list_grouped(pauli_list_grouped):
"""Print a list of Pauli operators which has been grouped into tensor
product basis (tpb) sets.
Args:
pauli_list_grouped (list of lists of (coeff, pauli) tuples): the
list of Pauli operators grouped into tpb sets
"""
for i, _ in enumerate(pauli_list_grouped):
print('Post Rotations of TPB set ' + str(i) + ':')
print(pauli_list_grouped[i][0][1].to_label())
print(str(pauli_list_grouped[i][0][0]) + '\n')
for j in range((len(pauli_list_grouped[i]) - 1)):
print(pauli_list_grouped[i][j + 1][1].to_label())
print("%.7f" % pauli_list_grouped[i][j + 1][0])
print('\n')
def eval_hamiltonian(hamiltonian, input_circuit, shots, device):
"""Calculates the average value of a Hamiltonian on a state created by the
input circuit
Args:
hamiltonian (array or matrix or list): a representation of the
Hamiltonian or observables to be measured. If it is a list, it is
a list of Pauli operators grouped into tpb sets.
input_circuit (QuantumCircuit): input circuit.
shots (int): number of shots considered in the averaging. If 1 the
averaging is exact.
device (str): the backend used to run the simulation.
Returns:
float: Average value of the Hamiltonian or observable.
"""
energy = 0
circuits = []
if 'statevector' in device:
circuits.append(input_circuit)
# Hamiltonian is not a pauli_list grouped into tpb sets
if not isinstance(hamiltonian, list):
result = execute(circuits, device, shots=shots).result()
statevector = result.get_statevector()
# Diagonal Hamiltonian represented by 1D array
if (hamiltonian.shape[0] == 1 or
np.shape(np.shape(np.array(hamiltonian))) == (1,)):
energy = np.sum(hamiltonian * np.absolute(statevector) ** 2)
# Hamiltonian represented by square matrix
elif hamiltonian.shape[0] == hamiltonian.shape[1]:
energy = np.inner(np.conjugate(statevector),
np.dot(hamiltonian, statevector))
# Hamiltonian represented by a Pauli list
else:
# Execute trial circuit with final rotations for each Pauli in
# hamiltonian and store from circuits[1] on
n_qubits = input_circuit.regs['q'].size
q = QuantumRegister(n_qubits, "q")
i = 1
for p in hamiltonian:
circuits.append(copy.deepcopy(input_circuit))
for j in range(n_qubits):
if p[1].v[j] == 0 and p[1].w[j] == 1:
circuits[i].x(q[j])
elif p[1].v[j] == 1 and p[1].w[j] == 0:
circuits[i].z(q[j])
elif p[1].v[j] == 1 and p[1].w[j] == 1:
circuits[i].y(q[j])
i += 1
result = execute(circuits, device, shots=shots).result()
# no Pauli final rotations
statevector_0 = result.get_statevector(circuits[0])
i = 1
for p in hamiltonian:
statevector_i = result.get_statevector(circuits[i])
# inner product with final rotations of (i-1)-th Pauli
energy += p[0] * np.inner(np.conjugate(statevector_0),
statevector_i)
i += 1
# finite number of shots and hamiltonian grouped in tpb sets
else:
n = int(len(hamiltonian[0][0][1].v))
q = QuantumRegister(n, "q")
c = ClassicalRegister(n, "c")
i = 0
for tpb_set in hamiltonian:
circuits.append(copy.deepcopy(input_circuit))
for j in range(n):
# Measure X
if tpb_set[0][1].v[j] == 0 and tpb_set[0][1].w[j] == 1:
circuits[i].h(q[j])
# Measure Y
elif tpb_set[0][1].v[j] == 1 and tpb_set[0][1].w[j] == 1:
circuits[i].s(q[j]).inverse()
circuits[i].h(q[j])
circuits[i].measure(q[j], c[j])
i += 1
result = execute(circuits, device, shots=shots).result()
for j, _ in enumerate(hamiltonian):
for k, _ in enumerate(hamiltonian[j]):
energy += hamiltonian[j][k][0] *\
measure_pauli_z(result.get_counts(circuits[j]),
hamiltonian[j][k][1])
return energy, circuits
def trial_circuit_ry(n, m, theta, entangler_map, meas_string=None,
measurement=True):
"""Creates a QuantumCircuit object ocnsisting in layers of
parametrized single-qubit Y rotations and CZ two-qubit gates
Args:
n (int): number of qubits
m (int): depth of the circuit
theta (array[float]): angles that parametrize the Y rotations
entangler_map (dict): CZ connectivity, e.g. {0: [1], 1: [2]}
meas_string (str): measure a given Pauli operator at the end of the
circuit
measurement (bool): whether to measure the qubit (register "q")
on classical bits (register "c")
Returns:
QuantumCircuit: A QuantumCircuit object
"""
q = QuantumRegister(n, "q")
c = ClassicalRegister(n, "c")
trial_circuit = QuantumCircuit(q, c)
trial_circuit.h(q)
if meas_string is None:
meas_string = [None for x in range(n)]
for i in range(m):
trial_circuit.barrier(q)
for node in entangler_map:
for j in entangler_map[node]:
trial_circuit.cz(q[node], q[j])
for j in range(n):
trial_circuit.ry(theta[n * i + j], q[j])
trial_circuit.barrier(q)
for j in range(n):
if meas_string[j] == 'X':
trial_circuit.h(q[j])
elif meas_string[j] == 'Y':
trial_circuit.s(q[j]).inverse()
trial_circuit.h(q[j])
if measurement:
for j in range(n):
trial_circuit.measure(q[j], c[j])
return trial_circuit
def trial_circuit_ryrz(n, m, theta, entangler_map, meas_string=None,
measurement=True):
"""Creates a QuantumCircuit object consisting in layers of
parametrized single-qubit Y and Z rotations and CZ two-qubit gates
Args:
n (int): number of qubits
m (int): depth of the circuit
theta (array[float]): angles that parametrize the Y and Z rotations
entangler_map (dict): CZ connectivity, e.g. {0: [1], 1: [2]}
meas_string (str): measure a given Pauli operator at the end of the
circuit
measurement (bool): whether to measure the qubit (register "q")
on classical bits (register "c")
Returns:
QuantumCircuit: A QuantumCircuit object
"""
q = QuantumRegister(n, "q")
c = ClassicalRegister(n, "c")
trial_circuit = QuantumCircuit(q, c)
trial_circuit.h(q)
if meas_string is None:
meas_string = [None for x in range(n)]
for i in range(m):
trial_circuit.barrier(q)
for node in entangler_map:
for j in entangler_map[node]:
trial_circuit.cz(q[node], q[j])
for j in range(n):
trial_circuit.ry(theta[n * i * 2 + 2 * j], q[j])
trial_circuit.rz(theta[n * i * 2 + 2 * j + 1], q[j])
trial_circuit.barrier(q)
for j in range(n):
if meas_string[j] == 'X':
trial_circuit.h(q[j])
elif meas_string[j] == 'Y':
trial_circuit.s(q[j]).inverse()
trial_circuit.h(q[j])
if measurement:
for j in range(n):
trial_circuit.measure(q[j], c[j])
return trial_circuit
def make_Hamiltonian(pauli_list):
"""Creates a matrix operator out of a list of Paulis.
Args:
pauli_list (list): list of list [coeff,Pauli]
Returns:
numpy.matrix: A matrix representing pauli_list
"""
Hamiltonian = 0
for p in pauli_list:
Hamiltonian += p[0] * p[1].to_matrix()
return Hamiltonian
def Hamiltonian_from_file(file_name):
"""Creates a matrix operator out of a file with a list
of Paulis.
Args:
file_name (str): a text file containing a list of Paulis and
coefficients.
Returns:
list: A matrix representing pauli_list
"""
with open(file_name, 'r+') as file:
ham_array = file.readlines()
ham_array = [x.strip() for x in ham_array]
pauli_list = []
for i in range(len(ham_array) // 2):
pauli = label_to_pauli(ham_array[2 * i])
Numb = float(ham_array[2 * i + 1])
pauli_list.append([Numb, pauli])
return pauli_list
<|code_end|>
|
qiskit/tools/apps/__init__.py
<|code_start|><|code_end|>
qiskit/tools/apps/fermion.py
<|code_start|><|code_end|>
qiskit/tools/apps/optimization.py
<|code_start|><|code_end|>
|
line_length in text drawer needs a default
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: master
- **Python version**:
- **Operating system**:
### What is the current behavior?
Large circuits are scrambled when using the text-based circuit drawer.

vs
<img width="824" alt="screen shot 2018-11-01 at 6 16 35 pm" src="https://user-images.githubusercontent.com/1249193/47883114-48f33780-de02-11e8-9c5d-9448bf45364c.png">
### Steps to reproduce the problem
Make a large circuit and draw it.
### What is the expected behavior?
### Suggested solutions
Have the text-based circuit wrap according to the size of the terminal or Jupyter notebook cell width, and split like the Matplotlib version does.
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import logging
import os
import subprocess
import tempfile
import warnings
from PIL import Image
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _latex
from qiskit.tools.visualization import _matplotlib
from qiskit.tools.visualization import _text
from qiskit.tools.visualization import _utils
from qiskit.transpiler import transpile_dag
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis=None,
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art string
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing. Defaults to
`"id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,cx,cy,cz,ch,crz,cu1,
cu3,swap,ccx,cswap"` This option is deprecated and will be removed
in the future.
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (str): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if
one is not specified it will use latex and if that fails fallback
to mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect
line_length (int): sets the length of the lines generated by `text`
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: (outputs `latex` and `python`) an in-memory representation of
the circuit diagram.
String: (outputs `text` and `latex_source`). The ascii art or the LaTeX
source code.
Raises:
VisualizationError: when an invalid output method is selected
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defaults to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'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'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
plotbarrier (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True. This is deprecated in the style dict
and will be removed in a future release. Use the `plot_barriers`
kwarg instead.
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
reversebits (bool): When set to True reverse the bit order inside
registers for the output visualization. This is deprecated in the
style dict and will be removed in a future release use the
`reverse_bits` kwarg instead.
"""
if basis is None:
basis = ("id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap")
else:
warnings.warn('The basis kwarg is deprecated and the circuit drawer '
'function will not be able to adjust basis gates itself '
'in a future release', DeprecationWarning)
im = None
if style:
if 'reversebits' in style:
warnings.warn('The reversebits key in style is deprecated and will'
'not work in the future. Instead use the '
'``reverse_bits`` kwarg.', DeprecationWarning)
reverse_bits = style.get('reversebits')
if 'plotbarrier' in style:
warnings.warn('The plotbarrier key in style is deprecated and will'
'not work in the future. Instead use the '
'``plot_barriers`` kwarg.', DeprecationWarning)
plot_barriers = style.get('plotbarrier')
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'"text" by default', DeprecationWarning)
try:
im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError, FileNotFoundError):
im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
else:
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename, basis=basis,
line_length=line_length,
reversebits=reverse_bits,
plotbarriers=plot_barriers)
elif output == 'latex':
im = _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'latex_source':
return _generate_latex_source(circuit, basis=basis,
filename=filename, scale=scale,
style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'mpl':
im = _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
else:
raise _error.VisualizationError(
'Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if im and interactive:
im.show()
return im
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap", line_length=None,
reversebits=False, plotbarriers=True):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
basis (str): Optional. Comma-separated list of gate names
line_length (int): Optional. Sometimes, your console is too small of the drawing. Give me
you maximum line length your console supports.
reversebits (bool): Rearrange the bits in reverse order.
plotbarriers (bool): Draws the barriers when they are there.
Returns:
String: The drawing in a loooong string.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
text = "\n".join(
_text.TextDrawing(json_circuit, reversebits=reversebits, plotbarriers=plotbarriers).lines(
line_length))
if filename:
with open(filename, mode='w', encoding="utf8") as text_file:
text_file.write(text)
return text
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to compile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _utils._trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename, basis=basis,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None, reverse_bits=False,
plot_barriers=True):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
qcimg = _latex.QCircuitImage(json_circuit, scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,'
'ry,rz,cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,'
'cswap',
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = _matplotlib.MatplotlibDrawer(basis=basis, scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
<|code_end|>
qiskit/tools/visualization/_text.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A module for drawing circuits in ascii art or some other text representation
"""
from itertools import groupby
from ._error import VisualizationError
class DrawElement():
""" An element is an instruction or an operation that need to be drawn."""
def __init__(self, label=None):
self._width = None
self.label = self.mid_content = label
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = self.bot_connect = " "
self.top_pad = self._mid_padding = self.bot_pad = " "
self.bot_connector = {}
self.top_connector = {}
self.right_fill = self.left_fill = 0
@property
def top(self):
""" Constructs the top line of the element"""
ret = self.top_format % self.top_connect.center(
self.width - self.left_fill - self.right_fill, self.top_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.top_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.top_pad)
return ret
@property
def mid(self):
""" Constructs the middle line of the element"""
ret = self.mid_format % self.mid_content.center(
self.width - self.left_fill - self.right_fill, self._mid_padding)
if self.right_fill:
ret = ret.ljust(self.right_fill, self._mid_padding)
if self.left_fill:
ret = ret.rjust(self.left_fill, self._mid_padding)
return ret
@property
def bot(self):
""" Constructs the bottom line of the element"""
ret = self.bot_format % self.bot_connect.center(
self.width - self.left_fill - self.right_fill, self.bot_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.bot_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.bot_pad)
return ret
@property
def length(self):
""" Returns the length of the element, including the box around."""
return max(len(self.top), len(self.mid), len(self.bot))
@length.setter
def length(self, value):
""" Adjusts width so the length fits."""
self.width = value - max(
[len(getattr(self, i) % '') for i in ["bot_format", "mid_format", "top_format"]])
@property
def width(self):
""" Returns the width of the label, including padding"""
if self._width:
return self._width
return len(self.mid_content)
@width.setter
def width(self, value):
self._width = value
def connect(self, wire_char, where, label=None):
"""
Connects boxes and elements using wire_char and setting proper connectors.
Args:
wire_char (char): For example '║' or '│'.
where (list["top", "bot"]): Where the connector should be set.
label (string): Some connectors have a label (see cu1, for example).
"""
if 'top' in where and self.top_connector:
self.top_connect = self.top_connector[wire_char]
if 'bot' in where and self.bot_connector:
self.bot_connect = self.bot_connector[wire_char]
if label:
self.top_format = self.top_format[:-1] + (label if label else "")
class BoxOnClWire(DrawElement):
""" Draws a box on the classical wire
top: ┌───┐ ┌───────┐
mid: ╡ A ╞ ╡ A ╞
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "╡ %s ╞"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
class BoxOnQuWire(DrawElement):
""" Draws a box on the quantum wire
top: ┌───┐ ┌───────┐
mid: ┤ A ├ ┤ A ├
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "┤ %s ├"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
self.top_connector = {"│": '┴'}
self.bot_connector = {"│": '┬'}
class MeasureTo(DrawElement):
""" The element on the classic wire to which the measure is performed
top: ║ ║
mid: ═╩═ ═══╩═══
bot:
"""
def __init__(self):
super().__init__()
self.top_connect = " ║ "
self.mid_content = "═╩═"
self.bot_connect = " "
self._mid_padding = "═"
class MeasureFrom(BoxOnQuWire):
""" The element on the quantum wire in which the measure is performed
top: ┌─┐ ┌─┐
mid: ┤M├ ───┤M├───
bot: └╥┘ └╥┘
"""
def __init__(self):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = "┌─┐"
self.mid_content = "┤M├"
self.bot_connect = "└╥┘"
class MultiBox(DrawElement):
"""Elements that is draw on over multiple wires."""
def center_label(self, input_length, order):
"""
In multi-bit elements, the label is centered vertically.
Args:
input_length (int): Rhe amount of wires affected.
order (int): Which middle element is this one?
"""
location_in_the_box = '*'.center(input_length * 2 - 1).index('*') + 1
top_limit = (order - 1) * 2 + 2
bot_limit = top_limit + 2
if top_limit <= location_in_the_box < bot_limit:
if location_in_the_box == top_limit:
self.top_connect = self.label
elif location_in_the_box == top_limit + 1:
self.mid_content = self.label
else:
self.bot_connect = self.label
class BoxOnQuWireTop(MultiBox, BoxOnQuWire):
""" Draws the top part of a box that affects more than one quantum wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnQuWireMid(MultiBox, BoxOnQuWire):
""" Draws the middle part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.center_label(input_length, order)
class BoxOnQuWireBot(MultiBox, BoxOnQuWire):
""" Draws the bottom part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length):
super().__init__(label)
self.top_format = "│ %s │"
self.mid_content = self.bot_connect = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class BoxOnClWireTop(MultiBox, BoxOnClWire):
""" Draws the top part of a conditional box that affects more than one classical wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnClWireMid(MultiBox, BoxOnClWire):
""" Draws the middle part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.mid_content = label
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.top_pad = self.bot_pad = ' '
self.top_connect = self.bot_connect = self.mid_content = ''
self.center_label(input_length, order)
class BoxOnClWireBot(MultiBox, BoxOnClWire):
""" Draws the bottom part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, bot_connect='─'):
super().__init__(label)
self.top_format = "│ %s │"
self.top_pad = " "
self.bot_connect = bot_connect
self.mid_content = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class DirectOnQuWire(DrawElement):
"""
Element to the wire (without the box).
"""
def __init__(self, label=""):
super().__init__(label)
self.top_format = ' %s '
self.mid_format = '─%s─'
self.bot_format = ' %s '
self._mid_padding = '─'
self.top_connector = {"│": '│'}
self.bot_connector = {"│": '│'}
class Barrier(DirectOnQuWire):
""" Draws a barrier.
top: ░ ░
mid: ─░─ ───░───
bot: ░ ░
"""
def __init__(self, label=""):
super().__init__("░")
self.top_connect = "░"
self.bot_connect = "░"
self.top_connector = {}
self.bot_connector = {}
class Ex(DirectOnQuWire):
""" Draws an X (usually with a connector). E.g. the top part of a swap gate
top:
mid: ─X─ ───X───
bot: │ │
"""
def __init__(self, bot_connect=" ", top_connect=" "):
super().__init__("X")
self.bot_connect = bot_connect
self.top_connect = top_connect
class Reset(DirectOnQuWire):
""" Draws a reset gate"""
def __init__(self):
super().__init__("|0>")
class Bullet(DirectOnQuWire):
""" Draws a bullet (usually with a connector). E.g. the top part of a CX gate.
top:
mid: ─■─ ───■───
bot: │ │
"""
def __init__(self, top_connect=" ", bot_connect=" "):
super().__init__('■')
self.top_connect = top_connect
self.bot_connect = bot_connect
class EmptyWire(DrawElement):
""" This element is just the wire, with no instructions nor operations."""
def __init__(self, wire):
super().__init__(wire)
self._mid_padding = wire
@staticmethod
def fillup_layer(layer, first_clbit):
"""
Given a layer, replace the Nones in it with EmptyWire elements.
Args:
layer (list): The layer that contains Nones.
first_clbit (int): The first wire that is classic.
Returns:
list: The new layer, with no Nones.
"""
for nones in [i for i, x in enumerate(layer) if x is None]:
layer[nones] = EmptyWire('═') if nones >= first_clbit else EmptyWire('─')
return layer
class BreakWire(DrawElement):
""" This element is used to break the drawing in several pages."""
def __init__(self, arrow_char):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = arrow_char
self.mid_content = arrow_char
self.bot_connect = arrow_char
@staticmethod
def fillup_layer(layer_length, arrow_char):
"""
Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer.
"""
breakwire_layer = []
for _ in range(layer_length):
breakwire_layer.append(BreakWire(arrow_char))
return breakwire_layer
class InputWire(DrawElement):
""" This element is the label and the initial value of a wire."""
def __init__(self, label):
super().__init__(label)
@staticmethod
def fillup_layer(names): # pylint: disable=arguments-differ
"""
Creates a layer with InputWire elements.
Args:
names (list): List of names for the wires.
Returns:
list: The new layer
"""
longest = max([len(name) for name in names])
inputs_wires = []
for name in names:
inputs_wires.append(InputWire(name.rjust(longest)))
return inputs_wires
class TextDrawing():
""" The text drawing"""
def __init__(self, json_circuit, reversebits=False, plotbarriers=True):
self.json_circuit = json_circuit
self.reversebits = reversebits
self.plotbarriers = plotbarriers
self.qubitorder = self._get_qubitorder()
self.clbitorder = self._get_clbitorder()
def _get_qubit_labels(self):
qubits = []
for qubit in self.json_circuit['header']['qubit_labels']:
qubits.append("%s_%s" % (qubit[0], qubit[1]))
return qubits
def _get_clbit_labels(self):
clbits = []
for creg in self.json_circuit['header']['clbit_labels']:
for clbit in range(creg[1]):
clbits.append("%s_%s" % (creg[0], clbit))
return clbits
def _get_qubitorder(self):
header = self.json_circuit['header']
if not self.reversebits:
return [qub for qub in range(header['number_of_qubits'])]
qreg_dest_order = []
for _, qubits in groupby(header['qubit_labels'], lambda x: x[0]):
qubits = [qubit for qubit in qubits]
qubits.reverse()
for qubit in qubits:
qreg_dest_order.append("%s_%s" % (qubit[0], qubit[1]))
return [qreg_dest_order.index(ind) for ind in self._get_qubit_labels()]
def _get_clbitorder(self):
header = self.json_circuit['header']
if not self.reversebits:
return [clb for clb in range(header['number_of_clbits'])]
creg_dest_order = []
for creg in self.json_circuit['header']['clbit_labels']:
bit_nos = [bit for bit in range(creg[1])]
bit_nos.reverse()
for clbit in bit_nos:
creg_dest_order.append("%s_%s" % (creg[0], clbit))
return [creg_dest_order.index(ind) for ind in self._get_clbit_labels()]
def lines(self, line_length=None):
"""
Generates a list with lines. These lines form the text drawing.
Args:
line_length (int): Optional. When given, breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console.
Returns:
list: A list of lines with the text drawing.
"""
noqubits = self.json_circuit['header']['number_of_qubits']
layers = self.build_layers()
# TODO compress layers
# -| H |----------
# --------| H |---
# should be
# -| H |---
# -| H |---
layer_groups = [[]]
rest_of_the_line = line_length
for layerno, layer in enumerate(layers):
# Replace the Nones with EmptyWire
layers[layerno] = EmptyWire.fillup_layer(layer, noqubits)
TextDrawing.normalize_width(layer)
if line_length is None:
# does not page
layer_groups[-1].append(layer)
continue
# chop the layer to the line_length (pager)
layer_length = layers[layerno][0].length
if layer_length < rest_of_the_line:
layer_groups[-1].append(layer)
rest_of_the_line -= layer_length
else:
layer_groups[-1].append(BreakWire.fillup_layer(len(layer), '»'))
# New group
layer_groups.append([BreakWire.fillup_layer(len(layer), '«')])
rest_of_the_line = line_length - layer_groups[-1][-1][0].length
layer_groups[-1].append(
InputWire.fillup_layer(self.wire_names(with_initial_value=False)))
rest_of_the_line -= layer_groups[-1][-1][0].length
layer_groups[-1].append(layer)
rest_of_the_line -= layer_groups[-1][-1][0].length
lines = []
for layer_group in layer_groups:
wires = [i for i in zip(*layer_group)]
lines += TextDrawing.draw_wires(wires)
return lines
def wire_names(self, with_initial_value=True):
"""
Returns a list of names for each wire.
Args:
with_initial_value (bool): Optional (Default: True). If true, adds the initial value to
the name.
Returns:
List: The list of wire names.
"""
qubit_labels = self._get_qubit_labels()
clbit_labels = self._get_clbit_labels()
if with_initial_value:
qubit_labels = ['%s: |0>' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: 0 ' % clbit for clbit in clbit_labels]
else:
qubit_labels = ['%s: ' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: ' % clbit for clbit in clbit_labels]
qubit_wires = [None] * self.json_circuit['header']['number_of_qubits']
clbit_wires = [None] * self.json_circuit['header']['number_of_clbits']
for order, label in enumerate(qubit_labels):
qubit_wires[self.qubitorder[order]] = label
for order, label in enumerate(clbit_labels):
clbit_wires[self.clbitorder[order]] = label
return qubit_wires + clbit_wires
@staticmethod
def draw_wires(wires):
"""
Given a list of wires, creates a list of lines with the text drawing.
Args:
wires (list): A list of wires with instructions.
Returns:
list: A list of lines with the text drawing.
"""
lines = []
bot_line = None
for wire in wires:
# TOP
top_line = ""
for instruction in wire:
top_line += instruction.top
if bot_line is None:
lines.append(top_line)
else:
lines.append(TextDrawing.merge_lines(lines.pop(), top_line))
# MID
mid_line = ""
for instruction in wire:
mid_line += instruction.mid
lines.append(TextDrawing.merge_lines(lines[-1], mid_line, icod="bot"))
# BOT
bot_line = ""
for instruction in wire:
bot_line += instruction.bot
lines.append(TextDrawing.merge_lines(lines[-1], bot_line, icod="bot"))
return lines
@staticmethod
def label_for_conditional(instruction):
""" Creates the label for a conditional instruction."""
return "%s %s" % ('=', instruction['conditional']['val'])
@staticmethod
def params_for_label(instruction):
"""Get the params and format them to add them to a label. None of there is no param."""
if 'params' in instruction and instruction['params']:
return ['%.5g' % i for i in instruction['params']]
return None
@staticmethod
def label_for_box(instruction):
""" Creates the label for a box."""
label = instruction['name'].capitalize()
params = TextDrawing.params_for_label(instruction)
if params:
label += "(%s)" % ','.join(params)
return label
@staticmethod
def merge_lines(top, bot, icod="top"):
"""
Merges two lines (top and bot) in the way that the overlapping make senses.
Args:
top (str): the top line
bot (str): the bottom line
icod (top or bot): in case of doubt, which line should have priority? Default: "top".
Returns:
str: The merge of both lines.
"""
ret = ""
for topc, botc in zip(top, bot):
if topc == botc:
ret += topc
elif topc in '┼╪' and botc == " ":
ret += "│"
elif topc == " ":
ret += botc
elif topc in '┬╥' and botc in " ║│":
ret += topc
elif topc in '┬│' and botc == "═":
ret += '╪'
elif topc in '┬│' and botc == "─":
ret += '┼'
elif topc in '└┘║│░' and botc == " ":
ret += topc
elif topc in '─═' and botc == " " and icod == "top":
ret += topc
elif topc in '─═' and botc == " " and icod == "bot":
ret += botc
elif topc in "║╥" and botc in "═":
ret += "╬"
elif topc in "║╥" and botc in "─":
ret += "╫"
elif topc in '╫╬' and botc in " ":
ret += "║"
elif topc == '└' and botc == "┌":
ret += "├"
elif topc == '┘' and botc == "┐":
ret += "┤"
else:
ret += botc
return ret
def clbit_index_from_mask(self, mask):
"""
Given a mask, returns a list of classical indexes affected by that mask.
Args:
mask (int): The mask.
Returns:
list: A list of indexes affected by the mask.
"""
clbit_len = self.json_circuit['header']['number_of_clbits']
bit_mask = [bool(mask & (1 << n)) for n in range(clbit_len)]
return [i for i, x in enumerate(bit_mask) if x]
@staticmethod
def normalize_width(layer):
"""
When the elements of the layer have different widths, sets the width to the max elements.
Args:
layer (list): A list of elements.
"""
instructions = [instruction for instruction in filter(lambda x: x is not None, layer)]
longest = max([instruction.length for instruction in instructions])
for instruction in instructions:
instruction.length = longest
def build_layers(self):
"""
Constructs layers.
Returns:
list: List of DrawElements.
Raises:
VisualizationError: When the drawing is, for some reason, impossible to be drawn.
"""
layers = []
layers.append(InputWire.fillup_layer(self.wire_names(with_initial_value=True)))
for instruction in self.json_circuit['instructions']:
layer = Layer(self.qubitorder, self.clbitorder)
connector_label = None
if instruction['name'] == 'measure':
layer.set_qubit(instruction['qubits'][0], MeasureFrom())
layer.set_clbit(instruction['clbits'][0], MeasureTo())
elif instruction['name'] == 'barrier':
# barrier
if not self.plotbarriers:
continue
for qubit in instruction['qubits']:
layer.set_qubit(qubit, Barrier())
elif instruction['name'] == 'swap':
# swap
for qubit in instruction['qubits']:
layer.set_qubit(qubit, Ex())
elif instruction['name'] == 'cswap':
# cswap
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Ex())
layer.set_qubit(instruction['qubits'][2], Ex())
elif instruction['name'] == 'reset':
layer.set_qubit(instruction['qubits'][0], Reset())
elif 'conditional' in instruction:
# conditional
clbits = self.clbit_index_from_mask(int(instruction['conditional']['mask'], 16))
cllabel = TextDrawing.label_for_conditional(instruction)
qulabel = TextDrawing.label_for_box(instruction)
layer.set_cl_multibox(clbits, cllabel, top_connect='┴')
layer.set_qubit(instruction['qubits'][0], BoxOnQuWire(qulabel, bot_connect='┬'))
elif instruction['name'] in ['cx', 'CX', 'ccx']:
# cx/ccx
for qubit in [qubit for qubit in instruction['qubits'][:-1]]:
layer.set_qubit(qubit, Bullet())
layer.set_qubit(instruction['qubits'][-1], BoxOnQuWire('X'))
elif instruction['name'] == 'cy':
# cy
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], BoxOnQuWire('Y'))
elif instruction['name'] == 'cz':
# cz
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Bullet())
elif instruction['name'] == 'ch':
# ch
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], BoxOnQuWire('H'))
elif instruction['name'] == 'cu1':
# cu1
connector_label = TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Bullet())
elif instruction['name'] == 'cu3':
# cu3
params = TextDrawing.params_for_label(instruction)
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1],
BoxOnQuWire("U3(%s)" % ','.join(params)))
elif instruction['name'] == 'crz':
# crz
label = "Rz(%s)" % TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1],
BoxOnQuWire(label))
elif len(instruction['qubits']) == 1 and 'clbits' not in instruction:
# unitary gate
layer.set_qubit(instruction['qubits'][0],
BoxOnQuWire(TextDrawing.label_for_box(instruction)))
elif len(instruction['qubits']) >= 2 and 'clbits' not in instruction:
# multiple qubit gate
layer.set_qu_multibox(instruction['qubits'], TextDrawing.label_for_box(instruction))
else:
raise VisualizationError(
"Text visualizer does not know how to handle this instruction", instruction)
layer.connect_with("│", connector_label)
layers.append(layer.full_layer)
return layers
class Layer:
""" A layer is the "column" of the circuit. """
def __init__(self, qubitorder, clbitorder):
self.qubitorder = qubitorder
self.clbitorder = clbitorder
self.qubit_layer = [None] * len(qubitorder)
self.clbit_layer = [None] * len(clbitorder)
@property
def full_layer(self):
"""
Returns the composition of qubits and classic wires.
Returns:
String: self.qubit_layer + self.clbit_layer
"""
return self.qubit_layer + self.clbit_layer
def set_qubit(self, qubit, element):
"""
Sets the qubit to the element
Args:
qubit (int): Qubit index.
element (DrawElement): Element to set in the qubit
"""
self.qubit_layer[self.qubitorder[qubit]] = element
def set_clbit(self, clbit, element):
"""
Sets the clbit to the element
Args:
clbit (int): Clbit index.
element (DrawElement): Element to set in the clbit
"""
self.clbit_layer[self.clbitorder[clbit]] = element
def _set_multibox(self, wire_type, bits, label, top_connect=None):
# pylint: disable=invalid-name
bits = sorted(bits)
if wire_type == "cl":
set_bit = self.set_clbit
BoxOnWire = BoxOnClWire
BoxOnWireTop = BoxOnClWireTop
BoxOnWireMid = BoxOnClWireMid
BoxOnWireBot = BoxOnClWireBot
elif wire_type == "qu":
set_bit = self.set_qubit
BoxOnWire = BoxOnQuWire
BoxOnWireTop = BoxOnQuWireTop
BoxOnWireMid = BoxOnQuWireMid
BoxOnWireBot = BoxOnQuWireBot
# Checks if qubits are consecutive
if bits != [i for i in range(bits[0], bits[-1] + 1)]:
raise VisualizationError("Text visualizaer does know how to build a gate with multiple"
"bits when they are not adjacent to each other")
if len(bits) == 1:
set_bit(bits[0], BoxOnWire(label, top_connect=top_connect))
else:
set_bit(bits[0], BoxOnWireTop(label, top_connect=top_connect))
for order, bit in enumerate(bits[1:-1], 1):
set_bit(bit, BoxOnWireMid(label, len(bits), order))
set_bit(bits[-1], BoxOnWireBot(label, len(bits)))
def set_cl_multibox(self, bits, label, top_connect='┴'):
"""
Sets the multi clbit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi clbit box.
top_connect (char): The char to connect the box on the top.
"""
self._set_multibox("cl", bits, label, top_connect=top_connect)
def set_qu_multibox(self, bits, label):
"""
Sets the multi qubit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi qubit box.
"""
self._set_multibox("qu", bits, label)
def connect_with(self, wire_char, label=None):
"""
Connects the elements in the layer using wire_char.
Args:
wire_char (char): For example '║' or '│'.
label (string): Some connectors have a label (see cu1, for example).
"""
affected_bits = [bit for bit in self.full_layer if bit is not None]
if len([qbit for qbit in self.qubit_layer if qbit is not None]) == 1:
# Nothing to connect
return
affected_bits[0].connect(wire_char, ['bot'])
for affected_bit in affected_bits[1:-1]:
affected_bit.connect(wire_char, ['bot', 'top'])
affected_bits[-1].connect(wire_char, ['top'], label)
if label:
for affected_bit in affected_bits:
affected_bit.right_fill = len(label) + len(affected_bit.mid)
<|code_end|>
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import logging
import os
import subprocess
import tempfile
import warnings
from PIL import Image
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _latex
from qiskit.tools.visualization import _matplotlib
from qiskit.tools.visualization import _text
from qiskit.tools.visualization import _utils
from qiskit.transpiler import transpile_dag
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis=None,
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art string
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing. Defaults to
`"id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,cx,cy,cz,ch,crz,cu1,
cu3,swap,ccx,cswap"` This option is deprecated and will be removed
in the future.
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (str): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if
one is not specified it will use latex and if that fails fallback
to mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect.
line_length (int): Sets the length of the lines generated by `text`
output type. This useful when the drawing does not fit in the
console. If None (default), it will try to guess the console width
using shutil.get_terminal_size(). If you don't want pagination at
all, set `line_length=-1`.
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: (outputs `latex` and `python`) an in-memory representation of
the circuit diagram.
String: (outputs `text` and `latex_source`). The ascii art or the LaTeX
source code.
Raises:
VisualizationError: when an invalid output method is selected
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defaults to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'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'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
plotbarrier (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True. This is deprecated in the style dict
and will be removed in a future release. Use the `plot_barriers`
kwarg instead.
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
reversebits (bool): When set to True reverse the bit order inside
registers for the output visualization. This is deprecated in the
style dict and will be removed in a future release use the
`reverse_bits` kwarg instead.
"""
if basis is None:
basis = ("id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap")
else:
warnings.warn('The basis kwarg is deprecated and the circuit drawer '
'function will not be able to adjust basis gates itself '
'in a future release', DeprecationWarning)
im = None
if style:
if 'reversebits' in style:
warnings.warn('The reversebits key in style is deprecated and will'
'not work in the future. Instead use the '
'``reverse_bits`` kwarg.', DeprecationWarning)
reverse_bits = style.get('reversebits')
if 'plotbarrier' in style:
warnings.warn('The plotbarrier key in style is deprecated and will'
'not work in the future. Instead use the '
'``plot_barriers`` kwarg.', DeprecationWarning)
plot_barriers = style.get('plotbarrier')
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'"text" by default', DeprecationWarning)
try:
im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError, FileNotFoundError):
im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
else:
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename, basis=basis,
line_length=line_length,
reversebits=reverse_bits,
plotbarriers=plot_barriers)
elif output == 'latex':
im = _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'latex_source':
return _generate_latex_source(circuit, basis=basis,
filename=filename, scale=scale,
style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'mpl':
im = _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
else:
raise _error.VisualizationError(
'Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if im and interactive:
im.show()
return im
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap", line_length=None,
reversebits=False, plotbarriers=True):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
basis (str): Optional. Comma-separated list of gate names
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
reversebits (bool): Rearrange the bits in reverse order.
plotbarriers (bool): Draws the barriers when they are there.
Returns:
String: The drawing in a loooong string.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
text = "\n".join(
_text.TextDrawing(json_circuit, reversebits=reversebits, plotbarriers=plotbarriers).lines(
line_length))
if filename:
with open(filename, mode='w', encoding="utf8") as text_file:
text_file.write(text)
return text
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to compile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _utils._trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename, basis=basis,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None, reverse_bits=False,
plot_barriers=True):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
qcimg = _latex.QCircuitImage(json_circuit, scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,'
'ry,rz,cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,'
'cswap',
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = _matplotlib.MatplotlibDrawer(basis=basis, scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
<|code_end|>
qiskit/tools/visualization/_text.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A module for drawing circuits in ascii art or some other text representation
"""
from itertools import groupby
from shutil import get_terminal_size
from ._error import VisualizationError
class DrawElement():
""" An element is an instruction or an operation that need to be drawn."""
def __init__(self, label=None):
self._width = None
self.label = self.mid_content = label
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = self.bot_connect = " "
self.top_pad = self._mid_padding = self.bot_pad = " "
self.bot_connector = {}
self.top_connector = {}
self.right_fill = self.left_fill = 0
@property
def top(self):
""" Constructs the top line of the element"""
ret = self.top_format % self.top_connect.center(
self.width - self.left_fill - self.right_fill, self.top_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.top_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.top_pad)
return ret
@property
def mid(self):
""" Constructs the middle line of the element"""
ret = self.mid_format % self.mid_content.center(
self.width - self.left_fill - self.right_fill, self._mid_padding)
if self.right_fill:
ret = ret.ljust(self.right_fill, self._mid_padding)
if self.left_fill:
ret = ret.rjust(self.left_fill, self._mid_padding)
return ret
@property
def bot(self):
""" Constructs the bottom line of the element"""
ret = self.bot_format % self.bot_connect.center(
self.width - self.left_fill - self.right_fill, self.bot_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.bot_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.bot_pad)
return ret
@property
def length(self):
""" Returns the length of the element, including the box around."""
return max(len(self.top), len(self.mid), len(self.bot))
@length.setter
def length(self, value):
""" Adjusts width so the length fits."""
self.width = value - max(
[len(getattr(self, i) % '') for i in ["bot_format", "mid_format", "top_format"]])
@property
def width(self):
""" Returns the width of the label, including padding"""
if self._width:
return self._width
return len(self.mid_content)
@width.setter
def width(self, value):
self._width = value
def connect(self, wire_char, where, label=None):
"""
Connects boxes and elements using wire_char and setting proper connectors.
Args:
wire_char (char): For example '║' or '│'.
where (list["top", "bot"]): Where the connector should be set.
label (string): Some connectors have a label (see cu1, for example).
"""
if 'top' in where and self.top_connector:
self.top_connect = self.top_connector[wire_char]
if 'bot' in where and self.bot_connector:
self.bot_connect = self.bot_connector[wire_char]
if label:
self.top_format = self.top_format[:-1] + (label if label else "")
class BoxOnClWire(DrawElement):
""" Draws a box on the classical wire
top: ┌───┐ ┌───────┐
mid: ╡ A ╞ ╡ A ╞
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "╡ %s ╞"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
class BoxOnQuWire(DrawElement):
""" Draws a box on the quantum wire
top: ┌───┐ ┌───────┐
mid: ┤ A ├ ┤ A ├
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "┤ %s ├"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
self.top_connector = {"│": '┴'}
self.bot_connector = {"│": '┬'}
class MeasureTo(DrawElement):
""" The element on the classic wire to which the measure is performed
top: ║ ║
mid: ═╩═ ═══╩═══
bot:
"""
def __init__(self):
super().__init__()
self.top_connect = " ║ "
self.mid_content = "═╩═"
self.bot_connect = " "
self._mid_padding = "═"
class MeasureFrom(BoxOnQuWire):
""" The element on the quantum wire in which the measure is performed
top: ┌─┐ ┌─┐
mid: ┤M├ ───┤M├───
bot: └╥┘ └╥┘
"""
def __init__(self):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = "┌─┐"
self.mid_content = "┤M├"
self.bot_connect = "└╥┘"
class MultiBox(DrawElement):
"""Elements that is draw on over multiple wires."""
def center_label(self, input_length, order):
"""
In multi-bit elements, the label is centered vertically.
Args:
input_length (int): Rhe amount of wires affected.
order (int): Which middle element is this one?
"""
location_in_the_box = '*'.center(input_length * 2 - 1).index('*') + 1
top_limit = (order - 1) * 2 + 2
bot_limit = top_limit + 2
if top_limit <= location_in_the_box < bot_limit:
if location_in_the_box == top_limit:
self.top_connect = self.label
elif location_in_the_box == top_limit + 1:
self.mid_content = self.label
else:
self.bot_connect = self.label
class BoxOnQuWireTop(MultiBox, BoxOnQuWire):
""" Draws the top part of a box that affects more than one quantum wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnQuWireMid(MultiBox, BoxOnQuWire):
""" Draws the middle part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.center_label(input_length, order)
class BoxOnQuWireBot(MultiBox, BoxOnQuWire):
""" Draws the bottom part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length):
super().__init__(label)
self.top_format = "│ %s │"
self.mid_content = self.bot_connect = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class BoxOnClWireTop(MultiBox, BoxOnClWire):
""" Draws the top part of a conditional box that affects more than one classical wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnClWireMid(MultiBox, BoxOnClWire):
""" Draws the middle part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.mid_content = label
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.top_pad = self.bot_pad = ' '
self.top_connect = self.bot_connect = self.mid_content = ''
self.center_label(input_length, order)
class BoxOnClWireBot(MultiBox, BoxOnClWire):
""" Draws the bottom part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, bot_connect='─'):
super().__init__(label)
self.top_format = "│ %s │"
self.top_pad = " "
self.bot_connect = bot_connect
self.mid_content = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class DirectOnQuWire(DrawElement):
"""
Element to the wire (without the box).
"""
def __init__(self, label=""):
super().__init__(label)
self.top_format = ' %s '
self.mid_format = '─%s─'
self.bot_format = ' %s '
self._mid_padding = '─'
self.top_connector = {"│": '│'}
self.bot_connector = {"│": '│'}
class Barrier(DirectOnQuWire):
""" Draws a barrier.
top: ░ ░
mid: ─░─ ───░───
bot: ░ ░
"""
def __init__(self, label=""):
super().__init__("░")
self.top_connect = "░"
self.bot_connect = "░"
self.top_connector = {}
self.bot_connector = {}
class Ex(DirectOnQuWire):
""" Draws an X (usually with a connector). E.g. the top part of a swap gate
top:
mid: ─X─ ───X───
bot: │ │
"""
def __init__(self, bot_connect=" ", top_connect=" "):
super().__init__("X")
self.bot_connect = bot_connect
self.top_connect = top_connect
class Reset(DirectOnQuWire):
""" Draws a reset gate"""
def __init__(self):
super().__init__("|0>")
class Bullet(DirectOnQuWire):
""" Draws a bullet (usually with a connector). E.g. the top part of a CX gate.
top:
mid: ─■─ ───■───
bot: │ │
"""
def __init__(self, top_connect=" ", bot_connect=" "):
super().__init__('■')
self.top_connect = top_connect
self.bot_connect = bot_connect
class EmptyWire(DrawElement):
""" This element is just the wire, with no instructions nor operations."""
def __init__(self, wire):
super().__init__(wire)
self._mid_padding = wire
@staticmethod
def fillup_layer(layer, first_clbit):
"""
Given a layer, replace the Nones in it with EmptyWire elements.
Args:
layer (list): The layer that contains Nones.
first_clbit (int): The first wire that is classic.
Returns:
list: The new layer, with no Nones.
"""
for nones in [i for i, x in enumerate(layer) if x is None]:
layer[nones] = EmptyWire('═') if nones >= first_clbit else EmptyWire('─')
return layer
class BreakWire(DrawElement):
""" This element is used to break the drawing in several pages."""
def __init__(self, arrow_char):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = arrow_char
self.mid_content = arrow_char
self.bot_connect = arrow_char
@staticmethod
def fillup_layer(layer_length, arrow_char):
"""
Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer.
"""
breakwire_layer = []
for _ in range(layer_length):
breakwire_layer.append(BreakWire(arrow_char))
return breakwire_layer
class InputWire(DrawElement):
""" This element is the label and the initial value of a wire."""
def __init__(self, label):
super().__init__(label)
@staticmethod
def fillup_layer(names): # pylint: disable=arguments-differ
"""
Creates a layer with InputWire elements.
Args:
names (list): List of names for the wires.
Returns:
list: The new layer
"""
longest = max([len(name) for name in names])
inputs_wires = []
for name in names:
inputs_wires.append(InputWire(name.rjust(longest)))
return inputs_wires
class TextDrawing():
""" The text drawing"""
def __init__(self, json_circuit, reversebits=False, plotbarriers=True):
self.json_circuit = json_circuit
self.reversebits = reversebits
self.plotbarriers = plotbarriers
self.qubitorder = self._get_qubitorder()
self.clbitorder = self._get_clbitorder()
def _get_qubit_labels(self):
qubits = []
for qubit in self.json_circuit['header']['qubit_labels']:
qubits.append("%s_%s" % (qubit[0], qubit[1]))
return qubits
def _get_clbit_labels(self):
clbits = []
for creg in self.json_circuit['header']['clbit_labels']:
for clbit in range(creg[1]):
clbits.append("%s_%s" % (creg[0], clbit))
return clbits
def _get_qubitorder(self):
header = self.json_circuit['header']
if not self.reversebits:
return [qub for qub in range(header['number_of_qubits'])]
qreg_dest_order = []
for _, qubits in groupby(header['qubit_labels'], lambda x: x[0]):
qubits = [qubit for qubit in qubits]
qubits.reverse()
for qubit in qubits:
qreg_dest_order.append("%s_%s" % (qubit[0], qubit[1]))
return [qreg_dest_order.index(ind) for ind in self._get_qubit_labels()]
def _get_clbitorder(self):
header = self.json_circuit['header']
if not self.reversebits:
return [clb for clb in range(header['number_of_clbits'])]
creg_dest_order = []
for creg in self.json_circuit['header']['clbit_labels']:
bit_nos = [bit for bit in range(creg[1])]
bit_nos.reverse()
for clbit in bit_nos:
creg_dest_order.append("%s_%s" % (creg[0], clbit))
return [creg_dest_order.index(ind) for ind in self._get_clbit_labels()]
def lines(self, line_length=None):
"""
Generates a list with lines. These lines form the text drawing.
Args:
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
Returns:
list: A list of lines with the text drawing.
"""
if line_length is None:
line_length, _ = get_terminal_size()
noqubits = self.json_circuit['header']['number_of_qubits']
layers = self.build_layers()
# TODO compress layers
# -| H |----------
# --------| H |---
# should be
# -| H |---
# -| H |---
layer_groups = [[]]
rest_of_the_line = line_length
for layerno, layer in enumerate(layers):
# Replace the Nones with EmptyWire
layers[layerno] = EmptyWire.fillup_layer(layer, noqubits)
TextDrawing.normalize_width(layer)
if line_length == -1:
# Do not use pagination (aka line breaking. aka ignore line_length).
layer_groups[-1].append(layer)
continue
# chop the layer to the line_length (pager)
layer_length = layers[layerno][0].length
if layer_length < rest_of_the_line:
layer_groups[-1].append(layer)
rest_of_the_line -= layer_length
else:
layer_groups[-1].append(BreakWire.fillup_layer(len(layer), '»'))
# New group
layer_groups.append([BreakWire.fillup_layer(len(layer), '«')])
rest_of_the_line = line_length - layer_groups[-1][-1][0].length
layer_groups[-1].append(
InputWire.fillup_layer(self.wire_names(with_initial_value=False)))
rest_of_the_line -= layer_groups[-1][-1][0].length
layer_groups[-1].append(layer)
rest_of_the_line -= layer_groups[-1][-1][0].length
lines = []
for layer_group in layer_groups:
wires = [i for i in zip(*layer_group)]
lines += TextDrawing.draw_wires(wires)
return lines
def wire_names(self, with_initial_value=True):
"""
Returns a list of names for each wire.
Args:
with_initial_value (bool): Optional (Default: True). If true, adds the initial value to
the name.
Returns:
List: The list of wire names.
"""
qubit_labels = self._get_qubit_labels()
clbit_labels = self._get_clbit_labels()
if with_initial_value:
qubit_labels = ['%s: |0>' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: 0 ' % clbit for clbit in clbit_labels]
else:
qubit_labels = ['%s: ' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: ' % clbit for clbit in clbit_labels]
qubit_wires = [None] * self.json_circuit['header']['number_of_qubits']
clbit_wires = [None] * self.json_circuit['header']['number_of_clbits']
for order, label in enumerate(qubit_labels):
qubit_wires[self.qubitorder[order]] = label
for order, label in enumerate(clbit_labels):
clbit_wires[self.clbitorder[order]] = label
return qubit_wires + clbit_wires
@staticmethod
def draw_wires(wires):
"""
Given a list of wires, creates a list of lines with the text drawing.
Args:
wires (list): A list of wires with instructions.
Returns:
list: A list of lines with the text drawing.
"""
lines = []
bot_line = None
for wire in wires:
# TOP
top_line = ""
for instruction in wire:
top_line += instruction.top
if bot_line is None:
lines.append(top_line)
else:
lines.append(TextDrawing.merge_lines(lines.pop(), top_line))
# MID
mid_line = ""
for instruction in wire:
mid_line += instruction.mid
lines.append(TextDrawing.merge_lines(lines[-1], mid_line, icod="bot"))
# BOT
bot_line = ""
for instruction in wire:
bot_line += instruction.bot
lines.append(TextDrawing.merge_lines(lines[-1], bot_line, icod="bot"))
return lines
@staticmethod
def label_for_conditional(instruction):
""" Creates the label for a conditional instruction."""
return "%s %s" % ('=', instruction['conditional']['val'])
@staticmethod
def params_for_label(instruction):
"""Get the params and format them to add them to a label. None of there is no param."""
if 'params' in instruction and instruction['params']:
return ['%.5g' % i for i in instruction['params']]
return None
@staticmethod
def label_for_box(instruction):
""" Creates the label for a box."""
label = instruction['name'].capitalize()
params = TextDrawing.params_for_label(instruction)
if params:
label += "(%s)" % ','.join(params)
return label
@staticmethod
def merge_lines(top, bot, icod="top"):
"""
Merges two lines (top and bot) in the way that the overlapping make senses.
Args:
top (str): the top line
bot (str): the bottom line
icod (top or bot): in case of doubt, which line should have priority? Default: "top".
Returns:
str: The merge of both lines.
"""
ret = ""
for topc, botc in zip(top, bot):
if topc == botc:
ret += topc
elif topc in '┼╪' and botc == " ":
ret += "│"
elif topc == " ":
ret += botc
elif topc in '┬╥' and botc in " ║│":
ret += topc
elif topc in '┬│' and botc == "═":
ret += '╪'
elif topc in '┬│' and botc == "─":
ret += '┼'
elif topc in '└┘║│░' and botc == " ":
ret += topc
elif topc in '─═' and botc == " " and icod == "top":
ret += topc
elif topc in '─═' and botc == " " and icod == "bot":
ret += botc
elif topc in "║╥" and botc in "═":
ret += "╬"
elif topc in "║╥" and botc in "─":
ret += "╫"
elif topc in '╫╬' and botc in " ":
ret += "║"
elif topc == '└' and botc == "┌":
ret += "├"
elif topc == '┘' and botc == "┐":
ret += "┤"
else:
ret += botc
return ret
def clbit_index_from_mask(self, mask):
"""
Given a mask, returns a list of classical indexes affected by that mask.
Args:
mask (int): The mask.
Returns:
list: A list of indexes affected by the mask.
"""
clbit_len = self.json_circuit['header']['number_of_clbits']
bit_mask = [bool(mask & (1 << n)) for n in range(clbit_len)]
return [i for i, x in enumerate(bit_mask) if x]
@staticmethod
def normalize_width(layer):
"""
When the elements of the layer have different widths, sets the width to the max elements.
Args:
layer (list): A list of elements.
"""
instructions = [instruction for instruction in filter(lambda x: x is not None, layer)]
longest = max([instruction.length for instruction in instructions])
for instruction in instructions:
instruction.length = longest
def build_layers(self):
"""
Constructs layers.
Returns:
list: List of DrawElements.
Raises:
VisualizationError: When the drawing is, for some reason, impossible to be drawn.
"""
layers = []
layers.append(InputWire.fillup_layer(self.wire_names(with_initial_value=True)))
for instruction in self.json_circuit['instructions']:
layer = Layer(self.qubitorder, self.clbitorder)
connector_label = None
if instruction['name'] == 'measure':
layer.set_qubit(instruction['qubits'][0], MeasureFrom())
layer.set_clbit(instruction['clbits'][0], MeasureTo())
elif instruction['name'] == 'barrier':
# barrier
if not self.plotbarriers:
continue
for qubit in instruction['qubits']:
layer.set_qubit(qubit, Barrier())
elif instruction['name'] == 'swap':
# swap
for qubit in instruction['qubits']:
layer.set_qubit(qubit, Ex())
elif instruction['name'] == 'cswap':
# cswap
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Ex())
layer.set_qubit(instruction['qubits'][2], Ex())
elif instruction['name'] == 'reset':
layer.set_qubit(instruction['qubits'][0], Reset())
elif 'conditional' in instruction:
# conditional
clbits = self.clbit_index_from_mask(int(instruction['conditional']['mask'], 16))
cllabel = TextDrawing.label_for_conditional(instruction)
qulabel = TextDrawing.label_for_box(instruction)
layer.set_cl_multibox(clbits, cllabel, top_connect='┴')
layer.set_qubit(instruction['qubits'][0], BoxOnQuWire(qulabel, bot_connect='┬'))
elif instruction['name'] in ['cx', 'CX', 'ccx']:
# cx/ccx
for qubit in [qubit for qubit in instruction['qubits'][:-1]]:
layer.set_qubit(qubit, Bullet())
layer.set_qubit(instruction['qubits'][-1], BoxOnQuWire('X'))
elif instruction['name'] == 'cy':
# cy
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], BoxOnQuWire('Y'))
elif instruction['name'] == 'cz':
# cz
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Bullet())
elif instruction['name'] == 'ch':
# ch
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], BoxOnQuWire('H'))
elif instruction['name'] == 'cu1':
# cu1
connector_label = TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Bullet())
elif instruction['name'] == 'cu3':
# cu3
params = TextDrawing.params_for_label(instruction)
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1],
BoxOnQuWire("U3(%s)" % ','.join(params)))
elif instruction['name'] == 'crz':
# crz
label = "Rz(%s)" % TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1],
BoxOnQuWire(label))
elif len(instruction['qubits']) == 1 and 'clbits' not in instruction:
# unitary gate
layer.set_qubit(instruction['qubits'][0],
BoxOnQuWire(TextDrawing.label_for_box(instruction)))
elif len(instruction['qubits']) >= 2 and 'clbits' not in instruction:
# multiple qubit gate
layer.set_qu_multibox(instruction['qubits'], TextDrawing.label_for_box(instruction))
else:
raise VisualizationError(
"Text visualizer does not know how to handle this instruction", instruction)
layer.connect_with("│", connector_label)
layers.append(layer.full_layer)
return layers
class Layer:
""" A layer is the "column" of the circuit. """
def __init__(self, qubitorder, clbitorder):
self.qubitorder = qubitorder
self.clbitorder = clbitorder
self.qubit_layer = [None] * len(qubitorder)
self.clbit_layer = [None] * len(clbitorder)
@property
def full_layer(self):
"""
Returns the composition of qubits and classic wires.
Returns:
String: self.qubit_layer + self.clbit_layer
"""
return self.qubit_layer + self.clbit_layer
def set_qubit(self, qubit, element):
"""
Sets the qubit to the element
Args:
qubit (int): Qubit index.
element (DrawElement): Element to set in the qubit
"""
self.qubit_layer[self.qubitorder[qubit]] = element
def set_clbit(self, clbit, element):
"""
Sets the clbit to the element
Args:
clbit (int): Clbit index.
element (DrawElement): Element to set in the clbit
"""
self.clbit_layer[self.clbitorder[clbit]] = element
def _set_multibox(self, wire_type, bits, label, top_connect=None):
# pylint: disable=invalid-name
bits = sorted(bits)
if wire_type == "cl":
set_bit = self.set_clbit
BoxOnWire = BoxOnClWire
BoxOnWireTop = BoxOnClWireTop
BoxOnWireMid = BoxOnClWireMid
BoxOnWireBot = BoxOnClWireBot
elif wire_type == "qu":
set_bit = self.set_qubit
BoxOnWire = BoxOnQuWire
BoxOnWireTop = BoxOnQuWireTop
BoxOnWireMid = BoxOnQuWireMid
BoxOnWireBot = BoxOnQuWireBot
# Checks if qubits are consecutive
if bits != [i for i in range(bits[0], bits[-1] + 1)]:
raise VisualizationError("Text visualizaer does know how to build a gate with multiple"
"bits when they are not adjacent to each other")
if len(bits) == 1:
set_bit(bits[0], BoxOnWire(label, top_connect=top_connect))
else:
set_bit(bits[0], BoxOnWireTop(label, top_connect=top_connect))
for order, bit in enumerate(bits[1:-1], 1):
set_bit(bit, BoxOnWireMid(label, len(bits), order))
set_bit(bits[-1], BoxOnWireBot(label, len(bits)))
def set_cl_multibox(self, bits, label, top_connect='┴'):
"""
Sets the multi clbit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi clbit box.
top_connect (char): The char to connect the box on the top.
"""
self._set_multibox("cl", bits, label, top_connect=top_connect)
def set_qu_multibox(self, bits, label):
"""
Sets the multi qubit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi qubit box.
"""
self._set_multibox("qu", bits, label)
def connect_with(self, wire_char, label=None):
"""
Connects the elements in the layer using wire_char.
Args:
wire_char (char): For example '║' or '│'.
label (string): Some connectors have a label (see cu1, for example).
"""
affected_bits = [bit for bit in self.full_layer if bit is not None]
if len([qbit for qbit in self.qubit_layer if qbit is not None]) == 1:
# Nothing to connect
return
affected_bits[0].connect(wire_char, ['bot'])
for affected_bit in affected_bits[1:-1]:
affected_bit.connect(wire_char, ['bot', 'top'])
affected_bits[-1].connect(wire_char, ['top'], label)
if label:
for affected_bit in affected_bits:
affected_bit.right_fill = len(label) + len(affected_bit.mid)
<|code_end|>
|
Job executing problem on RBPi with Raspbian Stretch in _parallel.py
### Informations
- **Qiskit Terra version**: 0.6.1
- **Python version**: 3.6
- **Operating system**: Raspbian Stretch
### What is the current behavior?
When trying to execute job on my Raspberry Pi B I get following error in _parallel.py:
"... _parallel.py", line 109, in parallel_map
if platform.system() != 'Windows' and num_processes > 1 \
TypeError: '>' not supported between instances of 'NoneType' and 'int'
From what I understand initialization of num_processes (or rather it's default value - CPU_COUNT = local_hardware_info()['cpus']) is a problem on selected os.
### Steps to reproduce the problem
Try to execute a job on Raspbian Stretch on RBPi.
### What is the expected behavior?
The job gets executed.
### Suggested solutions
Check if num_processes is an initialized int before comparison.
|
qiskit/_util.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=too-many-ancestors,broad-except
"""Common utilities for QISKit."""
import logging
import re
import sys
import platform
import warnings
import socket
import psutil
logger = logging.getLogger(__name__)
FIRST_CAP_RE = re.compile('(.)([A-Z][a-z]+)')
ALL_CAP_RE = re.compile('([a-z0-9])([A-Z])')
def _check_python_version():
"""Check for Python version 3.5+
"""
if sys.version_info < (3, 5):
raise Exception('QISKit requires Python version 3.5 or greater.')
def _enable_deprecation_warnings():
"""
Force the `DeprecationWarning` warnings to be displayed for the qiskit
module, overriding the system configuration as they are ignored by default
[1] for end-users.
TODO: on Python 3.7, this might not be needed due to PEP-0565 [2].
[1] https://docs.python.org/3/library/warnings.html#default-warning-filters
[2] https://www.python.org/dev/peps/pep-0565/
"""
# pylint: disable=invalid-name
deprecation_filter = ('always', None, DeprecationWarning,
re.compile(r'^qiskit\.*', re.UNICODE), 0)
# Instead of using warnings.simple_filter() directly, the internal
# _add_filter() function is used for being able to match against the
# module.
try:
warnings._add_filter(*deprecation_filter, append=False)
except AttributeError:
# ._add_filter is internal and not available in some Python versions.
pass
def _camel_case_to_snake_case(identifier):
"""Return a `snake_case` string from a `camelCase` string.
Args:
identifier (str): a `camelCase` string.
Returns:
str: a `snake_case` string.
"""
string_1 = FIRST_CAP_RE.sub(r'\1_\2', identifier)
return ALL_CAP_RE.sub(r'\1_\2', string_1).lower()
_check_python_version()
_enable_deprecation_warnings()
def local_hardware_info():
"""Basic hardware information about the local machine.
Gives actual number of CPU's in the machine, even when hyperthreading is
turned on.
Returns:
dict: The hardware information.
"""
results = {'os': platform.system()}
results['memory'] = psutil.virtual_memory().total / (1024**3)
results['cpus'] = psutil.cpu_count(logical=False)
return results
def _has_connection(hostname, port):
"""Checks to see if internet connection exists to host
via specified port
If any exception is raised while trying to open a socket this will return
false.
Args:
hostname (str): Hostname to connect to.
port (int): Port to connect to
Returns:
bool: Has connection or not
"""
try:
host = socket.gethostbyname(hostname)
socket.create_connection((host, port), 2)
return True
except Exception:
return False
<|code_end|>
|
qiskit/_util.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=too-many-ancestors,broad-except
"""Common utilities for QISKit."""
import logging
import re
import sys
import platform
import warnings
import socket
import psutil
logger = logging.getLogger(__name__)
FIRST_CAP_RE = re.compile('(.)([A-Z][a-z]+)')
ALL_CAP_RE = re.compile('([a-z0-9])([A-Z])')
def _check_python_version():
"""Check for Python version 3.5+
"""
if sys.version_info < (3, 5):
raise Exception('QISKit requires Python version 3.5 or greater.')
def _enable_deprecation_warnings():
"""
Force the `DeprecationWarning` warnings to be displayed for the qiskit
module, overriding the system configuration as they are ignored by default
[1] for end-users.
TODO: on Python 3.7, this might not be needed due to PEP-0565 [2].
[1] https://docs.python.org/3/library/warnings.html#default-warning-filters
[2] https://www.python.org/dev/peps/pep-0565/
"""
# pylint: disable=invalid-name
deprecation_filter = ('always', None, DeprecationWarning,
re.compile(r'^qiskit\.*', re.UNICODE), 0)
# Instead of using warnings.simple_filter() directly, the internal
# _add_filter() function is used for being able to match against the
# module.
try:
warnings._add_filter(*deprecation_filter, append=False)
except AttributeError:
# ._add_filter is internal and not available in some Python versions.
pass
def _camel_case_to_snake_case(identifier):
"""Return a `snake_case` string from a `camelCase` string.
Args:
identifier (str): a `camelCase` string.
Returns:
str: a `snake_case` string.
"""
string_1 = FIRST_CAP_RE.sub(r'\1_\2', identifier)
return ALL_CAP_RE.sub(r'\1_\2', string_1).lower()
_check_python_version()
_enable_deprecation_warnings()
def local_hardware_info():
"""Basic hardware information about the local machine.
Gives actual number of CPU's in the machine, even when hyperthreading is
turned on. CPU count defaults to 1 when true count can't be determined.
Returns:
dict: The hardware information.
"""
results = {'os': platform.system()}
results['memory'] = psutil.virtual_memory().total / (1024**3)
results['cpus'] = psutil.cpu_count(logical=False) or 1
return results
def _has_connection(hostname, port):
"""Checks to see if internet connection exists to host
via specified port
If any exception is raised while trying to open a socket this will return
false.
Args:
hostname (str): Hostname to connect to.
port (int): Port to connect to
Returns:
bool: Has connection or not
"""
try:
host = socket.gethostbyname(hostname)
socket.create_connection((host, port), 2)
return True
except Exception:
return False
<|code_end|>
|
test_compiler breaks AerJob status check
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: master
- **Python version**:
- **Operating system**:
### What is the current behavior?
When running the tests, the following does not work when run *after* the `test_compiler` module:
```python
backend = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend)
job_sim.status()
```
```
Traceback (most recent call last):
File "/Users/paul/Desktop/Github_repos/qiskit-core/test/python/test_cpp.py", line 34, in test_aer_status
job_sim.status()
File "/Users/paul/Desktop/Github_repos/qiskit-core/qiskit/backends/aer/aerjob.py", line 37, in _wrapper
return func(self, *args, **kwargs)
File "/Users/paul/Desktop/Github_repos/qiskit-core/qiskit/backends/aer/aerjob.py", line 118, in status
self.__class__.__name__))
qiskit.backends.joberror.JobError: 'Unexpected behavior of AerJob'
```
However, if run *before* that module, it works fine. This is true both when running locally and on Travis. This is blocking #975.
### Steps to reproduce the problem
### What is the expected behavior?
### Suggested solutions
|
qiskit/backends/aer/aerjob.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""This module implements the job class used for AerBackend objects."""
import warnings
from concurrent import futures
import logging
import sys
import functools
from qiskit.backends import BaseJob, JobStatus, JobError
from qiskit.qobj import validate_qobj_against_schema
logger = logging.getLogger(__name__)
def requires_submit(func):
"""
Decorator to ensure that a submit has been performed before
calling the method.
Args:
func (callable): test function to be decorated.
Returns:
callable: the decorated function.
"""
@functools.wraps(func)
def _wrapper(self, *args, **kwargs):
if self._future is None:
raise JobError("Job not submitted yet!. You have to .submit() first!")
return func(self, *args, **kwargs)
return _wrapper
class AerJob(BaseJob):
"""Aer Job class.
Attributes:
_executor (futures.Executor): executor to handle asynchronous jobs
"""
if sys.platform in ['darwin', 'win32']:
_executor = futures.ThreadPoolExecutor()
else:
_executor = futures.ProcessPoolExecutor()
def __init__(self, backend, job_id, fn, qobj):
super().__init__(backend, job_id)
self._fn = fn
self._qobj = qobj
self._future = None
def submit(self):
"""Submit the job to the backend for execution.
Raises:
QobjValidationError: if the JSON serialization of the Qobj passed
during construction does not validate against the Qobj schema.
JobError: if trying to re-submit the job.
"""
if self._future is not None:
raise JobError("We have already submitted the job!")
validate_qobj_against_schema(self._qobj)
self._future = self._executor.submit(self._fn, self._job_id, self._qobj)
@requires_submit
def result(self, timeout=None):
# pylint: disable=arguments-differ
"""Get job result. The behavior is the same as the underlying
concurrent Future objects,
https://docs.python.org/3/library/concurrent.futures.html#future-objects
Args:
timeout (float): number of seconds to wait for results.
Returns:
qiskit.Result: Result object
Raises:
concurrent.futures.TimeoutError: if timeout occurred.
concurrent.futures.CancelledError: if job cancelled before completed.
"""
return self._future.result(timeout=timeout)
@requires_submit
def cancel(self):
return self._future.cancel()
@requires_submit
def status(self):
"""Gets the status of the job by querying the Python's future
Returns:
JobStatus: The current JobStatus
Raises:
JobError: If the future is in unexpected state
concurrent.futures.TimeoutError: if timeout occurred.
"""
# The order is important here
if self._future.running():
_status = JobStatus.RUNNING
elif self._future.cancelled():
_status = JobStatus.CANCELLED
elif self._future.done():
_status = JobStatus.DONE if self._future.exception() is None else JobStatus.ERROR
else:
raise JobError('Unexpected behavior of {0}'.format(
self.__class__.__name__))
return _status
def backend_name(self):
"""
Return the name of the backend used for this job.
.. deprecated:: 0.6+
After 0.6, this function is deprecated. Please use
`job.backend().name()` instead.
"""
warnings.warn('The use of `job.backend_name()` is deprecated, use '
'`job.backend().name()` instead.', DeprecationWarning)
return self._backend.name()
def backend(self):
"""Return the instance of the backend used for this job."""
return self._backend
<|code_end|>
|
qiskit/backends/aer/aerjob.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""This module implements the job class used for AerBackend objects."""
import warnings
from concurrent import futures
import logging
import sys
import functools
from qiskit.backends import BaseJob, JobStatus, JobError
from qiskit.qobj import validate_qobj_against_schema
logger = logging.getLogger(__name__)
def requires_submit(func):
"""
Decorator to ensure that a submit has been performed before
calling the method.
Args:
func (callable): test function to be decorated.
Returns:
callable: the decorated function.
"""
@functools.wraps(func)
def _wrapper(self, *args, **kwargs):
if self._future is None:
raise JobError("Job not submitted yet!. You have to .submit() first!")
return func(self, *args, **kwargs)
return _wrapper
class AerJob(BaseJob):
"""Aer Job class.
Attributes:
_executor (futures.Executor): executor to handle asynchronous jobs
"""
if sys.platform in ['darwin', 'win32']:
_executor = futures.ThreadPoolExecutor()
else:
_executor = futures.ProcessPoolExecutor()
def __init__(self, backend, job_id, fn, qobj):
super().__init__(backend, job_id)
self._fn = fn
self._qobj = qobj
self._future = None
def submit(self):
"""Submit the job to the backend for execution.
Raises:
QobjValidationError: if the JSON serialization of the Qobj passed
during construction does not validate against the Qobj schema.
JobError: if trying to re-submit the job.
"""
if self._future is not None:
raise JobError("We have already submitted the job!")
validate_qobj_against_schema(self._qobj)
self._future = self._executor.submit(self._fn, self._job_id, self._qobj)
@requires_submit
def result(self, timeout=None):
# pylint: disable=arguments-differ
"""Get job result. The behavior is the same as the underlying
concurrent Future objects,
https://docs.python.org/3/library/concurrent.futures.html#future-objects
Args:
timeout (float): number of seconds to wait for results.
Returns:
qiskit.Result: Result object
Raises:
concurrent.futures.TimeoutError: if timeout occurred.
concurrent.futures.CancelledError: if job cancelled before completed.
"""
return self._future.result(timeout=timeout)
@requires_submit
def cancel(self):
return self._future.cancel()
@requires_submit
def status(self):
"""Gets the status of the job by querying the Python's future
Returns:
JobStatus: The current JobStatus
Raises:
JobError: If the future is in unexpected state
concurrent.futures.TimeoutError: if timeout occurred.
"""
# The order is important here
if self._future.running():
_status = JobStatus.RUNNING
elif self._future.cancelled():
_status = JobStatus.CANCELLED
elif self._future.done():
_status = JobStatus.DONE if self._future.exception() is None else JobStatus.ERROR
else:
# Note: There is an undocumented Future state: PENDING, that seems to show up when
# the job is enqueued, waiting for someone to pick it up. We need to deal with this
# state but there's no public API for it, so we are assuming that if the job is not
# in any of the previous states, is PENDING, ergo INITIALIZING for us.
_status = JobStatus.INITIALIZING
return _status
def backend_name(self):
"""
Return the name of the backend used for this job.
.. deprecated:: 0.6+
After 0.6, this function is deprecated. Please use
`job.backend().name()` instead.
"""
warnings.warn('The use of `job.backend_name()` is deprecated, use '
'`job.backend().name()` instead.', DeprecationWarning)
return self._backend.name()
def backend(self):
"""Return the instance of the backend used for this job."""
return self._backend
<|code_end|>
|
Duplicated code in _simulatortools.py and qasm_simulator_py.py
### Informations
- **Qiskit Terra version**: 0.6.1
- **Python version**: 3.6.1
- **Operating system**: Darwin 18.0.0
### The issue
While working on #1153, @charlesastaylor found several functions duplicated in `qiskit/backends/aer/_simulatortools.py` and `qiskit//backends/aer/qasm_simulator_py.py` (such as `index1`). This duplication should be removed.
|
qiskit/backends/aer/_simulatortools.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""Contains functions used by the simulators.
Functions
index2 -- Takes a bitstring k and inserts bits b1 as the i1th bit
and b2 as the i2th bit
"""
from string import ascii_uppercase, ascii_lowercase
import numpy as np
from sympy import Matrix, pi, E, I, cos, sin, N, sympify
from qiskit import QISKitError
def index1(b, i, k):
"""Magic index1 function.
Takes a bitstring k and inserts bit b as the ith bit,
shifting bits >= i over to make room.
"""
retval = k
lowbits = k & ((1 << i) - 1) # get the low i bits
retval >>= i
retval <<= 1
retval |= b
retval <<= i
retval |= lowbits
return retval
def index2(b1, i1, b2, i2, k):
"""Magic index1 function.
Takes a bitstring k and inserts bits b1 as the i1th bit
and b2 as the i2th bit
"""
if i1 == i2:
raise QISKitError("can't insert two bits to same place")
if i1 > i2:
# insert as (i1-1)th bit, will be shifted left 1 by next line
retval = index1(b1, i1-1, k)
retval = index1(b2, i2, retval)
else: # i2>i1
# insert as (i2-1)th bit, will be shifted left 1 by next line
retval = index1(b2, i2-1, k)
retval = index1(b1, i1, retval)
return retval
def single_gate_params(gate, params=None):
"""Apply a single qubit gate to the qubit.
Args:
gate(str): the single qubit gate name
params(list): the operation parameters op['params']
Returns:
tuple: a tuple of U gate parameters (theta, phi, lam)
Raises:
QISKitError: if the gate name is not valid
"""
if gate == 'U' or gate == 'u3':
return params[0], params[1], params[2]
elif gate == 'u2':
return np.pi/2, params[0], params[1]
elif gate == 'u1':
return 0, 0, params[0]
elif gate == 'id':
return 0, 0, 0
raise QISKitError('Gate is not among the valid types: %s' % gate)
def single_gate_matrix(gate, params=None):
"""Get the matrix for a single qubit.
Args:
gate(str): the single qubit gate name
params(list): the operation parameters op['params']
Returns:
array: A numpy array representing the matrix
"""
# Converting sym to floats improves the performance of the simulator 10x.
# This a is a probable a FIXME since it might show bugs in the simulator.
(theta, phi, lam) = map(float, single_gate_params(gate, params))
return np.array([[np.cos(theta/2),
-np.exp(1j*lam)*np.sin(theta/2)],
[np.exp(1j*phi)*np.sin(theta/2),
np.exp(1j*phi+1j*lam)*np.cos(theta/2)]])
def einsum_matmul_index(gate_indices, number_of_qubits):
"""Return the index string for Numpy.eignsum matrix multiplication.
The returned indices are to perform a matrix multiplication A.B where
the matrix A is an M-qubit matrix, matrix B is an N-qubit matrix, and
M <= N, and identity matrices are implied on the subsystems where A has no
support on B.
Args:
gate_indices (list[int]): the indices of the right matrix subsystems
to contract with the left matrix.
number_of_qubits (int): the total number of qubits for the right matrix.
Returns:
str: An indices string for the Numpy.einsum function.
Raises:
QISKitError: if the total number of qubits plus the number of
contracted indices is greater than 26.
"""
# Since we use ASCII alphabet for einsum index labels we are limited
# to 26 total free left (lowercase) and 26 right (uppercase) indexes.
# The rank of the contracted tensor reduces this as we need to use that
# many characters for the contracted indices
if len(gate_indices) + number_of_qubits > 26:
raise QISKitError("Total number of free indexes limited to 26")
# Right indices for the N-qubit input and output tensor
idx_right = ascii_uppercase[:number_of_qubits]
# Left ndicies for N-qubit input tensor
idx_left_in = ascii_lowercase[:number_of_qubits]
# Left indices for the N-qubit output tensor
idx_left_out = list(idx_left_in)
# Left and right indices for the M-qubit multiplying tensor
mat_left = ""
mat_right = ""
# Update left indices for mat and output
for pos, idx in enumerate(reversed(gate_indices)):
mat_left += ascii_lowercase[-1 - pos]
mat_right += idx_left_in[-1 - idx]
idx_left_out[-1 - idx] = ascii_lowercase[-1 - pos]
idx_left_out = "".join(idx_left_out)
# Combine indices into matrix multiplication string format
# for numpy.einsum function
return "{mat_l}{mat_r}, ".format(mat_l=mat_left, mat_r=mat_right) + \
"{tens_lin}{tens_r}->{tens_lout}{tens_r}".format(tens_lin=idx_left_in,
tens_lout=idx_left_out,
tens_r=idx_right)
# Functions used by the sympy simulators.
def regulate(theta):
"""
Return the regulated symbolic representation of `theta`::
* if it has a representation close enough to `pi` transformations,
return that representation (for example, `3.14` -> `sympy.pi`).
* otherwise, return a sympified representation of theta (for example,
`1.23` -> `sympy.Float(1.23)`).
See also `UGateGeneric`.
Args:
theta (float or sympy.Basic): the float value (e.g., 3.14) or the
symbolic value (e.g., pi)
Returns:
sympy.Basic: the sympy-regulated representation of `theta`
"""
error_margin = 0.01
targets = [pi, pi/2, pi * 2, pi / 4]
for t in targets:
if abs(N(theta - t)) < error_margin:
return t
return sympify(theta)
def compute_ugate_matrix(parameters):
"""Compute the matrix associated with a parameterized U gate.
Args:
parameters (list[float]): parameters carried by the U gate
Returns:
sympy.Matrix: the matrix associated with a parameterized U gate
"""
theta = regulate(parameters[0])
phi = regulate(parameters[1])
lamb = regulate(parameters[2])
left_up = cos(theta/2)
right_up = (-E**(I*lamb)) * sin(theta/2)
left_down = (E**(I*phi)) * sin(theta/2)
right_down = (E**(I*(phi + lamb))) * cos(theta/2)
return Matrix([[left_up, right_up], [left_down, right_down]])
<|code_end|>
qiskit/backends/aer/qasm_simulator_py.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""Contains a (slow) python simulator.
It simulates a qasm quantum circuit that has been compiled to run on the
simulator. It is exponential in the number of qubits.
We advise using the c++ simulator or online simulator for larger size systems.
The input is a qobj dictionary
and the output is a Results object
results['data']["counts"] where this is dict {"0000" : 454}
The simulator is run using
.. code-block:: python
QasmSimulatorPy(compiled_circuit,shots,seed).run().
.. code-block:: guess
compiled_circuit =
{
"header": {
"number_of_qubits": 2, // int
"number_of_clbits": 2, // int
"qubit_labels": [["q", 0], ["v", 0]], // list[list[string, int]]
"clbit_labels": [["c", 2]], // list[list[string, int]]
}
"operations": // list[map]
[
{
"name": , // required -- string
"params": , // optional -- list[double]
"qubits": , // required -- list[int]
"clbits": , // optional -- list[int]
"conditional": // optional -- map
{
"type": , // string
"mask": , // hex string
"val": , // bhex string
}
},
]
}
.. code-block:: python
result =
{
'data': {
'statevector': array([ 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j]),
'classical_state': 0
'counts': {'0000': 1}
'snapshots': { '0': {'statevector': array([1.+0.j, 0.+0.j,
0.+0.j, 0.+0.j])}}
}
}
'time_taken': 0.002
'status': 'DONE'
}
"""
import random
import uuid
import time
import logging
from collections import Counter
import numpy as np
from qiskit.result._utils import copy_qasm_from_qobj_into_result, result_from_old_style_dict
from qiskit.backends import BaseBackend
from qiskit.backends.aer.aerjob import AerJob
from ._simulatorerror import SimulatorError
from ._simulatortools import single_gate_matrix
logger = logging.getLogger(__name__)
class QasmSimulatorPy(BaseBackend):
"""Python implementation of a qasm simulator."""
DEFAULT_CONFIGURATION = {
'name': 'qasm_simulator_py',
'url': 'https://github.com/QISKit/qiskit-terra',
'simulator': True,
'local': True,
'description': 'A python simulator for qasm files',
'coupling_map': 'all-to-all',
'basis_gates': 'u1,u2,u3,cx,id,snapshot'
}
def __init__(self, configuration=None, provider=None):
super().__init__(configuration=configuration or self.DEFAULT_CONFIGURATION.copy(),
provider=provider)
self._local_random = random.Random()
# Define attributes in __init__.
self._classical_state = 0
self._statevector = 0
self._snapshots = {}
self._number_of_cbits = 0
self._number_of_qubits = 0
self._shots = 0
self._qobj_config = None
@staticmethod
def _index1(b, i, k):
"""Magic index1 function.
Takes a bitstring k and inserts bit b as the ith bit,
shifting bits >= i over to make room.
"""
retval = k
lowbits = k & ((1 << i) - 1) # get the low i bits
retval >>= i
retval <<= 1
retval |= b
retval <<= i
retval |= lowbits
return retval
@staticmethod
def _index2(b1, i1, b2, i2, k):
"""Magic index1 function.
Takes a bitstring k and inserts bits b1 as the i1th bit
and b2 as the i2th bit
"""
if i1 == i2:
raise SimulatorError("can't insert two bits to same place")
if i1 > i2:
# insert as (i1-1)th bit, will be shifted left 1 by next line
retval = QasmSimulatorPy._index1(b1, i1-1, k)
retval = QasmSimulatorPy._index1(b2, i2, retval)
else: # i2>i1
# insert as (i2-1)th bit, will be shifted left 1 by next line
retval = QasmSimulatorPy._index1(b2, i2-1, k)
retval = QasmSimulatorPy._index1(b1, i1, retval)
return retval
def _add_qasm_single(self, gate, qubit):
"""Apply an arbitrary 1-qubit operator to a qubit.
Gate is the single qubit applied.
qubit is the qubit the gate is applied to.
"""
psi = self._statevector
bit = 1 << qubit
for k1 in range(0, 1 << self._number_of_qubits, 1 << (qubit+1)):
for k2 in range(0, 1 << qubit, 1):
k = k1 | k2
cache0 = psi[k]
cache1 = psi[k | bit]
psi[k] = gate[0, 0] * cache0 + gate[0, 1] * cache1
psi[k | bit] = gate[1, 0] * cache0 + gate[1, 1] * cache1
def _add_qasm_cx(self, q0, q1):
"""Optimized ideal CX on two qubits.
q0 is the first qubit (control) counts from 0.
q1 is the second qubit (target).
"""
psi = self._statevector
for k in range(0, 1 << (self._number_of_qubits - 2)):
# first bit is control, second is target
ind1 = self._index2(1, q0, 0, q1, k)
# swap target if control is 1
ind3 = self._index2(1, q0, 1, q1, k)
cache0 = psi[ind1]
cache1 = psi[ind3]
psi[ind3] = cache0
psi[ind1] = cache1
def _add_qasm_decision(self, qubit):
"""Apply the decision of measurement/reset qubit gate.
qubit is the qubit that is measured/reset
"""
probability_zero = 0
random_number = self._local_random.random()
for ii in range(1 << self._number_of_qubits):
if ii & (1 << qubit) == 0:
probability_zero += np.abs(self._statevector[ii])**2
if random_number <= probability_zero:
outcome = '0'
norm = np.sqrt(probability_zero)
else:
outcome = '1'
norm = np.sqrt(1-probability_zero)
return (outcome, norm)
def _add_qasm_measure(self, qubit, cbit):
"""Apply the measurement qubit gate.
qubit is the qubit measured.
cbit is the classical bit the measurement is assigned to.
"""
outcome, norm = self._add_qasm_decision(qubit)
for ii in range(1 << self._number_of_qubits):
# update quantum state
if (ii >> qubit) & 1 == int(outcome):
self._statevector[ii] = self._statevector[ii]/norm
else:
self._statevector[ii] = 0
# update classical state
bit = 1 << cbit
self._classical_state = (self._classical_state & (~bit)) | (int(outcome) << cbit)
def _add_qasm_reset(self, qubit):
"""Apply the reset to the qubit.
This is done by doing a measruement and if 0 do nothing and
if 1 flip the qubit.
qubit is the qubit that is reset.
"""
# TODO: slow, refactor later
outcome, norm = self._add_qasm_decision(qubit)
temp = np.copy(self._statevector)
self._statevector.fill(0.0)
# measurement
for ii in range(1 << self._number_of_qubits):
if (ii >> qubit) & 1 == int(outcome):
temp[ii] = temp[ii]/norm
else:
temp[ii] = 0
# reset
if outcome == '1':
for ii in range(1 << self._number_of_qubits):
iip = (~ (1 << qubit)) & ii # bit number qubit set to zero
self._statevector[iip] += temp[ii]
else:
self._statevector = temp
def _add_qasm_snapshot(self, slot):
"""Snapshot instruction to record simulator's internal representation
of quantum statevector.
slot is an integer indicating a snapshot slot number.
"""
self._snapshots.setdefault(str(int(slot)),
{}).setdefault("statevector",
[]).append(np.copy(self._statevector))
def run(self, qobj):
"""Run qobj asynchronously.
Args:
qobj (dict): job description
Returns:
AerJob: derived from BaseJob
"""
job_id = str(uuid.uuid4())
aer_job = AerJob(self, job_id, self._run_job, qobj)
aer_job.submit()
return aer_job
def _run_job(self, job_id, qobj):
"""Run circuits in qobj"""
self._validate(qobj)
result_list = []
self._shots = qobj.config.shots
self._qobj_config = qobj.config
start = time.time()
for circuit in qobj.experiments:
result_list.append(self.run_circuit(circuit))
end = time.time()
result = {'backend': self._configuration['name'],
'id': qobj.qobj_id,
'job_id': job_id,
'result': result_list,
'status': 'COMPLETED',
'success': True,
'time_taken': (end - start)}
copy_qasm_from_qobj_into_result(qobj, result)
return result_from_old_style_dict(
result, [circuit.header.name for circuit in qobj.experiments])
def run_circuit(self, circuit):
"""Run a circuit and return a single Result.
Args:
circuit (QobjExperiment): experiment from qobj experiments list
Returns:
dict: A dictionary of results which looks something like::
{
"data":
{ #### DATA CAN BE A DIFFERENT DICTIONARY FOR EACH BACKEND ####
"counts": {'00000': XXXX, '00001': XXXXX},
"time" : xx.xxxxxxxx
},
"status": --status (string)--
}
Raises:
SimulatorError: if an error occurred.
"""
self._number_of_qubits = circuit.header.number_of_qubits
self._number_of_cbits = circuit.header.number_of_clbits
self._statevector = 0
self._classical_state = 0
self._snapshots = {}
cl_reg_index = [] # starting bit index of classical register
cl_reg_nbits = [] # number of bits in classical register
cbit_index = 0
for cl_reg in circuit.header.clbit_labels:
cl_reg_nbits.append(cl_reg[1])
cl_reg_index.append(cbit_index)
cbit_index += cl_reg[1]
# Get the seed looking in circuit, qobj, and then random.
seed = getattr(circuit.config, 'seed',
getattr(self._qobj_config, 'seed',
random.getrandbits(32)))
self._local_random.seed(seed)
outcomes = []
start = time.time()
for _ in range(self._shots):
self._statevector = np.zeros(1 << self._number_of_qubits,
dtype=complex)
self._statevector[0] = 1
self._classical_state = 0
for operation in circuit.instructions:
if getattr(operation, 'conditional', None):
mask = int(operation.conditional.mask, 16)
if mask > 0:
value = self._classical_state & mask
while (mask & 0x1) == 0:
mask >>= 1
value >>= 1
if value != int(operation.conditional.val, 16):
continue
# Check if single gate
if operation.name in ('U', 'u1', 'u2', 'u3'):
params = getattr(operation, 'params', None)
qubit = operation.qubits[0]
gate = single_gate_matrix(operation.name, params)
self._add_qasm_single(gate, qubit)
# Check if CX gate
elif operation.name in ('id', 'u0'):
pass
elif operation.name in ('CX', 'cx'):
qubit0 = operation.qubits[0]
qubit1 = operation.qubits[1]
self._add_qasm_cx(qubit0, qubit1)
# Check if measure
elif operation.name == 'measure':
qubit = operation.qubits[0]
cbit = operation.clbits[0]
self._add_qasm_measure(qubit, cbit)
# Check if reset
elif operation.name == 'reset':
qubit = operation.qubits[0]
self._add_qasm_reset(qubit)
# Check if barrier
elif operation.name == 'barrier':
pass
# Check if snapshot command
elif operation.name == 'snapshot':
params = operation.params
self._add_qasm_snapshot(params[0])
else:
backend = self._configuration['name']
err_msg = '{0} encountered unrecognized operation "{1}"'
raise SimulatorError(err_msg.format(backend,
operation.name))
# Turn classical_state (int) into bit string
outcomes.append(bin(self._classical_state)[2:].zfill(
self._number_of_cbits))
# Return the results
counts = dict(Counter(outcomes))
data = {
'counts': self._format_result(counts, cl_reg_index, cl_reg_nbits),
'snapshots': self._snapshots
}
end = time.time()
return {'name': circuit.header.name,
'seed': seed,
'shots': self._shots,
'data': data,
'status': 'DONE',
'success': True,
'time_taken': (end-start)}
def _validate(self, qobj):
for experiment in qobj.experiments:
if 'measure' not in [op.name for
op in experiment.instructions]:
logger.warning("no measurements in circuit '%s', "
"classical register will remain all zeros.",
experiment.header.name)
def _format_result(self, counts, cl_reg_index, cl_reg_nbits):
"""Format the result bit string.
This formats the result bit strings such that spaces are inserted
at register divisions.
Args:
counts (dict): dictionary of counts e.g. {'1111': 1000, '0000':5}
cl_reg_index (list): starting bit index of classical register
cl_reg_nbits (list): total amount of bits in classical register
Returns:
dict: spaces inserted into dictionary keys at register boundaries.
"""
fcounts = {}
for key, value in counts.items():
if cl_reg_nbits:
new_key = [key[-cl_reg_nbits[0]:]]
for index, nbits in zip(cl_reg_index[1:],
cl_reg_nbits[1:]):
new_key.insert(0, key[-(index+nbits):-index])
fcounts[' '.join(new_key)] = value
return fcounts
<|code_end|>
|
qiskit/backends/aer/_simulatortools.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""Contains functions used by the simulators.
Functions
index2 -- Takes a bitstring k and inserts bits b1 as the i1th bit
and b2 as the i2th bit
"""
from string import ascii_uppercase, ascii_lowercase
import numpy as np
from qiskit import QISKitError
def index1(b, i, k):
"""Magic index1 function.
Takes a bitstring k and inserts bit b as the ith bit,
shifting bits >= i over to make room.
"""
retval = k
lowbits = k & ((1 << i) - 1) # get the low i bits
retval >>= i
retval <<= 1
retval |= b
retval <<= i
retval |= lowbits
return retval
def index2(b1, i1, b2, i2, k):
"""Magic index2 function.
Takes a bitstring k and inserts bits b1 as the i1th bit
and b2 as the i2th bit
"""
if i1 == i2:
raise QISKitError("can't insert two bits to same place")
if i1 > i2:
# insert as (i1-1)th bit, will be shifted left 1 by next line
retval = index1(b1, i1-1, k)
retval = index1(b2, i2, retval)
else: # i2>i1
# insert as (i2-1)th bit, will be shifted left 1 by next line
retval = index1(b2, i2-1, k)
retval = index1(b1, i1, retval)
return retval
def single_gate_params(gate, params=None):
"""Apply a single qubit gate to the qubit.
Args:
gate(str): the single qubit gate name
params(list): the operation parameters op['params']
Returns:
tuple: a tuple of U gate parameters (theta, phi, lam)
Raises:
QISKitError: if the gate name is not valid
"""
if gate == 'U' or gate == 'u3':
return params[0], params[1], params[2]
elif gate == 'u2':
return np.pi/2, params[0], params[1]
elif gate == 'u1':
return 0, 0, params[0]
elif gate == 'id':
return 0, 0, 0
raise QISKitError('Gate is not among the valid types: %s' % gate)
def single_gate_matrix(gate, params=None):
"""Get the matrix for a single qubit.
Args:
gate(str): the single qubit gate name
params(list): the operation parameters op['params']
Returns:
array: A numpy array representing the matrix
"""
# Converting sym to floats improves the performance of the simulator 10x.
# This a is a probable a FIXME since it might show bugs in the simulator.
(theta, phi, lam) = map(float, single_gate_params(gate, params))
return np.array([[np.cos(theta/2),
-np.exp(1j*lam)*np.sin(theta/2)],
[np.exp(1j*phi)*np.sin(theta/2),
np.exp(1j*phi+1j*lam)*np.cos(theta/2)]])
def einsum_matmul_index(gate_indices, number_of_qubits):
"""Return the index string for Numpy.eignsum matrix multiplication.
The returned indices are to perform a matrix multiplication A.B where
the matrix A is an M-qubit matrix, matrix B is an N-qubit matrix, and
M <= N, and identity matrices are implied on the subsystems where A has no
support on B.
Args:
gate_indices (list[int]): the indices of the right matrix subsystems
to contract with the left matrix.
number_of_qubits (int): the total number of qubits for the right matrix.
Returns:
str: An indices string for the Numpy.einsum function.
Raises:
QISKitError: if the total number of qubits plus the number of
contracted indices is greater than 26.
"""
# Since we use ASCII alphabet for einsum index labels we are limited
# to 26 total free left (lowercase) and 26 right (uppercase) indexes.
# The rank of the contracted tensor reduces this as we need to use that
# many characters for the contracted indices
if len(gate_indices) + number_of_qubits > 26:
raise QISKitError("Total number of free indexes limited to 26")
# Right indices for the N-qubit input and output tensor
idx_right = ascii_uppercase[:number_of_qubits]
# Left ndicies for N-qubit input tensor
idx_left_in = ascii_lowercase[:number_of_qubits]
# Left indices for the N-qubit output tensor
idx_left_out = list(idx_left_in)
# Left and right indices for the M-qubit multiplying tensor
mat_left = ""
mat_right = ""
# Update left indices for mat and output
for pos, idx in enumerate(reversed(gate_indices)):
mat_left += ascii_lowercase[-1 - pos]
mat_right += idx_left_in[-1 - idx]
idx_left_out[-1 - idx] = ascii_lowercase[-1 - pos]
idx_left_out = "".join(idx_left_out)
# Combine indices into matrix multiplication string format
# for numpy.einsum function
return "{mat_l}{mat_r}, ".format(mat_l=mat_left, mat_r=mat_right) + \
"{tens_lin}{tens_r}->{tens_lout}{tens_r}".format(tens_lin=idx_left_in,
tens_lout=idx_left_out,
tens_r=idx_right)
<|code_end|>
qiskit/backends/aer/qasm_simulator_py.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""Contains a (slow) python simulator.
It simulates a qasm quantum circuit that has been compiled to run on the
simulator. It is exponential in the number of qubits.
We advise using the c++ simulator or online simulator for larger size systems.
The input is a qobj dictionary
and the output is a Results object
results['data']["counts"] where this is dict {"0000" : 454}
The simulator is run using
.. code-block:: python
QasmSimulatorPy(compiled_circuit,shots,seed).run().
.. code-block:: guess
compiled_circuit =
{
"header": {
"number_of_qubits": 2, // int
"number_of_clbits": 2, // int
"qubit_labels": [["q", 0], ["v", 0]], // list[list[string, int]]
"clbit_labels": [["c", 2]], // list[list[string, int]]
}
"operations": // list[map]
[
{
"name": , // required -- string
"params": , // optional -- list[double]
"qubits": , // required -- list[int]
"clbits": , // optional -- list[int]
"conditional": // optional -- map
{
"type": , // string
"mask": , // hex string
"val": , // bhex string
}
},
]
}
.. code-block:: python
result =
{
'data': {
'statevector': array([ 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j]),
'classical_state': 0
'counts': {'0000': 1}
'snapshots': { '0': {'statevector': array([1.+0.j, 0.+0.j,
0.+0.j, 0.+0.j])}}
}
}
'time_taken': 0.002
'status': 'DONE'
}
"""
import random
import uuid
import time
import logging
from collections import Counter
import numpy as np
from qiskit.result._utils import copy_qasm_from_qobj_into_result, result_from_old_style_dict
from qiskit.backends import BaseBackend
from qiskit.backends.aer.aerjob import AerJob
from ._simulatorerror import SimulatorError
from ._simulatortools import index2, single_gate_matrix
logger = logging.getLogger(__name__)
class QasmSimulatorPy(BaseBackend):
"""Python implementation of a qasm simulator."""
DEFAULT_CONFIGURATION = {
'name': 'qasm_simulator_py',
'url': 'https://github.com/QISKit/qiskit-terra',
'simulator': True,
'local': True,
'description': 'A python simulator for qasm files',
'coupling_map': 'all-to-all',
'basis_gates': 'u1,u2,u3,cx,id,snapshot'
}
def __init__(self, configuration=None, provider=None):
super().__init__(configuration=configuration or self.DEFAULT_CONFIGURATION.copy(),
provider=provider)
self._local_random = random.Random()
# Define attributes in __init__.
self._classical_state = 0
self._statevector = 0
self._snapshots = {}
self._number_of_cbits = 0
self._number_of_qubits = 0
self._shots = 0
self._qobj_config = None
def _add_qasm_single(self, gate, qubit):
"""Apply an arbitrary 1-qubit operator to a qubit.
Gate is the single qubit applied.
qubit is the qubit the gate is applied to.
"""
psi = self._statevector
bit = 1 << qubit
for k1 in range(0, 1 << self._number_of_qubits, 1 << (qubit+1)):
for k2 in range(0, 1 << qubit, 1):
k = k1 | k2
cache0 = psi[k]
cache1 = psi[k | bit]
psi[k] = gate[0, 0] * cache0 + gate[0, 1] * cache1
psi[k | bit] = gate[1, 0] * cache0 + gate[1, 1] * cache1
def _add_qasm_cx(self, q0, q1):
"""Optimized ideal CX on two qubits.
q0 is the first qubit (control) counts from 0.
q1 is the second qubit (target).
"""
psi = self._statevector
for k in range(0, 1 << (self._number_of_qubits - 2)):
# first bit is control, second is target
ind1 = index2(1, q0, 0, q1, k)
# swap target if control is 1
ind3 = index2(1, q0, 1, q1, k)
cache0 = psi[ind1]
cache1 = psi[ind3]
psi[ind3] = cache0
psi[ind1] = cache1
def _add_qasm_decision(self, qubit):
"""Apply the decision of measurement/reset qubit gate.
qubit is the qubit that is measured/reset
"""
probability_zero = 0
random_number = self._local_random.random()
for ii in range(1 << self._number_of_qubits):
if ii & (1 << qubit) == 0:
probability_zero += np.abs(self._statevector[ii])**2
if random_number <= probability_zero:
outcome = '0'
norm = np.sqrt(probability_zero)
else:
outcome = '1'
norm = np.sqrt(1-probability_zero)
return (outcome, norm)
def _add_qasm_measure(self, qubit, cbit):
"""Apply the measurement qubit gate.
qubit is the qubit measured.
cbit is the classical bit the measurement is assigned to.
"""
outcome, norm = self._add_qasm_decision(qubit)
for ii in range(1 << self._number_of_qubits):
# update quantum state
if (ii >> qubit) & 1 == int(outcome):
self._statevector[ii] = self._statevector[ii]/norm
else:
self._statevector[ii] = 0
# update classical state
bit = 1 << cbit
self._classical_state = (self._classical_state & (~bit)) | (int(outcome) << cbit)
def _add_qasm_reset(self, qubit):
"""Apply the reset to the qubit.
This is done by doing a measruement and if 0 do nothing and
if 1 flip the qubit.
qubit is the qubit that is reset.
"""
# TODO: slow, refactor later
outcome, norm = self._add_qasm_decision(qubit)
temp = np.copy(self._statevector)
self._statevector.fill(0.0)
# measurement
for ii in range(1 << self._number_of_qubits):
if (ii >> qubit) & 1 == int(outcome):
temp[ii] = temp[ii]/norm
else:
temp[ii] = 0
# reset
if outcome == '1':
for ii in range(1 << self._number_of_qubits):
iip = (~ (1 << qubit)) & ii # bit number qubit set to zero
self._statevector[iip] += temp[ii]
else:
self._statevector = temp
def _add_qasm_snapshot(self, slot):
"""Snapshot instruction to record simulator's internal representation
of quantum statevector.
slot is an integer indicating a snapshot slot number.
"""
self._snapshots.setdefault(str(int(slot)),
{}).setdefault("statevector",
[]).append(np.copy(self._statevector))
def run(self, qobj):
"""Run qobj asynchronously.
Args:
qobj (dict): job description
Returns:
AerJob: derived from BaseJob
"""
job_id = str(uuid.uuid4())
aer_job = AerJob(self, job_id, self._run_job, qobj)
aer_job.submit()
return aer_job
def _run_job(self, job_id, qobj):
"""Run circuits in qobj"""
self._validate(qobj)
result_list = []
self._shots = qobj.config.shots
self._qobj_config = qobj.config
start = time.time()
for circuit in qobj.experiments:
result_list.append(self.run_circuit(circuit))
end = time.time()
result = {'backend': self._configuration['name'],
'id': qobj.qobj_id,
'job_id': job_id,
'result': result_list,
'status': 'COMPLETED',
'success': True,
'time_taken': (end - start)}
copy_qasm_from_qobj_into_result(qobj, result)
return result_from_old_style_dict(
result, [circuit.header.name for circuit in qobj.experiments])
def run_circuit(self, circuit):
"""Run a circuit and return a single Result.
Args:
circuit (QobjExperiment): experiment from qobj experiments list
Returns:
dict: A dictionary of results which looks something like::
{
"data":
{ #### DATA CAN BE A DIFFERENT DICTIONARY FOR EACH BACKEND ####
"counts": {'00000': XXXX, '00001': XXXXX},
"time" : xx.xxxxxxxx
},
"status": --status (string)--
}
Raises:
SimulatorError: if an error occurred.
"""
self._number_of_qubits = circuit.header.number_of_qubits
self._number_of_cbits = circuit.header.number_of_clbits
self._statevector = 0
self._classical_state = 0
self._snapshots = {}
cl_reg_index = [] # starting bit index of classical register
cl_reg_nbits = [] # number of bits in classical register
cbit_index = 0
for cl_reg in circuit.header.clbit_labels:
cl_reg_nbits.append(cl_reg[1])
cl_reg_index.append(cbit_index)
cbit_index += cl_reg[1]
# Get the seed looking in circuit, qobj, and then random.
seed = getattr(circuit.config, 'seed',
getattr(self._qobj_config, 'seed',
random.getrandbits(32)))
self._local_random.seed(seed)
outcomes = []
start = time.time()
for _ in range(self._shots):
self._statevector = np.zeros(1 << self._number_of_qubits,
dtype=complex)
self._statevector[0] = 1
self._classical_state = 0
for operation in circuit.instructions:
if getattr(operation, 'conditional', None):
mask = int(operation.conditional.mask, 16)
if mask > 0:
value = self._classical_state & mask
while (mask & 0x1) == 0:
mask >>= 1
value >>= 1
if value != int(operation.conditional.val, 16):
continue
# Check if single gate
if operation.name in ('U', 'u1', 'u2', 'u3'):
params = getattr(operation, 'params', None)
qubit = operation.qubits[0]
gate = single_gate_matrix(operation.name, params)
self._add_qasm_single(gate, qubit)
# Check if CX gate
elif operation.name in ('id', 'u0'):
pass
elif operation.name in ('CX', 'cx'):
qubit0 = operation.qubits[0]
qubit1 = operation.qubits[1]
self._add_qasm_cx(qubit0, qubit1)
# Check if measure
elif operation.name == 'measure':
qubit = operation.qubits[0]
cbit = operation.clbits[0]
self._add_qasm_measure(qubit, cbit)
# Check if reset
elif operation.name == 'reset':
qubit = operation.qubits[0]
self._add_qasm_reset(qubit)
# Check if barrier
elif operation.name == 'barrier':
pass
# Check if snapshot command
elif operation.name == 'snapshot':
params = operation.params
self._add_qasm_snapshot(params[0])
else:
backend = self._configuration['name']
err_msg = '{0} encountered unrecognized operation "{1}"'
raise SimulatorError(err_msg.format(backend,
operation.name))
# Turn classical_state (int) into bit string
outcomes.append(bin(self._classical_state)[2:].zfill(
self._number_of_cbits))
# Return the results
counts = dict(Counter(outcomes))
data = {
'counts': self._format_result(counts, cl_reg_index, cl_reg_nbits),
'snapshots': self._snapshots
}
end = time.time()
return {'name': circuit.header.name,
'seed': seed,
'shots': self._shots,
'data': data,
'status': 'DONE',
'success': True,
'time_taken': (end-start)}
def _validate(self, qobj):
for experiment in qobj.experiments:
if 'measure' not in [op.name for
op in experiment.instructions]:
logger.warning("no measurements in circuit '%s', "
"classical register will remain all zeros.",
experiment.header.name)
def _format_result(self, counts, cl_reg_index, cl_reg_nbits):
"""Format the result bit string.
This formats the result bit strings such that spaces are inserted
at register divisions.
Args:
counts (dict): dictionary of counts e.g. {'1111': 1000, '0000':5}
cl_reg_index (list): starting bit index of classical register
cl_reg_nbits (list): total amount of bits in classical register
Returns:
dict: spaces inserted into dictionary keys at register boundaries.
"""
fcounts = {}
for key, value in counts.items():
if cl_reg_nbits:
new_key = [key[-cl_reg_nbits[0]:]]
for index, nbits in zip(cl_reg_index[1:],
cl_reg_nbits[1:]):
new_key.insert(0, key[-(index+nbits):-index])
fcounts[' '.join(new_key)] = value
return fcounts
<|code_end|>
|
Matplotlib circuit drawer returns NoneType rather than PIL.Image
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: master
- **Python version**:
- **Operating system**:
### What is the current behavior?
The matplotlib circuit drawer returns a NoneType rather than the `PIL.Image` as stated in the docstring for `circuit_drawer` and `matplotlib_circuit_drawer`. Thus, you can do nothing with the output. For example, it would be nice to grab the output and use it in a matplotlib `subplots` or the like and group circuits in a single figure.
### Steps to reproduce the problem
### What is the expected behavior?
### Suggested solutions
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import logging
import os
import subprocess
import tempfile
import warnings
from PIL import Image
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _latex
from qiskit.tools.visualization import _matplotlib
from qiskit.tools.visualization import _text
from qiskit.tools.visualization import _utils
from qiskit.transpiler import transpile_dag
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis=None,
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art TextDrawing that can be printed in the console.
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing. Defaults to
`"id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,cx,cy,cz,ch,crz,cu1,
cu3,swap,ccx,cswap"` This option is deprecated and will be removed
in the future.
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (TextDrawing): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if
one is not specified it will use latex and if that fails fallback
to mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect.
line_length (int): Sets the length of the lines generated by `text`
output type. This useful when the drawing does not fit in the
console. If None (default), it will try to guess the console width
using shutil.get_terminal_size(). If you don't want pagination at
all, set `line_length=-1`.
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: (outputs `latex` and `python`) an in-memory representation of
the circuit diagram.
String: (output `latex_source`). The LaTeX source code.
TextDrawing: (output `text`). A drawing that can be printed as ascii art
Raises:
VisualizationError: when an invalid output method is selected
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defaults to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'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'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
plotbarrier (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True. This is deprecated in the style dict
and will be removed in a future release. Use the `plot_barriers`
kwarg instead.
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
reversebits (bool): When set to True reverse the bit order inside
registers for the output visualization. This is deprecated in the
style dict and will be removed in a future release use the
`reverse_bits` kwarg instead.
"""
if basis is None:
basis = ("id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap")
else:
warnings.warn('The basis kwarg is deprecated and the circuit drawer '
'function will not be able to adjust basis gates itself '
'in a future release', DeprecationWarning)
im = None
if style:
if 'reversebits' in style:
warnings.warn('The reversebits key in style is deprecated and will'
'not work in the future. Instead use the '
'``reverse_bits`` kwarg.', DeprecationWarning)
reverse_bits = style.get('reversebits')
if 'plotbarrier' in style:
warnings.warn('The plotbarrier key in style is deprecated and will'
'not work in the future. Instead use the '
'``plot_barriers`` kwarg.', DeprecationWarning)
plot_barriers = style.get('plotbarrier')
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'"text" by default', DeprecationWarning)
try:
im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError, FileNotFoundError):
im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
else:
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename, basis=basis,
line_length=line_length,
reversebits=reverse_bits,
plotbarriers=plot_barriers)
elif output == 'latex':
im = _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'latex_source':
return _generate_latex_source(circuit, basis=basis,
filename=filename, scale=scale,
style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'mpl':
im = _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
else:
raise _error.VisualizationError(
'Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if im and interactive:
im.show()
return im
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap", line_length=None,
reversebits=False, plotbarriers=True):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
basis (str): Optional. Comma-separated list of gate names
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
reversebits (bool): Rearrange the bits in reverse order.
plotbarriers (bool): Draws the barriers when they are there.
Returns:
TextDrawing: An instances that, when printed, draws the circuit in ascii art.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
text_drawing = _text.TextDrawing(json_circuit, reversebits=reversebits)
text_drawing.plotbarriers = plotbarriers
text_drawing.line_length = line_length
if filename:
text_drawing.dump(filename)
return text_drawing
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to compile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _utils._trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename, basis=basis,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None, reverse_bits=False,
plot_barriers=True):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
qcimg = _latex.QCircuitImage(json_circuit, scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,'
'ry,rz,cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,'
'cswap',
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = _matplotlib.MatplotlibDrawer(basis=basis, scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
<|code_end|>
qiskit/tools/visualization/_matplotlib.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""mpl circuit visualization backend."""
import collections
import fractions
import itertools
import json
import logging
import math
import os
import tempfile
import numpy as np
import PIL
from matplotlib import get_backend as get_matplotlib_backend
from matplotlib import patches
from matplotlib import pyplot as plt
from qiskit import dagcircuit
from qiskit import transpiler
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _qcstyle
from qiskit.tools.visualization import _utils
logger = logging.getLogger(__name__)
Register = collections.namedtuple('Register', 'name index')
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=1.0, style=None, plot_barriers=True,
reverse_bits=False):
self._ast = None
self._basis = basis
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = collections.OrderedDict()
self._creg_dict = collections.OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = _qcstyle.QCStyle()
self.plot_barriers = plot_barriers
self.reverse_bits = reverse_bits
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False,
labelleft=False, labelright=False)
def parse_circuit(self, circuit):
dag_circuit = dagcircuit.DAGCircuit.fromQuantumCircuit(
circuit, expand_gates=False)
self._ast = transpiler.transpile_dag(dag_circuit,
basis_gates=self._basis,
format='json')
self._registers()
self._ops = self._ast['instructions']
def _registers(self):
# NOTE: formats of clbit and qubit are different!
header = self._ast['header']
self._creg = []
for e in header['clbit_labels']:
for i in range(e[1]):
self._creg.append(Register(name=e[0], index=i))
if len(self._creg) != header['number_of_clbits']:
raise _error.VisualizationError('internal error')
self._qreg = []
for e in header['qubit_labels']:
self._qreg.append(Register(name=e[0], index=e[1]))
if len(self._qreg) != header['number_of_qubits']:
raise _error.VisualizationError('internal error')
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(
xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center',
va='center', fontsize=self._style.fs,
color=self._style.gt, clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.sc, clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7,
height=HIG * 0.7, theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID],
[qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy + 0.35 * WID], lc=self._style.cc,
ls=self._style.cline)
arrowhead = patches.Polygon(((cx - 0.20 * WID, cy + 0.35 * WID),
(cx + 0.20 * WID, cy + 0.35 * WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'],
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if get_matplotlib_backend() == 'module://ipykernel.pylab.backend_inline':
# returns None when matplotlib is inline mode to prevent Jupyter
# with matplotlib inlining enabled to draw the diagram twice.
im = None
else:
# when matplotlib is not inline mode,
# self.figure.savefig is called twice because...
# ... this is needed to get the in-memory representation
with tempfile.TemporaryDirectory() as tmpdir:
tmpfile = os.path.join(tmpdir, 'circuit.png')
self.figure.savefig(tmpfile, dpi=self._style.dpi,
bbox_inches='tight')
im = PIL.Image.open(tmpfile)
_utils._trim(im)
os.remove(tmpfile)
# ... and this is needed to delegate in matplotlib the generation of
# the proper format.
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
return im
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(itertools.zip_longest(
self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
self._cond['n_lines'] += 1
idx += 1
# reverse bit order
if self.reverse_bits:
self._reverse_bits(self._qreg_dict)
self._reverse_bits(self._creg_dict)
def _reverse_bits(self, target_dict):
coord = {}
# grouping
for dict_ in target_dict.values():
if dict_['group'] not in coord:
coord[dict_['group']] = [dict_['y']]
else:
coord[dict_['group']].insert(0, dict_['y'])
# reverse bit order
for key in target_dict.keys():
target_dict[key]['y'] = coord[target_dict[key]['group']].pop(0)
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left',
va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc,
ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(
itertools.zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qubits' in op.keys():
q_idxs = op['qubits']
else:
q_idxs = []
# get creg index
if 'clbits' in op.keys():
c_idxs = op['clbits']
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied),
max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(
this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] == 'barrier' and not self.plot_barriers:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg coordinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for
ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc,
ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] == 'barrier':
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self.plot_barriers:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise _error.VisualizationError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (
self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.tc, clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if math.isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if math.isclose(math.fmod(abs_val, 1.0),
0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
if 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if math.isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return fractions.Fraction(i, j)
return None
<|code_end|>
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import logging
import os
import subprocess
import tempfile
import warnings
from PIL import Image
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _latex
from qiskit.tools.visualization import _matplotlib
from qiskit.tools.visualization import _text
from qiskit.tools.visualization import _utils
from qiskit.transpiler import transpile_dag
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis=None,
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art TextDrawing that can be printed in the console.
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing. Defaults to
`"id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,cx,cy,cz,ch,crz,cu1,
cu3,swap,ccx,cswap"` This option is deprecated and will be removed
in the future.
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (TextDrawing): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if
one is not specified it will use latex and if that fails fallback
to mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect.
line_length (int): Sets the length of the lines generated by `text`
output type. This useful when the drawing does not fit in the
console. If None (default), it will try to guess the console width
using shutil.get_terminal_size(). If you don't want pagination at
all, set `line_length=-1`.
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: (output `latex`) an in-memory representation of the image
of the circuit diagram.
matplotlib.figure: (output `mpl`) a matplotlib figure object for the
circuit diagram.
String: (output `latex_source`). The LaTeX source code.
TextDrawing: (output `text`). A drawing that can be printed as ascii art
Raises:
VisualizationError: when an invalid output method is selected
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defaults to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'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'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
plotbarrier (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True. This is deprecated in the style dict
and will be removed in a future release. Use the `plot_barriers`
kwarg instead.
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
reversebits (bool): When set to True reverse the bit order inside
registers for the output visualization. This is deprecated in the
style dict and will be removed in a future release use the
`reverse_bits` kwarg instead.
"""
if basis is None:
basis = ("id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap")
else:
warnings.warn('The basis kwarg is deprecated and the circuit drawer '
'function will not be able to adjust basis gates itself '
'in a future release', DeprecationWarning)
im = None
if style:
if 'reversebits' in style:
warnings.warn('The reversebits key in style is deprecated and will'
'not work in the future. Instead use the '
'``reverse_bits`` kwarg.', DeprecationWarning)
reverse_bits = style.get('reversebits')
if 'plotbarrier' in style:
warnings.warn('The plotbarrier key in style is deprecated and will'
'not work in the future. Instead use the '
'``plot_barriers`` kwarg.', DeprecationWarning)
plot_barriers = style.get('plotbarrier')
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'"text" by default', DeprecationWarning)
try:
im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError, FileNotFoundError):
im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
else:
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename, basis=basis,
line_length=line_length,
reversebits=reverse_bits,
plotbarriers=plot_barriers)
elif output == 'latex':
im = _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'latex_source':
return _generate_latex_source(circuit, basis=basis,
filename=filename, scale=scale,
style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'mpl':
im = _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
else:
raise _error.VisualizationError(
'Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if im and interactive:
im.show()
return im
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap", line_length=None,
reversebits=False, plotbarriers=True):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
basis (str): Optional. Comma-separated list of gate names
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
reversebits (bool): Rearrange the bits in reverse order.
plotbarriers (bool): Draws the barriers when they are there.
Returns:
TextDrawing: An instances that, when printed, draws the circuit in ascii art.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
text_drawing = _text.TextDrawing(json_circuit, reversebits=reversebits)
text_drawing.plotbarriers = plotbarriers
text_drawing.line_length = line_length
if filename:
text_drawing.dump(filename)
return text_drawing
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to compile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _utils._trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename, basis=basis,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None, reverse_bits=False,
plot_barriers=True):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
qcimg = _latex.QCircuitImage(json_circuit, scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,'
'ry,rz,cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,'
'cswap',
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
matplotlib.figure: a matplotlib figure object for the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = _matplotlib.MatplotlibDrawer(basis=basis, scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
<|code_end|>
qiskit/tools/visualization/_matplotlib.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""mpl circuit visualization backend."""
import collections
import fractions
import itertools
import json
import logging
import math
import numpy as np
from matplotlib import patches
from matplotlib import pyplot as plt
from qiskit import dagcircuit
from qiskit import transpiler
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _qcstyle
logger = logging.getLogger(__name__)
Register = collections.namedtuple('Register', 'name index')
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=1.0, style=None, plot_barriers=True,
reverse_bits=False):
self._ast = None
self._basis = basis
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = collections.OrderedDict()
self._creg_dict = collections.OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = _qcstyle.QCStyle()
self.plot_barriers = plot_barriers
self.reverse_bits = reverse_bits
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False,
labelleft=False, labelright=False)
def parse_circuit(self, circuit):
dag_circuit = dagcircuit.DAGCircuit.fromQuantumCircuit(
circuit, expand_gates=False)
self._ast = transpiler.transpile_dag(dag_circuit,
basis_gates=self._basis,
format='json')
self._registers()
self._ops = self._ast['instructions']
def _registers(self):
# NOTE: formats of clbit and qubit are different!
header = self._ast['header']
self._creg = []
for e in header['clbit_labels']:
for i in range(e[1]):
self._creg.append(Register(name=e[0], index=i))
if len(self._creg) != header['number_of_clbits']:
raise _error.VisualizationError('internal error')
self._qreg = []
for e in header['qubit_labels']:
self._qreg.append(Register(name=e[0], index=e[1]))
if len(self._qreg) != header['number_of_qubits']:
raise _error.VisualizationError('internal error')
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(
xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center',
va='center', fontsize=self._style.fs,
color=self._style.gt, clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.sc, clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7,
height=HIG * 0.7, theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID],
[qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy + 0.35 * WID], lc=self._style.cc,
ls=self._style.cline)
arrowhead = patches.Polygon(((cx - 0.20 * WID, cy + 0.35 * WID),
(cx + 0.20 * WID, cy + 0.35 * WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'],
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
return self.figure
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(itertools.zip_longest(
self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
self._cond['n_lines'] += 1
idx += 1
# reverse bit order
if self.reverse_bits:
self._reverse_bits(self._qreg_dict)
self._reverse_bits(self._creg_dict)
def _reverse_bits(self, target_dict):
coord = {}
# grouping
for dict_ in target_dict.values():
if dict_['group'] not in coord:
coord[dict_['group']] = [dict_['y']]
else:
coord[dict_['group']].insert(0, dict_['y'])
# reverse bit order
for key in target_dict.keys():
target_dict[key]['y'] = coord[target_dict[key]['group']].pop(0)
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left',
va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc,
ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(
itertools.zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qubits' in op.keys():
q_idxs = op['qubits']
else:
q_idxs = []
# get creg index
if 'clbits' in op.keys():
c_idxs = op['clbits']
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied),
max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(
this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] == 'barrier' and not self.plot_barriers:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg coordinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for
ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc,
ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] == 'barrier':
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self.plot_barriers:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise _error.VisualizationError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (
self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.tc, clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if math.isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if math.isclose(math.fmod(abs_val, 1.0),
0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
if 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if math.isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return fractions.Fraction(i, j)
return None
<|code_end|>
|
ConnectionRefusedError when importing from qiskit.tools.visualization
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
Qiskit 0.6.1
Python 3.5.6
MacOS Mojave 10.14.1
### What is the current behavior?
A ConnectionRefusedError occurs as soon as you attempt to load any visualization package from qiskit.tools.visualization.
`---------------------------------------------------------------------------
ConnectionRefusedError Traceback (most recent call last)
<ipython-input-2-d8b2a64d996f> in <module>()
3
4 # import state tomography functions
----> 5 from qiskit.tools.visualization import plot_histogram, plot_state
/anaconda3/envs/Qiskitenv/lib/python3.5/site-packages/qiskit/tools/visualization/__init__.py in <module>()
17
18 if ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
---> 19 if _has_connection('https://qvisualization.mybluemix.net/', 443):
20 from .interactive._iplot_state import iplot_state as plot_state
21 from .interactive._iplot_histogram import iplot_histogram as \
/anaconda3/envs/Qiskitenv/lib/python3.5/site-packages/qiskit/_util.py in _has_connection(hostname, port)
218 try:
219 host = socket.gethostbyname(hostname)
--> 220 socket.create_connection((host, port), 2)
221 return True
222 except socket.gaierror:
/anaconda3/envs/Qiskitenv/lib/python3.5/socket.py in create_connection(address, timeout, source_address)
710
711 if err is not None:
--> 712 raise err
713 else:
714 raise error("getaddrinfo returns an empty list")
/anaconda3/envs/Qiskitenv/lib/python3.5/socket.py in create_connection(address, timeout, source_address)
701 if source_address:
702 sock.bind(source_address)
--> 703 sock.connect(sa)
704 return sock
705
ConnectionRefusedError: [Errno 61] Connection refused`
### Steps to reproduce the problem
Load qiskit-tutorial and navigate to this notebook
https://github.com/Qiskit/qiskit-tutorial/blob/master/qiskit/basics/qiskit_visualizations.ipynb
### What is the expected behavior?
No errors should occur during import of packages.
### Suggested solutions
|
qiskit/_util.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=too-many-ancestors
"""Common utilities for QISKit."""
import logging
import re
import sys
import platform
import warnings
import socket
import psutil
logger = logging.getLogger(__name__)
FIRST_CAP_RE = re.compile('(.)([A-Z][a-z]+)')
ALL_CAP_RE = re.compile('([a-z0-9])([A-Z])')
def _check_python_version():
"""Check for Python version 3.5+
"""
if sys.version_info < (3, 5):
raise Exception('QISKit requires Python version 3.5 or greater.')
def _enable_deprecation_warnings():
"""
Force the `DeprecationWarning` warnings to be displayed for the qiskit
module, overriding the system configuration as they are ignored by default
[1] for end-users.
TODO: on Python 3.7, this might not be needed due to PEP-0565 [2].
[1] https://docs.python.org/3/library/warnings.html#default-warning-filters
[2] https://www.python.org/dev/peps/pep-0565/
"""
# pylint: disable=invalid-name
deprecation_filter = ('always', None, DeprecationWarning,
re.compile(r'^qiskit\.*', re.UNICODE), 0)
# Instead of using warnings.simple_filter() directly, the internal
# _add_filter() function is used for being able to match against the
# module.
try:
warnings._add_filter(*deprecation_filter, append=False)
except AttributeError:
# ._add_filter is internal and not available in some Python versions.
pass
def _camel_case_to_snake_case(identifier):
"""Return a `snake_case` string from a `camelCase` string.
Args:
identifier (str): a `camelCase` string.
Returns:
str: a `snake_case` string.
"""
string_1 = FIRST_CAP_RE.sub(r'\1_\2', identifier)
return ALL_CAP_RE.sub(r'\1_\2', string_1).lower()
_check_python_version()
_enable_deprecation_warnings()
def local_hardware_info():
"""Basic hardware information about the local machine.
Gives actual number of CPU's in the machine, even when hyperthreading is
turned on.
Returns:
dict: The hardware information.
"""
results = {'os': platform.system()}
results['memory'] = psutil.virtual_memory().total / (1024**3)
results['cpus'] = psutil.cpu_count(logical=False)
return results
def _has_connection(hostname, port):
"""Checks to see if internet connection exists to host
via specified port
Args:
hostname (str): Hostname to connect to.
port (int): Port to connect to
Returns:
bool: Has connection or not
Raises:
gaierror: No connection established.
"""
try:
host = socket.gethostbyname(hostname)
socket.create_connection((host, port), 2)
return True
except socket.gaierror:
pass
return False
<|code_end|>
|
qiskit/_util.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=too-many-ancestors,broad-except
"""Common utilities for QISKit."""
import logging
import re
import sys
import platform
import warnings
import socket
import psutil
logger = logging.getLogger(__name__)
FIRST_CAP_RE = re.compile('(.)([A-Z][a-z]+)')
ALL_CAP_RE = re.compile('([a-z0-9])([A-Z])')
def _check_python_version():
"""Check for Python version 3.5+
"""
if sys.version_info < (3, 5):
raise Exception('QISKit requires Python version 3.5 or greater.')
def _enable_deprecation_warnings():
"""
Force the `DeprecationWarning` warnings to be displayed for the qiskit
module, overriding the system configuration as they are ignored by default
[1] for end-users.
TODO: on Python 3.7, this might not be needed due to PEP-0565 [2].
[1] https://docs.python.org/3/library/warnings.html#default-warning-filters
[2] https://www.python.org/dev/peps/pep-0565/
"""
# pylint: disable=invalid-name
deprecation_filter = ('always', None, DeprecationWarning,
re.compile(r'^qiskit\.*', re.UNICODE), 0)
# Instead of using warnings.simple_filter() directly, the internal
# _add_filter() function is used for being able to match against the
# module.
try:
warnings._add_filter(*deprecation_filter, append=False)
except AttributeError:
# ._add_filter is internal and not available in some Python versions.
pass
def _camel_case_to_snake_case(identifier):
"""Return a `snake_case` string from a `camelCase` string.
Args:
identifier (str): a `camelCase` string.
Returns:
str: a `snake_case` string.
"""
string_1 = FIRST_CAP_RE.sub(r'\1_\2', identifier)
return ALL_CAP_RE.sub(r'\1_\2', string_1).lower()
_check_python_version()
_enable_deprecation_warnings()
def local_hardware_info():
"""Basic hardware information about the local machine.
Gives actual number of CPU's in the machine, even when hyperthreading is
turned on.
Returns:
dict: The hardware information.
"""
results = {'os': platform.system()}
results['memory'] = psutil.virtual_memory().total / (1024**3)
results['cpus'] = psutil.cpu_count(logical=False)
return results
def _has_connection(hostname, port):
"""Checks to see if internet connection exists to host
via specified port
If any exception is raised while trying to open a socket this will return
false.
Args:
hostname (str): Hostname to connect to.
port (int): Port to connect to
Returns:
bool: Has connection or not
"""
try:
host = socket.gethostbyname(hostname)
socket.create_connection((host, port), 2)
return True
except Exception:
return False
<|code_end|>
|
`qiskit.tools.visualization_state_visualization` module fails to import
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: latest master
- **Python version**: any
- **Operating system**: any
### What is the current behavior?
Since #1166 merged the api changed for the pauli_singles() function. However the `qiskit.tools.visualization_state_visualization` module still uses the old function and imports the function directly here: https://github.com/Qiskit/qiskit-terra/blob/master/qiskit/tools/visualization/_state_visualization.py#L23
### Steps to reproduce the problem
import qiskit.tools.visualization_state_visualization
### What is the expected behavior?
You can import the module and use all the functions in it.
### Suggested solutions
Update the use of `pauli_singles` to the new api post #1166
|
qiskit/tools/visualization/_state_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string
"""
Visualization functions for quantum states.
"""
from functools import reduce
import numpy as np
from matplotlib import cm
from matplotlib import pyplot as plt
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
from scipy import linalg
from qiskit.tools.qi.pauli import pauli_group, pauli_singles
from qiskit.tools.visualization import VisualizationError
from qiskit.tools.visualization._bloch import Bloch
class Arrow3D(FancyArrowPatch):
"""Standard 3D arrow."""
def __init__(self, xs, ys, zs, *args, **kwargs):
"""Create arrow."""
FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
self._verts3d = xs, ys, zs
def draw(self, renderer):
"""Draw the arrow."""
xs3d, ys3d, zs3d = self._verts3d
xs, ys, _ = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
FancyArrowPatch.draw(self, renderer)
def plot_bloch_vector(bloch, title="", filename=None):
"""Plot the Bloch sphere.
Plot a sphere, axes, the Bloch vector, and its projections onto each axis.
Args:
bloch (list[double]): array of three elements where [<x>, <y>,<z>]
title (str): a string that represents the plot title
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
"""
B = Bloch()
B.add_vectors(bloch)
if filename:
B.save(filename)
else:
B.show(title=title)
def plot_state_city(rho, title="", filename=None):
"""Plot the cityscape of quantum state.
Plot two 3d bargraphs (two dimensional) of the mixed state rho
Args:
rho (np.array[[complex]]): array of dimensions 2**n x 2**nn complex
numbers
title (str): a string that represents the plot title
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
"""
num = int(np.log2(len(rho)))
# get the real and imag parts of rho
datareal = np.real(rho)
dataimag = np.imag(rho)
# get the labels
column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
row_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
lx = len(datareal[0]) # Work out matrix dimensions
ly = len(datareal[:, 0])
xpos = np.arange(0, lx, 1) # Set up a mesh of positions
ypos = np.arange(0, ly, 1)
xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25)
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(lx*ly)
dx = 0.5 * np.ones_like(zpos) # width of bars
dy = dx.copy()
dzr = datareal.flatten()
dzi = dataimag.flatten()
fig = plt.figure(figsize=(8, 8))
ax1 = fig.add_subplot(2, 1, 1, projection='3d')
ax1.bar3d(xpos, ypos, zpos, dx, dy, dzr, color="g", alpha=0.5)
ax2 = fig.add_subplot(2, 1, 2, projection='3d')
ax2.bar3d(xpos, ypos, zpos, dx, dy, dzi, color="g", alpha=0.5)
ax1.set_xticks(np.arange(0.5, lx+0.5, 1))
ax1.set_yticks(np.arange(0.5, ly+0.5, 1))
ax1.axes.set_zlim3d(-1.0, 1.0001)
ax1.set_zticks(np.arange(-1, 1, 0.5))
ax1.w_xaxis.set_ticklabels(row_names, fontsize=12, rotation=45)
ax1.w_yaxis.set_ticklabels(column_names, fontsize=12, rotation=-22.5)
# ax1.set_xlabel('basis state', fontsize=12)
# ax1.set_ylabel('basis state', fontsize=12)
ax1.set_zlabel("Real[rho]")
ax2.set_xticks(np.arange(0.5, lx+0.5, 1))
ax2.set_yticks(np.arange(0.5, ly+0.5, 1))
ax2.axes.set_zlim3d(-1.0, 1.0001)
ax2.set_zticks(np.arange(-1, 1, 0.5))
ax2.w_xaxis.set_ticklabels(row_names, fontsize=12, rotation=45)
ax2.w_yaxis.set_ticklabels(column_names, fontsize=12, rotation=-22.5)
# ax2.set_xlabel('basis state', fontsize=12)
# ax2.set_ylabel('basis state', fontsize=12)
ax2.set_zlabel("Imag[rho]")
plt.title(title)
if filename:
plt.savefig(filename)
else:
plt.show()
def plot_state_paulivec(rho, title="", filename=None):
"""Plot the paulivec representation of a quantum state.
Plot a bargraph of the mixed state rho over the pauli matrices
Args:
rho (np.array[[complex]]): array of dimensions 2**n x 2**nn complex
numbers
title (str): a string that represents the plot title
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
"""
num = int(np.log2(len(rho)))
labels = list(map(lambda x: x.to_label(), pauli_group(num)))
values = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_group(num)))
numelem = len(values)
ind = np.arange(numelem) # the x locations for the groups
width = 0.5 # the width of the bars
_, ax = plt.subplots()
ax.grid(zorder=0)
ax.bar(ind, values, width, color='seagreen')
# add some text for labels, title, and axes ticks
ax.set_ylabel('Expectation value', fontsize=12)
ax.set_xticks(ind)
ax.set_yticks([-1, -0.5, 0, 0.5, 1])
ax.set_xticklabels(labels, fontsize=12, rotation=70)
ax.set_xlabel('Pauli', fontsize=12)
ax.set_ylim([-1, 1])
plt.title(title)
if filename:
plt.savefig(filename)
else:
plt.show()
def n_choose_k(n, k):
"""Return the number of combinations for n choose k.
Args:
n (int): the total number of options .
k (int): The number of elements.
Returns:
int: returns the binomial coefficient
"""
if n == 0:
return 0
return reduce(lambda x, y: x * y[0] / y[1],
zip(range(n - k + 1, n + 1),
range(1, k + 1)), 1)
def lex_index(n, k, lst):
"""Return the lex index of a combination..
Args:
n (int): the total number of options .
k (int): The number of elements.
lst (list): list
Returns:
int: returns int index for lex order
Raises:
VisualizationError: if length of list is not equal to k
"""
if len(lst) != k:
raise VisualizationError("list should have length k")
comb = list(map(lambda x: n - 1 - x, lst))
dualm = sum([n_choose_k(comb[k - 1 - i], i + 1) for i in range(k)])
return int(dualm)
def bit_string_index(s):
"""Return the index of a string of 0s and 1s."""
n = len(s)
k = s.count("1")
if s.count("0") != n - k:
raise VisualizationError("s must be a string of 0 and 1")
ones = [pos for pos, char in enumerate(s) if char == "1"]
return lex_index(n, k, ones)
def phase_to_color_wheel(complex_number):
"""Map a phase of a complexnumber to a color in (r,g,b).
complex_number is phase is first mapped to angle in the range
[0, 2pi] and then to a color wheel with blue at zero phase.
"""
angles = np.angle(complex_number)
angle_round = int(((angles + 2 * np.pi) % (2 * np.pi))/np.pi*6)
color_map = {
0: (0, 0, 1), # blue,
1: (0.5, 0, 1), # blue-violet
2: (1, 0, 1), # violet
3: (1, 0, 0.5), # red-violet,
4: (1, 0, 0), # red
5: (1, 0.5, 0), # red-oranage,
6: (1, 1, 0), # orange
7: (0.5, 1, 0), # orange-yellow
8: (0, 1, 0), # yellow,
9: (0, 1, 0.5), # yellow-green,
10: (0, 1, 1), # green,
11: (0, 0.5, 1) # green-blue,
}
return color_map[angle_round]
def plot_state_qsphere(rho, filename=None):
"""Plot the qsphere representation of a quantum state."""
num = int(np.log2(len(rho)))
# get the eigenvectors and eigenvalues
we, stateall = linalg.eigh(rho)
for k in range(2**num):
# start with the max
probmix = we.max()
prob_location = we.argmax()
if probmix > 0.001:
print("The " + str(k) + "th eigenvalue = " + str(probmix))
# get the max eigenvalue
state = stateall[:, prob_location]
loc = np.absolute(state).argmax()
# get the element location closes to lowest bin representation.
for j in range(2**num):
test = np.absolute(np.absolute(state[j]) -
np.absolute(state[loc]))
if test < 0.001:
loc = j
break
# remove the global phase
angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi)
angleset = np.exp(-1j*angles)
# print(state)
# print(angles)
state = angleset*state
# print(state)
state.flatten()
# start the plotting
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')
ax.axes.set_xlim3d(-1.0, 1.0)
ax.axes.set_ylim3d(-1.0, 1.0)
ax.axes.set_zlim3d(-1.0, 1.0)
ax.set_aspect("equal")
ax.axes.grid(False)
# Plot semi-transparent sphere
u = np.linspace(0, 2 * np.pi, 25)
v = np.linspace(0, np.pi, 25)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(x, y, z, rstride=1, cstride=1, color='k',
alpha=0.05, linewidth=0)
# wireframe
# Get rid of the panes
ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the spines
ax.w_xaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.w_yaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.w_zaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
d = num
for i in range(2**num):
# get x,y,z points
element = bin(i)[2:].zfill(num)
weight = element.count("1")
zvalue = -2 * weight / d + 1
number_of_divisions = n_choose_k(d, weight)
weight_order = bit_string_index(element)
# if weight_order >= number_of_divisions / 2:
# com_key = compliment(element)
# weight_order_temp = bit_string_index(com_key)
# weight_order = np.floor(
# number_of_divisions / 2) + weight_order_temp + 1
angle = weight_order * 2 * np.pi / number_of_divisions
xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle)
yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle)
ax.plot([xvalue], [yvalue], [zvalue],
markerfacecolor=(.5, .5, .5),
markeredgecolor=(.5, .5, .5),
marker='o', markersize=10, alpha=1)
# get prob and angle - prob will be shade and angle color
prob = np.real(np.dot(state[i], state[i].conj()))
colorstate = phase_to_color_wheel(state[i])
a = Arrow3D([0, xvalue], [0, yvalue], [0, zvalue],
mutation_scale=20, alpha=prob, arrowstyle="-",
color=colorstate, lw=10)
ax.add_artist(a)
# add weight lines
for weight in range(d + 1):
theta = np.linspace(-2 * np.pi, 2 * np.pi, 100)
z = -2 * weight / d + 1
r = np.sqrt(1 - z**2)
x = r * np.cos(theta)
y = r * np.sin(theta)
ax.plot(x, y, z, color=(.5, .5, .5))
# add center point
ax.plot([0], [0], [0], markerfacecolor=(.5, .5, .5),
markeredgecolor=(.5, .5, .5), marker='o', markersize=10,
alpha=1)
if filename:
plt.savefig(filename)
else:
plt.show()
we[prob_location] = 0
else:
break
def plot_state(quantum_state, method='city', filename=None):
"""Plot the quantum state.
Args:
quantum_state (ndarray): statevector or density matrix
representation of a quantum state.
method (str): Plotting method to use.
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window. If
`bloch` method is used a `-n` will be added to the filename before
the extension for each qubit.
Raises:
VisualizationError: if the input is not a statevector or density
matrix, or if the state is not an multi-qubit quantum state.
"""
# Check if input is a statevector, and convert to density matrix
rho = np.array(quantum_state)
if rho.ndim == 1:
rho = np.outer(rho, np.conj(rho))
# Check the shape of the input is a square matrix
shape = np.shape(rho)
if len(shape) != 2 or shape[0] != shape[1]:
raise VisualizationError("Input is not a valid quantum state.")
# Check state is an n-qubit state
num = int(np.log2(len(rho)))
if 2 ** num != len(rho):
raise VisualizationError("Input is not a multi-qubit quantum state.")
if method == 'city':
plot_state_city(rho, filename=filename)
elif method == "paulivec":
plot_state_paulivec(rho, filename=filename)
elif method == "qsphere":
plot_state_qsphere(rho, filename=filename)
elif method == "bloch":
orig_filename = filename
for i in range(num):
if orig_filename:
filename_parts = orig_filename.split('.')
filename_parts[-2] += '-%d' % i
filename = '.'.join(filename_parts)
print(filename)
bloch_state = list(
map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_singles(i, num)))
plot_bloch_vector(bloch_state, "qubit " + str(i), filename=filename)
elif method == "wigner":
plot_wigner_function(rho, filename=filename)
###############################################################
# Plotting Wigner functions
###############################################################
def plot_wigner_function(state, res=100, filename=None):
"""Plot the equal angle slice spin Wigner function of an arbitrary
quantum state.
Args:
state (np.matrix[[complex]]):
- Matrix of 2**n x 2**n complex numbers
- State Vector of 2**n x 1 complex numbers
res (int) : number of theta and phi values in meshgrid
on sphere (creates a res x res grid of points)
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
References:
[1] T. Tilma, M. J. Everitt, J. H. Samson, W. J. Munro,
and K. Nemoto, Phys. Rev. Lett. 117, 180401 (2016).
[2] R. P. Rundle, P. W. Mills, T. Tilma, J. H. Samson, and
M. J. Everitt, Phys. Rev. A 96, 022117 (2017).
"""
state = np.array(state)
if state.ndim == 1:
state = np.outer(state,
state) # turns state vector to a density matrix
state = np.matrix(state)
num = int(np.log2(len(state))) # number of qubits
phi_vals = np.linspace(0, np.pi, num=res,
dtype=np.complex_)
theta_vals = np.linspace(0, 0.5*np.pi, num=res,
dtype=np.complex_) # phi and theta values for WF
w = np.empty([res, res])
harr = np.sqrt(3)
delta_su2 = np.zeros((2, 2), dtype=np.complex_)
# create the spin Wigner function
for theta in range(res):
costheta = harr*np.cos(2*theta_vals[theta])
sintheta = harr*np.sin(2*theta_vals[theta])
for phi in range(res):
delta_su2[0, 0] = 0.5*(1+costheta)
delta_su2[0, 1] = -0.5*(np.exp(2j*phi_vals[phi])*sintheta)
delta_su2[1, 0] = -0.5*(np.exp(-2j*phi_vals[phi])*sintheta)
delta_su2[1, 1] = 0.5*(1-costheta)
kernel = 1
for _ in range(num):
kernel = np.kron(kernel,
delta_su2) # creates phase point kernel
w[phi, theta] = np.real(np.trace(state*kernel)) # Wigner function
# Plot a sphere (x,y,z) with Wigner function facecolor data stored in Wc
fig = plt.figure(figsize=(11, 9))
ax = fig.gca(projection='3d')
w_max = np.amax(w)
# Color data for plotting
w_c = cm.seismic_r((w+w_max)/(2*w_max)) # color data for sphere
w_c2 = cm.seismic_r((w[0:res, int(res/2):res]+w_max)/(2*w_max)) # bottom
w_c3 = cm.seismic_r((w[int(res/4):int(3*res/4), 0:res]+w_max) /
(2*w_max)) # side
w_c4 = cm.seismic_r((w[int(res/2):res, 0:res]+w_max)/(2*w_max)) # back
u = np.linspace(0, 2 * np.pi, res)
v = np.linspace(0, np.pi, res)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones(np.size(u)), np.cos(v)) # creates a sphere mesh
ax.plot_surface(x, y, z, facecolors=w_c,
vmin=-w_max, vmax=w_max,
rcount=res, ccount=res,
linewidth=0, zorder=0.5,
antialiased=False) # plots Wigner Bloch sphere
ax.plot_surface(x[0:res, int(res/2):res],
y[0:res, int(res/2):res],
-1.5*np.ones((res, int(res/2))),
facecolors=w_c2,
vmin=-w_max, vmax=w_max,
rcount=res/2, ccount=res/2,
linewidth=0, zorder=0.5,
antialiased=False) # plots bottom reflection
ax.plot_surface(-1.5*np.ones((int(res/2), res)),
y[int(res/4):int(3*res/4), 0:res],
z[int(res/4):int(3*res/4), 0:res],
facecolors=w_c3,
vmin=-w_max, vmax=w_max,
rcount=res/2, ccount=res/2,
linewidth=0, zorder=0.5,
antialiased=False) # plots side reflection
ax.plot_surface(x[int(res/2):res, 0:res],
1.5*np.ones((int(res/2), res)),
z[int(res/2):res, 0:res],
facecolors=w_c4,
vmin=-w_max, vmax=w_max,
rcount=res/2, ccount=res/2,
linewidth=0, zorder=0.5,
antialiased=False) # plots back reflection
ax.w_xaxis.set_pane_color((0.4, 0.4, 0.4, 1.0))
ax.w_yaxis.set_pane_color((0.4, 0.4, 0.4, 1.0))
ax.w_zaxis.set_pane_color((0.4, 0.4, 0.4, 1.0))
ax.set_xticks([], [])
ax.set_yticks([], [])
ax.set_zticks([], [])
ax.grid(False)
ax.xaxis.pane.set_edgecolor('black')
ax.yaxis.pane.set_edgecolor('black')
ax.zaxis.pane.set_edgecolor('black')
ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_zlim(-1.5, 1.5)
m = cm.ScalarMappable(cmap=cm.seismic_r)
m.set_array([-w_max, w_max])
plt.colorbar(m, shrink=0.5, aspect=10)
if filename:
plt.savefig(filename)
else:
plt.show()
def plot_wigner_curve(wigner_data, xaxis=None, filename=None):
"""Plots a curve for points in phase space of the spin Wigner function.
Args:
wigner_data(np.array): an array of points to plot as a 2d curve
xaxis (np.array): the range of the x axis
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
"""
if not xaxis:
xaxis = np.linspace(0, len(wigner_data)-1, num=len(wigner_data))
plt.plot(xaxis, wigner_data)
if filename:
plt.savefig(filename)
else:
plt.show()
def plot_wigner_plaquette(wigner_data, max_wigner='local', filename=None):
"""Plots plaquette of wigner function data, the plaquette will
consist of circles each colored to match the value of the Wigner
function at the given point in phase space.
Args:
wigner_data (matrix): array of Wigner function data where the
rows are plotted along the x axis and the
columns are plotted along the y axis
max_wigner (str or float):
- 'local' puts the maximum value to maximum of the points
- 'unit' sets maximum to 1
- float for a custom maximum.
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
"""
wigner_data = np.matrix(wigner_data)
dim = wigner_data.shape
if max_wigner == 'local':
w_max = np.amax(wigner_data)
elif max_wigner == 'unit':
w_max = 1
else:
w_max = max_wigner # For a float input
w_max = float(w_max)
cmap = plt.cm.get_cmap('seismic_r')
xax = dim[1]-0.5
yax = dim[0]-0.5
norm = np.amax(dim)
fig = plt.figure(figsize=((xax+0.5)*6/norm, (yax+0.5)*6/norm))
ax = fig.gca()
for x in range(int(dim[1])):
for y in range(int(dim[0])):
circle = plt.Circle(
(x, y), 0.49, color=cmap((wigner_data[y, x]+w_max)/(2*w_max)))
ax.add_artist(circle)
ax.set_xlim(-1, xax+0.5)
ax.set_ylim(-1, yax+0.5)
ax.set_xticks([], [])
ax.set_yticks([], [])
m = cm.ScalarMappable(cmap=cm.seismic_r)
m.set_array([-w_max, w_max])
plt.colorbar(m, shrink=0.5, aspect=10)
if filename:
plt.savefig(filename)
else:
plt.show()
def plot_wigner_data(wigner_data, phis=None, method=None, filename=None):
"""Plots Wigner results in appropriate format.
Args:
wigner_data (numpy.array): Output returned from the wigner_data
function
phis (numpy.array): Values of phi
method (str or None): how the data is to be plotted, methods are:
point: a single point in phase space
curve: a two dimensional curve
plaquette: points plotted as circles
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
"""
if not method:
wig_dim = len(np.shape(wigner_data))
if wig_dim == 1:
if np.shape(wigner_data) == 1:
method = 'point'
else:
method = 'curve'
elif wig_dim == 2:
method = 'plaquette'
if method == 'curve':
plot_wigner_curve(wigner_data, xaxis=phis, filename=filename)
elif method == 'plaquette':
plot_wigner_plaquette(wigner_data, filename=filename)
elif method == 'state':
plot_wigner_function(wigner_data, filename=filename)
elif method == 'point':
plot_wigner_plaquette(wigner_data, filename=filename)
print('point in phase space is '+str(wigner_data))
else:
print("No method given")
<|code_end|>
qiskit/tools/visualization/interactive/_iplot_blochsphere.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Bloch sphere visualization
"""
from string import Template
import sys
import time
import re
import numpy as np
from qiskit.tools.qi.pauli import pauli_singles
if ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
try:
from IPython.core.display import display, HTML
except ImportError:
print("Error importing IPython.core.display")
def iplot_blochsphere(rho, options=None):
""" Create a bloch sphere representation.
Graphical representation of the input array, using as much bloch
spheres as qubit are required.
Args:
rho (array): Density matrix
options (dict): Representation settings containing
- width (integer): graph horizontal size
- height (integer): graph vertical size
"""
# HTML
html_template = Template("""
<p>
<div id="content_$divNumber" style="position: absolute; z-index: 1;">
<div id="bloch_$divNumber"></div>
</div>
</p>
""")
# JavaScript
javascript_template = Template("""
<script>
requirejs.config({
paths: {
qVisualization: "https://qvisualization.mybluemix.net/q-visualizations"
}
});
data = $data;
dataValues = [];
for (var i = 0; i < data.length; i++) {
// Coordinates
var x = data[i][0];
var y = data[i][1];
var z = data[i][2];
var point = {'x': x,
'y': y,
'z': z};
dataValues.push(point);
}
require(["qVisualization"], function(qVisualizations) {
// Plot figure
qVisualizations.plotState("bloch_$divNumber",
"bloch",
dataValues,
$options);
});
</script>
""")
if not options:
options = {}
# Process data and execute
num = int(np.log2(len(rho)))
bloch_data = []
for i in range(num):
bloch_state = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_singles(i, num)))
bloch_data.append(bloch_state)
div_number = str(time.time())
div_number = re.sub('[.]', '', div_number)
html = html_template.substitute({
'divNumber': div_number
})
javascript = javascript_template.substitute({
'data': bloch_data,
'divNumber': div_number,
'options': options
})
display(HTML(html + javascript))
<|code_end|>
|
qiskit/tools/visualization/_state_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string
"""
Visualization functions for quantum states.
"""
from functools import reduce
import numpy as np
from matplotlib import cm
from matplotlib import pyplot as plt
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
from scipy import linalg
from qiskit.tools.qi.pauli import pauli_group, Pauli
from qiskit.tools.visualization import VisualizationError
from qiskit.tools.visualization._bloch import Bloch
class Arrow3D(FancyArrowPatch):
"""Standard 3D arrow."""
def __init__(self, xs, ys, zs, *args, **kwargs):
"""Create arrow."""
FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
self._verts3d = xs, ys, zs
def draw(self, renderer):
"""Draw the arrow."""
xs3d, ys3d, zs3d = self._verts3d
xs, ys, _ = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
FancyArrowPatch.draw(self, renderer)
def plot_bloch_vector(bloch, title="", filename=None):
"""Plot the Bloch sphere.
Plot a sphere, axes, the Bloch vector, and its projections onto each axis.
Args:
bloch (list[double]): array of three elements where [<x>, <y>,<z>]
title (str): a string that represents the plot title
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
"""
B = Bloch()
B.add_vectors(bloch)
if filename:
B.save(filename)
else:
B.show(title=title)
def plot_state_city(rho, title="", filename=None):
"""Plot the cityscape of quantum state.
Plot two 3d bargraphs (two dimensional) of the mixed state rho
Args:
rho (np.array[[complex]]): array of dimensions 2**n x 2**nn complex
numbers
title (str): a string that represents the plot title
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
"""
num = int(np.log2(len(rho)))
# get the real and imag parts of rho
datareal = np.real(rho)
dataimag = np.imag(rho)
# get the labels
column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
row_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
lx = len(datareal[0]) # Work out matrix dimensions
ly = len(datareal[:, 0])
xpos = np.arange(0, lx, 1) # Set up a mesh of positions
ypos = np.arange(0, ly, 1)
xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25)
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(lx*ly)
dx = 0.5 * np.ones_like(zpos) # width of bars
dy = dx.copy()
dzr = datareal.flatten()
dzi = dataimag.flatten()
fig = plt.figure(figsize=(8, 8))
ax1 = fig.add_subplot(2, 1, 1, projection='3d')
ax1.bar3d(xpos, ypos, zpos, dx, dy, dzr, color="g", alpha=0.5)
ax2 = fig.add_subplot(2, 1, 2, projection='3d')
ax2.bar3d(xpos, ypos, zpos, dx, dy, dzi, color="g", alpha=0.5)
ax1.set_xticks(np.arange(0.5, lx+0.5, 1))
ax1.set_yticks(np.arange(0.5, ly+0.5, 1))
ax1.axes.set_zlim3d(-1.0, 1.0001)
ax1.set_zticks(np.arange(-1, 1, 0.5))
ax1.w_xaxis.set_ticklabels(row_names, fontsize=12, rotation=45)
ax1.w_yaxis.set_ticklabels(column_names, fontsize=12, rotation=-22.5)
# ax1.set_xlabel('basis state', fontsize=12)
# ax1.set_ylabel('basis state', fontsize=12)
ax1.set_zlabel("Real[rho]")
ax2.set_xticks(np.arange(0.5, lx+0.5, 1))
ax2.set_yticks(np.arange(0.5, ly+0.5, 1))
ax2.axes.set_zlim3d(-1.0, 1.0001)
ax2.set_zticks(np.arange(-1, 1, 0.5))
ax2.w_xaxis.set_ticklabels(row_names, fontsize=12, rotation=45)
ax2.w_yaxis.set_ticklabels(column_names, fontsize=12, rotation=-22.5)
# ax2.set_xlabel('basis state', fontsize=12)
# ax2.set_ylabel('basis state', fontsize=12)
ax2.set_zlabel("Imag[rho]")
plt.title(title)
if filename:
plt.savefig(filename)
else:
plt.show()
def plot_state_paulivec(rho, title="", filename=None):
"""Plot the paulivec representation of a quantum state.
Plot a bargraph of the mixed state rho over the pauli matrices
Args:
rho (np.array[[complex]]): array of dimensions 2**n x 2**nn complex
numbers
title (str): a string that represents the plot title
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
"""
num = int(np.log2(len(rho)))
labels = list(map(lambda x: x.to_label(), pauli_group(num)))
values = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_group(num)))
numelem = len(values)
ind = np.arange(numelem) # the x locations for the groups
width = 0.5 # the width of the bars
_, ax = plt.subplots()
ax.grid(zorder=0)
ax.bar(ind, values, width, color='seagreen')
# add some text for labels, title, and axes ticks
ax.set_ylabel('Expectation value', fontsize=12)
ax.set_xticks(ind)
ax.set_yticks([-1, -0.5, 0, 0.5, 1])
ax.set_xticklabels(labels, fontsize=12, rotation=70)
ax.set_xlabel('Pauli', fontsize=12)
ax.set_ylim([-1, 1])
plt.title(title)
if filename:
plt.savefig(filename)
else:
plt.show()
def n_choose_k(n, k):
"""Return the number of combinations for n choose k.
Args:
n (int): the total number of options .
k (int): The number of elements.
Returns:
int: returns the binomial coefficient
"""
if n == 0:
return 0
return reduce(lambda x, y: x * y[0] / y[1],
zip(range(n - k + 1, n + 1),
range(1, k + 1)), 1)
def lex_index(n, k, lst):
"""Return the lex index of a combination..
Args:
n (int): the total number of options .
k (int): The number of elements.
lst (list): list
Returns:
int: returns int index for lex order
Raises:
VisualizationError: if length of list is not equal to k
"""
if len(lst) != k:
raise VisualizationError("list should have length k")
comb = list(map(lambda x: n - 1 - x, lst))
dualm = sum([n_choose_k(comb[k - 1 - i], i + 1) for i in range(k)])
return int(dualm)
def bit_string_index(s):
"""Return the index of a string of 0s and 1s."""
n = len(s)
k = s.count("1")
if s.count("0") != n - k:
raise VisualizationError("s must be a string of 0 and 1")
ones = [pos for pos, char in enumerate(s) if char == "1"]
return lex_index(n, k, ones)
def phase_to_color_wheel(complex_number):
"""Map a phase of a complexnumber to a color in (r,g,b).
complex_number is phase is first mapped to angle in the range
[0, 2pi] and then to a color wheel with blue at zero phase.
"""
angles = np.angle(complex_number)
angle_round = int(((angles + 2 * np.pi) % (2 * np.pi))/np.pi*6)
color_map = {
0: (0, 0, 1), # blue,
1: (0.5, 0, 1), # blue-violet
2: (1, 0, 1), # violet
3: (1, 0, 0.5), # red-violet,
4: (1, 0, 0), # red
5: (1, 0.5, 0), # red-oranage,
6: (1, 1, 0), # orange
7: (0.5, 1, 0), # orange-yellow
8: (0, 1, 0), # yellow,
9: (0, 1, 0.5), # yellow-green,
10: (0, 1, 1), # green,
11: (0, 0.5, 1) # green-blue,
}
return color_map[angle_round]
def plot_state_qsphere(rho, filename=None):
"""Plot the qsphere representation of a quantum state."""
num = int(np.log2(len(rho)))
# get the eigenvectors and eigenvalues
we, stateall = linalg.eigh(rho)
for k in range(2**num):
# start with the max
probmix = we.max()
prob_location = we.argmax()
if probmix > 0.001:
print("The " + str(k) + "th eigenvalue = " + str(probmix))
# get the max eigenvalue
state = stateall[:, prob_location]
loc = np.absolute(state).argmax()
# get the element location closes to lowest bin representation.
for j in range(2**num):
test = np.absolute(np.absolute(state[j]) -
np.absolute(state[loc]))
if test < 0.001:
loc = j
break
# remove the global phase
angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi)
angleset = np.exp(-1j*angles)
# print(state)
# print(angles)
state = angleset*state
# print(state)
state.flatten()
# start the plotting
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')
ax.axes.set_xlim3d(-1.0, 1.0)
ax.axes.set_ylim3d(-1.0, 1.0)
ax.axes.set_zlim3d(-1.0, 1.0)
ax.set_aspect("equal")
ax.axes.grid(False)
# Plot semi-transparent sphere
u = np.linspace(0, 2 * np.pi, 25)
v = np.linspace(0, np.pi, 25)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(x, y, z, rstride=1, cstride=1, color='k',
alpha=0.05, linewidth=0)
# wireframe
# Get rid of the panes
ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the spines
ax.w_xaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.w_yaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.w_zaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
d = num
for i in range(2**num):
# get x,y,z points
element = bin(i)[2:].zfill(num)
weight = element.count("1")
zvalue = -2 * weight / d + 1
number_of_divisions = n_choose_k(d, weight)
weight_order = bit_string_index(element)
# if weight_order >= number_of_divisions / 2:
# com_key = compliment(element)
# weight_order_temp = bit_string_index(com_key)
# weight_order = np.floor(
# number_of_divisions / 2) + weight_order_temp + 1
angle = weight_order * 2 * np.pi / number_of_divisions
xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle)
yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle)
ax.plot([xvalue], [yvalue], [zvalue],
markerfacecolor=(.5, .5, .5),
markeredgecolor=(.5, .5, .5),
marker='o', markersize=10, alpha=1)
# get prob and angle - prob will be shade and angle color
prob = np.real(np.dot(state[i], state[i].conj()))
colorstate = phase_to_color_wheel(state[i])
a = Arrow3D([0, xvalue], [0, yvalue], [0, zvalue],
mutation_scale=20, alpha=prob, arrowstyle="-",
color=colorstate, lw=10)
ax.add_artist(a)
# add weight lines
for weight in range(d + 1):
theta = np.linspace(-2 * np.pi, 2 * np.pi, 100)
z = -2 * weight / d + 1
r = np.sqrt(1 - z**2)
x = r * np.cos(theta)
y = r * np.sin(theta)
ax.plot(x, y, z, color=(.5, .5, .5))
# add center point
ax.plot([0], [0], [0], markerfacecolor=(.5, .5, .5),
markeredgecolor=(.5, .5, .5), marker='o', markersize=10,
alpha=1)
if filename:
plt.savefig(filename)
else:
plt.show()
we[prob_location] = 0
else:
break
def plot_state(quantum_state, method='city', filename=None):
"""Plot the quantum state.
Args:
quantum_state (ndarray): statevector or density matrix
representation of a quantum state.
method (str): Plotting method to use.
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window. If
`bloch` method is used a `-n` will be added to the filename before
the extension for each qubit.
Raises:
VisualizationError: if the input is not a statevector or density
matrix, or if the state is not an multi-qubit quantum state.
"""
# Check if input is a statevector, and convert to density matrix
rho = np.array(quantum_state)
if rho.ndim == 1:
rho = np.outer(rho, np.conj(rho))
# Check the shape of the input is a square matrix
shape = np.shape(rho)
if len(shape) != 2 or shape[0] != shape[1]:
raise VisualizationError("Input is not a valid quantum state.")
# Check state is an n-qubit state
num = int(np.log2(len(rho)))
if 2 ** num != len(rho):
raise VisualizationError("Input is not a multi-qubit quantum state.")
if method == 'city':
plot_state_city(rho, filename=filename)
elif method == "paulivec":
plot_state_paulivec(rho, filename=filename)
elif method == "qsphere":
plot_state_qsphere(rho, filename=filename)
elif method == "bloch":
orig_filename = filename
for i in range(num):
if orig_filename:
filename_parts = orig_filename.split('.')
filename_parts[-2] += '-%d' % i
filename = '.'.join(filename_parts)
print(filename)
pauli_singles = [Pauli.pauli_single(num, i, 'X'), Pauli.pauli_single(num, i, 'Y'),
Pauli.pauli_single(num, i, 'Z')]
bloch_state = list(
map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))), pauli_singles))
plot_bloch_vector(bloch_state, "qubit " + str(i), filename=filename)
elif method == "wigner":
plot_wigner_function(rho, filename=filename)
###############################################################
# Plotting Wigner functions
###############################################################
def plot_wigner_function(state, res=100, filename=None):
"""Plot the equal angle slice spin Wigner function of an arbitrary
quantum state.
Args:
state (np.matrix[[complex]]):
- Matrix of 2**n x 2**n complex numbers
- State Vector of 2**n x 1 complex numbers
res (int) : number of theta and phi values in meshgrid
on sphere (creates a res x res grid of points)
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
References:
[1] T. Tilma, M. J. Everitt, J. H. Samson, W. J. Munro,
and K. Nemoto, Phys. Rev. Lett. 117, 180401 (2016).
[2] R. P. Rundle, P. W. Mills, T. Tilma, J. H. Samson, and
M. J. Everitt, Phys. Rev. A 96, 022117 (2017).
"""
state = np.array(state)
if state.ndim == 1:
state = np.outer(state,
state) # turns state vector to a density matrix
state = np.matrix(state)
num = int(np.log2(len(state))) # number of qubits
phi_vals = np.linspace(0, np.pi, num=res,
dtype=np.complex_)
theta_vals = np.linspace(0, 0.5*np.pi, num=res,
dtype=np.complex_) # phi and theta values for WF
w = np.empty([res, res])
harr = np.sqrt(3)
delta_su2 = np.zeros((2, 2), dtype=np.complex_)
# create the spin Wigner function
for theta in range(res):
costheta = harr*np.cos(2*theta_vals[theta])
sintheta = harr*np.sin(2*theta_vals[theta])
for phi in range(res):
delta_su2[0, 0] = 0.5*(1+costheta)
delta_su2[0, 1] = -0.5*(np.exp(2j*phi_vals[phi])*sintheta)
delta_su2[1, 0] = -0.5*(np.exp(-2j*phi_vals[phi])*sintheta)
delta_su2[1, 1] = 0.5*(1-costheta)
kernel = 1
for _ in range(num):
kernel = np.kron(kernel,
delta_su2) # creates phase point kernel
w[phi, theta] = np.real(np.trace(state*kernel)) # Wigner function
# Plot a sphere (x,y,z) with Wigner function facecolor data stored in Wc
fig = plt.figure(figsize=(11, 9))
ax = fig.gca(projection='3d')
w_max = np.amax(w)
# Color data for plotting
w_c = cm.seismic_r((w+w_max)/(2*w_max)) # color data for sphere
w_c2 = cm.seismic_r((w[0:res, int(res/2):res]+w_max)/(2*w_max)) # bottom
w_c3 = cm.seismic_r((w[int(res/4):int(3*res/4), 0:res]+w_max) /
(2*w_max)) # side
w_c4 = cm.seismic_r((w[int(res/2):res, 0:res]+w_max)/(2*w_max)) # back
u = np.linspace(0, 2 * np.pi, res)
v = np.linspace(0, np.pi, res)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones(np.size(u)), np.cos(v)) # creates a sphere mesh
ax.plot_surface(x, y, z, facecolors=w_c,
vmin=-w_max, vmax=w_max,
rcount=res, ccount=res,
linewidth=0, zorder=0.5,
antialiased=False) # plots Wigner Bloch sphere
ax.plot_surface(x[0:res, int(res/2):res],
y[0:res, int(res/2):res],
-1.5*np.ones((res, int(res/2))),
facecolors=w_c2,
vmin=-w_max, vmax=w_max,
rcount=res/2, ccount=res/2,
linewidth=0, zorder=0.5,
antialiased=False) # plots bottom reflection
ax.plot_surface(-1.5*np.ones((int(res/2), res)),
y[int(res/4):int(3*res/4), 0:res],
z[int(res/4):int(3*res/4), 0:res],
facecolors=w_c3,
vmin=-w_max, vmax=w_max,
rcount=res/2, ccount=res/2,
linewidth=0, zorder=0.5,
antialiased=False) # plots side reflection
ax.plot_surface(x[int(res/2):res, 0:res],
1.5*np.ones((int(res/2), res)),
z[int(res/2):res, 0:res],
facecolors=w_c4,
vmin=-w_max, vmax=w_max,
rcount=res/2, ccount=res/2,
linewidth=0, zorder=0.5,
antialiased=False) # plots back reflection
ax.w_xaxis.set_pane_color((0.4, 0.4, 0.4, 1.0))
ax.w_yaxis.set_pane_color((0.4, 0.4, 0.4, 1.0))
ax.w_zaxis.set_pane_color((0.4, 0.4, 0.4, 1.0))
ax.set_xticks([], [])
ax.set_yticks([], [])
ax.set_zticks([], [])
ax.grid(False)
ax.xaxis.pane.set_edgecolor('black')
ax.yaxis.pane.set_edgecolor('black')
ax.zaxis.pane.set_edgecolor('black')
ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_zlim(-1.5, 1.5)
m = cm.ScalarMappable(cmap=cm.seismic_r)
m.set_array([-w_max, w_max])
plt.colorbar(m, shrink=0.5, aspect=10)
if filename:
plt.savefig(filename)
else:
plt.show()
def plot_wigner_curve(wigner_data, xaxis=None, filename=None):
"""Plots a curve for points in phase space of the spin Wigner function.
Args:
wigner_data(np.array): an array of points to plot as a 2d curve
xaxis (np.array): the range of the x axis
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
"""
if not xaxis:
xaxis = np.linspace(0, len(wigner_data)-1, num=len(wigner_data))
plt.plot(xaxis, wigner_data)
if filename:
plt.savefig(filename)
else:
plt.show()
def plot_wigner_plaquette(wigner_data, max_wigner='local', filename=None):
"""Plots plaquette of wigner function data, the plaquette will
consist of circles each colored to match the value of the Wigner
function at the given point in phase space.
Args:
wigner_data (matrix): array of Wigner function data where the
rows are plotted along the x axis and the
columns are plotted along the y axis
max_wigner (str or float):
- 'local' puts the maximum value to maximum of the points
- 'unit' sets maximum to 1
- float for a custom maximum.
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
"""
wigner_data = np.matrix(wigner_data)
dim = wigner_data.shape
if max_wigner == 'local':
w_max = np.amax(wigner_data)
elif max_wigner == 'unit':
w_max = 1
else:
w_max = max_wigner # For a float input
w_max = float(w_max)
cmap = plt.cm.get_cmap('seismic_r')
xax = dim[1]-0.5
yax = dim[0]-0.5
norm = np.amax(dim)
fig = plt.figure(figsize=((xax+0.5)*6/norm, (yax+0.5)*6/norm))
ax = fig.gca()
for x in range(int(dim[1])):
for y in range(int(dim[0])):
circle = plt.Circle(
(x, y), 0.49, color=cmap((wigner_data[y, x]+w_max)/(2*w_max)))
ax.add_artist(circle)
ax.set_xlim(-1, xax+0.5)
ax.set_ylim(-1, yax+0.5)
ax.set_xticks([], [])
ax.set_yticks([], [])
m = cm.ScalarMappable(cmap=cm.seismic_r)
m.set_array([-w_max, w_max])
plt.colorbar(m, shrink=0.5, aspect=10)
if filename:
plt.savefig(filename)
else:
plt.show()
def plot_wigner_data(wigner_data, phis=None, method=None, filename=None):
"""Plots Wigner results in appropriate format.
Args:
wigner_data (numpy.array): Output returned from the wigner_data
function
phis (numpy.array): Values of phi
method (str or None): how the data is to be plotted, methods are:
point: a single point in phase space
curve: a two dimensional curve
plaquette: points plotted as circles
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
"""
if not method:
wig_dim = len(np.shape(wigner_data))
if wig_dim == 1:
if np.shape(wigner_data) == 1:
method = 'point'
else:
method = 'curve'
elif wig_dim == 2:
method = 'plaquette'
if method == 'curve':
plot_wigner_curve(wigner_data, xaxis=phis, filename=filename)
elif method == 'plaquette':
plot_wigner_plaquette(wigner_data, filename=filename)
elif method == 'state':
plot_wigner_function(wigner_data, filename=filename)
elif method == 'point':
plot_wigner_plaquette(wigner_data, filename=filename)
print('point in phase space is '+str(wigner_data))
else:
print("No method given")
<|code_end|>
qiskit/tools/visualization/interactive/_iplot_blochsphere.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Bloch sphere visualization
"""
from string import Template
import sys
import time
import re
import numpy as np
from qiskit.tools.qi.pauli import Pauli
if ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
try:
from IPython.core.display import display, HTML
except ImportError:
print("Error importing IPython.core.display")
def iplot_blochsphere(rho, options=None):
""" Create a bloch sphere representation.
Graphical representation of the input array, using as much bloch
spheres as qubit are required.
Args:
rho (array): Density matrix
options (dict): Representation settings containing
- width (integer): graph horizontal size
- height (integer): graph vertical size
"""
# HTML
html_template = Template("""
<p>
<div id="content_$divNumber" style="position: absolute; z-index: 1;">
<div id="bloch_$divNumber"></div>
</div>
</p>
""")
# JavaScript
javascript_template = Template("""
<script>
requirejs.config({
paths: {
qVisualization: "https://qvisualization.mybluemix.net/q-visualizations"
}
});
data = $data;
dataValues = [];
for (var i = 0; i < data.length; i++) {
// Coordinates
var x = data[i][0];
var y = data[i][1];
var z = data[i][2];
var point = {'x': x,
'y': y,
'z': z};
dataValues.push(point);
}
require(["qVisualization"], function(qVisualizations) {
// Plot figure
qVisualizations.plotState("bloch_$divNumber",
"bloch",
dataValues,
$options);
});
</script>
""")
if not options:
options = {}
# Process data and execute
num = int(np.log2(len(rho)))
bloch_data = []
for i in range(num):
pauli_singles = [Pauli.pauli_single(num, i, 'X'), Pauli.pauli_single(num, i, 'Y'),
Pauli.pauli_single(num, i, 'Z')]
bloch_state = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_singles))
bloch_data.append(bloch_state)
div_number = str(time.time())
div_number = re.sub('[.]', '', div_number)
html = html_template.substitute({
'divNumber': div_number
})
javascript = javascript_template.substitute({
'data': bloch_data,
'divNumber': div_number,
'options': options
})
display(HTML(html + javascript))
<|code_end|>
|
os.errno doesn't exists anymore in Python 3.7
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: 0.6.1
- **Python version**: 3.7.0 − Jupyter Notebook
- **Operating system**: Ubuntu 16.04.1
### What is the current behavior?
I used circuit_drawer() on a Jupyter notebook without having latex installed on my computer, but instead of getting the message `WARNING: Unable to compile latex. Is `pdflatex` installed?`, I got the following error:
```
~/miniconda3/envs/qiskit/lib/python3.7/site-packages/qiskit/tools/visualization/_circuit_visualization.py in latex_circuit_drawer(circuit, basis, scale, filename, style)
292 check=True)
293 except OSError as e:
--> 294 if e.errno == os.errno.ENOENT:
295 logger.warning('WARNING: Unable to compile latex. '
296 'Is `pdflatex` installed? '
AttributeError: module 'os' has no attribute 'errno'
```
### Suggested solutions
Replacing `os.errno` by just `errno` (after having imported it). See for instance [this thread](https://bugs.python.org/issue33666) on the Python bug tracker
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import logging
import os
import subprocess
import tempfile
import warnings
from PIL import Image
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _latex
from qiskit.tools.visualization import _matplotlib
from qiskit.tools.visualization import _text
from qiskit.tools.visualization import _utils
from qiskit.transpiler import transpile_dag
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
im = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if im:
im.show()
def circuit_drawer(circuit,
basis=None,
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art TextDrawing that can be printed in the console.
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing. Defaults to
`"id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,cx,cy,cz,ch,crz,cu1,
cu3,swap,ccx,cswap"` This option is deprecated and will be removed
in the future.
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (TextDrawing): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if
one is not specified it will use latex and if that fails fallback
to mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect.
line_length (int): Sets the length of the lines generated by `text`
output type. This useful when the drawing does not fit in the
console. If None (default), it will try to guess the console width
using shutil.get_terminal_size(). If you don't want pagination at
all, set `line_length=-1`.
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: (output `latex`) an in-memory representation of the image
of the circuit diagram.
matplotlib.figure: (output `mpl`) a matplotlib figure object for the
circuit diagram.
String: (output `latex_source`). The LaTeX source code.
TextDrawing: (output `text`). A drawing that can be printed as ascii art
Raises:
VisualizationError: when an invalid output method is selected
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defaults to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'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'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
plotbarrier (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True. This is deprecated in the style dict
and will be removed in a future release. Use the `plot_barriers`
kwarg instead.
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
reversebits (bool): When set to True reverse the bit order inside
registers for the output visualization. This is deprecated in the
style dict and will be removed in a future release use the
`reverse_bits` kwarg instead.
"""
if basis is None:
basis = ("id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap")
else:
warnings.warn('The basis kwarg is deprecated and the circuit drawer '
'function will not be able to adjust basis gates itself '
'in a future release', DeprecationWarning)
im = None
if style:
if 'reversebits' in style:
warnings.warn('The reversebits key in style is deprecated and will'
'not work in the future. Instead use the '
'``reverse_bits`` kwarg.', DeprecationWarning)
reverse_bits = style.get('reversebits')
if 'plotbarrier' in style:
warnings.warn('The plotbarrier key in style is deprecated and will'
'not work in the future. Instead use the '
'``plot_barriers`` kwarg.', DeprecationWarning)
plot_barriers = style.get('plotbarrier')
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'"text" by default', DeprecationWarning)
try:
im = _latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError, FileNotFoundError):
im = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
else:
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename, basis=basis,
line_length=line_length,
reversebits=reverse_bits,
plotbarriers=plot_barriers)
elif output == 'latex':
im = _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'latex_source':
return _generate_latex_source(circuit, basis=basis,
filename=filename, scale=scale,
style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'mpl':
im = _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
else:
raise _error.VisualizationError(
'Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if im and interactive:
im.show()
return im
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap", line_length=None,
reversebits=False, plotbarriers=True):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
basis (str): Optional. Comma-separated list of gate names
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
reversebits (bool): Rearrange the bits in reverse order.
plotbarriers (bool): Draws the barriers when they are there.
Returns:
TextDrawing: An instances that, when printed, draws the circuit in ascii art.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
text_drawing = _text.TextDrawing(json_circuit, reversebits=reversebits)
text_drawing.plotbarriers = plotbarriers
text_drawing.line_length = line_length
if filename:
text_drawing.dump(filename)
return text_drawing
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
im = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as e:
with open('latex_error.log', 'wb') as error_file:
error_file.write(e.stdout)
logger.warning('WARNING Unable to compile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
im = Image.open(base + '.png')
im = _utils._trim(im)
os.remove(base + '.png')
if filename:
im.save(filename, 'PNG')
except OSError as e:
if e.errno == os.errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return im
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename, basis=basis,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None, reverse_bits=False,
plot_barriers=True):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
qcimg = _latex.QCircuitImage(json_circuit, scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,'
'ry,rz,cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,'
'cswap',
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
matplotlib.figure: a matplotlib figure object for the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = _matplotlib.MatplotlibDrawer(basis=basis, scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
<|code_end|>
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import errno
import logging
import os
import subprocess
import tempfile
import warnings
from PIL import Image
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _latex
from qiskit.tools.visualization import _matplotlib
from qiskit.tools.visualization import _text
from qiskit.tools.visualization import _utils
from qiskit.transpiler import transpile_dag
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)
Defaults to an overcomplete basis, in order to not alter gates.
"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
image = circuit_drawer(circuit, basis=basis, scale=scale, style=style)
if image:
image.show()
def circuit_drawer(circuit,
basis=None,
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art TextDrawing that can be printed in the console.
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
circuit (QuantumCircuit): the quantum circuit to draw
basis (str): the basis to unroll to prior to drawing. Defaults to
`"id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,cx,cy,cz,ch,crz,cu1,
cu3,swap,ccx,cswap"` This option is deprecated and will be removed
in the future.
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (TextDrawing): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if
one is not specified it will use latex and if that fails fallback
to mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect.
line_length (int): Sets the length of the lines generated by `text`
output type. This useful when the drawing does not fit in the
console. If None (default), it will try to guess the console width
using shutil.get_terminal_size(). If you don't want pagination at
all, set `line_length=-1`.
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: (output `latex`) an in-memory representation of the image
of the circuit diagram.
matplotlib.figure: (output `mpl`) a matplotlib figure object for the
circuit diagram.
String: (output `latex_source`). The LaTeX source code.
TextDrawing: (output `text`). A drawing that can be printed as ascii art
Raises:
VisualizationError: when an invalid output method is selected
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defaults to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'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'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
plotbarrier (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True. This is deprecated in the style dict
and will be removed in a future release. Use the `plot_barriers`
kwarg instead.
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
reversebits (bool): When set to True reverse the bit order inside
registers for the output visualization. This is deprecated in the
style dict and will be removed in a future release use the
`reverse_bits` kwarg instead.
"""
if basis is None:
basis = ("id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap")
else:
warnings.warn('The basis kwarg is deprecated and the circuit drawer '
'function will not be able to adjust basis gates itself '
'in a future release', DeprecationWarning)
image = None
if style:
if 'reversebits' in style:
warnings.warn('The reversebits key in style is deprecated and will'
'not work in the future. Instead use the '
'``reverse_bits`` kwarg.', DeprecationWarning)
reverse_bits = style.get('reversebits')
if 'plotbarrier' in style:
warnings.warn('The plotbarrier key in style is deprecated and will'
'not work in the future. Instead use the '
'``plot_barriers`` kwarg.', DeprecationWarning)
plot_barriers = style.get('plotbarrier')
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'"text" by default', DeprecationWarning)
try:
image = _latex_circuit_drawer(circuit, basis, scale, filename, style)
except (OSError, subprocess.CalledProcessError, FileNotFoundError):
image = _matplotlib_circuit_drawer(circuit, basis, scale, filename,
style)
else:
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename, basis=basis,
line_length=line_length,
reversebits=reverse_bits,
plotbarriers=plot_barriers)
elif output == 'latex':
image = _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'latex_source':
return _generate_latex_source(circuit, basis=basis,
filename=filename, scale=scale,
style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'mpl':
image = _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
else:
raise _error.VisualizationError(
'Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if image and interactive:
image.show()
return image
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
"""Return default style for matplotlib_circuit_drawer (IBM QX style)."""
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap", line_length=None,
reversebits=False, plotbarriers=True):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
basis (str): Optional. Comma-separated list of gate names
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
reversebits (bool): Rearrange the bits in reverse order.
plotbarriers (bool): Draws the barriers when they are there.
Returns:
TextDrawing: An instances that, when printed, draws the circuit in ascii art.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
text_drawing = _text.TextDrawing(json_circuit, reversebits=reversebits)
text_drawing.plotbarriers = plotbarriers
text_drawing.line_length = line_length
if filename:
text_drawing.dump(filename)
return text_drawing
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath, basis=basis,
scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
image = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as ex:
with open('latex_error.log', 'wb') as error_file:
error_file.write(ex.stdout)
logger.warning('WARNING Unable to compile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
image = Image.open(base + '.png')
image = _utils._trim(image)
os.remove(base + '.png')
if filename:
image.save(filename, 'PNG')
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return image
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename, basis=basis,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None, reverse_bits=False,
plot_barriers=True):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
str: Latex string appropriate for writing to file.
"""
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
qcimg = _latex.QCircuitImage(json_circuit, scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, basis=basis, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,'
'ry,rz,cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,'
'cswap',
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
matplotlib.figure: a matplotlib figure object for the circuit diagram
"""
if ',' not in basis:
logger.warning('Warning: basis is not comma separated: "%s". '
'Perhaps you set `filename` to `basis`.', basis)
qcd = _matplotlib.MatplotlibDrawer(basis=basis, scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
<|code_end|>
|
test.python.quantum_info.test_states.TestStates.test_random_state fails by returning nan
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: master
- **Python version**: any
- **Operating system**: any
### What is the current behavior?
Occasionally in CI we're encountering failures caused by `test.python.quantum_info.test_states.TestStates.test_random_state` generating `nan` instead of a value converged to `1/8`. For example see:
https://ci.appveyor.com/project/QISKit/qiskit-sdk-py/builds/20165445/job/r5t0rtgv445hcuqt#L927
```
test.python.quantum_info.test_states.TestStates.test_random_state
-----------------------------------------------------------------
Captured traceback:
~~~~~~~~~~~~~~~~~~~
b'Traceback (most recent call last):'
b' File "C:\\projects\\qiskit-sdk-py\\test\\python\\quantum_info\\test_states.py", line 90, in test_random_state'
b' self.assertAlmostEqual(E_P0, 1/8, places=2)'
b' File "C:\\Python35\\lib\\unittest\\case.py", line 877, in assertAlmostEqual'
b' raise self.failureException(msg)'
b'AssertionError: nan != 0.125 within 2 places'
b''
======
```
### Steps to reproduce the problem
It's occurring in CI occasionally, see the referenced failures.
### What is the expected behavior?
The test passes 100% of the time.
### Suggested solutions
Figure out the source of the failure (likely something with calling randint in the test) and fix it so that it always passes.
|
qiskit/quantum_info/states/_states.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string
"""
A collection of useful quantum information functions for states.
"""
import numpy as np
from qiskit import QISKitError
def basis_state(str_state, num):
"""
Return a basis state ndarray.
Args:
str_state (string): a string representing the state.
num (int): the number of qubits
Returns:
ndarray: state(2**num) a quantum state with basis basis state.
Raises:
QISKitError: if the dimensions is wrong
"""
n = int(str_state, 2)
if num >= len(str_state):
state = np.zeros(1 << num, dtype=complex)
state[n] = 1
return state
else:
raise QISKitError('size of bitstring is greater than num.')
def random_state(num):
"""
Return a random quantum state from the uniform (Haar) measure on
state space.
Args:
num (int): the number of qubits
Returns:
ndarray: state(2**num) a random quantum state.
"""
x = np.random.random(1 << num)+0.00000001
x = -np.log(x)
sumx = sum(x)
phases = np.random.random(1 << num)*2.0*np.pi
return np.sqrt(x/sumx)*np.exp(1j*phases)
def projector(state, flatten=False):
"""
maps a pure state to a state matrix
Args:
state (ndarray): the number of qubits
flatten (bool): determine if state matrix of column work
Returns:
ndarray: state_mat(2**num, 2**num) if flatten is false
ndarray: state_mat(4**num) if flatten is true stacked on by the column
"""
density_matrix = np.outer(state.conjugate(), state)
if flatten:
return density_matrix.flatten(order='F')
return density_matrix
<|code_end|>
|
qiskit/quantum_info/states/_states.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string
"""
A collection of useful quantum information functions for states.
"""
import numpy as np
from qiskit import QISKitError
def basis_state(str_state, num):
"""
Return a basis state ndarray.
Args:
str_state (string): a string representing the state.
num (int): the number of qubits
Returns:
ndarray: state(2**num) a quantum state with basis basis state.
Raises:
QISKitError: if the dimensions is wrong
"""
n = int(str_state, 2)
if num >= len(str_state):
state = np.zeros(1 << num, dtype=complex)
state[n] = 1
return state
else:
raise QISKitError('size of bitstring is greater than num.')
def random_state(num):
"""
Return a random quantum state from the uniform (Haar) measure on
state space.
Args:
num (int): the number of qubits
Returns:
ndarray: state(2**num) a random quantum state.
"""
# Random array over interval (0, 1]
x = np.random.random(1 << num)
x += x == 0
x = -np.log(x)
sumx = sum(x)
phases = np.random.random(1 << num)*2.0*np.pi
return np.sqrt(x/sumx)*np.exp(1j*phases)
def projector(state, flatten=False):
"""
maps a pure state to a state matrix
Args:
state (ndarray): the number of qubits
flatten (bool): determine if state matrix of column work
Returns:
ndarray: state_mat(2**num, 2**num) if flatten is false
ndarray: state_mat(4**num) if flatten is true stacked on by the column
"""
density_matrix = np.outer(state.conjugate(), state)
if flatten:
return density_matrix.flatten(order='F')
return density_matrix
<|code_end|>
|
latex_source visualizer should not use transpiler(format='json')
We are going to remove the option `format='json'` from the transpiler (see #1129). For that, we need to move the visualizers into the function `get_instractions` introduced in PR #1187.
The function `_generate_latex_source` calls `transpile_dag(dag_circuit, basis_gates=basis, format='json')`. This needs to be removed in favor of `_utils.get_instructions(dag)`.
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# TODO(mtreinish): Remove after 0.7 and the deprecated methods are removed
# pylint: disable=unused-argument
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import errno
import logging
import os
import subprocess
import tempfile
import warnings
from PIL import Image
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _latex
from qiskit.tools.visualization import _text
from qiskit.tools.visualization import _utils
from qiskit.transpiler import transpile_dag
from qiskit.tools.visualization import _matplotlib
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
image = circuit_drawer(circuit, scale=scale, style=style)
if image:
image.show()
def circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art TextDrawing that can be printed in the console.
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Args:
circuit (QuantumCircuit): the quantum circuit to draw
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (TextDrawing): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if
one is not specified it will use latex and if that fails fallback
to mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect.
line_length (int): Sets the length of the lines generated by `text`
output type. This useful when the drawing does not fit in the
console. If None (default), it will try to guess the console width
using shutil.get_terminal_size(). If you don't want pagination at
all, set `line_length=-1`.
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: (output `latex`) an in-memory representation of the image
of the circuit diagram.
matplotlib.figure: (output `mpl`) a matplotlib figure object for the
circuit diagram.
String: (output `latex_source`). The LaTeX source code.
TextDrawing: (output `text`). A drawing that can be printed as ascii art
Raises:
VisualizationError: when an invalid output method is selected
ImportError: when the output methods requieres non-installed libraries.
.. _style-dict-doc:
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defaults to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'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'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
plotbarrier (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True. This is deprecated in the style dict
and will be removed in a future release. Use the `plot_barriers`
kwarg instead.
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
reversebits (bool): When set to True reverse the bit order inside
registers for the output visualization. This is deprecated in the
style dict and will be removed in a future release use the
`reverse_bits` kwarg instead.
"""
image = None
if style:
if 'reversebits' in style:
warnings.warn('The reversebits key in style is deprecated and will'
'not work in the future. Instead use the '
'``reverse_bits`` kwarg.', DeprecationWarning)
reverse_bits = style.get('reversebits')
if 'plotbarrier' in style:
warnings.warn('The plotbarrier key in style is deprecated and will'
'not work in the future. Instead use the '
'``plot_barriers`` kwarg.', DeprecationWarning)
plot_barriers = style.get('plotbarrier')
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'"text" by default', DeprecationWarning)
try:
image = _latex_circuit_drawer(circuit, scale, filename, style)
except (OSError, subprocess.CalledProcessError, FileNotFoundError):
if _matplotlib.HAS_MATPLOTLIB:
image = _matplotlib_circuit_drawer(circuit, scale, filename,
style)
else:
raise ImportError('The default output needs matplotlib. '
'Run "pip install matplotlib" before.')
else:
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename,
line_length=line_length,
reversebits=reverse_bits,
plotbarriers=plot_barriers)
elif output == 'latex':
image = _latex_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'latex_source':
return _generate_latex_source(circuit,
filename=filename, scale=scale,
style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'mpl':
image = _matplotlib_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
else:
raise _error.VisualizationError(
'Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if image and interactive:
image.show()
return image
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
"""Return default style for matplotlib_circuit_drawer (IBM QX style)."""
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None, line_length=None, reversebits=False,
plotbarriers=True):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
reversebits (bool): Rearrange the bits in reverse order.
plotbarriers (bool): Draws the barriers when they are there.
Returns:
TextDrawing: An instances that, when printed, draws the circuit in ascii art.
"""
qregs, cregs, ops = _utils._get_instructions(circuit, reversebits=reversebits)
text_drawing = _text.TextDrawing(qregs, cregs, ops)
text_drawing.plotbarriers = plotbarriers
text_drawing.line_length = line_length
if filename:
text_drawing.dump(filename)
return text_drawing
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath,
scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
image = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as ex:
with open('latex_error.log', 'wb') as error_file:
error_file.write(ex.stdout)
logger.warning('WARNING Unable to compile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
image = Image.open(base + '.png')
image = _utils._trim(image)
os.remove(base + '.png')
if filename:
image.save(filename, 'PNG')
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return image
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
scale=0.7, style=None, reverse_bits=False,
plot_barriers=True):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
str: Latex string appropriate for writing to file.
"""
basis = ("id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap")
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
qcimg = _latex.QCircuitImage(json_circuit, scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
matplotlib.figure: a matplotlib figure object for the circuit diagram
"""
qcd = _matplotlib.MatplotlibDrawer(scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
<|code_end|>
qiskit/tools/visualization/_latex.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""latex circuit visualization backends."""
import collections
import io
import itertools
import json
import math
import operator
import re
import numpy as np
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _qcstyle
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, circuit, scale, style=None, plot_barriers=True,
reverse_bits=False):
"""
Args:
circuit (dict): compiled_circuit from qobj
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
"""
# style sheet
self._style = _qcstyle.QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.circuit = circuit
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
self.reverse_bits = reverse_bits
self.plot_barriers = plot_barriers
#################################
self.header = self.circuit['header']
self.qregs = collections.OrderedDict(_get_register_specs(
self.header['qubit_labels']))
self.qubit_list = []
for qr in self.qregs:
for i in range(self.qregs[qr]):
self.qubit_list.append((qr, i))
self.cregs = collections.OrderedDict()
if 'clbit_labels' in self.header:
for item in self.header['clbit_labels']:
self.cregs[item[0]] = item[1]
self.clbit_list = []
cregs = self.cregs
if self.reverse_bits:
self.orig_cregs = self.cregs
cregs = reversed(self.cregs)
for cr in cregs:
for i in range(self.cregs[cr]):
self.clbit_list.append((cr, i))
self.ordered_regs = [(item[0], item[1]) for
item in self.header['qubit_labels']]
if self.reverse_bits:
reg_size = []
reg_labels = []
new_ordered_regs = []
for regs in self.ordered_regs:
if regs[0] in reg_labels:
continue
reg_labels.append(regs[0])
reg_size.append(len(
[x for x in self.ordered_regs if x[0] == regs[0]]))
index = 0
for size in reg_size:
new_index = index + size
for i in range(new_index - 1, index - 1, -1):
new_ordered_regs.append(self.ordered_regs[i])
index = new_index
self.ordered_regs = new_ordered_regs
if 'clbit_labels' in self.header:
for clabel in self.header['clbit_labels']:
if self.reverse_bits:
for cind in reversed(range(clabel[1])):
self.ordered_regs.append((clabel[0], cind))
else:
for cind in range(clabel[1]):
self.ordered_regs.append((clabel[0], cind))
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = io.StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\' + '\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
VisualizationError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.circuit['instructions']:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's',
'sdg', 't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy',
'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image
# scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self.reverse_bits:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self.reverse_bits:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self.reverse_bits:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['texparams']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float, arg)
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
if len(op['clbits']) != 1 or len(op['qubits']) != 1:
raise _error.VisualizationError("bad operation record")
if 'conditional' in op:
raise _error.VisualizationError(
'conditional measures currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise _error.VisualizationError(
'conditional reset currently not supported.')
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
raise _error.VisualizationError("bad node data")
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns + 1, math.ceil(sum_column_widths) + 4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet
# (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above
example, index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _convert_mask(self, mask):
orig_clbit_list = []
for cr in self.orig_cregs:
for i in range(self.orig_cregs[cr]):
orig_clbit_list.append((cr, i))
bit_list = [(mask >> bit) & 1 for bit in range(
len(orig_clbit_list) - 1, -1, -1)]
converted_mask_list = [None] * len(bit_list)
converted_mask = 0
for pos, bit in enumerate(reversed(bit_list)):
new_pos = self.clbit_list.index(orig_clbit_list[pos])
converted_mask_list[new_pos] = bit
if None in converted_mask_list:
raise _error.VisualizationError('Reverse mask creation failed')
converted_mask_list = list(reversed(converted_mask_list))
for bit in converted_mask_list:
converted_mask = (converted_mask << 1) | bit
return converted_mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.circuit['instructions']):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self.reverse_bits:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier', 'snapshot', 'load',
'save', 'noise']:
nm = op['name']
qarglist = [self.qubit_list[i] for i in op['qubits']]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
if self.reverse_bits:
mask = self._convert_mask(mask)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["texparams"][0],
op["texparams"][1],
op["texparams"][2]))
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["texparams"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["texparams"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["texparams"][0], op["texparams"][1])
elif nm == "u3":
self._latex[pos_1][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["texparams"][0],
op["texparams"][1],
op["texparams"][2]))
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["texparams"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["texparams"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["texparams"][0])
elif nm == "reset":
self._latex[pos_1][columns] = (
"\\push{\\rule{.6em}{0em}\\ket{0}\\"
"rule{.2em}{0em}} \\qw")
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["texparams"][0],
op["texparams"][1],
op["texparams"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["texparams"][0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["texparams"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["texparams"][0],
op["texparams"][1],
op["texparams"][2]))
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-0.65em]{')
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(
pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-0.65em]{')
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(
pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
if (len(op['clbits']) != 1
or len(op['qubits']) != 1
or 'params' in op):
raise _error.VisualizationError("bad operation record")
if 'conditional' in op:
raise _error.VisualizationError(
"If controlled measures currently not supported.")
qname, qindex = self.total_2_register_index(
op['qubits'][0], self.qregs)
cname, cindex = self.total_2_register_index(
op['clbits'][0], self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise _error.VisualizationError(
'Error during Latex building: %s' % str(e))
elif op['name'] in ["barrier", 'snapshot', 'load', 'save',
'noise']:
if self.plot_barriers:
qarglist = [self.qubit_list[i] for i in op['qubits']]
if self.reverse_bits:
qarglist = list(reversed(qarglist))
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qubits']) - 1
self._latex[start][columns] += " \\barrier{" + str(
span) + "}"
else:
raise _error.VisualizationError("bad node data")
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
if self.reverse_bits:
return origin + 1
return origin - 1
def _get_register_specs(bit_labels):
"""Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = itertools.groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
<|code_end|>
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# TODO(mtreinish): Remove after 0.7 and the deprecated methods are removed
# pylint: disable=unused-argument
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import errno
import logging
import os
import subprocess
import tempfile
import warnings
from PIL import Image
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _latex
from qiskit.tools.visualization import _text
from qiskit.tools.visualization import _utils
from qiskit.tools.visualization import _matplotlib
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
image = circuit_drawer(circuit, scale=scale, style=style)
if image:
image.show()
def circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art TextDrawing that can be printed in the console.
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Args:
circuit (QuantumCircuit): the quantum circuit to draw
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (TextDrawing): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if
one is not specified it will use latex and if that fails fallback
to mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect.
line_length (int): Sets the length of the lines generated by `text`
output type. This useful when the drawing does not fit in the
console. If None (default), it will try to guess the console width
using shutil.get_terminal_size(). If you don't want pagination at
all, set `line_length=-1`.
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: (output `latex`) an in-memory representation of the image
of the circuit diagram.
matplotlib.figure: (output `mpl`) a matplotlib figure object for the
circuit diagram.
String: (output `latex_source`). The LaTeX source code.
TextDrawing: (output `text`). A drawing that can be printed as ascii art
Raises:
VisualizationError: when an invalid output method is selected
ImportError: when the output methods requieres non-installed libraries.
.. _style-dict-doc:
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defaults to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'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'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
plotbarrier (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True. This is deprecated in the style dict
and will be removed in a future release. Use the `plot_barriers`
kwarg instead.
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
reversebits (bool): When set to True reverse the bit order inside
registers for the output visualization. This is deprecated in the
style dict and will be removed in a future release use the
`reverse_bits` kwarg instead.
"""
image = None
if style:
if 'reversebits' in style:
warnings.warn('The reversebits key in style is deprecated and will'
'not work in the future. Instead use the '
'``reverse_bits`` kwarg.', DeprecationWarning)
reverse_bits = style.get('reversebits')
if 'plotbarrier' in style:
warnings.warn('The plotbarrier key in style is deprecated and will'
'not work in the future. Instead use the '
'``plot_barriers`` kwarg.', DeprecationWarning)
plot_barriers = style.get('plotbarrier')
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'"text" by default', DeprecationWarning)
try:
image = _latex_circuit_drawer(circuit, scale, filename, style)
except (OSError, subprocess.CalledProcessError, FileNotFoundError):
if _matplotlib.HAS_MATPLOTLIB:
image = _matplotlib_circuit_drawer(circuit, scale, filename,
style)
else:
raise ImportError('The default output needs matplotlib. '
'Run "pip install matplotlib" before.')
else:
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename,
line_length=line_length,
reversebits=reverse_bits,
plotbarriers=plot_barriers)
elif output == 'latex':
image = _latex_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'latex_source':
return _generate_latex_source(circuit,
filename=filename, scale=scale,
style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'mpl':
image = _matplotlib_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
else:
raise _error.VisualizationError(
'Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if image and interactive:
image.show()
return image
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
"""Return default style for matplotlib_circuit_drawer (IBM QX style)."""
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None, line_length=None, reversebits=False,
plotbarriers=True):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
reversebits (bool): Rearrange the bits in reverse order.
plotbarriers (bool): Draws the barriers when they are there.
Returns:
TextDrawing: An instances that, when printed, draws the circuit in ascii art.
"""
qregs, cregs, ops = _utils._get_instructions(circuit, reversebits=reversebits)
text_drawing = _text.TextDrawing(qregs, cregs, ops)
text_drawing.plotbarriers = plotbarriers
text_drawing.line_length = line_length
if filename:
text_drawing.dump(filename)
return text_drawing
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath,
scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
image = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as ex:
with open('latex_error.log', 'wb') as error_file:
error_file.write(ex.stdout)
logger.warning('WARNING Unable to compile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
image = Image.open(base + '.png')
image = _utils._trim(image)
os.remove(base + '.png')
if filename:
image.save(filename, 'PNG')
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return image
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
scale=0.7, style=None, reverse_bits=False,
plot_barriers=True):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
str: Latex string appropriate for writing to file.
"""
qregs, cregs, ops = _utils._get_instructions(circuit,
reversebits=reverse_bits)
qcimg = _latex.QCircuitImage(qregs, cregs, ops, scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
matplotlib.figure: a matplotlib figure object for the circuit diagram
"""
qcd = _matplotlib.MatplotlibDrawer(scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
<|code_end|>
qiskit/tools/visualization/_latex.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""latex circuit visualization backends."""
import collections
import io
import itertools
import json
import math
import operator
import re
import numpy as np
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _qcstyle
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, qregs, cregs, ops, scale, style=None,
plot_barriers=True, reverse_bits=False):
"""
Args:
qregs (list): A list of tuples for the quantum registers
cregs (list): A list of tuples for the classical registers
ops (list): A list of dicts where each entry is a operation from
the circuit.
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
"""
# style sheet
self._style = _qcstyle.QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.ops = ops
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
self.reverse_bits = reverse_bits
self.plot_barriers = plot_barriers
#################################
self.qregs = collections.OrderedDict(_get_register_specs(qregs))
self.qubit_list = qregs
self.ordered_regs = qregs + cregs
self.cregs = collections.OrderedDict(_get_register_specs(cregs))
self.clbit_list = cregs
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = io.StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\' + '\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
VisualizationError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.ops:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's',
'sdg', 't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy',
'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image
# scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['params']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float, str(arg))
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
if len(op['cargs']) != 1 or len(op['qargs']) != 1:
raise _error.VisualizationError("bad operation record")
if 'conditional' in op:
raise _error.VisualizationError(
'conditional measures currently not supported.')
qindex = self._get_qubit_index(op['qargs'][0])
cindex = self._get_clbit_index(op['cargs'][0])
qname, qindex = self.total_2_register_index(
qindex, self.qregs)
cname, cindex = self.total_2_register_index(
cindex, self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise _error.VisualizationError(
'conditional reset currently not supported.')
qindex = self._get_qubit_index(op['qargs'][0])
qname, qindex = self.total_2_register_index(
qindex, self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
raise _error.VisualizationError("bad node data")
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns + 1, math.ceil(sum_column_widths) + 4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet
# (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def _get_qubit_index(self, qubit):
"""Get the index number for a quantum bit
Args:
qubit (tuple): The tuple of the bit of the form
(register_name, bit_number)
Returns:
int: The index in the bit list
Raises:
VisualizationError: If the bit isn't found
"""
for i, bit in enumerate(self.qubit_list):
if qubit == bit:
qindex = i
break
else:
raise _error.VisualizationError(
"unable to find bit for operation")
return qindex
def _get_clbit_index(self, clbit):
"""Get the index number for a classical bit
Args:
clbit (tuple): The tuple of the bit of the form
(register_name, bit_number)
Returns:
int: The index in the bit list
Raises:
VisualizationError: If the bit isn't found
"""
for i, bit in enumerate(self.clbit_list):
if clbit == bit:
cindex = i
break
else:
raise _error.VisualizationError(
"unable to find bit for operation")
return cindex
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above
example, index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.ops):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier', 'snapshot', 'load',
'save', 'noise']:
nm = op['name']
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["params"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["params"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["params"][0], op["params"][1])
elif nm == "u3":
self._latex[pos_1][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["params"][0],
op["params"][1],
op["params"][2]))
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["params"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["params"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["params"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["params"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["params"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["params"][0], op["params"][1])
elif nm == "u3":
self._latex[pos_1][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["params"][0],
op["params"][1],
op["params"][2]))
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["params"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["params"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["params"][0])
elif nm == "reset":
self._latex[pos_1][columns] = (
"\\push{\\rule{.6em}{0em}\\ket{0}\\"
"rule{.2em}{0em}} \\qw")
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["params"][0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["params"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["params"][0],
op["params"][1],
op["params"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["params"][0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["params"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["params"][0],
op["params"][1],
op["params"][2]))
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-0.65em]{')
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(
pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-0.65em]{')
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(
pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
if (len(op['cargs']) != 1
or len(op['qargs']) != 1
or op['params']):
raise _error.VisualizationError("bad operation record")
if 'conditional' in op:
raise _error.VisualizationError(
"If controlled measures currently not supported.")
qindex = self._get_qubit_index(op['qargs'][0])
cindex = self._get_clbit_index(op['cargs'][0])
qname, qindex = self.total_2_register_index(
qindex, self.qregs)
cname, cindex = self.total_2_register_index(
cindex, self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise _error.VisualizationError(
'Error during Latex building: %s' % str(e))
elif op['name'] in ["barrier", 'snapshot', 'load', 'save',
'noise']:
if self.plot_barriers:
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qargs']) - 1
self._latex[start][columns] += " \\barrier{" + str(
span) + "}"
else:
raise _error.VisualizationError("bad node data")
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
return origin - 1
def _get_register_specs(bit_labels):
"""Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = itertools.groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
<|code_end|>
|
matplotlib visualizer should not use transpiler(format='json')
We are going to remove the option `format='json'` from the transpiler (see #1129). For that, we need to move the visualizers into the function `get_instractions` introduced in PR #1187.
The file `qiskit/tools/visualization//_matplotlib.py` calls `transpiler.transpile_dag(dag_circuit, basis_gates=self._basis, format='json')`. This needs to be removed in favor of `_utils.get_instructions`.
|
qiskit/tools/visualization/_matplotlib.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""mpl circuit visualization backend."""
import collections
import fractions
import itertools
import json
import logging
import math
import numpy as np
try:
from matplotlib import patches
from matplotlib import pyplot as plt
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
from qiskit import dagcircuit
from qiskit import transpiler
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _qcstyle
logger = logging.getLogger(__name__)
Register = collections.namedtuple('Register', 'name index')
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
scale=1.0, style=None, plot_barriers=True,
reverse_bits=False):
if not HAS_MATPLOTLIB:
raise ImportError('The class MatplotlibDrawer needs matplotlib. '
'Run "pip install matplotlib" before.')
self._ast = None
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = collections.OrderedDict()
self._creg_dict = collections.OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = _qcstyle.QCStyle()
self.plot_barriers = plot_barriers
self.reverse_bits = reverse_bits
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False,
labelleft=False, labelright=False)
def parse_circuit(self, circuit):
dag_circuit = dagcircuit.DAGCircuit.fromQuantumCircuit(
circuit, expand_gates=False)
basis = ("id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap")
self._ast = transpiler.transpile_dag(dag_circuit,
basis_gates=basis,
format='json')
self._registers()
self._ops = self._ast['instructions']
def _registers(self):
# NOTE: formats of clbit and qubit are different!
header = self._ast['header']
self._creg = []
for e in header['clbit_labels']:
for i in range(e[1]):
self._creg.append(Register(name=e[0], index=i))
if len(self._creg) != header['number_of_clbits']:
raise _error.VisualizationError('internal error')
self._qreg = []
for e in header['qubit_labels']:
self._qreg.append(Register(name=e[0], index=e[1]))
if len(self._qreg) != header['number_of_qubits']:
raise _error.VisualizationError('internal error')
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(
xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center',
va='center', fontsize=self._style.fs,
color=self._style.gt, clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.sc, clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7,
height=HIG * 0.7, theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID],
[qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy + 0.35 * WID], lc=self._style.cc,
ls=self._style.cline)
arrowhead = patches.Polygon(((cx - 0.20 * WID, cy + 0.35 * WID),
(cx + 0.20 * WID, cy + 0.35 * WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'],
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
plt.close(self.figure)
return self.figure
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(itertools.zip_longest(
self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
self._cond['n_lines'] += 1
idx += 1
# reverse bit order
if self.reverse_bits:
self._reverse_bits(self._qreg_dict)
self._reverse_bits(self._creg_dict)
def _reverse_bits(self, target_dict):
coord = {}
# grouping
for dict_ in target_dict.values():
if dict_['group'] not in coord:
coord[dict_['group']] = [dict_['y']]
else:
coord[dict_['group']].insert(0, dict_['y'])
# reverse bit order
for key in target_dict.keys():
target_dict[key]['y'] = coord[target_dict[key]['group']].pop(0)
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left',
va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc,
ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(
itertools.zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qubits' in op.keys():
q_idxs = op['qubits']
else:
q_idxs = []
# get creg index
if 'clbits' in op.keys():
c_idxs = op['clbits']
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied),
max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(
this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] in [
'barrier', 'snapshot', 'load', 'save',
'noise'] and not self.plot_barriers:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg coordinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for
ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc,
ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] in ['barrier', 'snapshot', 'load', 'save',
'noise']:
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self.plot_barriers:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise _error.VisualizationError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (
self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.tc, clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if math.isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if math.isclose(math.fmod(abs_val, 1.0),
0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
if 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if math.isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return fractions.Fraction(i, j)
return None
<|code_end|>
|
qiskit/tools/visualization/_matplotlib.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""mpl circuit visualization backend."""
import collections
import fractions
import itertools
import json
import logging
import math
import numpy as np
try:
from matplotlib import patches
from matplotlib import pyplot as plt
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _qcstyle
from qiskit.tools.visualization import _utils
logger = logging.getLogger(__name__)
Register = collections.namedtuple('Register', 'name index')
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
scale=1.0, style=None, plot_barriers=True,
reverse_bits=False):
if not HAS_MATPLOTLIB:
raise ImportError('The class MatplotlibDrawer needs matplotlib. '
'Run "pip install matplotlib" before.')
self._ast = None
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = collections.OrderedDict()
self._creg_dict = collections.OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = _qcstyle.QCStyle()
self.plot_barriers = plot_barriers
self.reverse_bits = reverse_bits
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False,
labelleft=False, labelright=False)
def parse_circuit(self, circuit):
qregs, cregs, ops = _utils._get_instructions(
circuit, reversebits=self.reverse_bits)
self._registers(cregs, qregs)
self._ops = ops
def _registers(self, creg, qreg):
# NOTE: formats of clbit and qubit are different!
self._creg = []
for e in creg:
self._creg.append(Register(name=e[0], index=e[1]))
self._qreg = []
for e in qreg:
self._qreg.append(Register(name=e[0], index=e[1]))
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(
xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center',
va='center', fontsize=self._style.fs,
color=self._style.gt, clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.sc, clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7,
height=HIG * 0.7, theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID],
[qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy + 0.35 * WID], lc=self._style.cc,
ls=self._style.cline)
arrowhead = patches.Polygon(((cx - 0.20 * WID, cy + 0.35 * WID),
(cx + 0.20 * WID, cy + 0.35 * WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'],
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
plt.close(self.figure)
return self.figure
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(itertools.zip_longest(
self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
self._cond['n_lines'] += 1
idx += 1
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left',
va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc,
ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(
itertools.zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qargs' in op.keys():
q_idxs = []
for qarg in op['qargs']:
for index, reg in self._qreg_dict.items():
if (reg['group'] == qarg[0] and
reg['index'] == qarg[1]):
q_idxs.append(index)
break
else:
q_idxs = []
# get creg index
if 'cargs' in op.keys():
c_idxs = []
for carg in op['cargs']:
for index, reg in self._creg_dict.items():
if (reg['group'] == carg[0] and
reg['index'] == carg[1]):
c_idxs.append(index)
break
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied),
max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(
this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] in [
'barrier', 'snapshot', 'load', 'save',
'noise'] and not self.plot_barriers:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg coordinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for
ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc,
ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] in ['barrier', 'snapshot', 'load', 'save',
'noise']:
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self.plot_barriers:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise _error.VisualizationError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (
self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.tc, clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if math.isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if math.isclose(math.fmod(abs_val, 1.0),
0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
if 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if math.isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return fractions.Fraction(i, j)
return None
<|code_end|>
|
text visualizer should not use transpiler(format='json')
We are going to remove the option `format='json'` from the transpiler (see #1129). For that, we need to move the visualizers into the function `get_instractions` introduced in PR #1187.
The function `_text_circuit_drawer` calls `transpile_dag(dag_circuit, basis_gates=basis, format='json')`. This needs to be removed in favor of `_utils.get_instructions(dag)`.
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# TODO(mtreinish): Remove after 0.7 and the deprecated methods are removed
# pylint: disable=unused-argument
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import errno
import logging
import os
import subprocess
import tempfile
import warnings
from PIL import Image
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _latex
from qiskit.tools.visualization import _text
from qiskit.tools.visualization import _utils
from qiskit.transpiler import transpile_dag
from qiskit.tools.visualization import _matplotlib
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
image = circuit_drawer(circuit, scale=scale, style=style)
if image:
image.show()
def circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art TextDrawing that can be printed in the console.
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Args:
circuit (QuantumCircuit): the quantum circuit to draw
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (TextDrawing): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if
one is not specified it will use latex and if that fails fallback
to mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect.
line_length (int): Sets the length of the lines generated by `text`
output type. This useful when the drawing does not fit in the
console. If None (default), it will try to guess the console width
using shutil.get_terminal_size(). If you don't want pagination at
all, set `line_length=-1`.
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: (output `latex`) an in-memory representation of the image
of the circuit diagram.
matplotlib.figure: (output `mpl`) a matplotlib figure object for the
circuit diagram.
String: (output `latex_source`). The LaTeX source code.
TextDrawing: (output `text`). A drawing that can be printed as ascii art
Raises:
VisualizationError: when an invalid output method is selected
ImportError: when the output methods requieres non-installed libraries.
.. _style-dict-doc:
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defaults to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'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'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
plotbarrier (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True. This is deprecated in the style dict
and will be removed in a future release. Use the `plot_barriers`
kwarg instead.
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
reversebits (bool): When set to True reverse the bit order inside
registers for the output visualization. This is deprecated in the
style dict and will be removed in a future release use the
`reverse_bits` kwarg instead.
"""
image = None
if style:
if 'reversebits' in style:
warnings.warn('The reversebits key in style is deprecated and will'
'not work in the future. Instead use the '
'``reverse_bits`` kwarg.', DeprecationWarning)
reverse_bits = style.get('reversebits')
if 'plotbarrier' in style:
warnings.warn('The plotbarrier key in style is deprecated and will'
'not work in the future. Instead use the '
'``plot_barriers`` kwarg.', DeprecationWarning)
plot_barriers = style.get('plotbarrier')
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'"text" by default', DeprecationWarning)
try:
image = _latex_circuit_drawer(circuit, scale, filename, style)
except (OSError, subprocess.CalledProcessError, FileNotFoundError):
if _matplotlib.HAS_MATPLOTLIB:
image = _matplotlib_circuit_drawer(circuit, scale, filename,
style)
else:
raise ImportError('The default output needs matplotlib. '
'Run "pip install matplotlib" before.')
else:
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename,
line_length=line_length,
reversebits=reverse_bits,
plotbarriers=plot_barriers)
elif output == 'latex':
image = _latex_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'latex_source':
return _generate_latex_source(circuit,
filename=filename, scale=scale,
style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'mpl':
image = _matplotlib_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
else:
raise _error.VisualizationError(
'Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if image and interactive:
image.show()
return image
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
"""Return default style for matplotlib_circuit_drawer (IBM QX style)."""
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None,
line_length=None, reversebits=False,
plotbarriers=True):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
reversebits (bool): Rearrange the bits in reverse order.
plotbarriers (bool): Draws the barriers when they are there.
Returns:
TextDrawing: An instances that, when printed, draws the circuit in ascii art.
"""
basis = ("id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap")
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
text_drawing = _text.TextDrawing(json_circuit, reversebits=reversebits)
text_drawing.plotbarriers = plotbarriers
text_drawing.line_length = line_length
if filename:
text_drawing.dump(filename)
return text_drawing
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath,
scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
image = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as ex:
with open('latex_error.log', 'wb') as error_file:
error_file.write(ex.stdout)
logger.warning('WARNING Unable to compile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
image = Image.open(base + '.png')
image = _utils._trim(image)
os.remove(base + '.png')
if filename:
image.save(filename, 'PNG')
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return image
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
scale=0.7, style=None, reverse_bits=False,
plot_barriers=True):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
str: Latex string appropriate for writing to file.
"""
basis = ("id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap")
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
qcimg = _latex.QCircuitImage(json_circuit, scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
matplotlib.figure: a matplotlib figure object for the circuit diagram
"""
qcd = _matplotlib.MatplotlibDrawer(scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
<|code_end|>
qiskit/tools/visualization/_text.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A module for drawing circuits in ascii art or some other text representation
"""
from itertools import groupby
from shutil import get_terminal_size
from ._error import VisualizationError
class DrawElement():
""" An element is an instruction or an operation that need to be drawn."""
def __init__(self, label=None):
self._width = None
self.label = self.mid_content = label
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = self.bot_connect = " "
self.top_pad = self._mid_padding = self.bot_pad = " "
self.bot_connector = {}
self.top_connector = {}
self.right_fill = self.left_fill = 0
@property
def top(self):
""" Constructs the top line of the element"""
ret = self.top_format % self.top_connect.center(
self.width - self.left_fill - self.right_fill, self.top_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.top_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.top_pad)
return ret
@property
def mid(self):
""" Constructs the middle line of the element"""
ret = self.mid_format % self.mid_content.center(
self.width - self.left_fill - self.right_fill, self._mid_padding)
if self.right_fill:
ret = ret.ljust(self.right_fill, self._mid_padding)
if self.left_fill:
ret = ret.rjust(self.left_fill, self._mid_padding)
return ret
@property
def bot(self):
""" Constructs the bottom line of the element"""
ret = self.bot_format % self.bot_connect.center(
self.width - self.left_fill - self.right_fill, self.bot_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.bot_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.bot_pad)
return ret
@property
def length(self):
""" Returns the length of the element, including the box around."""
return max(len(self.top), len(self.mid), len(self.bot))
@length.setter
def length(self, value):
""" Adjusts width so the length fits."""
self.width = value - max(
[len(getattr(self, i) % '') for i in ["bot_format", "mid_format", "top_format"]])
@property
def width(self):
""" Returns the width of the label, including padding"""
if self._width:
return self._width
return len(self.mid_content)
@width.setter
def width(self, value):
self._width = value
def connect(self, wire_char, where, label=None):
"""
Connects boxes and elements using wire_char and setting proper connectors.
Args:
wire_char (char): For example '║' or '│'.
where (list["top", "bot"]): Where the connector should be set.
label (string): Some connectors have a label (see cu1, for example).
"""
if 'top' in where and self.top_connector:
self.top_connect = self.top_connector[wire_char]
if 'bot' in where and self.bot_connector:
self.bot_connect = self.bot_connector[wire_char]
if label:
self.top_format = self.top_format[:-1] + (label if label else "")
class BoxOnClWire(DrawElement):
""" Draws a box on the classical wire
top: ┌───┐ ┌───────┐
mid: ╡ A ╞ ╡ A ╞
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "╡ %s ╞"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
class BoxOnQuWire(DrawElement):
""" Draws a box on the quantum wire
top: ┌───┐ ┌───────┐
mid: ┤ A ├ ┤ A ├
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "┤ %s ├"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
self.top_connector = {"│": '┴'}
self.bot_connector = {"│": '┬'}
class MeasureTo(DrawElement):
""" The element on the classic wire to which the measure is performed
top: ║ ║
mid: ═╩═ ═══╩═══
bot:
"""
def __init__(self):
super().__init__()
self.top_connect = " ║ "
self.mid_content = "═╩═"
self.bot_connect = " "
self._mid_padding = "═"
class MeasureFrom(BoxOnQuWire):
""" The element on the quantum wire in which the measure is performed
top: ┌─┐ ┌─┐
mid: ┤M├ ───┤M├───
bot: └╥┘ └╥┘
"""
def __init__(self):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = "┌─┐"
self.mid_content = "┤M├"
self.bot_connect = "└╥┘"
class MultiBox(DrawElement):
"""Elements that is draw on over multiple wires."""
def center_label(self, input_length, order):
"""
In multi-bit elements, the label is centered vertically.
Args:
input_length (int): Rhe amount of wires affected.
order (int): Which middle element is this one?
"""
location_in_the_box = '*'.center(input_length * 2 - 1).index('*') + 1
top_limit = (order - 1) * 2 + 2
bot_limit = top_limit + 2
if top_limit <= location_in_the_box < bot_limit:
if location_in_the_box == top_limit:
self.top_connect = self.label
elif location_in_the_box == top_limit + 1:
self.mid_content = self.label
else:
self.bot_connect = self.label
class BoxOnQuWireTop(MultiBox, BoxOnQuWire):
""" Draws the top part of a box that affects more than one quantum wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnQuWireMid(MultiBox, BoxOnQuWire):
""" Draws the middle part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.center_label(input_length, order)
class BoxOnQuWireBot(MultiBox, BoxOnQuWire):
""" Draws the bottom part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length):
super().__init__(label)
self.top_format = "│ %s │"
self.mid_content = self.bot_connect = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class BoxOnClWireTop(MultiBox, BoxOnClWire):
""" Draws the top part of a conditional box that affects more than one classical wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnClWireMid(MultiBox, BoxOnClWire):
""" Draws the middle part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.mid_content = label
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.top_pad = self.bot_pad = ' '
self.top_connect = self.bot_connect = self.mid_content = ''
self.center_label(input_length, order)
class BoxOnClWireBot(MultiBox, BoxOnClWire):
""" Draws the bottom part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, bot_connect='─'):
super().__init__(label)
self.top_format = "│ %s │"
self.top_pad = " "
self.bot_connect = bot_connect
self.mid_content = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class DirectOnQuWire(DrawElement):
"""
Element to the wire (without the box).
"""
def __init__(self, label=""):
super().__init__(label)
self.top_format = ' %s '
self.mid_format = '─%s─'
self.bot_format = ' %s '
self._mid_padding = '─'
self.top_connector = {"│": '│'}
self.bot_connector = {"│": '│'}
class Barrier(DirectOnQuWire):
""" Draws a barrier.
top: ░ ░
mid: ─░─ ───░───
bot: ░ ░
"""
def __init__(self, label=""):
super().__init__("░")
self.top_connect = "░"
self.bot_connect = "░"
self.top_connector = {}
self.bot_connector = {}
class Ex(DirectOnQuWire):
""" Draws an X (usually with a connector). E.g. the top part of a swap gate
top:
mid: ─X─ ───X───
bot: │ │
"""
def __init__(self, bot_connect=" ", top_connect=" "):
super().__init__("X")
self.bot_connect = bot_connect
self.top_connect = top_connect
class Reset(DirectOnQuWire):
""" Draws a reset gate"""
def __init__(self):
super().__init__("|0>")
class Bullet(DirectOnQuWire):
""" Draws a bullet (usually with a connector). E.g. the top part of a CX gate.
top:
mid: ─■─ ───■───
bot: │ │
"""
def __init__(self, top_connect=" ", bot_connect=" "):
super().__init__('■')
self.top_connect = top_connect
self.bot_connect = bot_connect
class EmptyWire(DrawElement):
""" This element is just the wire, with no instructions nor operations."""
def __init__(self, wire):
super().__init__(wire)
self._mid_padding = wire
@staticmethod
def fillup_layer(layer, first_clbit):
"""
Given a layer, replace the Nones in it with EmptyWire elements.
Args:
layer (list): The layer that contains Nones.
first_clbit (int): The first wire that is classic.
Returns:
list: The new layer, with no Nones.
"""
for nones in [i for i, x in enumerate(layer) if x is None]:
layer[nones] = EmptyWire('═') if nones >= first_clbit else EmptyWire('─')
return layer
class BreakWire(DrawElement):
""" This element is used to break the drawing in several pages."""
def __init__(self, arrow_char):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = arrow_char
self.mid_content = arrow_char
self.bot_connect = arrow_char
@staticmethod
def fillup_layer(layer_length, arrow_char):
"""
Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer.
"""
breakwire_layer = []
for _ in range(layer_length):
breakwire_layer.append(BreakWire(arrow_char))
return breakwire_layer
class InputWire(DrawElement):
""" This element is the label and the initial value of a wire."""
def __init__(self, label):
super().__init__(label)
@staticmethod
def fillup_layer(names): # pylint: disable=arguments-differ
"""
Creates a layer with InputWire elements.
Args:
names (list): List of names for the wires.
Returns:
list: The new layer
"""
longest = max([len(name) for name in names])
inputs_wires = []
for name in names:
inputs_wires.append(InputWire(name.rjust(longest)))
return inputs_wires
class TextDrawing():
""" The text drawing"""
def __init__(self, json_circuit, reversebits=False, plotbarriers=True, line_length=None):
self.json_circuit = json_circuit
self.reversebits = reversebits
self.plotbarriers = plotbarriers
self.line_length = line_length
self.qubitorder = self._get_qubitorder()
self.clbitorder = self._get_clbitorder()
def __str__(self):
return self.single_string()
def _repr_html_(self):
return '<pre style="line-height: 15px;">%s</pre>' % self.single_string()
def _get_qubit_labels(self):
qubits = []
for qubit in self.json_circuit['header']['qubit_labels']:
qubits.append("%s_%s" % (qubit[0], qubit[1]))
return qubits
def _get_clbit_labels(self):
clbits = []
for creg in self.json_circuit['header']['clbit_labels']:
for clbit in range(creg[1]):
clbits.append("%s_%s" % (creg[0], clbit))
return clbits
def _get_qubitorder(self):
header = self.json_circuit['header']
if not self.reversebits:
return [qub for qub in range(header['number_of_qubits'])]
qreg_dest_order = []
for _, qubits in groupby(header['qubit_labels'], lambda x: x[0]):
qubits = [qubit for qubit in qubits]
qubits.reverse()
for qubit in qubits:
qreg_dest_order.append("%s_%s" % (qubit[0], qubit[1]))
return [qreg_dest_order.index(ind) for ind in self._get_qubit_labels()]
def _get_clbitorder(self):
header = self.json_circuit['header']
if not self.reversebits:
return [clb for clb in range(header['number_of_clbits'])]
creg_dest_order = []
for creg in self.json_circuit['header']['clbit_labels']:
bit_nos = [bit for bit in range(creg[1])]
bit_nos.reverse()
for clbit in bit_nos:
creg_dest_order.append("%s_%s" % (creg[0], clbit))
return [creg_dest_order.index(ind) for ind in self._get_clbit_labels()]
def single_string(self):
"""
Creates a loong string with the ascii art
Returns:
str: The lines joined by '\n'
"""
return "\n".join(self.lines())
def dump(self, filename, encoding="utf8"):
"""
Dumps the ascii art in the file.
Args:
filename (str): File to dump the ascii art.
encoding (str): Optional. Default "utf-8".
"""
with open(filename, mode='w', encoding=encoding) as text_file:
text_file.write(self.single_string())
def lines(self, line_length=None):
"""
Generates a list with lines. These lines form the text drawing.
Args:
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
Returns:
list: A list of lines with the text drawing.
"""
if line_length is None:
line_length = self.line_length
if line_length is None:
line_length, _ = get_terminal_size()
noqubits = self.json_circuit['header']['number_of_qubits']
layers = self.build_layers()
# TODO compress layers
# -| H |----------
# --------| H |---
# should be
# -| H |---
# -| H |---
if not line_length:
line_length = self.line_length
layer_groups = [[]]
rest_of_the_line = line_length
for layerno, layer in enumerate(layers):
# Replace the Nones with EmptyWire
layers[layerno] = EmptyWire.fillup_layer(layer, noqubits)
TextDrawing.normalize_width(layer)
if line_length == -1:
# Do not use pagination (aka line breaking. aka ignore line_length).
layer_groups[-1].append(layer)
continue
# chop the layer to the line_length (pager)
layer_length = layers[layerno][0].length
if layer_length < rest_of_the_line:
layer_groups[-1].append(layer)
rest_of_the_line -= layer_length
else:
layer_groups[-1].append(BreakWire.fillup_layer(len(layer), '»'))
# New group
layer_groups.append([BreakWire.fillup_layer(len(layer), '«')])
rest_of_the_line = line_length - layer_groups[-1][-1][0].length
layer_groups[-1].append(
InputWire.fillup_layer(self.wire_names(with_initial_value=False)))
rest_of_the_line -= layer_groups[-1][-1][0].length
layer_groups[-1].append(layer)
rest_of_the_line -= layer_groups[-1][-1][0].length
lines = []
for layer_group in layer_groups:
wires = [i for i in zip(*layer_group)]
lines += TextDrawing.draw_wires(wires)
return lines
def wire_names(self, with_initial_value=True):
"""
Returns a list of names for each wire.
Args:
with_initial_value (bool): Optional (Default: True). If true, adds the initial value to
the name.
Returns:
List: The list of wire names.
"""
qubit_labels = self._get_qubit_labels()
clbit_labels = self._get_clbit_labels()
if with_initial_value:
qubit_labels = ['%s: |0>' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: 0 ' % clbit for clbit in clbit_labels]
else:
qubit_labels = ['%s: ' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: ' % clbit for clbit in clbit_labels]
qubit_wires = [None] * self.json_circuit['header']['number_of_qubits']
clbit_wires = [None] * self.json_circuit['header']['number_of_clbits']
for order, label in enumerate(qubit_labels):
qubit_wires[self.qubitorder[order]] = label
for order, label in enumerate(clbit_labels):
clbit_wires[self.clbitorder[order]] = label
return qubit_wires + clbit_wires
@staticmethod
def draw_wires(wires):
"""
Given a list of wires, creates a list of lines with the text drawing.
Args:
wires (list): A list of wires with instructions.
Returns:
list: A list of lines with the text drawing.
"""
lines = []
bot_line = None
for wire in wires:
# TOP
top_line = ""
for instruction in wire:
top_line += instruction.top
if bot_line is None:
lines.append(top_line)
else:
lines.append(TextDrawing.merge_lines(lines.pop(), top_line))
# MID
mid_line = ""
for instruction in wire:
mid_line += instruction.mid
lines.append(TextDrawing.merge_lines(lines[-1], mid_line, icod="bot"))
# BOT
bot_line = ""
for instruction in wire:
bot_line += instruction.bot
lines.append(TextDrawing.merge_lines(lines[-1], bot_line, icod="bot"))
return lines
@staticmethod
def label_for_conditional(instruction):
""" Creates the label for a conditional instruction."""
return "%s %s" % ('=', instruction['conditional']['val'])
@staticmethod
def params_for_label(instruction):
"""Get the params and format them to add them to a label. None of there is no param."""
if 'params' in instruction and instruction['params']:
return ['%.5g' % i for i in instruction['params']]
return None
@staticmethod
def label_for_box(instruction):
""" Creates the label for a box."""
label = instruction['name'].capitalize()
params = TextDrawing.params_for_label(instruction)
if params:
label += "(%s)" % ','.join(params)
return label
@staticmethod
def merge_lines(top, bot, icod="top"):
"""
Merges two lines (top and bot) in the way that the overlapping make senses.
Args:
top (str): the top line
bot (str): the bottom line
icod (top or bot): in case of doubt, which line should have priority? Default: "top".
Returns:
str: The merge of both lines.
"""
ret = ""
for topc, botc in zip(top, bot):
if topc == botc:
ret += topc
elif topc in '┼╪' and botc == " ":
ret += "│"
elif topc == " ":
ret += botc
elif topc in '┬╥' and botc in " ║│":
ret += topc
elif topc in '┬│' and botc == "═":
ret += '╪'
elif topc in '┬│' and botc == "─":
ret += '┼'
elif topc in '└┘║│░' and botc == " ":
ret += topc
elif topc in '─═' and botc == " " and icod == "top":
ret += topc
elif topc in '─═' and botc == " " and icod == "bot":
ret += botc
elif topc in "║╥" and botc in "═":
ret += "╬"
elif topc in "║╥" and botc in "─":
ret += "╫"
elif topc in '╫╬' and botc in " ":
ret += "║"
elif topc == '└' and botc == "┌":
ret += "├"
elif topc == '┘' and botc == "┐":
ret += "┤"
else:
ret += botc
return ret
def clbit_index_from_mask(self, mask):
"""
Given a mask, returns a list of classical indexes affected by that mask.
Args:
mask (int): The mask.
Returns:
list: A list of indexes affected by the mask.
"""
clbit_len = self.json_circuit['header']['number_of_clbits']
bit_mask = [bool(mask & (1 << n)) for n in range(clbit_len)]
return [i for i, x in enumerate(bit_mask) if x]
@staticmethod
def normalize_width(layer):
"""
When the elements of the layer have different widths, sets the width to the max elements.
Args:
layer (list): A list of elements.
"""
instructions = [instruction for instruction in filter(lambda x: x is not None, layer)]
longest = max([instruction.length for instruction in instructions])
for instruction in instructions:
instruction.length = longest
def build_layers(self):
"""
Constructs layers.
Returns:
list: List of DrawElements.
Raises:
VisualizationError: When the drawing is, for some reason, impossible to be drawn.
"""
layers = []
layers.append(InputWire.fillup_layer(self.wire_names(with_initial_value=True)))
for instruction in self.json_circuit['instructions']:
layer = Layer(self.qubitorder, self.clbitorder)
connector_label = None
if instruction['name'] == 'measure':
layer.set_qubit(instruction['qubits'][0], MeasureFrom())
layer.set_clbit(instruction['clbits'][0], MeasureTo())
elif instruction['name'] in ['barrier', 'snapshot', 'save', 'load',
'noise']:
# barrier
if not self.plotbarriers:
continue
for qubit in instruction['qubits']:
layer.set_qubit(qubit, Barrier())
elif instruction['name'] == 'swap':
# swap
for qubit in instruction['qubits']:
layer.set_qubit(qubit, Ex())
elif instruction['name'] == 'cswap':
# cswap
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Ex())
layer.set_qubit(instruction['qubits'][2], Ex())
elif instruction['name'] == 'reset':
layer.set_qubit(instruction['qubits'][0], Reset())
elif 'conditional' in instruction:
# conditional
clbits = self.clbit_index_from_mask(int(instruction['conditional']['mask'], 16))
cllabel = TextDrawing.label_for_conditional(instruction)
qulabel = TextDrawing.label_for_box(instruction)
layer.set_cl_multibox(clbits, cllabel, top_connect='┴')
layer.set_qubit(instruction['qubits'][0], BoxOnQuWire(qulabel, bot_connect='┬'))
elif instruction['name'] in ['cx', 'CX', 'ccx']:
# cx/ccx
for qubit in [qubit for qubit in instruction['qubits'][:-1]]:
layer.set_qubit(qubit, Bullet())
layer.set_qubit(instruction['qubits'][-1], BoxOnQuWire('X'))
elif instruction['name'] == 'cy':
# cy
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], BoxOnQuWire('Y'))
elif instruction['name'] == 'cz':
# cz
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Bullet())
elif instruction['name'] == 'ch':
# ch
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], BoxOnQuWire('H'))
elif instruction['name'] == 'cu1':
# cu1
connector_label = TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1], Bullet())
elif instruction['name'] == 'cu3':
# cu3
params = TextDrawing.params_for_label(instruction)
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1],
BoxOnQuWire("U3(%s)" % ','.join(params)))
elif instruction['name'] == 'crz':
# crz
label = "Rz(%s)" % TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qubits'][0], Bullet())
layer.set_qubit(instruction['qubits'][1],
BoxOnQuWire(label))
elif len(instruction['qubits']) == 1 and 'clbits' not in instruction:
# unitary gate
layer.set_qubit(instruction['qubits'][0],
BoxOnQuWire(TextDrawing.label_for_box(instruction)))
elif len(instruction['qubits']) >= 2 and 'clbits' not in instruction:
# multiple qubit gate
layer.set_qu_multibox(instruction['qubits'], TextDrawing.label_for_box(instruction))
else:
raise VisualizationError(
"Text visualizer does not know how to handle this instruction", instruction)
layer.connect_with("│", connector_label)
layers.append(layer.full_layer)
return layers
class Layer:
""" A layer is the "column" of the circuit. """
def __init__(self, qubitorder, clbitorder):
self.qubitorder = qubitorder
self.clbitorder = clbitorder
self.qubit_layer = [None] * len(qubitorder)
self.clbit_layer = [None] * len(clbitorder)
@property
def full_layer(self):
"""
Returns the composition of qubits and classic wires.
Returns:
String: self.qubit_layer + self.clbit_layer
"""
return self.qubit_layer + self.clbit_layer
def set_qubit(self, qubit, element):
"""
Sets the qubit to the element
Args:
qubit (int): Qubit index.
element (DrawElement): Element to set in the qubit
"""
self.qubit_layer[self.qubitorder[qubit]] = element
def set_clbit(self, clbit, element):
"""
Sets the clbit to the element
Args:
clbit (int): Clbit index.
element (DrawElement): Element to set in the clbit
"""
self.clbit_layer[self.clbitorder[clbit]] = element
def _set_multibox(self, wire_type, bits, label, top_connect=None):
# pylint: disable=invalid-name
bits = sorted(bits)
if wire_type == "cl":
set_bit = self.set_clbit
BoxOnWire = BoxOnClWire
BoxOnWireTop = BoxOnClWireTop
BoxOnWireMid = BoxOnClWireMid
BoxOnWireBot = BoxOnClWireBot
elif wire_type == "qu":
set_bit = self.set_qubit
BoxOnWire = BoxOnQuWire
BoxOnWireTop = BoxOnQuWireTop
BoxOnWireMid = BoxOnQuWireMid
BoxOnWireBot = BoxOnQuWireBot
# Checks if qubits are consecutive
if bits != [i for i in range(bits[0], bits[-1] + 1)]:
raise VisualizationError("Text visualizaer does know how to build a gate with multiple"
"bits when they are not adjacent to each other")
if len(bits) == 1:
set_bit(bits[0], BoxOnWire(label, top_connect=top_connect))
else:
set_bit(bits[0], BoxOnWireTop(label, top_connect=top_connect))
for order, bit in enumerate(bits[1:-1], 1):
set_bit(bit, BoxOnWireMid(label, len(bits), order))
set_bit(bits[-1], BoxOnWireBot(label, len(bits)))
def set_cl_multibox(self, bits, label, top_connect='┴'):
"""
Sets the multi clbit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi clbit box.
top_connect (char): The char to connect the box on the top.
"""
self._set_multibox("cl", bits, label, top_connect=top_connect)
def set_qu_multibox(self, bits, label):
"""
Sets the multi qubit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi qubit box.
"""
self._set_multibox("qu", bits, label)
def connect_with(self, wire_char, label=None):
"""
Connects the elements in the layer using wire_char.
Args:
wire_char (char): For example '║' or '│'.
label (string): Some connectors have a label (see cu1, for example).
"""
affected_bits = [bit for bit in self.full_layer if bit is not None]
if len([qbit for qbit in self.qubit_layer if qbit is not None]) == 1:
# Nothing to connect
return
affected_bits[0].connect(wire_char, ['bot'])
for affected_bit in affected_bits[1:-1]:
affected_bit.connect(wire_char, ['bot', 'top'])
affected_bits[-1].connect(wire_char, ['top'], label)
if label:
for affected_bit in affected_bits:
affected_bit.right_fill = len(label) + len(affected_bit.mid)
<|code_end|>
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# TODO(mtreinish): Remove after 0.7 and the deprecated methods are removed
# pylint: disable=unused-argument
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import errno
import logging
import os
import subprocess
import tempfile
import warnings
from PIL import Image
from qiskit.dagcircuit import DAGCircuit
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _latex
from qiskit.tools.visualization import _text
from qiskit.tools.visualization import _utils
from qiskit.transpiler import transpile_dag
from qiskit.tools.visualization import _matplotlib
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
image = circuit_drawer(circuit, scale=scale, style=style)
if image:
image.show()
def circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art TextDrawing that can be printed in the console.
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Args:
circuit (QuantumCircuit): the quantum circuit to draw
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (TextDrawing): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if
one is not specified it will use latex and if that fails fallback
to mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect.
line_length (int): Sets the length of the lines generated by `text`
output type. This useful when the drawing does not fit in the
console. If None (default), it will try to guess the console width
using shutil.get_terminal_size(). If you don't want pagination at
all, set `line_length=-1`.
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: (output `latex`) an in-memory representation of the image
of the circuit diagram.
matplotlib.figure: (output `mpl`) a matplotlib figure object for the
circuit diagram.
String: (output `latex_source`). The LaTeX source code.
TextDrawing: (output `text`). A drawing that can be printed as ascii art
Raises:
VisualizationError: when an invalid output method is selected
ImportError: when the output methods requieres non-installed libraries.
.. _style-dict-doc:
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defaults to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'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'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
plotbarrier (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True. This is deprecated in the style dict
and will be removed in a future release. Use the `plot_barriers`
kwarg instead.
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
reversebits (bool): When set to True reverse the bit order inside
registers for the output visualization. This is deprecated in the
style dict and will be removed in a future release use the
`reverse_bits` kwarg instead.
"""
image = None
if style:
if 'reversebits' in style:
warnings.warn('The reversebits key in style is deprecated and will'
'not work in the future. Instead use the '
'``reverse_bits`` kwarg.', DeprecationWarning)
reverse_bits = style.get('reversebits')
if 'plotbarrier' in style:
warnings.warn('The plotbarrier key in style is deprecated and will'
'not work in the future. Instead use the '
'``plot_barriers`` kwarg.', DeprecationWarning)
plot_barriers = style.get('plotbarrier')
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'"text" by default', DeprecationWarning)
try:
image = _latex_circuit_drawer(circuit, scale, filename, style)
except (OSError, subprocess.CalledProcessError, FileNotFoundError):
if _matplotlib.HAS_MATPLOTLIB:
image = _matplotlib_circuit_drawer(circuit, scale, filename,
style)
else:
raise ImportError('The default output needs matplotlib. '
'Run "pip install matplotlib" before.')
else:
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename,
line_length=line_length,
reversebits=reverse_bits,
plotbarriers=plot_barriers)
elif output == 'latex':
image = _latex_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'latex_source':
return _generate_latex_source(circuit,
filename=filename, scale=scale,
style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'mpl':
image = _matplotlib_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
else:
raise _error.VisualizationError(
'Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if image and interactive:
image.show()
return image
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
"""Return default style for matplotlib_circuit_drawer (IBM QX style)."""
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None, line_length=None, reversebits=False,
plotbarriers=True):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
reversebits (bool): Rearrange the bits in reverse order.
plotbarriers (bool): Draws the barriers when they are there.
Returns:
TextDrawing: An instances that, when printed, draws the circuit in ascii art.
"""
qregs, cregs, ops = _utils._get_instructions(circuit, reversebits=reversebits)
text_drawing = _text.TextDrawing(qregs, cregs, ops)
text_drawing.plotbarriers = plotbarriers
text_drawing.line_length = line_length
if filename:
text_drawing.dump(filename)
return text_drawing
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath,
scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
image = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as ex:
with open('latex_error.log', 'wb') as error_file:
error_file.write(ex.stdout)
logger.warning('WARNING Unable to compile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
image = Image.open(base + '.png')
image = _utils._trim(image)
os.remove(base + '.png')
if filename:
image.save(filename, 'PNG')
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return image
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
scale=0.7, style=None, reverse_bits=False,
plot_barriers=True):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
str: Latex string appropriate for writing to file.
"""
basis = ("id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap")
dag_circuit = DAGCircuit.fromQuantumCircuit(circuit, expand_gates=False)
json_circuit = transpile_dag(dag_circuit, basis_gates=basis, format='json')
qcimg = _latex.QCircuitImage(json_circuit, scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
matplotlib.figure: a matplotlib figure object for the circuit diagram
"""
qcd = _matplotlib.MatplotlibDrawer(scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
<|code_end|>
qiskit/tools/visualization/_text.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A module for drawing circuits in ascii art or some other text representation
"""
from shutil import get_terminal_size
from ._error import VisualizationError
class DrawElement():
""" An element is an instruction or an operation that need to be drawn."""
def __init__(self, label=None):
self._width = None
self.label = self.mid_content = label
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = self.bot_connect = " "
self.top_pad = self._mid_padding = self.bot_pad = " "
self.bot_connector = {}
self.top_connector = {}
self.right_fill = self.left_fill = 0
@property
def top(self):
""" Constructs the top line of the element"""
ret = self.top_format % self.top_connect.center(
self.width - self.left_fill - self.right_fill, self.top_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.top_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.top_pad)
return ret
@property
def mid(self):
""" Constructs the middle line of the element"""
ret = self.mid_format % self.mid_content.center(
self.width - self.left_fill - self.right_fill, self._mid_padding)
if self.right_fill:
ret = ret.ljust(self.right_fill, self._mid_padding)
if self.left_fill:
ret = ret.rjust(self.left_fill, self._mid_padding)
return ret
@property
def bot(self):
""" Constructs the bottom line of the element"""
ret = self.bot_format % self.bot_connect.center(
self.width - self.left_fill - self.right_fill, self.bot_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.bot_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.bot_pad)
return ret
@property
def length(self):
""" Returns the length of the element, including the box around."""
return max(len(self.top), len(self.mid), len(self.bot))
@length.setter
def length(self, value):
""" Adjusts width so the length fits."""
self.width = value - max(
[len(getattr(self, i) % '') for i in ["bot_format", "mid_format", "top_format"]])
@property
def width(self):
""" Returns the width of the label, including padding"""
if self._width:
return self._width
return len(self.mid_content)
@width.setter
def width(self, value):
self._width = value
def connect(self, wire_char, where, label=None):
"""
Connects boxes and elements using wire_char and setting proper connectors.
Args:
wire_char (char): For example '║' or '│'.
where (list["top", "bot"]): Where the connector should be set.
label (string): Some connectors have a label (see cu1, for example).
"""
if 'top' in where and self.top_connector:
self.top_connect = self.top_connector[wire_char]
if 'bot' in where and self.bot_connector:
self.bot_connect = self.bot_connector[wire_char]
if label:
self.top_format = self.top_format[:-1] + (label if label else "")
class BoxOnClWire(DrawElement):
""" Draws a box on the classical wire
top: ┌───┐ ┌───────┐
mid: ╡ A ╞ ╡ A ╞
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "╡ %s ╞"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
class BoxOnQuWire(DrawElement):
""" Draws a box on the quantum wire
top: ┌───┐ ┌───────┐
mid: ┤ A ├ ┤ A ├
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "┤ %s ├"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
self.top_connector = {"│": '┴'}
self.bot_connector = {"│": '┬'}
class MeasureTo(DrawElement):
""" The element on the classic wire to which the measure is performed
top: ║ ║
mid: ═╩═ ═══╩═══
bot:
"""
def __init__(self):
super().__init__()
self.top_connect = " ║ "
self.mid_content = "═╩═"
self.bot_connect = " "
self._mid_padding = "═"
class MeasureFrom(BoxOnQuWire):
""" The element on the quantum wire in which the measure is performed
top: ┌─┐ ┌─┐
mid: ┤M├ ───┤M├───
bot: └╥┘ └╥┘
"""
def __init__(self):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = "┌─┐"
self.mid_content = "┤M├"
self.bot_connect = "└╥┘"
class MultiBox(DrawElement):
"""Elements that is draw on over multiple wires."""
def center_label(self, input_length, order):
"""
In multi-bit elements, the label is centered vertically.
Args:
input_length (int): Rhe amount of wires affected.
order (int): Which middle element is this one?
"""
location_in_the_box = '*'.center(input_length * 2 - 1).index('*') + 1
top_limit = (order - 1) * 2 + 2
bot_limit = top_limit + 2
if top_limit <= location_in_the_box < bot_limit:
if location_in_the_box == top_limit:
self.top_connect = self.label
elif location_in_the_box == top_limit + 1:
self.mid_content = self.label
else:
self.bot_connect = self.label
class BoxOnQuWireTop(MultiBox, BoxOnQuWire):
""" Draws the top part of a box that affects more than one quantum wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnQuWireMid(MultiBox, BoxOnQuWire):
""" Draws the middle part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.center_label(input_length, order)
class BoxOnQuWireBot(MultiBox, BoxOnQuWire):
""" Draws the bottom part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length):
super().__init__(label)
self.top_format = "│ %s │"
self.mid_content = self.bot_connect = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class BoxOnClWireTop(MultiBox, BoxOnClWire):
""" Draws the top part of a conditional box that affects more than one classical wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnClWireMid(MultiBox, BoxOnClWire):
""" Draws the middle part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.mid_content = label
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.top_pad = self.bot_pad = ' '
self.top_connect = self.bot_connect = self.mid_content = ''
self.center_label(input_length, order)
class BoxOnClWireBot(MultiBox, BoxOnClWire):
""" Draws the bottom part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, bot_connect='─'):
super().__init__(label)
self.top_format = "│ %s │"
self.top_pad = " "
self.bot_connect = bot_connect
self.mid_content = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class DirectOnQuWire(DrawElement):
"""
Element to the wire (without the box).
"""
def __init__(self, label=""):
super().__init__(label)
self.top_format = ' %s '
self.mid_format = '─%s─'
self.bot_format = ' %s '
self._mid_padding = '─'
self.top_connector = {"│": '│'}
self.bot_connector = {"│": '│'}
class Barrier(DirectOnQuWire):
""" Draws a barrier.
top: ░ ░
mid: ─░─ ───░───
bot: ░ ░
"""
def __init__(self, label=""):
super().__init__("░")
self.top_connect = "░"
self.bot_connect = "░"
self.top_connector = {}
self.bot_connector = {}
class Ex(DirectOnQuWire):
""" Draws an X (usually with a connector). E.g. the top part of a swap gate
top:
mid: ─X─ ───X───
bot: │ │
"""
def __init__(self, bot_connect=" ", top_connect=" "):
super().__init__("X")
self.bot_connect = bot_connect
self.top_connect = top_connect
class Reset(DirectOnQuWire):
""" Draws a reset gate"""
def __init__(self):
super().__init__("|0>")
class Bullet(DirectOnQuWire):
""" Draws a bullet (usually with a connector). E.g. the top part of a CX gate.
top:
mid: ─■─ ───■───
bot: │ │
"""
def __init__(self, top_connect=" ", bot_connect=" "):
super().__init__('■')
self.top_connect = top_connect
self.bot_connect = bot_connect
class EmptyWire(DrawElement):
""" This element is just the wire, with no instructions nor operations."""
def __init__(self, wire):
super().__init__(wire)
self._mid_padding = wire
@staticmethod
def fillup_layer(layer, first_clbit):
"""
Given a layer, replace the Nones in it with EmptyWire elements.
Args:
layer (list): The layer that contains Nones.
first_clbit (int): The first wire that is classic.
Returns:
list: The new layer, with no Nones.
"""
for nones in [i for i, x in enumerate(layer) if x is None]:
layer[nones] = EmptyWire('═') if nones >= first_clbit else EmptyWire('─')
return layer
class BreakWire(DrawElement):
""" This element is used to break the drawing in several pages."""
def __init__(self, arrow_char):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = arrow_char
self.mid_content = arrow_char
self.bot_connect = arrow_char
@staticmethod
def fillup_layer(layer_length, arrow_char):
"""
Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer.
"""
breakwire_layer = []
for _ in range(layer_length):
breakwire_layer.append(BreakWire(arrow_char))
return breakwire_layer
class InputWire(DrawElement):
""" This element is the label and the initial value of a wire."""
def __init__(self, label):
super().__init__(label)
@staticmethod
def fillup_layer(names): # pylint: disable=arguments-differ
"""
Creates a layer with InputWire elements.
Args:
names (list): List of names for the wires.
Returns:
list: The new layer
"""
longest = max([len(name) for name in names])
inputs_wires = []
for name in names:
inputs_wires.append(InputWire(name.rjust(longest)))
return inputs_wires
class TextDrawing():
""" The text drawing"""
def __init__(self, qregs, cregs, instructions, plotbarriers=True, line_length=None):
self.qregs = qregs
self.cregs = cregs
self.instructions = instructions
self.plotbarriers = plotbarriers
self.line_length = line_length
def __str__(self):
return self.single_string()
def _repr_html_(self):
return '<pre style="line-height: 15px;">%s</pre>' % self.single_string()
def _get_qubit_labels(self):
qubits = []
for qubit in self.qregs:
qubits.append("%s_%s" % (qubit[0], qubit[1]))
return qubits
def _get_clbit_labels(self):
clbits = []
for clbit in self.cregs:
clbits.append("%s_%s" % (clbit[0], clbit[1]))
return clbits
def single_string(self):
"""
Creates a loong string with the ascii art
Returns:
str: The lines joined by '\n'
"""
return "\n".join(self.lines())
def dump(self, filename, encoding="utf8"):
"""
Dumps the ascii art in the file.
Args:
filename (str): File to dump the ascii art.
encoding (str): Optional. Default "utf-8".
"""
with open(filename, mode='w', encoding=encoding) as text_file:
text_file.write(self.single_string())
def lines(self, line_length=None):
"""
Generates a list with lines. These lines form the text drawing.
Args:
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
Returns:
list: A list of lines with the text drawing.
"""
if line_length is None:
line_length = self.line_length
if line_length is None:
line_length, _ = get_terminal_size()
noqubits = len(self.qregs)
layers = self.build_layers()
# TODO compress layers
# -| H |----------
# --------| H |---
# should be
# -| H |---
# -| H |---
if not line_length:
line_length = self.line_length
layer_groups = [[]]
rest_of_the_line = line_length
for layerno, layer in enumerate(layers):
# Replace the Nones with EmptyWire
layers[layerno] = EmptyWire.fillup_layer(layer, noqubits)
TextDrawing.normalize_width(layer)
if line_length == -1:
# Do not use pagination (aka line breaking. aka ignore line_length).
layer_groups[-1].append(layer)
continue
# chop the layer to the line_length (pager)
layer_length = layers[layerno][0].length
if layer_length < rest_of_the_line:
layer_groups[-1].append(layer)
rest_of_the_line -= layer_length
else:
layer_groups[-1].append(BreakWire.fillup_layer(len(layer), '»'))
# New group
layer_groups.append([BreakWire.fillup_layer(len(layer), '«')])
rest_of_the_line = line_length - layer_groups[-1][-1][0].length
layer_groups[-1].append(
InputWire.fillup_layer(self.wire_names(with_initial_value=False)))
rest_of_the_line -= layer_groups[-1][-1][0].length
layer_groups[-1].append(layer)
rest_of_the_line -= layer_groups[-1][-1][0].length
lines = []
for layer_group in layer_groups:
wires = [i for i in zip(*layer_group)]
lines += TextDrawing.draw_wires(wires)
return lines
def wire_names(self, with_initial_value=True):
"""
Returns a list of names for each wire.
Args:
with_initial_value (bool): Optional (Default: True). If true, adds the initial value to
the name.
Returns:
List: The list of wire names.
"""
qubit_labels = self._get_qubit_labels()
clbit_labels = self._get_clbit_labels()
if with_initial_value:
qubit_labels = ['%s: |0>' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: 0 ' % clbit for clbit in clbit_labels]
else:
qubit_labels = ['%s: ' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: ' % clbit for clbit in clbit_labels]
return qubit_labels + clbit_labels
@staticmethod
def draw_wires(wires):
"""
Given a list of wires, creates a list of lines with the text drawing.
Args:
wires (list): A list of wires with instructions.
Returns:
list: A list of lines with the text drawing.
"""
lines = []
bot_line = None
for wire in wires:
# TOP
top_line = ""
for instruction in wire:
top_line += instruction.top
if bot_line is None:
lines.append(top_line)
else:
lines.append(TextDrawing.merge_lines(lines.pop(), top_line))
# MID
mid_line = ""
for instruction in wire:
mid_line += instruction.mid
lines.append(TextDrawing.merge_lines(lines[-1], mid_line, icod="bot"))
# BOT
bot_line = ""
for instruction in wire:
bot_line += instruction.bot
lines.append(TextDrawing.merge_lines(lines[-1], bot_line, icod="bot"))
return lines
@staticmethod
def label_for_conditional(instruction):
""" Creates the label for a conditional instruction."""
return "%s %s" % ('=', instruction['condition'][1])
@staticmethod
def params_for_label(instruction):
"""Get the params and format them to add them to a label. None of there is no param."""
if 'params' in instruction and instruction['params']:
return ['%.5g' % i for i in instruction['params']]
return None
@staticmethod
def label_for_box(instruction):
""" Creates the label for a box."""
label = instruction['name'].capitalize()
params = TextDrawing.params_for_label(instruction)
if params:
label += "(%s)" % ','.join(params)
return label
@staticmethod
def merge_lines(top, bot, icod="top"):
"""
Merges two lines (top and bot) in the way that the overlapping make senses.
Args:
top (str): the top line
bot (str): the bottom line
icod (top or bot): in case of doubt, which line should have priority? Default: "top".
Returns:
str: The merge of both lines.
"""
ret = ""
for topc, botc in zip(top, bot):
if topc == botc:
ret += topc
elif topc in '┼╪' and botc == " ":
ret += "│"
elif topc == " ":
ret += botc
elif topc in '┬╥' and botc in " ║│":
ret += topc
elif topc in '┬│' and botc == "═":
ret += '╪'
elif topc in '┬│' and botc == "─":
ret += '┼'
elif topc in '└┘║│░' and botc == " ":
ret += topc
elif topc in '─═' and botc == " " and icod == "top":
ret += topc
elif topc in '─═' and botc == " " and icod == "bot":
ret += botc
elif topc in "║╥" and botc in "═":
ret += "╬"
elif topc in "║╥" and botc in "─":
ret += "╫"
elif topc in '╫╬' and botc in " ":
ret += "║"
elif topc == '└' and botc == "┌":
ret += "├"
elif topc == '┘' and botc == "┐":
ret += "┤"
else:
ret += botc
return ret
@staticmethod
def normalize_width(layer):
"""
When the elements of the layer have different widths, sets the width to the max elements.
Args:
layer (list): A list of elements.
"""
instructions = [instruction for instruction in filter(lambda x: x is not None, layer)]
longest = max([instruction.length for instruction in instructions])
for instruction in instructions:
instruction.length = longest
def build_layers(self):
"""
Constructs layers.
Returns:
list: List of DrawElements.
Raises:
VisualizationError: When the drawing is, for some reason, impossible to be drawn.
"""
layers = []
layers.append(InputWire.fillup_layer(self.wire_names(with_initial_value=True)))
for instruction in self.instructions:
layer = Layer(self.qregs, self.cregs)
connector_label = None
if instruction['name'] == 'measure':
layer.set_qubit(instruction['qargs'][0], MeasureFrom())
layer.set_clbit(instruction['cargs'][0], MeasureTo())
elif instruction['name'] in ['barrier', 'snapshot', 'save', 'load',
'noise']:
# barrier
if not self.plotbarriers:
continue
for qubit in instruction['qargs']:
layer.set_qubit(qubit, Barrier())
elif instruction['name'] == 'swap':
# swap
for qubit in instruction['qargs']:
layer.set_qubit(qubit, Ex())
elif instruction['name'] == 'cswap':
# cswap
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], Ex())
layer.set_qubit(instruction['qargs'][2], Ex())
elif instruction['name'] == 'reset':
layer.set_qubit(instruction['qargs'][0], Reset())
elif instruction['condition'] is not None:
# conditional
cllabel = TextDrawing.label_for_conditional(instruction)
qulabel = TextDrawing.label_for_box(instruction)
layer.set_cl_multibox(instruction['condition'][0], cllabel, top_connect='┴')
layer.set_qubit(instruction['qargs'][0], BoxOnQuWire(qulabel, bot_connect='┬'))
elif instruction['name'] in ['cx', 'CX', 'ccx']:
# cx/ccx
for qubit in [qubit for qubit in instruction['qargs'][:-1]]:
layer.set_qubit(qubit, Bullet())
layer.set_qubit(instruction['qargs'][-1], BoxOnQuWire('X'))
elif instruction['name'] == 'cy':
# cy
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], BoxOnQuWire('Y'))
elif instruction['name'] == 'cz':
# cz
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], Bullet())
elif instruction['name'] == 'ch':
# ch
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], BoxOnQuWire('H'))
elif instruction['name'] == 'cu1':
# cu1
connector_label = TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], Bullet())
elif instruction['name'] == 'cu3':
# cu3
params = TextDrawing.params_for_label(instruction)
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1],
BoxOnQuWire("U3(%s)" % ','.join(params)))
elif instruction['name'] == 'crz':
# crz
label = "Rz(%s)" % TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], BoxOnQuWire(label))
elif len(instruction['qargs']) == 1 and not instruction['cargs']:
# unitary gate
layer.set_qubit(instruction['qargs'][0],
BoxOnQuWire(TextDrawing.label_for_box(instruction)))
elif len(instruction['qubits']) >= 2 and not instruction['cargs']:
# multiple qubit gate
layer.set_qu_multibox(instruction['qubits'], TextDrawing.label_for_box(instruction))
else:
raise VisualizationError(
"Text visualizer does not know how to handle this instruction", instruction)
layer.connect_with("│", connector_label)
layers.append(layer.full_layer)
return layers
class Layer:
""" A layer is the "column" of the circuit. """
def __init__(self, qregs, cregs):
self.qregs = qregs
self.cregs = cregs
self.qubit_layer = [None] * len(qregs)
self.clbit_layer = [None] * len(cregs)
@property
def full_layer(self):
"""
Returns the composition of qubits and classic wires.
Returns:
String: self.qubit_layer + self.clbit_layer
"""
return self.qubit_layer + self.clbit_layer
def set_qubit(self, qubit, element):
"""
Sets the qubit to the element
Args:
qubit (qbit): Element of self.qregs.
element (DrawElement): Element to set in the qubit
"""
self.qubit_layer[self.qregs.index(qubit)] = element
def set_clbit(self, clbit, element):
"""
Sets the clbit to the element
Args:
clbit (cbit): Element of self.cregs.
element (DrawElement): Element to set in the clbit
"""
self.clbit_layer[self.cregs.index(clbit)] = element
def _set_multibox(self, wire_type, bits, label, top_connect=None):
# pylint: disable=invalid-name
if wire_type == "cl":
bit_index = sorted([i for i, x in enumerate(self.cregs) if x in bits])
bits.sort(key=self.cregs.index)
set_bit = self.set_clbit
BoxOnWire = BoxOnClWire
BoxOnWireTop = BoxOnClWireTop
BoxOnWireMid = BoxOnClWireMid
BoxOnWireBot = BoxOnClWireBot
elif wire_type == "qu":
bit_index = sorted([i for i, x in enumerate(self.qregs) if x in bits])
bits.sort(key=self.qregs.index)
set_bit = self.set_qubit
BoxOnWire = BoxOnQuWire
BoxOnWireTop = BoxOnQuWireTop
BoxOnWireMid = BoxOnQuWireMid
BoxOnWireBot = BoxOnQuWireBot
else:
raise VisualizationError("_set_multibox only supports 'cl' and 'qu' as wire types.")
# Checks if bits are consecutive
if bit_index != [i for i in range(bit_index[0], bit_index[-1] + 1)]:
raise VisualizationError("Text visualizaer does know how to build a gate with multiple"
"bits when they are not adjacent to each other")
if len(bit_index) == 1:
set_bit(bits[0], BoxOnWire(label, top_connect=top_connect))
else:
set_bit(bits[0], BoxOnWireTop(label, top_connect=top_connect))
for order, bit in enumerate(bits[1:-1], 1):
set_bit(bit, BoxOnWireMid(label, len(bit_index), order))
set_bit(bits[-1], BoxOnWireBot(label, len(bit_index)))
def set_cl_multibox(self, creg, label, top_connect='┴'):
"""
Sets the multi clbit box.
Args:
creg (string): The affected classical register.
label (string): The label for the multi clbit box.
top_connect (char): The char to connect the box on the top.
"""
clbit = [bit for bit in self.cregs if bit[0] == creg]
self._set_multibox("cl", clbit, label, top_connect=top_connect)
def set_qu_multibox(self, bits, label):
"""
Sets the multi qubit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi qubit box.
"""
self._set_multibox("qu", bits, label)
def connect_with(self, wire_char, label=None):
"""
Connects the elements in the layer using wire_char.
Args:
wire_char (char): For example '║' or '│'.
label (string): Some connectors have a label (see cu1, for example).
"""
affected_bits = [bit for bit in self.full_layer if bit is not None]
if len([qbit for qbit in self.qubit_layer if qbit is not None]) == 1:
# Nothing to connect
return
affected_bits[0].connect(wire_char, ['bot'])
for affected_bit in affected_bits[1:-1]:
affected_bit.connect(wire_char, ['bot', 'top'])
affected_bits[-1].connect(wire_char, ['top'], label)
if label:
for affected_bit in affected_bits:
affected_bit.right_fill = len(label) + len(affected_bit.mid)
<|code_end|>
|
Return important circuit properties from a QuantumCircuit
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
It is often of interest to compute several properties of a quantum circuit after compiling to a given device. For example, # of gates, # of cx-gates, depth, and # of swap gates added, are all properties of interest. However, only some of these values (# gates, and cx gates) can actually be extracted from the qasm in a qobj, others require going qobj -> circuit -> DAG. Some, like # of swaps added, cannot be gathered from the given information. These values should be reported in the qobj experiment headers.
|
qiskit/_quantumcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=cyclic-import
"""
Quantum circuit object.
"""
import itertools
import warnings
from collections import OrderedDict
from copy import deepcopy
from qiskit.qasm import _qasm
from qiskit.unrollers import _unroller
from qiskit.unrollers import _circuitbackend
from qiskit._qiskiterror import QISKitError
from qiskit._quantumregister import QuantumRegister
from qiskit._classicalregister import ClassicalRegister
from qiskit.tools import visualization
def _circuit_from_qasm(qasm, basis=None):
default_basis = ["id", "u0", "u1", "u2", "u3", "x", "y", "z", "h", "s",
"sdg", "t", "tdg", "rx", "ry", "rz", "cx", "cy", "cz",
"ch", "crz", "cu1", "cu3", "swap", "ccx", "cswap"]
if not basis:
basis = default_basis
ast = qasm.parse()
unroll = _unroller.Unroller(
ast, _circuitbackend.CircuitBackend(basis))
circuit = unroll.execute()
return circuit
class QuantumCircuit(object):
"""Quantum circuit."""
instances = 0
prefix = 'circuit'
# Class variable OPENQASM header
header = "OPENQASM 2.0;"
# Class variable with gate definitions
# This is a dict whose values are dicts with the
# following keys:
# "print" = True or False
# "opaque" = True or False
# "n_args" = number of real parameters
# "n_bits" = number of qubits
# "args" = list of parameter names
# "bits" = list of qubit names
# "body" = GateBody AST node
definitions = OrderedDict()
@staticmethod
def from_qasm_file(path):
"""Take in a QASM file and generate a QuantumCircuit object.
Args:
path (str): Path to the file for a QASM program
Return:
QuantumCircuit: The QuantumCircuit object for the input QASM
"""
qasm = _qasm.Qasm(filename=path)
return _circuit_from_qasm(qasm)
@staticmethod
def from_qasm_str(qasm_str):
"""Take in a QASM string and generate a QuantumCircuit object.
Args:
qasm_str (str): A QASM program string
Return:
QuantumCircuit: The QuantumCircuit object for the input QASM
"""
qasm = _qasm.Qasm(data=qasm_str)
return _circuit_from_qasm(qasm)
def __init__(self, *regs, name=None):
"""Create a new circuit.
A circuit is a list of instructions bound to some registers.
Args:
*regs (Registers): registers to include in the circuit.
name (str or None): the name of the quantum circuit. If
None, an automatically generated string will be assigned.
Raises:
QISKitError: if the circuit name, if given, is not valid.
"""
if name is None:
name = self.cls_prefix() + str(self.cls_instances())
self._increment_instances()
if not isinstance(name, str):
raise QISKitError("The circuit name should be a string "
"(or None to auto-generate a name).")
self.name = name
# Data contains a list of instructions in the order they were applied.
self.data = []
# This is a map of registers bound to this circuit, by name.
self.qregs = []
self.cregs = []
self.add_register(*regs)
@classmethod
def _increment_instances(cls):
cls.instances += 1
@classmethod
def cls_instances(cls):
"""Return the current number of instances of this class,
useful for auto naming."""
return cls.instances
@classmethod
def cls_prefix(cls):
"""Return the prefix to use for auto naming."""
return cls.prefix
def has_register(self, register):
"""
Test if this circuit has the register r.
Args:
register (Register): a quantum or classical register.
Returns:
bool: True if the register is contained in this circuit.
"""
has_reg = False
if (isinstance(register, QuantumRegister) and
register in self.qregs):
has_reg = True
elif (isinstance(register, ClassicalRegister) and
register in self.cregs):
has_reg = True
return has_reg
def combine(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Return self + rhs as a new object.
"""
# Check registers in LHS are compatible with RHS
self._check_compatible_regs(rhs)
# Make new circuit with combined registers
combined_qregs = deepcopy(self.qregs)
combined_cregs = deepcopy(self.cregs)
for element in rhs.qregs:
if element not in self.qregs:
combined_qregs.append(element)
for element in rhs.cregs:
if element not in self.cregs:
combined_cregs.append(element)
circuit = QuantumCircuit(*combined_qregs, *combined_cregs)
for gate in itertools.chain(self.data, rhs.data):
gate.reapply(circuit)
return circuit
def extend(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Modify and return self.
"""
# Check registers in LHS are compatible with RHS
self._check_compatible_regs(rhs)
# Add new registers
for element in rhs.qregs:
if element not in self.qregs:
self.qregs.append(element)
for element in rhs.cregs:
if element not in self.cregs:
self.cregs.append(element)
# Add new gates
for gate in rhs.data:
gate.reapply(self)
return self
def __add__(self, rhs):
"""Overload + to implement self.concatenate."""
return self.combine(rhs)
def __iadd__(self, rhs):
"""Overload += to implement self.extend."""
return self.extend(rhs)
def __len__(self):
"""Return number of operations in circuit."""
return len(self.data)
def __getitem__(self, item):
"""Return indexed operation."""
return self.data[item]
def _attach(self, instruction):
"""Attach an instruction."""
self.data.append(instruction)
return instruction
def add_register(self, *regs):
"""Add registers."""
for register in regs:
if register in self.qregs or register in self.cregs:
raise QISKitError("register name \"%s\" already exists"
% register.name)
if isinstance(register, QuantumRegister):
self.qregs.append(register)
elif isinstance(register, ClassicalRegister):
self.cregs.append(register)
else:
raise QISKitError("expected a register")
def add(self, *regs):
"""Add registers."""
warnings.warn('The add() function is deprecated and will be '
'removed in a future release. Instead use '
'QuantumCircuit.add_register().', DeprecationWarning)
self.add_register(*regs)
def _check_qreg(self, register):
"""Raise exception if r is not in this circuit or not qreg."""
if not isinstance(register, QuantumRegister):
raise QISKitError("expected quantum register")
if not self.has_register(register):
raise QISKitError(
"register '%s' not in this circuit" %
register.name)
def _check_qubit(self, qubit):
"""Raise exception if qubit is not in this circuit or bad format."""
if not isinstance(qubit, tuple):
raise QISKitError("%s is not a tuple."
"A qubit should be formated as a tuple." % str(qubit))
if not len(qubit) == 2:
raise QISKitError("%s is not a tuple with two elements, but %i instead" % len(qubit))
if not isinstance(qubit[1], int):
raise QISKitError("The second element of a tuple defining a qubit should be an int:"
"%s was found instead" % type(qubit[1]).__name__)
self._check_qreg(qubit[0])
qubit[0].check_range(qubit[1])
def _check_creg(self, register):
"""Raise exception if r is not in this circuit or not creg."""
if not isinstance(register, ClassicalRegister):
raise QISKitError("expected classical register")
if not self.has_register(register):
raise QISKitError(
"register '%s' not in this circuit" %
register.name)
def _check_dups(self, qubits):
"""Raise exception if list of qubits contains duplicates."""
squbits = set(qubits)
if len(squbits) != len(qubits):
raise QISKitError("duplicate qubit arguments")
def _check_compatible_regs(self, rhs):
"""Raise exception if the circuits are defined on incompatible registers"""
list1 = self.qregs + self.cregs
list2 = rhs.qregs + rhs.cregs
for element1 in list1:
for element2 in list2:
if element2.name == element1.name:
if element1 != element2:
raise QISKitError("circuits are not compatible")
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.definitions[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.definitions[name]["n_args"] > 0:
out += "(" + ",".join(self.definitions[name]["args"]) + ")"
out += " " + ",".join(self.definitions[name]["bits"])
if self.definitions[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.definitions[name]["body"].qasm() + "}\n"
return out
def qasm(self):
"""Return OPENQASM string."""
string_temp = self.header + "\n"
for gate_name in self.definitions:
if self.definitions[gate_name]["print"]:
string_temp += self._gate_string(gate_name)
for register in self.qregs:
string_temp += register.qasm() + "\n"
for register in self.cregs:
string_temp += register.qasm() + "\n"
for instruction in self.data:
string_temp += instruction.qasm() + "\n"
return string_temp
def draw(self, scale=0.7, filename=None, style=None, output='text',
interactive=False, line_length=None, plot_barriers=True,
reverse_bits=False):
"""Draw the quantum circuit
Using the output parameter you can specify the format. The choices are:
0. text: ASCII art string
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style
file. You can refer to the
:ref:`Style Dict Doc <style-dict-doc>` for
more information on the contents.
output (str): Select the output method to use for drawing the
circuit. Valid choices are `text`, `latex`, `latex_source`,
`mpl`.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the
latex_source output type this has no effect
line_length (int): sets the length of the lines generated by `text`
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: (output `latex`) an in-memory representation of the
image of the circuit diagram.
matplotlib.figure: (output `mpl`) a matplotlib figure object for
the circuit diagram.
String: (output `latex_source`). The LaTeX source code.
TextDrawing: (output `text`). A drawing that can be printed as
ascii art
Raises:
VisualizationError: when an invalid output method is selected
"""
return visualization.circuit_drawer(self, scale=scale,
filename=filename, style=style,
output=output,
interactive=interactive,
line_length=line_length,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
def __str__(self):
return str(self.draw(output='text'))
<|code_end|>
qiskit/dagcircuit/_dagcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Object to represent a quantum circuit as a directed acyclic graph.
The nodes in the graph are either input/output nodes or operation nodes.
The operation nodes are elements of a basis that is part of the circuit.
The QASM definitions of the basis elements are carried with the circuit.
The edges correspond to qubits or bits in the circuit. A directed edge
from node A to node B means that the (qu)bit passes from the output of A
to the input of B. The object's methods allow circuits to be constructed,
composed, and modified. Some natural properties like depth can be computed
directly from the graph.
"""
from collections import OrderedDict
import copy
import itertools
import networkx as nx
import sympy
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QISKitError
from qiskit import _compositegate
from ._dagcircuiterror import DAGCircuitError
class DAGCircuit:
"""
Quantum circuit as a directed acyclic graph.
There are 3 types of nodes in the graph: inputs, outputs, and operations.
The nodes are connected by directed edges that correspond to qubits and
bits.
"""
# pylint: disable=invalid-name
def __init__(self):
"""Create an empty circuit."""
# Circuit name. Generally, this corresponds to the name
# of the QuantumCircuit from which the DAG was generated.
self.name = None
# Map from a wire's name (reg,idx) to a Bool that is True if the
# wire is a classical bit and False if the wire is a qubit.
self.wire_type = OrderedDict()
# Map from wire names (reg,idx) to input nodes of the graph
self.input_map = OrderedDict()
# Map from wire names (reg,idx) to output nodes of the graph
self.output_map = OrderedDict()
# Running count of the total number of nodes
self.node_counter = 0
# Map of named operations in this circuit and their signatures.
# The signature is an integer tuple (nq,nc,np) specifying the
# number of input qubits, input bits, and real parameters.
# The definition is external to the circuit object.
self.basis = OrderedDict()
# Directed multigraph whose nodes are inputs, outputs, or operations.
# Operation nodes have equal in- and out-degrees and carry
# additional data about the operation, including the argument order
# and parameter values.
# Input nodes have out-degree 1 and output nodes have in-degree 1.
# Edges carry wire labels (reg,idx) and each operation has
# corresponding in- and out-edges with the same wire labels.
self.multi_graph = nx.MultiDiGraph()
# Map of qregs to sizes
self.qregs = OrderedDict()
# Map of cregs to sizes
self.cregs = OrderedDict()
# Map of user defined gates to ast nodes defining them
self.gates = OrderedDict()
# Output precision for printing floats
self.prec = 10
# layout of dag quantum registers on the chip
# TODO: rethink this. doesn't seem related to concept of DAG,
# but if we want to be able to generate qobj
# directly from a dag, we need it.
self.layout = []
def get_qubits(self):
"""Return a list of qubits as (qreg, index) pairs."""
return [(k, i) for k, v in self.qregs.items() for i in range(v.size)]
def rename_register(self, regname, newname):
"""Rename a classical or quantum register throughout the circuit.
regname = existing register name string
newname = replacement register name string
"""
if regname == newname:
return
if newname in self.qregs or newname in self.cregs:
raise DAGCircuitError("duplicate register name %s" % newname)
if regname not in self.qregs and regname not in self.cregs:
raise DAGCircuitError("no register named %s" % regname)
iscreg = False
if regname in self.qregs:
self.qregs[newname] = self.qregs[regname]
self.qregs.pop(regname, None)
reg_size = self.qregs[newname].size
if regname in self.cregs:
self.cregs[newname] = self.cregs[regname]
self.cregs.pop(regname, None)
reg_size = self.cregs[newname].size
iscreg = True
for i in range(reg_size):
self.wire_type[(newname, i)] = iscreg
self.wire_type.pop((regname, i), None)
self.input_map[(newname, i)] = self.input_map[(regname, i)]
self.input_map.pop((regname, i), None)
self.output_map[(newname, i)] = self.output_map[(regname, i)]
self.output_map.pop((regname, i), None)
# n node d = data
for _, d in self.multi_graph.nodes(data=True):
if d["type"] == "in" or d["type"] == "out":
if d["name"][0] == regname:
d["name"] = (newname, d["name"][1])
elif d["type"] == "op":
qa = []
for a in d["qargs"]:
if a[0] == regname:
a = (newname, a[1])
qa.append(a)
d["qargs"] = qa
ca = []
for a in d["cargs"]:
if a[0] == regname:
a = (newname, a[1])
ca.append(a)
d["cargs"] = ca
if d["condition"] is not None:
if d["condition"][0] == regname:
d["condition"] = (newname, d["condition"][1])
# eX = edge, d= data
for _, _, d in self.multi_graph.edges(data=True):
if d["name"][0] == regname:
d["name"] = (newname, d["name"][1])
def remove_all_ops_named(self, opname):
"""Remove all operation nodes with the given name."""
for n in self.get_named_nodes(opname):
self._remove_op_node(n)
def fs(self, number):
"""Format a float f as a string with self.prec digits."""
fmt = "{0:0.%snumber}" % self.prec
return fmt.format(number)
def add_qreg(self, qreg):
"""Add all wires in a quantum register."""
if not isinstance(qreg, QuantumRegister):
raise DAGCircuitError("not a QuantumRegister instance.")
if qreg.name in self.qregs:
raise DAGCircuitError("duplicate register %s" % qreg.name)
self.qregs[qreg.name] = qreg
for j in range(qreg.size):
self._add_wire((qreg.name, j))
def add_creg(self, creg):
"""Add all wires in a classical register."""
if not isinstance(creg, ClassicalRegister):
raise DAGCircuitError("not a ClassicalRegister instance.")
if creg.name in self.cregs:
raise DAGCircuitError("duplicate register %s" % creg.name)
self.cregs[creg.name] = creg
for j in range(creg.size):
self._add_wire((creg.name, j), True)
def _add_wire(self, name, isClassical=False):
"""Add a qubit or bit to the circuit.
name is a (string,int) tuple containing register name and index
This adds a pair of in and out nodes connected by an edge.
"""
if name not in self.wire_type:
self.wire_type[name] = isClassical
self.node_counter += 1
self.input_map[name] = self.node_counter
self.node_counter += 1
self.output_map[name] = self.node_counter
in_node = self.input_map[name]
out_node = self.output_map[name]
self.multi_graph.add_edge(in_node, out_node)
self.multi_graph.node[in_node]["type"] = "in"
self.multi_graph.node[out_node]["type"] = "out"
self.multi_graph.node[in_node]["name"] = name
self.multi_graph.node[out_node]["name"] = name
self.multi_graph.adj[in_node][out_node][0]["name"] = name
else:
raise DAGCircuitError("duplicate wire %s" % name)
def add_basis_element(self, name, number_qubits,
number_classical=0, number_parameters=0):
"""Add an operation to the basis.
name is string label for operation
number_qubits is number of qubit arguments
number_classical is number of bit arguments
number_parameters is number of real parameters
The parameters (nq,nc,np) are ignored for the special case
when name = "barrier". The barrier instruction has a variable
number of qubit arguments.
"""
if name not in self.basis:
self.basis[name] = (
number_qubits,
number_classical,
number_parameters)
if name in self.gates:
if self.gates[name]["n_args"] != number_parameters or \
self.gates[name]["n_bits"] != number_qubits or number_classical != 0:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def add_gate_data(self, name, gatedata):
"""Add the definition of a gate.
gatedata is dict with fields:
"print" = True or False
"opaque" = True or False
"n_args" = number of real parameters
"n_bits" = number of qubits
"args" = list of parameter names
"bits" = list of qubit names
"body" = GateBody AST node
"""
if name not in self.gates:
self.gates[name] = gatedata
if name in self.basis:
if self.basis[name][0] != self.gates[name]["n_bits"] or \
self.basis[name][1] != 0 or \
self.basis[name][2] != self.gates[name]["n_args"]:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def _check_basis_data(self, name, qargs, cargs, params):
"""Check the arguments against the data for this operation.
name is a string
qargs is a list of tuples like ("q",0)
cargs is a list of tuples like ("c",0)
params is a list of strings that represent floats
"""
# Check that we have this operation
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
# Check the number of arguments matches the signature
if name in ["barrier"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if params:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
elif name in ["snapshot", "noise", "save", "load"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if not params:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
else:
if len(qargs) != self.basis[name][0]:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if len(cargs) != self.basis[name][1]:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if len(params) != self.basis[name][2]:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
def _check_condition(self, name, condition):
"""Verify that the condition is valid.
name is a string used for error reporting
condition is either None or a tuple (string,int) giving (creg,value)
"""
# Verify creg exists
if condition is not None and condition[0] not in self.cregs:
raise DAGCircuitError("invalid creg in condition for %s" % name)
def _check_bits(self, args, amap, bval):
"""Check the values of a list of (qu)bit arguments.
For each element A of args, check that amap contains A and
self.wire_type[A] equals bval.
args is a list of (regname,idx) tuples
amap is a dictionary keyed on (regname,idx) tuples
bval is boolean
"""
# Check for each wire
for q in args:
if q not in amap:
raise DAGCircuitError("(qu)bit %s not found" % (q,))
if self.wire_type[q] != bval:
raise DAGCircuitError("expected wire type %s for %s"
% (bval, q))
def _bits_in_condition(self, cond):
"""Return a list of bits (regname,idx) in the given condition.
cond is either None or a (regname,int) tuple specifying
a classical if condition.
"""
all_bits = []
if cond is not None:
all_bits.extend([(cond[0], j) for j in range(self.cregs[cond[0]].size)])
return all_bits
def _add_op_node(self, nname, nqargs, ncargs, nparams, ncondition, nop):
"""Add a new operation node to the graph and assign properties.
nname node name
nqargs quantum arguments
ncargs classical arguments
nparams parameters
ncondition classical condition (or None)
nop Instruction instance representing this operation
"""
# Add a new operation node to the graph
self.node_counter += 1
self.multi_graph.add_node(self.node_counter)
# Update that operation node's data
self.multi_graph.node[self.node_counter]["type"] = "op"
self.multi_graph.node[self.node_counter]["name"] = nname
self.multi_graph.node[self.node_counter]["qargs"] = nqargs
self.multi_graph.node[self.node_counter]["cargs"] = ncargs
self.multi_graph.node[self.node_counter]["params"] = nparams
self.multi_graph.node[self.node_counter]["condition"] = ncondition
self.multi_graph.node[self.node_counter]["op"] = nop
def apply_operation_back(self, name, qargs, cargs=None, params=None,
condition=None, op=None):
"""Apply an operation to the output of the circuit.
name is a string
qargs is a list of tuples like ("q",0)
cargs is a list of tuples like ("c",0)
params is a list of symbols that represent numbers
condition is either None or a tuple (string,int) giving (creg,value)
op is an Instruction instance representing this node
"""
cargs = cargs or []
params = params or []
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(name, qargs, cargs, params)
self._check_condition(name, condition)
self._check_bits(qargs, self.output_map, False)
self._check_bits(all_cbits, self.output_map, True)
self._add_op_node(name, qargs, cargs, params, condition, op)
# Add new in-edges from predecessors of the output nodes to the
# operation node while deleting the old in-edges of the output nodes
# and adding new edges from the operation node to each output node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.predecessors(self.output_map[q]))
if len(ie) != 1:
raise QISKitError("output node has multiple in-edges")
self.multi_graph.add_edge(ie[0], self.node_counter, name=q)
self.multi_graph.remove_edge(ie[0], self.output_map[q])
self.multi_graph.add_edge(
self.node_counter, self.output_map[q], name=q)
def apply_operation_front(self, name, qargs, cargs=None, params=None,
condition=None, op=None):
"""Apply an operation to the input of the circuit.
name is a string
qargs is a list of strings like "q[0]"
cargs is a list of strings like "c[0]"
params is a list of strings that represent floats
condition is either None or a tuple (string,int) giving (creg,value)
"""
cargs = cargs or []
params = params or []
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(name, qargs, cargs, params)
self._check_condition(name, condition)
self._check_bits(qargs, self.input_map, False)
self._check_bits(all_cbits, self.input_map, True)
self._add_op_node(name, qargs, cargs, params, condition, op)
# Add new out-edges to successors of the input nodes from the
# operation node while deleting the old out-edges of the input nodes
# and adding new edges to the operation node from each input node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = self.multi_graph.successors(self.input_map[q])
if len(ie) != 1:
raise QISKitError("input node has multiple out-edges")
self.multi_graph.add_edge(self.node_counter, ie[0], name=q)
self.multi_graph.remove_edge(self.input_map[q], ie[0])
self.multi_graph.add_edge(
self.input_map[q], self.node_counter, name=q)
def _make_union_basis(self, input_circuit):
"""Return a new basis map.
The new basis is a copy of self.basis with
new elements of input_circuit.basis added.
input_circuit is a DAGCircuit
"""
union_basis = self.basis.copy()
for g in input_circuit.basis:
if g not in union_basis:
union_basis[g] = input_circuit.basis[g]
if union_basis[g] != input_circuit.basis[g]:
raise DAGCircuitError("incompatible basis")
return union_basis
def _make_union_gates(self, input_circuit):
"""Return a new gates map.
The new gates are a copy of self.gates with
new elements of input_circuit.gates added.
input_circuit is a DAGCircuit
NOTE: gates in input_circuit that are also in self must
be *identical* to the gates in self
"""
union_gates = {}
for k, v in self.gates.items():
union_gates[k] = v
for k, v in input_circuit.gates.items():
if k not in union_gates:
union_gates[k] = v
if union_gates[k]["opaque"] != input_circuit.gates[k]["opaque"] or \
union_gates[k]["n_args"] != input_circuit.gates[k]["n_args"] or \
union_gates[k]["n_bits"] != input_circuit.gates[k]["n_bits"] or \
union_gates[k]["args"] != input_circuit.gates[k]["args"] or \
union_gates[k]["bits"] != input_circuit.gates[k]["bits"]:
raise DAGCircuitError("inequivalent gate definitions for %s"
% k)
return union_gates
def _check_wiremap_registers(self, wire_map, keyregs, valregs,
valreg=True):
"""Check that wiremap neither fragments nor leaves duplicate registers.
1. There are no fragmented registers. A register in keyregs
is fragmented if not all of its (qu)bits are renamed by wire_map.
2. There are no duplicate registers. A register is duplicate if
it appears in both self and keyregs but not in wire_map.
wire_map is a map from (regname,idx) in keyregs to (regname,idx)
in valregs
keyregs is a map from register names to Register objects
valregs is a map from register names to Register objects
valreg is a Bool, if False the method ignores valregs and does not
add regs for bits in the wire_map image that don't appear in valregs
Return the set of regs to add to self
"""
add_regs = set()
reg_frag_chk = {}
for k, v in keyregs.items():
reg_frag_chk[k] = {j: False for j in range(v.size)}
for k in wire_map.keys():
if k[0] in keyregs:
reg_frag_chk[k[0]][k[1]] = True
for k, v in reg_frag_chk.items():
rname = ",".join(map(str, k))
s = set(v.values())
if len(s) == 2:
raise DAGCircuitError("wire_map fragments reg %s" % rname)
elif s == set([False]):
if k in self.qregs or k in self.cregs:
raise DAGCircuitError("unmapped duplicate reg %s" % rname)
else:
# Add registers that appear only in keyregs
add_regs.add(keyregs[k])
else:
if valreg:
# If mapping to a register not in valregs, add it.
# (k,0) exists in wire_map because wire_map doesn't
# fragment k
if not wire_map[(k, 0)][0] in valregs:
size = max(map(lambda x: x[1], filter(lambda x: x[0] == wire_map[(k, 0)][0],
wire_map.values())))
qreg = QuantumRegister(wire_map[(k, 0)][0], size + 1)
add_regs.add(qreg)
return add_regs
def _check_wiremap_validity(self, wire_map, keymap, valmap, input_circuit):
"""Check that the wiremap is consistent.
Check that the wiremap refers to valid wires and that
those wires have consistent types.
wire_map is a map from (regname,idx) in keymap to (regname,idx)
in valmap
keymap is a map whose keys are wire_map keys
valmap is a map whose keys are wire_map values
input_circuit is a DAGCircuit
"""
for k, v in wire_map.items():
kname = ",".join(map(str, k))
vname = ",".join(map(str, v))
if k not in keymap:
raise DAGCircuitError("invalid wire mapping key %s" % kname)
if v not in valmap:
raise DAGCircuitError("invalid wire mapping value %s"
% vname)
if input_circuit.wire_type[k] != self.wire_type[v]:
raise DAGCircuitError("inconsistent wire_map at (%s,%s)"
% (kname, vname))
def _map_condition(self, wire_map, condition):
"""Use the wire_map dict to change the condition tuple's creg name.
wire_map is map from wires to wires
condition is a tuple (reg,int)
Returns the new condition tuple
"""
if condition is None:
n_condition = None
else:
# Map the register name, using fact that registers must not be
# fragmented by the wire_map (this must have been checked
# elsewhere)
bit0 = (condition[0], 0)
n_condition = (wire_map.get(bit0, bit0)[0], condition[1])
return n_condition
def compose_back(self, input_circuit, wire_map=None):
"""Apply the input circuit to the output of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of input qubits of the input circuit are mapped
to a subset of output qubits of this circuit.
wire_map[input_qubit_to_input_circuit] = output_qubit_of_self
"""
wire_map = wire_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map for duplicate values
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_wiremap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.input_map,
self.output_map, input_circuit)
# Compose
self.basis = union_basis
self.gates = union_gates
for node in nx.topological_sort(input_circuit.multi_graph):
nd = input_circuit.multi_graph.node[node]
if nd["type"] == "in":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["name"], nd["name"])
# the mapped wire should already exist
if m_name not in self.output_map:
raise QISKitError("wire (%s,%d) not in self" % (m_name[0], m_name[1]))
if nd["name"] not in input_circuit.wire_type:
raise QISKitError("inconsistent wire_type for (%s,%d) in input_circuit"
% (nd["name"][0], nd["name"][1]))
elif nd["type"] == "out":
# ignore output nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: wire_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x), nd["cargs"]))
self.apply_operation_back(nd["name"], m_qargs, m_cargs,
nd["params"], condition, nd["op"])
else:
raise QISKitError("bad node type %s" % nd["type"])
def compose_front(self, input_circuit, wire_map=None):
"""Apply the input circuit to the input of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of output qubits of the input circuit are mapped
to a subset of input qubits of
this circuit.
"""
wire_map = wire_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_wiremap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.output_map,
self.input_map, input_circuit)
# Compose
self.basis = union_basis
self.gates = union_gates
for n in reversed(list(nx.topological_sort(input_circuit.multi_graph))):
nd = input_circuit.multi_graph.node[n]
if nd["type"] == "out":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["name"], nd["name"])
# the mapped wire should already exist
if m_name not in self.input_map:
raise QISKitError("wire (%s,%d) not in self" % (m_name[0], m_name[1]))
if nd["name"] not in input_circuit.wire_type:
raise QISKitError(
"inconsistent wire_type for (%s,%d) in input_circuit"
% (nd["name"][0], nd["name"][1]))
elif nd["type"] == "in":
# ignore input nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: wire_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x), nd["cargs"]))
self.apply_operation_front(nd["name"], m_qargs, m_cargs,
nd["params"], condition, nd["op"])
else:
raise QISKitError("bad node type %s" % nd["type"])
def size(self):
"""Return the number of operations."""
return self.multi_graph.order() - 2 * len(self.wire_type)
def depth(self):
"""Return the circuit depth."""
if not nx.is_directed_acyclic_graph(self.multi_graph):
raise QISKitError("not a DAG")
return nx.dag_longest_path_length(self.multi_graph) - 1
def width(self):
"""Return the total number of qubits used by the circuit."""
return len(self.wire_type) - self.num_cbits()
def num_cbits(self):
"""Return the total number of bits used by the circuit."""
return list(self.wire_type.values()).count(True)
def num_tensor_factors(self):
"""Compute how many components the circuit can decompose into."""
return nx.number_weakly_connected_components(self.multi_graph)
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.gates[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.gates[name]["n_args"] > 0:
out += "(" + ",".join(self.gates[name]["args"]) + ")"
out += " " + ",".join(self.gates[name]["bits"])
if self.gates[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.gates[name]["body"].qasm() + "}"
return out
def qasm(self, decls_only=False, add_swap=False,
no_decls=False, qeflag=False, aliases=None, eval_symbols=False):
"""Return a string containing QASM for this circuit.
if qeflag is True, add a line to include "qelib1.inc"
and only generate gate code for gates not in qelib1.
if eval_symbols is True, evaluate all symbolic
expressions to their floating point representation.
if no_decls is True, only print the instructions.
if aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
if decls_only is True, only print the declarations.
if add_swap is True, add the definition of swap in terms of
cx if necessary.
"""
# TODO: some of the input flags are not needed anymore
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
# Write top matter
if no_decls:
out = ""
else:
printed_gates = []
out = "OPENQASM 2.0;\n"
if qeflag:
out += "include \"qelib1.inc\";\n"
for k, v in sorted(qregdata.items()):
out += "qreg %s[%d];\n" % (k, v.size)
for k, v in sorted(self.cregs.items()):
out += "creg %s[%d];\n" % (k, v.size)
omit = ["U", "CX", "measure", "reset", "barrier"]
# TODO: dagcircuit shouldn't know about extensions
if qeflag:
qelib = ["u3", "u2", "u1", "cx", "id", "x", "y", "z", "h",
"s", "sdg", "t", "tdg", "cz", "cy", "ccx", "cu1",
"cu3", "swap", "cswap", "u0", "rx", "ry", "rz",
"ch", "crz", "rzz"]
omit.extend(qelib)
printed_gates.extend(qelib)
simulator_instructions = ["snapshot", "save", "load", "noise", "wait"]
omit.extend(simulator_instructions)
for k in self.basis.keys():
if k not in omit:
if not self.gates[k]["opaque"]:
calls = self.gates[k]["body"].calls()
for c in calls:
if c not in printed_gates:
out += self._gate_string(c) + "\n"
printed_gates.append(c)
if k not in printed_gates:
out += self._gate_string(k) + "\n"
printed_gates.append(k)
if add_swap and not qeflag and "cx" not in self.basis:
out += "gate cx a,b { CX a,b; }\n"
if add_swap and "swap" not in self.basis:
out += "gate swap a,b { cx a,b; cx b,a; cx a,b; }\n"
# Write the instructions
if not decls_only:
for n in nx.lexicographical_topological_sort(self.multi_graph):
nd = self.multi_graph.node[n]
if nd["type"] == "op":
if nd["condition"] is not None:
out += "if(%s==%d) " \
% (nd["condition"][0], nd["condition"][1])
if not nd["cargs"]:
nm = nd["name"]
if aliases:
qarglist = map(lambda x: aliases[x], nd["qargs"])
else:
qarglist = nd["qargs"]
qarg = ",".join(map(lambda x: "%s[%d]" % (x[0], x[1]),
qarglist))
if nd["params"]:
if eval_symbols:
param = ",".join(map(lambda x: str(sympy.N(x)),
nd["params"]))
else:
param = ",".join(map(lambda x: x.replace("**", "^"),
map(str, nd["params"])))
out += "%s(%s) %s;\n" % (nm, param, qarg)
else:
out += "%s %s;\n" % (nm, qarg)
else:
if nd["name"] == "measure":
if len(nd["cargs"]) != 1 or len(nd["qargs"]) != 1 \
or nd["params"]:
raise QISKitError("bad node data")
qname = nd["qargs"][0][0]
qindex = nd["qargs"][0][1]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
out += "measure %s[%d] -> %s[%d];\n" \
% (qname,
qindex,
nd["cargs"][0][0],
nd["cargs"][0][1])
else:
raise QISKitError("bad node data")
return out
def _check_wires_list(self, wires, name, input_circuit, condition=None):
"""Check that a list of wires satisfies some conditions.
wires = list of (register_name, index) tuples
name = name of operation
input_circuit = replacement circuit for operation
condition = None or (creg_name, value) if this instance of the
operation is classically controlled
The wires give an order for (qu)bits in the input circuit
that is replacing the named operation.
- no duplicate names
- correct length for named operation
- elements are wires of input_circuit
Raises an exception otherwise.
"""
if len(set(wires)) != len(wires):
raise DAGCircuitError("duplicate wires")
wire_tot = self.basis[name][0] + self.basis[name][1]
if condition is not None:
wire_tot += self.cregs[condition[0]].size
if len(wires) != wire_tot:
raise DAGCircuitError("expected %d wires, got %d"
% (wire_tot, len(wires)))
for w in wires:
if w not in input_circuit.wire_type:
raise DAGCircuitError("wire (%s,%d) not in input circuit"
% (w[0], w[1]))
def _make_pred_succ_maps(self, n):
"""Return predecessor and successor dictionaries.
These map from wire names to predecessor and successor
nodes for the operation node n in self.multi_graph.
"""
pred_map = {e[2]['name']: e[0] for e in
self.multi_graph.in_edges(nbunch=n, data=True)}
succ_map = {e[2]['name']: e[1] for e in
self.multi_graph.out_edges(nbunch=n, data=True)}
return pred_map, succ_map
def _full_pred_succ_maps(self, pred_map, succ_map, input_circuit,
wire_map):
"""Map all wires of the input circuit.
Map all wires of the input circuit to predecessor and
successor nodes in self, keyed on wires in self.
pred_map, succ_map dicts come from _make_pred_succ_maps
input_circuit is the input circuit
wire_map is the wire map from wires of input_circuit to wires of self
returns full_pred_map, full_succ_map
"""
full_pred_map = {}
full_succ_map = {}
for w in input_circuit.input_map:
# If w is wire mapped, find the corresponding predecessor
# of the node
if w in wire_map:
full_pred_map[wire_map[w]] = pred_map[wire_map[w]]
full_succ_map[wire_map[w]] = succ_map[wire_map[w]]
else:
# Otherwise, use the corresponding output nodes of self
# and compute the predecessor.
full_succ_map[w] = self.output_map[w]
full_pred_map[w] = self.multi_graph.predecessors(
self.output_map[w])[0]
if len(list(self.multi_graph.predecessors(self.output_map[w]))) != 1:
raise QISKitError(
"too many predecessors for (%s,%d) output node" % (w[0], w[1])
)
return full_pred_map, full_succ_map
def node_nums_in_topological_order(self):
"""
Returns the nodes (their ids) in topological order.
Returns:
List(int): The list of node numbers in topological order
"""
return nx.topological_sort(self.multi_graph)
def substitute_circuit_all(self, name, input_circuit, wires=None):
"""Replace every occurrence of named operation with input_circuit."""
# TODO: rewrite this method to call substitute_circuit_one
wires = wires or None
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
self._check_wires_list(wires, name, input_circuit)
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: ("", 0) for w in wires}
add_qregs = self._check_wiremap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Iterate through the nodes of self and replace the selected nodes
# by iterating through the input_circuit, constructing and
# checking the validity of the wire_map for each replacement
# NOTE: We do not replace conditioned gates. One way to implement
# this later is to add or update the conditions of each gate
# that we add from the input_circuit.
self.basis = union_basis
self.gates = union_gates
for n in self.node_nums_in_topological_order():
nd = self.multi_graph.node[n]
if nd["type"] == "op" and nd["name"] == name:
if nd["condition"] is None:
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"], nd["cargs"]]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map, input_circuit)
pred_map, succ_map = self._make_pred_succ_maps(n)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(n)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map,
md["condition"])
m_qargs = [wire_map.get(x, x) for x in md["qargs0"]]
m_cargs = [wire_map.get(x, x) for x in md["cargs0"]]
self._add_op_node(md["name"], m_qargs, m_cargs,
md["params"], condition, md["op"])
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter, name=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w], full_succ_map[w],
name=w)
o_pred = list(self.multi_graph.predecessors(
self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise QISKitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise QISKitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(
p[0], self.output_map[w])
def substitute_circuit_one(self, node, input_circuit, wires=None):
"""Replace one node with input_circuit.
node is a reference to a node of self.multi_graph of type "op"
input_circuit is a DAGCircuit
"""
wires = wires or None
nd = self.multi_graph.node[node]
name = nd["name"]
self._check_wires_list(wires, name, input_circuit, nd["condition"])
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: ("", 0) for w in wires}
add_qregs = self._check_wiremap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Replace the node by iterating through the input_circuit.
# Constructing and checking the validity of the wire_map.
# If a gate is conditioned, we expect the replacement subcircuit
# to depend on those control bits as well.
self.basis = union_basis
self.gates = union_gates
if nd["type"] != "op":
raise DAGCircuitError("expected node type \"op\", got %s"
% nd["type"])
condition_bit_list = self._bits_in_condition(nd["condition"])
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"],
nd["cargs"],
condition_bit_list]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map, input_circuit)
pred_map, succ_map = self._make_pred_succ_maps(node)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(node)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map, md["condition"])
m_qargs = list(map(lambda x: wire_map.get(x, x),
md["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x),
md["cargs"]))
self._add_op_node(md["name"], m_qargs, m_cargs,
md["params"], condition, md["op"])
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter,
name=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(
full_pred_map[w], full_succ_map[w], name=w)
o_pred = list(self.multi_graph.predecessors(self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise QISKitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise QISKitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(p[0], self.output_map[w])
def get_named_nodes(self, name):
"""Get the set of "op" node ids with the given name."""
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
# We need to instantiate the full list now because the underlying multi_graph
# may change when users iterate over the named nodes.
return {node_id for node_id, data in self.multi_graph.nodes(data=True)
if data["type"] == "op" and data["name"] == name}
def _remove_op_node(self, n):
"""Remove an operation node n.
Add edges from predecessors to successors.
"""
pred_map, succ_map = self._make_pred_succ_maps(n)
self.multi_graph.remove_node(n)
for w in pred_map.keys():
self.multi_graph.add_edge(pred_map[w], succ_map[w], name=w)
def remove_ancestors_of(self, node):
"""Remove all of the ancestor operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
# TODO: probably better to do all at once using
# multi_graph.remove_nodes_from; same for related functions ...
for n in anc:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_descendants_of(self, node):
"""Remove all of the descendant operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
for n in dec:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nonancestors_of(self, node):
"""Remove all of the non-ancestors operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(anc))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nondescendants_of(self, node):
"""Remove all of the non-descendants operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(dec))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def layers(self):
"""Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit.
A layer is a circuit whose gates act on disjoint qubits, i.e.
a layer has depth 1. The total number of layers equals the
circuit depth d. The layers are indexed from 0 to d-1 with the
earliest layer at index 0. The layers are constructed using a
greedy algorithm. Each returned layer is a dict containing
{"graph": circuit graph, "partition": list of qubit lists}.
TODO: Gates that use the same cbits will end up in different
layers as this is currently implemented. This may not be
the desired behavior.
"""
graph_layers = self.multigraph_layers()
try:
next(graph_layers) # Remove input nodes
except StopIteration:
return
def nodes_data(nodes):
"""Construct full nodes from just node ids."""
return ((node_id, self.multi_graph.nodes[node_id]) for node_id in nodes)
for graph_layer in graph_layers:
# Get the op nodes from the layer, removing any input and output nodes.
op_nodes = [node for node in nodes_data(graph_layer) if node[1]["type"] == "op"]
# Stop yielding once there are no more op_nodes in a layer.
if not op_nodes:
return
# Construct a shallow copy of self
new_layer = copy.copy(self)
new_layer.multi_graph = nx.MultiDiGraph()
new_layer.multi_graph.add_nodes_from(nodes_data(self.input_map.values()))
new_layer.multi_graph.add_nodes_from(nodes_data(self.output_map.values()))
# The quantum registers that have an operation in this layer.
support_list = [
op_node[1]["qargs"]
for op_node in op_nodes
if op_node[1]["name"] not in {"barrier", "snapshot", "save", "load", "noise"}
]
new_layer.multi_graph.add_nodes_from(op_nodes)
# Now add the edges to the multi_graph
# By default we just wire inputs to the outputs.
wires = {self.input_map[register]: self.output_map[register]
for register in self.wire_type}
# Wire inputs to op nodes, and op nodes to outputs.
for op_node in op_nodes:
args = self._bits_in_condition(op_node[1]["condition"]) \
+ op_node[1]["cargs"] + op_node[1]["qargs"]
arg_ids = (self.input_map[arg] for arg in args) # map from ("q",0) to node id.
for arg_id in arg_ids:
wires[arg_id], wires[op_node[0]] = op_node[0], wires[arg_id]
# Add wiring to/from the operations and between unused inputs & outputs.
new_layer.multi_graph.add_edges_from(wires.items())
yield {"graph": new_layer, "partition": support_list}
def serial_layers(self):
"""Yield a layer for all gates of this circuit.
A serial layer is a circuit with one gate. The layers have the
same structure as in layers().
"""
for n in self.node_nums_in_topological_order():
nxt_nd = self.multi_graph.node[n]
if nxt_nd["type"] == "op":
new_layer = DAGCircuit()
for qreg in self.qregs.values():
new_layer.add_qreg(qreg)
for creg in self.cregs.values():
new_layer.add_creg(creg)
new_layer.basis = self.basis.copy()
new_layer.gates = self.gates.copy()
# Save the support of the operation we add to the layer
support_list = []
# Operation data
qa = copy.copy(nxt_nd["qargs"])
ca = copy.copy(nxt_nd["cargs"])
pa = copy.copy(nxt_nd["params"])
co = copy.copy(nxt_nd["condition"])
op = copy.copy(nxt_nd["op"])
_ = self._bits_in_condition(co)
# Add node to new_layer
new_layer.apply_operation_back(nxt_nd["name"],
qa, ca, pa, co, op)
# Add operation to partition
if nxt_nd["name"] not in ["barrier",
"snapshot", "save", "load", "noise"]:
# support_list.append(list(set(qa) | set(ca) | set(cob)))
support_list.append(list(qa))
l_dict = {"graph": new_layer, "partition": support_list}
yield l_dict
def multigraph_layers(self):
"""Yield layers of the multigraph."""
predecessor_count = dict() # Dict[node, predecessors not visited]
cur_layer = [node for node in self.input_map.values()]
yield cur_layer
next_layer = []
while cur_layer:
for node in cur_layer:
# Count multiedges with multiplicity.
for successor in self.multi_graph.successors(node):
multiplicity = self.multi_graph.number_of_edges(node, successor)
if successor in predecessor_count:
predecessor_count[successor] -= multiplicity
else:
predecessor_count[successor] = \
self.multi_graph.in_degree(successor) - multiplicity
if predecessor_count[successor] == 0:
next_layer.append(successor)
del predecessor_count[successor]
yield next_layer
cur_layer = next_layer
next_layer = []
def collect_runs(self, namelist):
"""Return a set of runs of "op" nodes with the given names.
For example, "... h q[0]; cx q[0],q[1]; cx q[0],q[1]; h q[1]; .."
would produce the tuple of cx nodes as an element of the set returned
from a call to collect_runs(["cx"]). If instead the cx nodes were
"cx q[0],q[1]; cx q[1],q[0];", the method would still return the
pair in a tuple. The namelist can contain names that are not
in the circuit's basis.
Nodes must have only one successor to continue the run.
"""
group_list = []
# Iterate through the nodes of self in topological order
# and form tuples containing sequences of gates
# on the same qubit(s).
ts = list(self.node_nums_in_topological_order())
nodes_seen = dict(zip(ts, [False] * len(ts)))
for node in ts:
nd = self.multi_graph.node[node]
if nd["type"] == "op" and nd["name"] in namelist \
and not nodes_seen[node]:
group = [node]
nodes_seen[node] = True
s = list(self.multi_graph.successors(node))
while len(s) == 1 and \
self.multi_graph.node[s[0]]["type"] == "op" and \
self.multi_graph.node[s[0]]["name"] in namelist:
group.append(s[0])
nodes_seen[s[0]] = True
s = list(self.multi_graph.successors(s[0]))
if len(group) > 1:
group_list.append(tuple(group))
return set(group_list)
def count_ops(self):
"""Count the occurrences of operation names.
Returns a dictionary of counts keyed on the operation name.
"""
op_dict = {}
for node in self.node_nums_in_topological_order():
nd = self.multi_graph.node[node]
name = nd["name"]
if nd["type"] == "op":
if name not in op_dict:
op_dict[name] = 1
else:
op_dict[name] += 1
return op_dict
def property_summary(self):
"""Return a dictionary of circuit properties."""
summary = {"size": self.size(),
"depth": self.depth(),
"width": self.width(),
"bits": self.num_cbits(),
"factors": self.num_tensor_factors(),
"operations": self.count_ops()}
return summary
@staticmethod
def fromQuantumCircuit(circuit, expand_gates=True):
"""Build a ``DAGCircuit`` object from a ``QuantumCircuit``.
Args:
circuit (QuantumCircuit): the input circuit.
expand_gates (bool): if ``False``, none of the gates are expanded,
i.e. the gates that are defined in the circuit are included in
the DAG basis.
Return:
DAGCircuit: the DAG representing the input circuit.
"""
dagcircuit = DAGCircuit()
dagcircuit.name = circuit.name
for register in circuit.qregs:
dagcircuit.add_qreg(register)
for register in circuit.cregs:
dagcircuit.add_creg(register)
# Add user gate definitions
for name, data in circuit.definitions.items():
dagcircuit.add_basis_element(name, data["n_bits"], 0,
data["n_args"])
dagcircuit.add_gate_data(name, data)
# Add instructions
builtins = {
"U": ["U", 1, 0, 3],
"CX": ["CX", 2, 0, 0],
"measure": ["measure", 1, 1, 0],
"reset": ["reset", 1, 0, 0],
"barrier": ["barrier", -1, 0, 0]
}
# Add simulator instructions
simulator_instructions = {
"snapshot": ["snapshot", -1, 0, 1],
"save": ["save", -1, 0, 1],
"load": ["load", -1, 0, 1],
"noise": ["noise", -1, 0, 1]
}
for main_instruction in circuit.data:
# TODO: generate definitions and nodes for CompositeGates,
# for now simply drop their instructions into the DAG
instruction_list = []
is_composite = isinstance(main_instruction,
_compositegate.CompositeGate)
if is_composite and expand_gates:
instruction_list = main_instruction.instruction_list()
else:
instruction_list.append(main_instruction)
for instruction in instruction_list:
# Add OpenQASM built-in gates on demand
if instruction.name in builtins:
dagcircuit.add_basis_element(*builtins[instruction.name])
# Add simulator extension instructions
if instruction.name in simulator_instructions:
dagcircuit.add_basis_element(*simulator_instructions[instruction.name])
# Separate classical arguments to measurements
if instruction.name == "measure":
qargs = [(instruction.qargs[0][0].name, instruction.qargs[0][1])]
cargs = [(instruction.cargs[0][0].name, instruction.cargs[0][1])]
else:
qargs = list(map(lambda x: (x[0].name, x[1]), instruction.qargs))
cargs = []
# Get arguments for classical control (if any)
if instruction.control is None:
control = None
else:
control = (instruction.control[0].name, instruction.control[1])
if is_composite and not expand_gates:
is_inverse = instruction.inverse_flag
name = instruction.name if not is_inverse else instruction.inverse_name
else:
name = instruction.name
dagcircuit.apply_operation_back(name, qargs, cargs,
instruction.param,
control, instruction)
return dagcircuit
<|code_end|>
qiskit/transpiler/_transpiler.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Tools for compiling a batch of quantum circuits."""
import logging
import numpy as np
import scipy.sparse as sp
import scipy.sparse.csgraph as cs
from qiskit.transpiler._transpilererror import TranspilerError
from qiskit._qiskiterror import QISKitError
from qiskit.dagcircuit import DAGCircuit
from qiskit import _quantumcircuit
from qiskit.unrollers import _dagunroller
from qiskit.unrollers import _dagbackend
from qiskit.unrollers import _jsonbackend
from qiskit.mapper import (Coupling, optimize_1q_gates, coupling_list2dict, swap_mapper,
cx_cancellation, direction_mapper,
remove_last_measurements, return_last_measurements)
from qiskit._pubsub import Publisher, Subscriber
from ._parallel import parallel_map
logger = logging.getLogger(__name__)
def transpile(circuits, backend, basis_gates=None, coupling_map=None, initial_layout=None,
seed_mapper=None, hpc=None, pass_manager=None):
"""transpile a list of circuits into a dags.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend): a backend to compile for
basis_gates (str): comma-separated basis gate set to compile to
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
seed_mapper (int): random seed for the swap_mapper
hpc (dict): HPC simulator parameters
pass_manager (PassManager): a pass_manager for the transpiler stage
Returns:
dags: a list of dags.
Raises:
TranspilerError: in case of bad compile options, e.g. the hpc options.
"""
if isinstance(circuits, _quantumcircuit.QuantumCircuit):
circuits = [circuits]
# FIXME: THIS NEEDS TO BE CLEANED UP -- some things to decide for list of circuits:
# 1. do all circuits have same coupling map?
# 2. do all circuit have the same basis set?
# 3. do they all have same registers etc?
backend_conf = backend.configuration()
# Check for valid parameters for the experiments.
if hpc is not None and \
not all(key in hpc for key in ('multi_shot_optimization', 'omp_num_threads')):
raise TranspilerError('Unknown HPC parameter format!')
basis_gates = basis_gates or backend_conf['basis_gates']
coupling_map = coupling_map or backend_conf['coupling_map']
# step 1: Making the list of dag circuits
dags = _circuits_2_dags(circuits)
# step 2: Transpile all the dags
# FIXME: Work-around for transpiling multiple circuits with different qreg names.
# Make compile take a list of initial_layouts.
_initial_layout = initial_layout
# Pick a good initial layout if coupling_map is not already satisfied
# otherwise keep it as q[i]->q[i].
# TODO: move this inside mapper pass.
initial_layouts = []
for dag in dags:
if (initial_layout is None and not backend.configuration()['simulator']
and not _matches_coupling_map(dag, coupling_map)):
_initial_layout = _pick_best_layout(dag, backend)
initial_layouts.append(_initial_layout)
dags = _dags_2_dags(dags, basis_gates=basis_gates, coupling_map=coupling_map,
initial_layouts=initial_layouts, seed_mapper=seed_mapper,
pass_manager=pass_manager)
# TODO: change it to circuits
# TODO: make it parallel
return dags
def _circuits_2_dags(circuits):
"""Convert a list of circuits into a list of dags.
Args:
circuits (list[QuantumCircuit]): circuit to compile
Returns:
list[DAGCircuit]: the dag representation of the circuits
to be used in the transpiler
"""
dags = parallel_map(DAGCircuit.fromQuantumCircuit, circuits)
return dags
def _dags_2_dags(dags, basis_gates='u1,u2,u3,cx,id', coupling_map=None,
initial_layouts=None, seed_mapper=None, pass_manager=None):
"""Transform multiple dags through a sequence of passes.
Args:
dags (list[DAGCircuit]): dag circuits to transform
basis_gates (str): a comma separated string for the target basis gates
coupling_map (list): A graph of coupling
initial_layouts (list[dict]): A mapping of qubit to qubit for each dag
seed_mapper (int): random seed_mapper for the swap mapper
pass_manager (PassManager): pass manager instance for the transpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
list[DAGCircuit]: the dag circuits after going through transpilation
Raises:
TranspilerError: if the format is not valid.
Events:
terra.transpiler.transpile_dag.start: When the transpilation of the dags is about to start
terra.transpiler.transpile_dag.done: When one of the dags has finished it's transpilation
terra.transpiler.transpile_dag.finish: When all the dags have finished transpiling
"""
def _emmit_start(num_dags):
""" Emmit a dag transpilation start event
Arg:
num_dags: Number of dags to be transpiled"""
Publisher().publish("terra.transpiler.transpile_dag.start", num_dags)
Subscriber().subscribe("terra.transpiler.parallel.start", _emmit_start)
def _emmit_done(progress):
""" Emmit a dag transpilation done event
Arg:
progress: The dag number that just has finshed transpile"""
Publisher().publish("terra.transpiler.transpile_dag.done", progress)
Subscriber().subscribe("terra.transpiler.parallel.done", _emmit_done)
def _emmit_finish():
""" Emmit a dag transpilation finish event
Arg:
progress: The dag number that just has finshed transpile"""
Publisher().publish("terra.transpiler.transpile_dag.finish")
Subscriber().subscribe("terra.transpiler.parallel.finish", _emmit_finish)
dags_layouts = list(zip(dags, initial_layouts))
final_dags = parallel_map(_transpile_dags_parallel, dags_layouts,
task_kwargs={'basis_gates': basis_gates,
'coupling_map': coupling_map,
'seed_mapper': seed_mapper,
'pass_manager': pass_manager})
return final_dags
def _transpile_dags_parallel(dag_layout_tuple, basis_gates='u1,u2,u3,cx,id',
coupling_map=None, seed_mapper=None, pass_manager=None):
"""Helper function for transpiling in parallel (if available).
Args:
dag_layout_tuple (tuple): Tuples of dags and their initial_layouts
basis_gates (str): a comma separated string for the target basis gates
coupling_map (list): A graph of coupling
seed_mapper (int): random seed_mapper for the swap mapper
pass_manager (PassManager): pass manager instance for the transpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
DAGCircuit: DAG circuit after going through transpilation.
"""
final_dag, final_layout = transpile_dag(
dag_layout_tuple[0],
basis_gates=basis_gates,
coupling_map=coupling_map,
initial_layout=dag_layout_tuple[1],
get_layout=True,
seed_mapper=seed_mapper,
pass_manager=pass_manager)
final_dag.layout = [[k, v]
for k, v in final_layout.items()] if final_layout else None
return final_dag
# pylint: disable=redefined-builtin
def transpile_dag(dag, basis_gates='u1,u2,u3,cx,id', coupling_map=None,
initial_layout=None, get_layout=False,
format='dag', seed_mapper=None, pass_manager=None):
"""Transform a dag circuit into another dag circuit (transpile), through
consecutive passes on the dag.
Args:
dag (DAGCircuit): dag circuit to transform via transpilation
basis_gates (str): a comma separated string for the target basis gates
coupling_map (list): A graph of coupling::
[
[control0(int), target0(int)],
[control1(int), target1(int)],
]
eg. [[0, 2], [1, 2], [1, 3], [3, 4]}
initial_layout (dict): A mapping of qubit to qubit::
{
("q", start(int)): ("q", final(int)),
...
}
eg.
{
("q", 0): ("q", 0),
("q", 1): ("q", 1),
("q", 2): ("q", 2),
("q", 3): ("q", 3)
}
get_layout (bool): flag for returning the final layout after mapping
format (str): The target format of the compilation:
{'dag', 'json', 'qasm'}
seed_mapper (int): random seed_mapper for the swap mapper
pass_manager (PassManager): pass manager instance for the transpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
DAGCircuit: transformed dag
DAGCircuit, dict: transformed dag along with the final layout on backend qubits
Raises:
TranspilerError: if the format is not valid.
"""
# TODO: `basis_gates` will be removed after we have the unroller pass.
# TODO: `coupling_map`, `initial_layout`, `get_layout`, `seed_mapper` removed after mapper pass.
# TODO: move this to the mapper pass
num_qubits = sum([qreg.size for qreg in dag.qregs.values()])
if num_qubits == 1 or coupling_map == "all-to-all":
coupling_map = None
final_layout = None
if pass_manager:
# run the passes specified by the pass manager
# TODO return the property set too. See #1086
dag = pass_manager.run_passes(dag)
else:
# default set of passes
# TODO: move each step here to a pass, and use a default passmanager below
basis = basis_gates.split(',') if basis_gates else []
dag_unroller = _dagunroller.DagUnroller(
dag, _dagbackend.DAGBackend(basis))
dag = dag_unroller.expand_gates()
# if a coupling map is given compile to the map
if coupling_map:
logger.info("pre-mapping properties: %s",
dag.property_summary())
# Insert swap gates
coupling = Coupling(coupling_list2dict(coupling_map))
removed_meas = remove_last_measurements(dag)
logger.info("measurements moved: %s", removed_meas)
logger.info("initial layout: %s", initial_layout)
dag, final_layout, last_layout = swap_mapper(
dag, coupling, initial_layout, trials=20, seed=seed_mapper)
logger.info("final layout: %s", final_layout)
# Expand swaps
dag_unroller = _dagunroller.DagUnroller(
dag, _dagbackend.DAGBackend(basis))
dag = dag_unroller.expand_gates()
# Change cx directions
dag = direction_mapper(dag, coupling)
# Simplify cx gates
cx_cancellation(dag)
# Simplify single qubit gates
dag = optimize_1q_gates(dag)
return_last_measurements(dag, removed_meas,
last_layout)
logger.info("post-mapping properties: %s",
dag.property_summary())
# choose output format
# TODO: do we need all of these formats, or just the dag?
if format == 'dag':
compiled_circuit = dag
elif format == 'json':
# FIXME: JsonBackend is wrongly taking an ordered dict as basis, not list
dag_unroller = _dagunroller.DagUnroller(
dag, _jsonbackend.JsonBackend(dag.basis))
compiled_circuit = dag_unroller.execute()
elif format == 'qasm':
compiled_circuit = dag.qasm()
else:
raise TranspilerError('unrecognized circuit format')
if get_layout:
return compiled_circuit, final_layout
return compiled_circuit
def _best_subset(backend, n_qubits):
"""Computes the qubit mapping with the best
connectivity.
Parameters:
backend (Qiskit.BaseBackend): A QISKit backend instance.
n_qubits (int): Number of subset qubits to consider.
Returns:
ndarray: Array of qubits to use for best
connectivity mapping.
Raises:
QISKitError: Wrong number of qubits given.
"""
if n_qubits == 1:
return np.array([0])
elif n_qubits <= 0:
raise QISKitError('Number of qubits <= 0.')
device_qubits = backend.configuration()['n_qubits']
if n_qubits > device_qubits:
raise QISKitError('Number of qubits greater than device.')
cmap = np.asarray(backend.configuration()['coupling_map'])
data = np.ones_like(cmap[:, 0])
sp_cmap = sp.coo_matrix((data, (cmap[:, 0], cmap[:, 1])),
shape=(device_qubits, device_qubits)).tocsr()
best = 0
best_map = None
# do bfs with each node as starting point
for k in range(sp_cmap.shape[0]):
bfs = cs.breadth_first_order(sp_cmap, i_start=k, directed=False,
return_predecessors=False)
connection_count = 0
for i in range(n_qubits):
node_idx = bfs[i]
for j in range(sp_cmap.indptr[node_idx],
sp_cmap.indptr[node_idx + 1]):
node = sp_cmap.indices[j]
for counter in range(n_qubits):
if node == bfs[counter]:
connection_count += 1
break
if connection_count > best:
best = connection_count
best_map = bfs[0:n_qubits]
return best_map
def _matches_coupling_map(dag, coupling_map):
"""Iterate over circuit gates to check if all multi-qubit couplings
match the qubit coupling graph in the backend.
Parameters:
dag (DAGCircuit): DAG representation of circuit.
coupling_map (list): Backend coupling map, represented as an adjacency list.
Returns:
bool: True if all gates readily fit the backend coupling graph.
False if there's at least one gate that uses multiple qubits
which does not match the backend couplings.
"""
match = True
for _, data in dag.multi_graph.nodes(data=True):
if data['type'] == 'op':
gate_map = [qr[1] for qr in data['qargs']]
if len(gate_map) > 1:
if gate_map not in coupling_map:
match = False
break
return match
def _pick_best_layout(dag, backend):
"""Pick a convenient layout depending on the best matching qubit connectivity
Parameters:
dag (DAGCircuit): DAG representation of circuit.
backend (BaseBackend) : The backend with the coupling_map for searching
Returns:
dict: A special ordered initial_layout
"""
num_qubits = sum([qreg.size for qreg in dag.qregs.values()])
best_sub = _best_subset(backend, num_qubits)
layout = {}
map_iter = 0
for key, value in dag.qregs.items():
for i in range(value.size):
layout[(key, i)] = ('q', best_sub[map_iter])
map_iter += 1
return layout
<|code_end|>
|
qiskit/_quantumcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=cyclic-import
"""
Quantum circuit object.
"""
import itertools
import warnings
from collections import OrderedDict
from copy import deepcopy
from qiskit.qasm import _qasm
from qiskit.unrollers import _unroller
from qiskit.unrollers import _circuitbackend
from qiskit._qiskiterror import QISKitError
from qiskit._quantumregister import QuantumRegister
from qiskit._classicalregister import ClassicalRegister
from qiskit.tools import visualization
from qiskit.dagcircuit import DAGCircuit
def _circuit_from_qasm(qasm, basis=None):
default_basis = ["id", "u0", "u1", "u2", "u3", "x", "y", "z", "h", "s",
"sdg", "t", "tdg", "rx", "ry", "rz", "cx", "cy", "cz",
"ch", "crz", "cu1", "cu3", "swap", "ccx", "cswap"]
if not basis:
basis = default_basis
ast = qasm.parse()
unroll = _unroller.Unroller(
ast, _circuitbackend.CircuitBackend(basis))
circuit = unroll.execute()
return circuit
class QuantumCircuit(object):
"""Quantum circuit."""
instances = 0
prefix = 'circuit'
# Class variable OPENQASM header
header = "OPENQASM 2.0;"
# Class variable with gate definitions
# This is a dict whose values are dicts with the
# following keys:
# "print" = True or False
# "opaque" = True or False
# "n_args" = number of real parameters
# "n_bits" = number of qubits
# "args" = list of parameter names
# "bits" = list of qubit names
# "body" = GateBody AST node
definitions = OrderedDict()
@staticmethod
def from_qasm_file(path):
"""Take in a QASM file and generate a QuantumCircuit object.
Args:
path (str): Path to the file for a QASM program
Return:
QuantumCircuit: The QuantumCircuit object for the input QASM
"""
qasm = _qasm.Qasm(filename=path)
return _circuit_from_qasm(qasm)
@staticmethod
def from_qasm_str(qasm_str):
"""Take in a QASM string and generate a QuantumCircuit object.
Args:
qasm_str (str): A QASM program string
Return:
QuantumCircuit: The QuantumCircuit object for the input QASM
"""
qasm = _qasm.Qasm(data=qasm_str)
return _circuit_from_qasm(qasm)
def __init__(self, *regs, name=None):
"""Create a new circuit.
A circuit is a list of instructions bound to some registers.
Args:
*regs (Registers): registers to include in the circuit.
name (str or None): the name of the quantum circuit. If
None, an automatically generated string will be assigned.
Raises:
QISKitError: if the circuit name, if given, is not valid.
"""
if name is None:
name = self.cls_prefix() + str(self.cls_instances())
self._increment_instances()
if not isinstance(name, str):
raise QISKitError("The circuit name should be a string "
"(or None to auto-generate a name).")
self.name = name
# Data contains a list of instructions in the order they were applied.
self.data = []
# This is a map of registers bound to this circuit, by name.
self.qregs = []
self.cregs = []
self.add_register(*regs)
@classmethod
def _increment_instances(cls):
cls.instances += 1
@classmethod
def cls_instances(cls):
"""Return the current number of instances of this class,
useful for auto naming."""
return cls.instances
@classmethod
def cls_prefix(cls):
"""Return the prefix to use for auto naming."""
return cls.prefix
def has_register(self, register):
"""
Test if this circuit has the register r.
Args:
register (Register): a quantum or classical register.
Returns:
bool: True if the register is contained in this circuit.
"""
has_reg = False
if (isinstance(register, QuantumRegister) and
register in self.qregs):
has_reg = True
elif (isinstance(register, ClassicalRegister) and
register in self.cregs):
has_reg = True
return has_reg
def combine(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Return self + rhs as a new object.
"""
# Check registers in LHS are compatible with RHS
self._check_compatible_regs(rhs)
# Make new circuit with combined registers
combined_qregs = deepcopy(self.qregs)
combined_cregs = deepcopy(self.cregs)
for element in rhs.qregs:
if element not in self.qregs:
combined_qregs.append(element)
for element in rhs.cregs:
if element not in self.cregs:
combined_cregs.append(element)
circuit = QuantumCircuit(*combined_qregs, *combined_cregs)
for gate in itertools.chain(self.data, rhs.data):
gate.reapply(circuit)
return circuit
def extend(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Modify and return self.
"""
# Check registers in LHS are compatible with RHS
self._check_compatible_regs(rhs)
# Add new registers
for element in rhs.qregs:
if element not in self.qregs:
self.qregs.append(element)
for element in rhs.cregs:
if element not in self.cregs:
self.cregs.append(element)
# Add new gates
for gate in rhs.data:
gate.reapply(self)
return self
def __add__(self, rhs):
"""Overload + to implement self.concatenate."""
return self.combine(rhs)
def __iadd__(self, rhs):
"""Overload += to implement self.extend."""
return self.extend(rhs)
def __len__(self):
"""Return number of operations in circuit."""
return len(self.data)
def __getitem__(self, item):
"""Return indexed operation."""
return self.data[item]
def _attach(self, instruction):
"""Attach an instruction."""
self.data.append(instruction)
return instruction
def add_register(self, *regs):
"""Add registers."""
for register in regs:
if register in self.qregs or register in self.cregs:
raise QISKitError("register name \"%s\" already exists"
% register.name)
if isinstance(register, QuantumRegister):
self.qregs.append(register)
elif isinstance(register, ClassicalRegister):
self.cregs.append(register)
else:
raise QISKitError("expected a register")
def add(self, *regs):
"""Add registers."""
warnings.warn('The add() function is deprecated and will be '
'removed in a future release. Instead use '
'QuantumCircuit.add_register().', DeprecationWarning)
self.add_register(*regs)
def _check_qreg(self, register):
"""Raise exception if r is not in this circuit or not qreg."""
if not isinstance(register, QuantumRegister):
raise QISKitError("expected quantum register")
if not self.has_register(register):
raise QISKitError(
"register '%s' not in this circuit" %
register.name)
def _check_qubit(self, qubit):
"""Raise exception if qubit is not in this circuit or bad format."""
if not isinstance(qubit, tuple):
raise QISKitError("%s is not a tuple."
"A qubit should be formated as a tuple." % str(qubit))
if not len(qubit) == 2:
raise QISKitError("%s is not a tuple with two elements, but %i instead" % len(qubit))
if not isinstance(qubit[1], int):
raise QISKitError("The second element of a tuple defining a qubit should be an int:"
"%s was found instead" % type(qubit[1]).__name__)
self._check_qreg(qubit[0])
qubit[0].check_range(qubit[1])
def _check_creg(self, register):
"""Raise exception if r is not in this circuit or not creg."""
if not isinstance(register, ClassicalRegister):
raise QISKitError("expected classical register")
if not self.has_register(register):
raise QISKitError(
"register '%s' not in this circuit" %
register.name)
def _check_dups(self, qubits):
"""Raise exception if list of qubits contains duplicates."""
squbits = set(qubits)
if len(squbits) != len(qubits):
raise QISKitError("duplicate qubit arguments")
def _check_compatible_regs(self, rhs):
"""Raise exception if the circuits are defined on incompatible registers"""
list1 = self.qregs + self.cregs
list2 = rhs.qregs + rhs.cregs
for element1 in list1:
for element2 in list2:
if element2.name == element1.name:
if element1 != element2:
raise QISKitError("circuits are not compatible")
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.definitions[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.definitions[name]["n_args"] > 0:
out += "(" + ",".join(self.definitions[name]["args"]) + ")"
out += " " + ",".join(self.definitions[name]["bits"])
if self.definitions[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.definitions[name]["body"].qasm() + "}\n"
return out
def qasm(self):
"""Return OPENQASM string."""
string_temp = self.header + "\n"
for gate_name in self.definitions:
if self.definitions[gate_name]["print"]:
string_temp += self._gate_string(gate_name)
for register in self.qregs:
string_temp += register.qasm() + "\n"
for register in self.cregs:
string_temp += register.qasm() + "\n"
for instruction in self.data:
string_temp += instruction.qasm() + "\n"
return string_temp
def draw(self, scale=0.7, filename=None, style=None, output='text',
interactive=False, line_length=None, plot_barriers=True,
reverse_bits=False):
"""Draw the quantum circuit
Using the output parameter you can specify the format. The choices are:
0. text: ASCII art string
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style
file. You can refer to the
:ref:`Style Dict Doc <style-dict-doc>` for
more information on the contents.
output (str): Select the output method to use for drawing the
circuit. Valid choices are `text`, `latex`, `latex_source`,
`mpl`.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the
latex_source output type this has no effect
line_length (int): sets the length of the lines generated by `text`
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: (output `latex`) an in-memory representation of the
image of the circuit diagram.
matplotlib.figure: (output `mpl`) a matplotlib figure object for
the circuit diagram.
String: (output `latex_source`). The LaTeX source code.
TextDrawing: (output `text`). A drawing that can be printed as
ascii art
Raises:
VisualizationError: when an invalid output method is selected
"""
return visualization.circuit_drawer(self, scale=scale,
filename=filename, style=style,
output=output,
interactive=interactive,
line_length=line_length,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
def size(self):
"""Return total number of operations in circuit."""
dag = DAGCircuit.fromQuantumCircuit(self)
return dag.size()
def depth(self):
"""Return circuit depth (i.e. length of critical path)."""
dag = DAGCircuit.fromQuantumCircuit(self)
return dag.depth()
def width(self):
"""Return number of qubits in circuit."""
dag = DAGCircuit.fromQuantumCircuit(self)
return dag.width()
def count_ops(self):
"""Count each operation kind in the circuit.
Returns:
dict: a breakdown of how many operations of each kind.
"""
dag = DAGCircuit.fromQuantumCircuit(self)
return dag.count_ops()
def num_tensor_factors(self):
"""How many non-entangled subcircuits can the circuit be factored to."""
dag = DAGCircuit.fromQuantumCircuit(self)
return dag.num_tensor_factors()
def __str__(self):
return str(self.draw(output='text'))
<|code_end|>
qiskit/dagcircuit/_dagcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Object to represent a quantum circuit as a directed acyclic graph.
The nodes in the graph are either input/output nodes or operation nodes.
The operation nodes are elements of a basis that is part of the circuit.
The QASM definitions of the basis elements are carried with the circuit.
The edges correspond to qubits or bits in the circuit. A directed edge
from node A to node B means that the (qu)bit passes from the output of A
to the input of B. The object's methods allow circuits to be constructed,
composed, and modified. Some natural properties like depth can be computed
directly from the graph.
"""
from collections import OrderedDict
import copy
import itertools
import networkx as nx
import sympy
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QISKitError
from qiskit import _compositegate
from ._dagcircuiterror import DAGCircuitError
class DAGCircuit:
"""
Quantum circuit as a directed acyclic graph.
There are 3 types of nodes in the graph: inputs, outputs, and operations.
The nodes are connected by directed edges that correspond to qubits and
bits.
"""
# pylint: disable=invalid-name
def __init__(self):
"""Create an empty circuit."""
# Circuit name. Generally, this corresponds to the name
# of the QuantumCircuit from which the DAG was generated.
self.name = None
# Map from a wire's name (reg,idx) to a Bool that is True if the
# wire is a classical bit and False if the wire is a qubit.
self.wire_type = OrderedDict()
# Map from wire names (reg,idx) to input nodes of the graph
self.input_map = OrderedDict()
# Map from wire names (reg,idx) to output nodes of the graph
self.output_map = OrderedDict()
# Running count of the total number of nodes
self.node_counter = 0
# Map of named operations in this circuit and their signatures.
# The signature is an integer tuple (nq,nc,np) specifying the
# number of input qubits, input bits, and real parameters.
# The definition is external to the circuit object.
self.basis = OrderedDict()
# Directed multigraph whose nodes are inputs, outputs, or operations.
# Operation nodes have equal in- and out-degrees and carry
# additional data about the operation, including the argument order
# and parameter values.
# Input nodes have out-degree 1 and output nodes have in-degree 1.
# Edges carry wire labels (reg,idx) and each operation has
# corresponding in- and out-edges with the same wire labels.
self.multi_graph = nx.MultiDiGraph()
# Map of qregs to sizes
self.qregs = OrderedDict()
# Map of cregs to sizes
self.cregs = OrderedDict()
# Map of user defined gates to ast nodes defining them
self.gates = OrderedDict()
# Output precision for printing floats
self.prec = 10
# layout of dag quantum registers on the chip
# TODO: rethink this. doesn't seem related to concept of DAG,
# but if we want to be able to generate qobj
# directly from a dag, we need it.
self.layout = []
def get_qubits(self):
"""Return a list of qubits as (qreg, index) pairs."""
return [(k, i) for k, v in self.qregs.items() for i in range(v.size)]
def rename_register(self, regname, newname):
"""Rename a classical or quantum register throughout the circuit.
regname = existing register name string
newname = replacement register name string
"""
if regname == newname:
return
if newname in self.qregs or newname in self.cregs:
raise DAGCircuitError("duplicate register name %s" % newname)
if regname not in self.qregs and regname not in self.cregs:
raise DAGCircuitError("no register named %s" % regname)
iscreg = False
if regname in self.qregs:
self.qregs[newname] = self.qregs[regname]
self.qregs.pop(regname, None)
reg_size = self.qregs[newname].size
if regname in self.cregs:
self.cregs[newname] = self.cregs[regname]
self.cregs.pop(regname, None)
reg_size = self.cregs[newname].size
iscreg = True
for i in range(reg_size):
self.wire_type[(newname, i)] = iscreg
self.wire_type.pop((regname, i), None)
self.input_map[(newname, i)] = self.input_map[(regname, i)]
self.input_map.pop((regname, i), None)
self.output_map[(newname, i)] = self.output_map[(regname, i)]
self.output_map.pop((regname, i), None)
# n node d = data
for _, d in self.multi_graph.nodes(data=True):
if d["type"] == "in" or d["type"] == "out":
if d["name"][0] == regname:
d["name"] = (newname, d["name"][1])
elif d["type"] == "op":
qa = []
for a in d["qargs"]:
if a[0] == regname:
a = (newname, a[1])
qa.append(a)
d["qargs"] = qa
ca = []
for a in d["cargs"]:
if a[0] == regname:
a = (newname, a[1])
ca.append(a)
d["cargs"] = ca
if d["condition"] is not None:
if d["condition"][0] == regname:
d["condition"] = (newname, d["condition"][1])
# eX = edge, d= data
for _, _, d in self.multi_graph.edges(data=True):
if d["name"][0] == regname:
d["name"] = (newname, d["name"][1])
def remove_all_ops_named(self, opname):
"""Remove all operation nodes with the given name."""
for n in self.get_named_nodes(opname):
self._remove_op_node(n)
def fs(self, number):
"""Format a float f as a string with self.prec digits."""
fmt = "{0:0.%snumber}" % self.prec
return fmt.format(number)
def add_qreg(self, qreg):
"""Add all wires in a quantum register."""
if not isinstance(qreg, QuantumRegister):
raise DAGCircuitError("not a QuantumRegister instance.")
if qreg.name in self.qregs:
raise DAGCircuitError("duplicate register %s" % qreg.name)
self.qregs[qreg.name] = qreg
for j in range(qreg.size):
self._add_wire((qreg.name, j))
def add_creg(self, creg):
"""Add all wires in a classical register."""
if not isinstance(creg, ClassicalRegister):
raise DAGCircuitError("not a ClassicalRegister instance.")
if creg.name in self.cregs:
raise DAGCircuitError("duplicate register %s" % creg.name)
self.cregs[creg.name] = creg
for j in range(creg.size):
self._add_wire((creg.name, j), True)
def _add_wire(self, name, isClassical=False):
"""Add a qubit or bit to the circuit.
name is a (string,int) tuple containing register name and index
This adds a pair of in and out nodes connected by an edge.
"""
if name not in self.wire_type:
self.wire_type[name] = isClassical
self.node_counter += 1
self.input_map[name] = self.node_counter
self.node_counter += 1
self.output_map[name] = self.node_counter
in_node = self.input_map[name]
out_node = self.output_map[name]
self.multi_graph.add_edge(in_node, out_node)
self.multi_graph.node[in_node]["type"] = "in"
self.multi_graph.node[out_node]["type"] = "out"
self.multi_graph.node[in_node]["name"] = name
self.multi_graph.node[out_node]["name"] = name
self.multi_graph.adj[in_node][out_node][0]["name"] = name
else:
raise DAGCircuitError("duplicate wire %s" % name)
def add_basis_element(self, name, number_qubits,
number_classical=0, number_parameters=0):
"""Add an operation to the basis.
name is string label for operation
number_qubits is number of qubit arguments
number_classical is number of bit arguments
number_parameters is number of real parameters
The parameters (nq,nc,np) are ignored for the special case
when name = "barrier". The barrier instruction has a variable
number of qubit arguments.
"""
if name not in self.basis:
self.basis[name] = (
number_qubits,
number_classical,
number_parameters)
if name in self.gates:
if self.gates[name]["n_args"] != number_parameters or \
self.gates[name]["n_bits"] != number_qubits or number_classical != 0:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def add_gate_data(self, name, gatedata):
"""Add the definition of a gate.
gatedata is dict with fields:
"print" = True or False
"opaque" = True or False
"n_args" = number of real parameters
"n_bits" = number of qubits
"args" = list of parameter names
"bits" = list of qubit names
"body" = GateBody AST node
"""
if name not in self.gates:
self.gates[name] = gatedata
if name in self.basis:
if self.basis[name][0] != self.gates[name]["n_bits"] or \
self.basis[name][1] != 0 or \
self.basis[name][2] != self.gates[name]["n_args"]:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def _check_basis_data(self, name, qargs, cargs, params):
"""Check the arguments against the data for this operation.
name is a string
qargs is a list of tuples like ("q",0)
cargs is a list of tuples like ("c",0)
params is a list of strings that represent floats
"""
# Check that we have this operation
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
# Check the number of arguments matches the signature
if name in ["barrier"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if params:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
elif name in ["snapshot", "noise", "save", "load"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if not params:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
else:
if len(qargs) != self.basis[name][0]:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if len(cargs) != self.basis[name][1]:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if len(params) != self.basis[name][2]:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
def _check_condition(self, name, condition):
"""Verify that the condition is valid.
name is a string used for error reporting
condition is either None or a tuple (string,int) giving (creg,value)
"""
# Verify creg exists
if condition is not None and condition[0] not in self.cregs:
raise DAGCircuitError("invalid creg in condition for %s" % name)
def _check_bits(self, args, amap, bval):
"""Check the values of a list of (qu)bit arguments.
For each element A of args, check that amap contains A and
self.wire_type[A] equals bval.
args is a list of (regname,idx) tuples
amap is a dictionary keyed on (regname,idx) tuples
bval is boolean
"""
# Check for each wire
for q in args:
if q not in amap:
raise DAGCircuitError("(qu)bit %s not found" % (q,))
if self.wire_type[q] != bval:
raise DAGCircuitError("expected wire type %s for %s"
% (bval, q))
def _bits_in_condition(self, cond):
"""Return a list of bits (regname,idx) in the given condition.
cond is either None or a (regname,int) tuple specifying
a classical if condition.
"""
all_bits = []
if cond is not None:
all_bits.extend([(cond[0], j) for j in range(self.cregs[cond[0]].size)])
return all_bits
def _add_op_node(self, nname, nqargs, ncargs, nparams, ncondition, nop):
"""Add a new operation node to the graph and assign properties.
nname node name
nqargs quantum arguments
ncargs classical arguments
nparams parameters
ncondition classical condition (or None)
nop Instruction instance representing this operation
"""
# Add a new operation node to the graph
self.node_counter += 1
self.multi_graph.add_node(self.node_counter)
# Update that operation node's data
self.multi_graph.node[self.node_counter]["type"] = "op"
self.multi_graph.node[self.node_counter]["name"] = nname
self.multi_graph.node[self.node_counter]["qargs"] = nqargs
self.multi_graph.node[self.node_counter]["cargs"] = ncargs
self.multi_graph.node[self.node_counter]["params"] = nparams
self.multi_graph.node[self.node_counter]["condition"] = ncondition
self.multi_graph.node[self.node_counter]["op"] = nop
def apply_operation_back(self, name, qargs, cargs=None, params=None,
condition=None, op=None):
"""Apply an operation to the output of the circuit.
name is a string
qargs is a list of tuples like ("q",0)
cargs is a list of tuples like ("c",0)
params is a list of symbols that represent numbers
condition is either None or a tuple (string,int) giving (creg,value)
op is an Instruction instance representing this node
"""
cargs = cargs or []
params = params or []
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(name, qargs, cargs, params)
self._check_condition(name, condition)
self._check_bits(qargs, self.output_map, False)
self._check_bits(all_cbits, self.output_map, True)
self._add_op_node(name, qargs, cargs, params, condition, op)
# Add new in-edges from predecessors of the output nodes to the
# operation node while deleting the old in-edges of the output nodes
# and adding new edges from the operation node to each output node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.predecessors(self.output_map[q]))
if len(ie) != 1:
raise QISKitError("output node has multiple in-edges")
self.multi_graph.add_edge(ie[0], self.node_counter, name=q)
self.multi_graph.remove_edge(ie[0], self.output_map[q])
self.multi_graph.add_edge(
self.node_counter, self.output_map[q], name=q)
def apply_operation_front(self, name, qargs, cargs=None, params=None,
condition=None, op=None):
"""Apply an operation to the input of the circuit.
name is a string
qargs is a list of strings like "q[0]"
cargs is a list of strings like "c[0]"
params is a list of strings that represent floats
condition is either None or a tuple (string,int) giving (creg,value)
"""
cargs = cargs or []
params = params or []
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(name, qargs, cargs, params)
self._check_condition(name, condition)
self._check_bits(qargs, self.input_map, False)
self._check_bits(all_cbits, self.input_map, True)
self._add_op_node(name, qargs, cargs, params, condition, op)
# Add new out-edges to successors of the input nodes from the
# operation node while deleting the old out-edges of the input nodes
# and adding new edges to the operation node from each input node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = self.multi_graph.successors(self.input_map[q])
if len(ie) != 1:
raise QISKitError("input node has multiple out-edges")
self.multi_graph.add_edge(self.node_counter, ie[0], name=q)
self.multi_graph.remove_edge(self.input_map[q], ie[0])
self.multi_graph.add_edge(
self.input_map[q], self.node_counter, name=q)
def _make_union_basis(self, input_circuit):
"""Return a new basis map.
The new basis is a copy of self.basis with
new elements of input_circuit.basis added.
input_circuit is a DAGCircuit
"""
union_basis = self.basis.copy()
for g in input_circuit.basis:
if g not in union_basis:
union_basis[g] = input_circuit.basis[g]
if union_basis[g] != input_circuit.basis[g]:
raise DAGCircuitError("incompatible basis")
return union_basis
def _make_union_gates(self, input_circuit):
"""Return a new gates map.
The new gates are a copy of self.gates with
new elements of input_circuit.gates added.
input_circuit is a DAGCircuit
NOTE: gates in input_circuit that are also in self must
be *identical* to the gates in self
"""
union_gates = {}
for k, v in self.gates.items():
union_gates[k] = v
for k, v in input_circuit.gates.items():
if k not in union_gates:
union_gates[k] = v
if union_gates[k]["opaque"] != input_circuit.gates[k]["opaque"] or \
union_gates[k]["n_args"] != input_circuit.gates[k]["n_args"] or \
union_gates[k]["n_bits"] != input_circuit.gates[k]["n_bits"] or \
union_gates[k]["args"] != input_circuit.gates[k]["args"] or \
union_gates[k]["bits"] != input_circuit.gates[k]["bits"]:
raise DAGCircuitError("inequivalent gate definitions for %s"
% k)
return union_gates
def _check_wiremap_registers(self, wire_map, keyregs, valregs,
valreg=True):
"""Check that wiremap neither fragments nor leaves duplicate registers.
1. There are no fragmented registers. A register in keyregs
is fragmented if not all of its (qu)bits are renamed by wire_map.
2. There are no duplicate registers. A register is duplicate if
it appears in both self and keyregs but not in wire_map.
wire_map is a map from (regname,idx) in keyregs to (regname,idx)
in valregs
keyregs is a map from register names to Register objects
valregs is a map from register names to Register objects
valreg is a Bool, if False the method ignores valregs and does not
add regs for bits in the wire_map image that don't appear in valregs
Return the set of regs to add to self
"""
add_regs = set()
reg_frag_chk = {}
for k, v in keyregs.items():
reg_frag_chk[k] = {j: False for j in range(v.size)}
for k in wire_map.keys():
if k[0] in keyregs:
reg_frag_chk[k[0]][k[1]] = True
for k, v in reg_frag_chk.items():
rname = ",".join(map(str, k))
s = set(v.values())
if len(s) == 2:
raise DAGCircuitError("wire_map fragments reg %s" % rname)
elif s == set([False]):
if k in self.qregs or k in self.cregs:
raise DAGCircuitError("unmapped duplicate reg %s" % rname)
else:
# Add registers that appear only in keyregs
add_regs.add(keyregs[k])
else:
if valreg:
# If mapping to a register not in valregs, add it.
# (k,0) exists in wire_map because wire_map doesn't
# fragment k
if not wire_map[(k, 0)][0] in valregs:
size = max(map(lambda x: x[1], filter(lambda x: x[0] == wire_map[(k, 0)][0],
wire_map.values())))
qreg = QuantumRegister(wire_map[(k, 0)][0], size + 1)
add_regs.add(qreg)
return add_regs
def _check_wiremap_validity(self, wire_map, keymap, valmap, input_circuit):
"""Check that the wiremap is consistent.
Check that the wiremap refers to valid wires and that
those wires have consistent types.
wire_map is a map from (regname,idx) in keymap to (regname,idx)
in valmap
keymap is a map whose keys are wire_map keys
valmap is a map whose keys are wire_map values
input_circuit is a DAGCircuit
"""
for k, v in wire_map.items():
kname = ",".join(map(str, k))
vname = ",".join(map(str, v))
if k not in keymap:
raise DAGCircuitError("invalid wire mapping key %s" % kname)
if v not in valmap:
raise DAGCircuitError("invalid wire mapping value %s"
% vname)
if input_circuit.wire_type[k] != self.wire_type[v]:
raise DAGCircuitError("inconsistent wire_map at (%s,%s)"
% (kname, vname))
def _map_condition(self, wire_map, condition):
"""Use the wire_map dict to change the condition tuple's creg name.
wire_map is map from wires to wires
condition is a tuple (reg,int)
Returns the new condition tuple
"""
if condition is None:
n_condition = None
else:
# Map the register name, using fact that registers must not be
# fragmented by the wire_map (this must have been checked
# elsewhere)
bit0 = (condition[0], 0)
n_condition = (wire_map.get(bit0, bit0)[0], condition[1])
return n_condition
def compose_back(self, input_circuit, wire_map=None):
"""Apply the input circuit to the output of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of input qubits of the input circuit are mapped
to a subset of output qubits of this circuit.
wire_map[input_qubit_to_input_circuit] = output_qubit_of_self
"""
wire_map = wire_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map for duplicate values
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_wiremap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.input_map,
self.output_map, input_circuit)
# Compose
self.basis = union_basis
self.gates = union_gates
for node in nx.topological_sort(input_circuit.multi_graph):
nd = input_circuit.multi_graph.node[node]
if nd["type"] == "in":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["name"], nd["name"])
# the mapped wire should already exist
if m_name not in self.output_map:
raise QISKitError("wire (%s,%d) not in self" % (m_name[0], m_name[1]))
if nd["name"] not in input_circuit.wire_type:
raise QISKitError("inconsistent wire_type for (%s,%d) in input_circuit"
% (nd["name"][0], nd["name"][1]))
elif nd["type"] == "out":
# ignore output nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: wire_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x), nd["cargs"]))
self.apply_operation_back(nd["name"], m_qargs, m_cargs,
nd["params"], condition, nd["op"])
else:
raise QISKitError("bad node type %s" % nd["type"])
def compose_front(self, input_circuit, wire_map=None):
"""Apply the input circuit to the input of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of output qubits of the input circuit are mapped
to a subset of input qubits of
this circuit.
"""
wire_map = wire_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_wiremap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.output_map,
self.input_map, input_circuit)
# Compose
self.basis = union_basis
self.gates = union_gates
for n in reversed(list(nx.topological_sort(input_circuit.multi_graph))):
nd = input_circuit.multi_graph.node[n]
if nd["type"] == "out":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["name"], nd["name"])
# the mapped wire should already exist
if m_name not in self.input_map:
raise QISKitError("wire (%s,%d) not in self" % (m_name[0], m_name[1]))
if nd["name"] not in input_circuit.wire_type:
raise QISKitError(
"inconsistent wire_type for (%s,%d) in input_circuit"
% (nd["name"][0], nd["name"][1]))
elif nd["type"] == "in":
# ignore input nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: wire_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x), nd["cargs"]))
self.apply_operation_front(nd["name"], m_qargs, m_cargs,
nd["params"], condition, nd["op"])
else:
raise QISKitError("bad node type %s" % nd["type"])
def size(self):
"""Return the number of operations."""
return self.multi_graph.order() - 2 * len(self.wire_type)
def depth(self):
"""Return the circuit depth."""
if not nx.is_directed_acyclic_graph(self.multi_graph):
raise QISKitError("not a DAG")
return nx.dag_longest_path_length(self.multi_graph) - 1
def width(self):
"""Return the total number of qubits used by the circuit."""
return len(self.wire_type) - self.num_cbits()
def num_cbits(self):
"""Return the total number of bits used by the circuit."""
return list(self.wire_type.values()).count(True)
def num_tensor_factors(self):
"""Compute how many components the circuit can decompose into."""
return nx.number_weakly_connected_components(self.multi_graph)
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.gates[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.gates[name]["n_args"] > 0:
out += "(" + ",".join(self.gates[name]["args"]) + ")"
out += " " + ",".join(self.gates[name]["bits"])
if self.gates[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.gates[name]["body"].qasm() + "}"
return out
def qasm(self, decls_only=False, add_swap=False,
no_decls=False, qeflag=False, aliases=None, eval_symbols=False):
"""Return a string containing QASM for this circuit.
if qeflag is True, add a line to include "qelib1.inc"
and only generate gate code for gates not in qelib1.
if eval_symbols is True, evaluate all symbolic
expressions to their floating point representation.
if no_decls is True, only print the instructions.
if aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
if decls_only is True, only print the declarations.
if add_swap is True, add the definition of swap in terms of
cx if necessary.
"""
# TODO: some of the input flags are not needed anymore
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
# Write top matter
if no_decls:
out = ""
else:
printed_gates = []
out = "OPENQASM 2.0;\n"
if qeflag:
out += "include \"qelib1.inc\";\n"
for k, v in sorted(qregdata.items()):
out += "qreg %s[%d];\n" % (k, v.size)
for k, v in sorted(self.cregs.items()):
out += "creg %s[%d];\n" % (k, v.size)
omit = ["U", "CX", "measure", "reset", "barrier"]
# TODO: dagcircuit shouldn't know about extensions
if qeflag:
qelib = ["u3", "u2", "u1", "cx", "id", "x", "y", "z", "h",
"s", "sdg", "t", "tdg", "cz", "cy", "ccx", "cu1",
"cu3", "swap", "cswap", "u0", "rx", "ry", "rz",
"ch", "crz", "rzz"]
omit.extend(qelib)
printed_gates.extend(qelib)
simulator_instructions = ["snapshot", "save", "load", "noise", "wait"]
omit.extend(simulator_instructions)
for k in self.basis.keys():
if k not in omit:
if not self.gates[k]["opaque"]:
calls = self.gates[k]["body"].calls()
for c in calls:
if c not in printed_gates:
out += self._gate_string(c) + "\n"
printed_gates.append(c)
if k not in printed_gates:
out += self._gate_string(k) + "\n"
printed_gates.append(k)
if add_swap and not qeflag and "cx" not in self.basis:
out += "gate cx a,b { CX a,b; }\n"
if add_swap and "swap" not in self.basis:
out += "gate swap a,b { cx a,b; cx b,a; cx a,b; }\n"
# Write the instructions
if not decls_only:
for n in nx.lexicographical_topological_sort(self.multi_graph):
nd = self.multi_graph.node[n]
if nd["type"] == "op":
if nd["condition"] is not None:
out += "if(%s==%d) " \
% (nd["condition"][0], nd["condition"][1])
if not nd["cargs"]:
nm = nd["name"]
if aliases:
qarglist = map(lambda x: aliases[x], nd["qargs"])
else:
qarglist = nd["qargs"]
qarg = ",".join(map(lambda x: "%s[%d]" % (x[0], x[1]),
qarglist))
if nd["params"]:
if eval_symbols:
param = ",".join(map(lambda x: str(sympy.N(x)),
nd["params"]))
else:
param = ",".join(map(lambda x: x.replace("**", "^"),
map(str, nd["params"])))
out += "%s(%s) %s;\n" % (nm, param, qarg)
else:
out += "%s %s;\n" % (nm, qarg)
else:
if nd["name"] == "measure":
if len(nd["cargs"]) != 1 or len(nd["qargs"]) != 1 \
or nd["params"]:
raise QISKitError("bad node data")
qname = nd["qargs"][0][0]
qindex = nd["qargs"][0][1]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
out += "measure %s[%d] -> %s[%d];\n" \
% (qname,
qindex,
nd["cargs"][0][0],
nd["cargs"][0][1])
else:
raise QISKitError("bad node data")
return out
def _check_wires_list(self, wires, name, input_circuit, condition=None):
"""Check that a list of wires satisfies some conditions.
wires = list of (register_name, index) tuples
name = name of operation
input_circuit = replacement circuit for operation
condition = None or (creg_name, value) if this instance of the
operation is classically controlled
The wires give an order for (qu)bits in the input circuit
that is replacing the named operation.
- no duplicate names
- correct length for named operation
- elements are wires of input_circuit
Raises an exception otherwise.
"""
if len(set(wires)) != len(wires):
raise DAGCircuitError("duplicate wires")
wire_tot = self.basis[name][0] + self.basis[name][1]
if condition is not None:
wire_tot += self.cregs[condition[0]].size
if len(wires) != wire_tot:
raise DAGCircuitError("expected %d wires, got %d"
% (wire_tot, len(wires)))
for w in wires:
if w not in input_circuit.wire_type:
raise DAGCircuitError("wire (%s,%d) not in input circuit"
% (w[0], w[1]))
def _make_pred_succ_maps(self, n):
"""Return predecessor and successor dictionaries.
These map from wire names to predecessor and successor
nodes for the operation node n in self.multi_graph.
"""
pred_map = {e[2]['name']: e[0] for e in
self.multi_graph.in_edges(nbunch=n, data=True)}
succ_map = {e[2]['name']: e[1] for e in
self.multi_graph.out_edges(nbunch=n, data=True)}
return pred_map, succ_map
def _full_pred_succ_maps(self, pred_map, succ_map, input_circuit,
wire_map):
"""Map all wires of the input circuit.
Map all wires of the input circuit to predecessor and
successor nodes in self, keyed on wires in self.
pred_map, succ_map dicts come from _make_pred_succ_maps
input_circuit is the input circuit
wire_map is the wire map from wires of input_circuit to wires of self
returns full_pred_map, full_succ_map
"""
full_pred_map = {}
full_succ_map = {}
for w in input_circuit.input_map:
# If w is wire mapped, find the corresponding predecessor
# of the node
if w in wire_map:
full_pred_map[wire_map[w]] = pred_map[wire_map[w]]
full_succ_map[wire_map[w]] = succ_map[wire_map[w]]
else:
# Otherwise, use the corresponding output nodes of self
# and compute the predecessor.
full_succ_map[w] = self.output_map[w]
full_pred_map[w] = self.multi_graph.predecessors(
self.output_map[w])[0]
if len(list(self.multi_graph.predecessors(self.output_map[w]))) != 1:
raise QISKitError(
"too many predecessors for (%s,%d) output node" % (w[0], w[1])
)
return full_pred_map, full_succ_map
def node_nums_in_topological_order(self):
"""
Returns the nodes (their ids) in topological order.
Returns:
List(int): The list of node numbers in topological order
"""
return nx.topological_sort(self.multi_graph)
def substitute_circuit_all(self, name, input_circuit, wires=None):
"""Replace every occurrence of named operation with input_circuit."""
# TODO: rewrite this method to call substitute_circuit_one
wires = wires or None
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
self._check_wires_list(wires, name, input_circuit)
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: ("", 0) for w in wires}
add_qregs = self._check_wiremap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Iterate through the nodes of self and replace the selected nodes
# by iterating through the input_circuit, constructing and
# checking the validity of the wire_map for each replacement
# NOTE: We do not replace conditioned gates. One way to implement
# this later is to add or update the conditions of each gate
# that we add from the input_circuit.
self.basis = union_basis
self.gates = union_gates
for n in self.node_nums_in_topological_order():
nd = self.multi_graph.node[n]
if nd["type"] == "op" and nd["name"] == name:
if nd["condition"] is None:
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"], nd["cargs"]]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map, input_circuit)
pred_map, succ_map = self._make_pred_succ_maps(n)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(n)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map,
md["condition"])
m_qargs = [wire_map.get(x, x) for x in md["qargs0"]]
m_cargs = [wire_map.get(x, x) for x in md["cargs0"]]
self._add_op_node(md["name"], m_qargs, m_cargs,
md["params"], condition, md["op"])
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter, name=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w], full_succ_map[w],
name=w)
o_pred = list(self.multi_graph.predecessors(
self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise QISKitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise QISKitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(
p[0], self.output_map[w])
def substitute_circuit_one(self, node, input_circuit, wires=None):
"""Replace one node with input_circuit.
node is a reference to a node of self.multi_graph of type "op"
input_circuit is a DAGCircuit
"""
wires = wires or None
nd = self.multi_graph.node[node]
name = nd["name"]
self._check_wires_list(wires, name, input_circuit, nd["condition"])
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: ("", 0) for w in wires}
add_qregs = self._check_wiremap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Replace the node by iterating through the input_circuit.
# Constructing and checking the validity of the wire_map.
# If a gate is conditioned, we expect the replacement subcircuit
# to depend on those control bits as well.
self.basis = union_basis
self.gates = union_gates
if nd["type"] != "op":
raise DAGCircuitError("expected node type \"op\", got %s"
% nd["type"])
condition_bit_list = self._bits_in_condition(nd["condition"])
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"],
nd["cargs"],
condition_bit_list]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map, input_circuit)
pred_map, succ_map = self._make_pred_succ_maps(node)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(node)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map, md["condition"])
m_qargs = list(map(lambda x: wire_map.get(x, x),
md["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x),
md["cargs"]))
self._add_op_node(md["name"], m_qargs, m_cargs,
md["params"], condition, md["op"])
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter,
name=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(
full_pred_map[w], full_succ_map[w], name=w)
o_pred = list(self.multi_graph.predecessors(self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise QISKitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise QISKitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(p[0], self.output_map[w])
def get_named_nodes(self, name):
"""Get the set of "op" node ids with the given name."""
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
# We need to instantiate the full list now because the underlying multi_graph
# may change when users iterate over the named nodes.
return {node_id for node_id, data in self.multi_graph.nodes(data=True)
if data["type"] == "op" and data["name"] == name}
def _remove_op_node(self, n):
"""Remove an operation node n.
Add edges from predecessors to successors.
"""
pred_map, succ_map = self._make_pred_succ_maps(n)
self.multi_graph.remove_node(n)
for w in pred_map.keys():
self.multi_graph.add_edge(pred_map[w], succ_map[w], name=w)
def remove_ancestors_of(self, node):
"""Remove all of the ancestor operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
# TODO: probably better to do all at once using
# multi_graph.remove_nodes_from; same for related functions ...
for n in anc:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_descendants_of(self, node):
"""Remove all of the descendant operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
for n in dec:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nonancestors_of(self, node):
"""Remove all of the non-ancestors operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(anc))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nondescendants_of(self, node):
"""Remove all of the non-descendants operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(dec))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def layers(self):
"""Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit.
A layer is a circuit whose gates act on disjoint qubits, i.e.
a layer has depth 1. The total number of layers equals the
circuit depth d. The layers are indexed from 0 to d-1 with the
earliest layer at index 0. The layers are constructed using a
greedy algorithm. Each returned layer is a dict containing
{"graph": circuit graph, "partition": list of qubit lists}.
TODO: Gates that use the same cbits will end up in different
layers as this is currently implemented. This may not be
the desired behavior.
"""
graph_layers = self.multigraph_layers()
try:
next(graph_layers) # Remove input nodes
except StopIteration:
return
def nodes_data(nodes):
"""Construct full nodes from just node ids."""
return ((node_id, self.multi_graph.nodes[node_id]) for node_id in nodes)
for graph_layer in graph_layers:
# Get the op nodes from the layer, removing any input and output nodes.
op_nodes = [node for node in nodes_data(graph_layer) if node[1]["type"] == "op"]
# Stop yielding once there are no more op_nodes in a layer.
if not op_nodes:
return
# Construct a shallow copy of self
new_layer = copy.copy(self)
new_layer.multi_graph = nx.MultiDiGraph()
new_layer.multi_graph.add_nodes_from(nodes_data(self.input_map.values()))
new_layer.multi_graph.add_nodes_from(nodes_data(self.output_map.values()))
# The quantum registers that have an operation in this layer.
support_list = [
op_node[1]["qargs"]
for op_node in op_nodes
if op_node[1]["name"] not in {"barrier", "snapshot", "save", "load", "noise"}
]
new_layer.multi_graph.add_nodes_from(op_nodes)
# Now add the edges to the multi_graph
# By default we just wire inputs to the outputs.
wires = {self.input_map[register]: self.output_map[register]
for register in self.wire_type}
# Wire inputs to op nodes, and op nodes to outputs.
for op_node in op_nodes:
args = self._bits_in_condition(op_node[1]["condition"]) \
+ op_node[1]["cargs"] + op_node[1]["qargs"]
arg_ids = (self.input_map[arg] for arg in args) # map from ("q",0) to node id.
for arg_id in arg_ids:
wires[arg_id], wires[op_node[0]] = op_node[0], wires[arg_id]
# Add wiring to/from the operations and between unused inputs & outputs.
new_layer.multi_graph.add_edges_from(wires.items())
yield {"graph": new_layer, "partition": support_list}
def serial_layers(self):
"""Yield a layer for all gates of this circuit.
A serial layer is a circuit with one gate. The layers have the
same structure as in layers().
"""
for n in self.node_nums_in_topological_order():
nxt_nd = self.multi_graph.node[n]
if nxt_nd["type"] == "op":
new_layer = DAGCircuit()
for qreg in self.qregs.values():
new_layer.add_qreg(qreg)
for creg in self.cregs.values():
new_layer.add_creg(creg)
new_layer.basis = self.basis.copy()
new_layer.gates = self.gates.copy()
# Save the support of the operation we add to the layer
support_list = []
# Operation data
qa = copy.copy(nxt_nd["qargs"])
ca = copy.copy(nxt_nd["cargs"])
pa = copy.copy(nxt_nd["params"])
co = copy.copy(nxt_nd["condition"])
op = copy.copy(nxt_nd["op"])
_ = self._bits_in_condition(co)
# Add node to new_layer
new_layer.apply_operation_back(nxt_nd["name"],
qa, ca, pa, co, op)
# Add operation to partition
if nxt_nd["name"] not in ["barrier",
"snapshot", "save", "load", "noise"]:
# support_list.append(list(set(qa) | set(ca) | set(cob)))
support_list.append(list(qa))
l_dict = {"graph": new_layer, "partition": support_list}
yield l_dict
def multigraph_layers(self):
"""Yield layers of the multigraph."""
predecessor_count = dict() # Dict[node, predecessors not visited]
cur_layer = [node for node in self.input_map.values()]
yield cur_layer
next_layer = []
while cur_layer:
for node in cur_layer:
# Count multiedges with multiplicity.
for successor in self.multi_graph.successors(node):
multiplicity = self.multi_graph.number_of_edges(node, successor)
if successor in predecessor_count:
predecessor_count[successor] -= multiplicity
else:
predecessor_count[successor] = \
self.multi_graph.in_degree(successor) - multiplicity
if predecessor_count[successor] == 0:
next_layer.append(successor)
del predecessor_count[successor]
yield next_layer
cur_layer = next_layer
next_layer = []
def collect_runs(self, namelist):
"""Return a set of runs of "op" nodes with the given names.
For example, "... h q[0]; cx q[0],q[1]; cx q[0],q[1]; h q[1]; .."
would produce the tuple of cx nodes as an element of the set returned
from a call to collect_runs(["cx"]). If instead the cx nodes were
"cx q[0],q[1]; cx q[1],q[0];", the method would still return the
pair in a tuple. The namelist can contain names that are not
in the circuit's basis.
Nodes must have only one successor to continue the run.
"""
group_list = []
# Iterate through the nodes of self in topological order
# and form tuples containing sequences of gates
# on the same qubit(s).
ts = list(self.node_nums_in_topological_order())
nodes_seen = dict(zip(ts, [False] * len(ts)))
for node in ts:
nd = self.multi_graph.node[node]
if nd["type"] == "op" and nd["name"] in namelist \
and not nodes_seen[node]:
group = [node]
nodes_seen[node] = True
s = list(self.multi_graph.successors(node))
while len(s) == 1 and \
self.multi_graph.node[s[0]]["type"] == "op" and \
self.multi_graph.node[s[0]]["name"] in namelist:
group.append(s[0])
nodes_seen[s[0]] = True
s = list(self.multi_graph.successors(s[0]))
if len(group) > 1:
group_list.append(tuple(group))
return set(group_list)
def count_ops(self):
"""Count the occurrences of operation names.
Returns a dictionary of counts keyed on the operation name.
"""
op_dict = {}
for node in self.node_nums_in_topological_order():
nd = self.multi_graph.node[node]
name = nd["name"]
if nd["type"] == "op":
if name not in op_dict:
op_dict[name] = 1
else:
op_dict[name] += 1
return op_dict
def properties(self):
"""Return a dictionary of circuit properties."""
summary = {"size": self.size(),
"depth": self.depth(),
"width": self.width(),
"bits": self.num_cbits(),
"factors": self.num_tensor_factors(),
"operations": self.count_ops()}
return summary
@staticmethod
def fromQuantumCircuit(circuit, expand_gates=True):
"""Build a ``DAGCircuit`` object from a ``QuantumCircuit``.
Args:
circuit (QuantumCircuit): the input circuit.
expand_gates (bool): if ``False``, none of the gates are expanded,
i.e. the gates that are defined in the circuit are included in
the DAG basis.
Return:
DAGCircuit: the DAG representing the input circuit.
"""
dagcircuit = DAGCircuit()
dagcircuit.name = circuit.name
for register in circuit.qregs:
dagcircuit.add_qreg(register)
for register in circuit.cregs:
dagcircuit.add_creg(register)
# Add user gate definitions
for name, data in circuit.definitions.items():
dagcircuit.add_basis_element(name, data["n_bits"], 0,
data["n_args"])
dagcircuit.add_gate_data(name, data)
# Add instructions
builtins = {
"U": ["U", 1, 0, 3],
"CX": ["CX", 2, 0, 0],
"measure": ["measure", 1, 1, 0],
"reset": ["reset", 1, 0, 0],
"barrier": ["barrier", -1, 0, 0]
}
# Add simulator instructions
simulator_instructions = {
"snapshot": ["snapshot", -1, 0, 1],
"save": ["save", -1, 0, 1],
"load": ["load", -1, 0, 1],
"noise": ["noise", -1, 0, 1]
}
for main_instruction in circuit.data:
# TODO: generate definitions and nodes for CompositeGates,
# for now simply drop their instructions into the DAG
instruction_list = []
is_composite = isinstance(main_instruction,
_compositegate.CompositeGate)
if is_composite and expand_gates:
instruction_list = main_instruction.instruction_list()
else:
instruction_list.append(main_instruction)
for instruction in instruction_list:
# Add OpenQASM built-in gates on demand
if instruction.name in builtins:
dagcircuit.add_basis_element(*builtins[instruction.name])
# Add simulator extension instructions
if instruction.name in simulator_instructions:
dagcircuit.add_basis_element(*simulator_instructions[instruction.name])
# Separate classical arguments to measurements
if instruction.name == "measure":
qargs = [(instruction.qargs[0][0].name, instruction.qargs[0][1])]
cargs = [(instruction.cargs[0][0].name, instruction.cargs[0][1])]
else:
qargs = list(map(lambda x: (x[0].name, x[1]), instruction.qargs))
cargs = []
# Get arguments for classical control (if any)
if instruction.control is None:
control = None
else:
control = (instruction.control[0].name, instruction.control[1])
if is_composite and not expand_gates:
is_inverse = instruction.inverse_flag
name = instruction.name if not is_inverse else instruction.inverse_name
else:
name = instruction.name
dagcircuit.apply_operation_back(name, qargs, cargs,
instruction.param,
control, instruction)
return dagcircuit
<|code_end|>
qiskit/transpiler/_transpiler.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Tools for compiling a batch of quantum circuits."""
import logging
import numpy as np
import scipy.sparse as sp
import scipy.sparse.csgraph as cs
from qiskit.transpiler._transpilererror import TranspilerError
from qiskit._qiskiterror import QISKitError
from qiskit.dagcircuit import DAGCircuit
from qiskit import _quantumcircuit
from qiskit.unrollers import _dagunroller
from qiskit.unrollers import _dagbackend
from qiskit.unrollers import _jsonbackend
from qiskit.mapper import (Coupling, optimize_1q_gates, coupling_list2dict, swap_mapper,
cx_cancellation, direction_mapper,
remove_last_measurements, return_last_measurements)
from qiskit._pubsub import Publisher, Subscriber
from ._parallel import parallel_map
logger = logging.getLogger(__name__)
def transpile(circuits, backend, basis_gates=None, coupling_map=None, initial_layout=None,
seed_mapper=None, hpc=None, pass_manager=None):
"""transpile a list of circuits into a dags.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend): a backend to compile for
basis_gates (str): comma-separated basis gate set to compile to
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
seed_mapper (int): random seed for the swap_mapper
hpc (dict): HPC simulator parameters
pass_manager (PassManager): a pass_manager for the transpiler stage
Returns:
dags: a list of dags.
Raises:
TranspilerError: in case of bad compile options, e.g. the hpc options.
"""
if isinstance(circuits, _quantumcircuit.QuantumCircuit):
circuits = [circuits]
# FIXME: THIS NEEDS TO BE CLEANED UP -- some things to decide for list of circuits:
# 1. do all circuits have same coupling map?
# 2. do all circuit have the same basis set?
# 3. do they all have same registers etc?
backend_conf = backend.configuration()
# Check for valid parameters for the experiments.
if hpc is not None and \
not all(key in hpc for key in ('multi_shot_optimization', 'omp_num_threads')):
raise TranspilerError('Unknown HPC parameter format!')
basis_gates = basis_gates or backend_conf['basis_gates']
coupling_map = coupling_map or backend_conf['coupling_map']
# step 1: Making the list of dag circuits
dags = _circuits_2_dags(circuits)
# step 2: Transpile all the dags
# FIXME: Work-around for transpiling multiple circuits with different qreg names.
# Make compile take a list of initial_layouts.
_initial_layout = initial_layout
# Pick a good initial layout if coupling_map is not already satisfied
# otherwise keep it as q[i]->q[i].
# TODO: move this inside mapper pass.
initial_layouts = []
for dag in dags:
if (initial_layout is None and not backend.configuration()['simulator']
and not _matches_coupling_map(dag, coupling_map)):
_initial_layout = _pick_best_layout(dag, backend)
initial_layouts.append(_initial_layout)
dags = _dags_2_dags(dags, basis_gates=basis_gates, coupling_map=coupling_map,
initial_layouts=initial_layouts, seed_mapper=seed_mapper,
pass_manager=pass_manager)
# TODO: change it to circuits
# TODO: make it parallel
return dags
def _circuits_2_dags(circuits):
"""Convert a list of circuits into a list of dags.
Args:
circuits (list[QuantumCircuit]): circuit to compile
Returns:
list[DAGCircuit]: the dag representation of the circuits
to be used in the transpiler
"""
dags = parallel_map(DAGCircuit.fromQuantumCircuit, circuits)
return dags
def _dags_2_dags(dags, basis_gates='u1,u2,u3,cx,id', coupling_map=None,
initial_layouts=None, seed_mapper=None, pass_manager=None):
"""Transform multiple dags through a sequence of passes.
Args:
dags (list[DAGCircuit]): dag circuits to transform
basis_gates (str): a comma separated string for the target basis gates
coupling_map (list): A graph of coupling
initial_layouts (list[dict]): A mapping of qubit to qubit for each dag
seed_mapper (int): random seed_mapper for the swap mapper
pass_manager (PassManager): pass manager instance for the transpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
list[DAGCircuit]: the dag circuits after going through transpilation
Raises:
TranspilerError: if the format is not valid.
Events:
terra.transpiler.transpile_dag.start: When the transpilation of the dags is about to start
terra.transpiler.transpile_dag.done: When one of the dags has finished it's transpilation
terra.transpiler.transpile_dag.finish: When all the dags have finished transpiling
"""
def _emmit_start(num_dags):
""" Emmit a dag transpilation start event
Arg:
num_dags: Number of dags to be transpiled"""
Publisher().publish("terra.transpiler.transpile_dag.start", num_dags)
Subscriber().subscribe("terra.transpiler.parallel.start", _emmit_start)
def _emmit_done(progress):
""" Emmit a dag transpilation done event
Arg:
progress: The dag number that just has finshed transpile"""
Publisher().publish("terra.transpiler.transpile_dag.done", progress)
Subscriber().subscribe("terra.transpiler.parallel.done", _emmit_done)
def _emmit_finish():
""" Emmit a dag transpilation finish event
Arg:
progress: The dag number that just has finshed transpile"""
Publisher().publish("terra.transpiler.transpile_dag.finish")
Subscriber().subscribe("terra.transpiler.parallel.finish", _emmit_finish)
dags_layouts = list(zip(dags, initial_layouts))
final_dags = parallel_map(_transpile_dags_parallel, dags_layouts,
task_kwargs={'basis_gates': basis_gates,
'coupling_map': coupling_map,
'seed_mapper': seed_mapper,
'pass_manager': pass_manager})
return final_dags
def _transpile_dags_parallel(dag_layout_tuple, basis_gates='u1,u2,u3,cx,id',
coupling_map=None, seed_mapper=None, pass_manager=None):
"""Helper function for transpiling in parallel (if available).
Args:
dag_layout_tuple (tuple): Tuples of dags and their initial_layouts
basis_gates (str): a comma separated string for the target basis gates
coupling_map (list): A graph of coupling
seed_mapper (int): random seed_mapper for the swap mapper
pass_manager (PassManager): pass manager instance for the transpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
DAGCircuit: DAG circuit after going through transpilation.
"""
final_dag, final_layout = transpile_dag(
dag_layout_tuple[0],
basis_gates=basis_gates,
coupling_map=coupling_map,
initial_layout=dag_layout_tuple[1],
get_layout=True,
seed_mapper=seed_mapper,
pass_manager=pass_manager)
final_dag.layout = [[k, v]
for k, v in final_layout.items()] if final_layout else None
return final_dag
# pylint: disable=redefined-builtin
def transpile_dag(dag, basis_gates='u1,u2,u3,cx,id', coupling_map=None,
initial_layout=None, get_layout=False,
format='dag', seed_mapper=None, pass_manager=None):
"""Transform a dag circuit into another dag circuit (transpile), through
consecutive passes on the dag.
Args:
dag (DAGCircuit): dag circuit to transform via transpilation
basis_gates (str): a comma separated string for the target basis gates
coupling_map (list): A graph of coupling::
[
[control0(int), target0(int)],
[control1(int), target1(int)],
]
eg. [[0, 2], [1, 2], [1, 3], [3, 4]}
initial_layout (dict): A mapping of qubit to qubit::
{
("q", start(int)): ("q", final(int)),
...
}
eg.
{
("q", 0): ("q", 0),
("q", 1): ("q", 1),
("q", 2): ("q", 2),
("q", 3): ("q", 3)
}
get_layout (bool): flag for returning the final layout after mapping
format (str): The target format of the compilation:
{'dag', 'json', 'qasm'}
seed_mapper (int): random seed_mapper for the swap mapper
pass_manager (PassManager): pass manager instance for the transpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
DAGCircuit: transformed dag
DAGCircuit, dict: transformed dag along with the final layout on backend qubits
Raises:
TranspilerError: if the format is not valid.
"""
# TODO: `basis_gates` will be removed after we have the unroller pass.
# TODO: `coupling_map`, `initial_layout`, `get_layout`, `seed_mapper` removed after mapper pass.
# TODO: move this to the mapper pass
num_qubits = sum([qreg.size for qreg in dag.qregs.values()])
if num_qubits == 1 or coupling_map == "all-to-all":
coupling_map = None
final_layout = None
if pass_manager:
# run the passes specified by the pass manager
# TODO return the property set too. See #1086
dag = pass_manager.run_passes(dag)
else:
# default set of passes
# TODO: move each step here to a pass, and use a default passmanager below
basis = basis_gates.split(',') if basis_gates else []
dag_unroller = _dagunroller.DagUnroller(
dag, _dagbackend.DAGBackend(basis))
dag = dag_unroller.expand_gates()
# if a coupling map is given compile to the map
if coupling_map:
logger.info("pre-mapping properties: %s",
dag.properties())
# Insert swap gates
coupling = Coupling(coupling_list2dict(coupling_map))
removed_meas = remove_last_measurements(dag)
logger.info("measurements moved: %s", removed_meas)
logger.info("initial layout: %s", initial_layout)
dag, final_layout, last_layout = swap_mapper(
dag, coupling, initial_layout, trials=20, seed=seed_mapper)
logger.info("final layout: %s", final_layout)
# Expand swaps
dag_unroller = _dagunroller.DagUnroller(
dag, _dagbackend.DAGBackend(basis))
dag = dag_unroller.expand_gates()
# Change cx directions
dag = direction_mapper(dag, coupling)
# Simplify cx gates
cx_cancellation(dag)
# Simplify single qubit gates
dag = optimize_1q_gates(dag)
return_last_measurements(dag, removed_meas,
last_layout)
logger.info("post-mapping properties: %s",
dag.properties())
# choose output format
# TODO: do we need all of these formats, or just the dag?
if format == 'dag':
compiled_circuit = dag
elif format == 'json':
# FIXME: JsonBackend is wrongly taking an ordered dict as basis, not list
dag_unroller = _dagunroller.DagUnroller(
dag, _jsonbackend.JsonBackend(dag.basis))
compiled_circuit = dag_unroller.execute()
elif format == 'qasm':
compiled_circuit = dag.qasm()
else:
raise TranspilerError('unrecognized circuit format')
if get_layout:
return compiled_circuit, final_layout
return compiled_circuit
def _best_subset(backend, n_qubits):
"""Computes the qubit mapping with the best
connectivity.
Parameters:
backend (Qiskit.BaseBackend): A QISKit backend instance.
n_qubits (int): Number of subset qubits to consider.
Returns:
ndarray: Array of qubits to use for best
connectivity mapping.
Raises:
QISKitError: Wrong number of qubits given.
"""
if n_qubits == 1:
return np.array([0])
elif n_qubits <= 0:
raise QISKitError('Number of qubits <= 0.')
device_qubits = backend.configuration()['n_qubits']
if n_qubits > device_qubits:
raise QISKitError('Number of qubits greater than device.')
cmap = np.asarray(backend.configuration()['coupling_map'])
data = np.ones_like(cmap[:, 0])
sp_cmap = sp.coo_matrix((data, (cmap[:, 0], cmap[:, 1])),
shape=(device_qubits, device_qubits)).tocsr()
best = 0
best_map = None
# do bfs with each node as starting point
for k in range(sp_cmap.shape[0]):
bfs = cs.breadth_first_order(sp_cmap, i_start=k, directed=False,
return_predecessors=False)
connection_count = 0
for i in range(n_qubits):
node_idx = bfs[i]
for j in range(sp_cmap.indptr[node_idx],
sp_cmap.indptr[node_idx + 1]):
node = sp_cmap.indices[j]
for counter in range(n_qubits):
if node == bfs[counter]:
connection_count += 1
break
if connection_count > best:
best = connection_count
best_map = bfs[0:n_qubits]
return best_map
def _matches_coupling_map(dag, coupling_map):
"""Iterate over circuit gates to check if all multi-qubit couplings
match the qubit coupling graph in the backend.
Parameters:
dag (DAGCircuit): DAG representation of circuit.
coupling_map (list): Backend coupling map, represented as an adjacency list.
Returns:
bool: True if all gates readily fit the backend coupling graph.
False if there's at least one gate that uses multiple qubits
which does not match the backend couplings.
"""
match = True
for _, data in dag.multi_graph.nodes(data=True):
if data['type'] == 'op':
gate_map = [qr[1] for qr in data['qargs']]
if len(gate_map) > 1:
if gate_map not in coupling_map:
match = False
break
return match
def _pick_best_layout(dag, backend):
"""Pick a convenient layout depending on the best matching qubit connectivity
Parameters:
dag (DAGCircuit): DAG representation of circuit.
backend (BaseBackend) : The backend with the coupling_map for searching
Returns:
dict: A special ordered initial_layout
"""
num_qubits = sum([qreg.size for qreg in dag.qregs.values()])
best_sub = _best_subset(backend, num_qubits)
layout = {}
map_iter = 0
for key, value in dag.qregs.items():
for i in range(value.size):
layout[(key, i)] = ('q', best_sub[map_iter])
map_iter += 1
return layout
<|code_end|>
|
update example visualizing_circuits
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected behavior?
when the ascii drawer is in place update the `visualizing_circuits.py` example and show it using circuit.draw()
as for me on a mac I cant user matplotlib with just python. Need to use the pythonw.
|
examples/python/visualizing_circuits.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Example showing how to draw a quantum circuit using Qiskit Terra.
"""
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.tools.visualization import circuit_drawer
def build_bell_circuit():
"""Returns a circuit putting 2 qubits in the Bell state."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.cx(q[0], q[1])
qc.measure(q, c)
return qc
# Create the circuit
bell_circuit = build_bell_circuit()
# Provide a name to write the diagram to the filesystem
circuit_drawer(bell_circuit, filename='./bell_circuit.png')
# Use the return value with show() to display the diagram
diagram = circuit_drawer(bell_circuit)
diagram.show()
<|code_end|>
examples/python/qft.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Quantum Fourier Transform examples.
Note: if you have only cloned the Qiskit repository but not
used `pip install`, the examples only work from the root directory.
"""
import math
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import execute, Aer, IBMQ
from qiskit.backends.ibmq import least_busy
###############################################################
# make the qft
###############################################################
def input_state(circ, q, n):
"""n-qubit input state for QFT that produces output 1."""
for j in range(n):
circ.h(q[j])
circ.u1(math.pi/float(2**(j)), q[j]).inverse()
def qft(circ, q, n):
"""n-qubit QFT on q in circ."""
for j in range(n):
for k in range(j):
circ.cu1(math.pi/float(2**(j-k)), q[j], q[k])
circ.h(q[j])
q = QuantumRegister(5, "q")
c = ClassicalRegister(5, "c")
qft3 = QuantumCircuit(q, c, name="qft3")
qft4 = QuantumCircuit(q, c, name="qft4")
qft5 = QuantumCircuit(q, c, name="qft5")
input_state(qft3, q, 3)
qft3.barrier()
qft(qft3, q, 3)
qft3.barrier()
for j in range(3):
qft3.measure(q[j], c[j])
input_state(qft4, q, 4)
qft4.barrier()
qft(qft4, q, 4)
qft4.barrier()
for j in range(4):
qft4.measure(q[j], c[j])
input_state(qft5, q, 5)
qft5.barrier()
qft(qft5, q, 5)
qft5.barrier()
for j in range(5):
qft5.measure(q[j], c[j])
print(qft3.qasm())
print(qft4.qasm())
print(qft5.qasm())
###############################################################
# Set up the API and execute the program.
###############################################################
try:
IBMQ.load_accounts()
except:
print("""WARNING: There's no connection with the API for remote backends.
Have you initialized a file with your personal token?
For now, there's only access to local simulator backends...""")
print('Qasm simulator')
sim_backend = Aer.get_backend('qasm_simulator')
job = execute([qft3, qft4, qft5], sim_backend, shots=1024)
result = job.result()
print(result)
print(result.get_counts(qft3))
print(result.get_counts(qft4))
print(result.get_counts(qft5))
# Second version: real device
least_busy_device = least_busy(IBMQ.backends(simulator=False,
filters=lambda x: x.configuration()['n_qubits'] > 4))
print("Running on current least busy device: ", least_busy_device)
job = execute([qft3, qft4, qft5], least_busy_device, shots=1024)
result = job.result()
print(result)
print(result.get_counts(qft3))
print(result.get_counts(qft4))
print(result.get_counts(qft5))
<|code_end|>
|
examples/python/circuit_draw.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Example showing how to draw a quantum circuit using Qiskit Terra.
"""
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
def build_bell_circuit():
"""Returns a circuit putting 2 qubits in the Bell state."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.cx(q[0], q[1])
qc.measure(q, c)
return qc
# Create the circuit
bell_circuit = build_bell_circuit()
# Use the internal .draw() to print the circuit
print(bell_circuit)
<|code_end|>
examples/python/qft.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Quantum Fourier Transform examples.
Note: if you have only cloned the Qiskit repository but not
used `pip install`, the examples only work from the root directory.
"""
import math
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import execute, Aer, IBMQ
from qiskit.backends.ibmq import least_busy
###############################################################
# make the qft
###############################################################
def input_state(circ, q, n):
"""n-qubit input state for QFT that produces output 1."""
for j in range(n):
circ.h(q[j])
circ.u1(math.pi/float(2**(j)), q[j]).inverse()
def qft(circ, q, n):
"""n-qubit QFT on q in circ."""
for j in range(n):
for k in range(j):
circ.cu1(math.pi/float(2**(j-k)), q[j], q[k])
circ.h(q[j])
q = QuantumRegister(5, "q")
c = ClassicalRegister(5, "c")
qft3 = QuantumCircuit(q, c, name="qft3")
qft4 = QuantumCircuit(q, c, name="qft4")
qft5 = QuantumCircuit(q, c, name="qft5")
input_state(qft3, q, 3)
qft3.barrier()
qft(qft3, q, 3)
qft3.barrier()
for j in range(3):
qft3.measure(q[j], c[j])
input_state(qft4, q, 4)
qft4.barrier()
qft(qft4, q, 4)
qft4.barrier()
for j in range(4):
qft4.measure(q[j], c[j])
input_state(qft5, q, 5)
qft5.barrier()
qft(qft5, q, 5)
qft5.barrier()
for j in range(5):
qft5.measure(q[j], c[j])
print(qft3)
print(qft4)
print(qft5)
###############################################################
# Set up the API and execute the program.
###############################################################
try:
IBMQ.load_accounts()
except:
print("""WARNING: There's no connection with the API for remote backends.
Have you initialized a file with your personal token?
For now, there's only access to local simulator backends...""")
print('Qasm simulator')
sim_backend = Aer.get_backend('qasm_simulator')
job = execute([qft3, qft4, qft5], sim_backend, shots=1024)
result = job.result()
print(result)
print(result.get_counts(qft3))
print(result.get_counts(qft4))
print(result.get_counts(qft5))
# Second version: real device
least_busy_device = least_busy(IBMQ.backends(simulator=False,
filters=lambda x: x.configuration()['n_qubits'] > 4))
print("Running on current least busy device: ", least_busy_device)
job = execute([qft3, qft4, qft5], least_busy_device, shots=1024)
result = job.result()
print(result)
print(result.get_counts(qft3))
print(result.get_counts(qft4))
print(result.get_counts(qft5))
<|code_end|>
|
load_qasm example should use the quantumcircuit
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected behavior?
Need to update the load_qasm with the new from file qasm load.
|
examples/python/load_qasm.py
<|code_start|>"""
Example on how to use: load_qasm_file
"""
from qiskit.wrapper import load_qasm_file
from qiskit import QISKitError, execute, Aer
try:
qc = load_qasm_file("examples/qasm/entangled_registers.qasm")
# See a list of available local simulators
print("Aer backends: ", Aer.backends())
sim_backend = Aer.get_backend('qasm_simulator')
# Compile and run the Quantum circuit on a local simulator backend
job_sim = execute(qc, sim_backend)
sim_result = job_sim.result()
# Show the results
print("simulation: ", sim_result)
print(sim_result.get_counts(qc))
except QISKitError as ex:
print('There was an internal Qiskit error. Error = {}'.format(ex))
<|code_end|>
|
examples/python/load_qasm.py
<|code_start|>"""
Example on how to load a file into a QuantumCircuit
"""
from qiskit import QuantumCircuit
from qiskit import QISKitError, execute, Aer
try:
circ = QuantumCircuit.from_qasm_file("examples/qasm/entangled_registers.qasm")
print(circ.draw())
# See the backend
sim_backend = Aer.get_backend('qasm_simulator')
# Compile and run the Quantum circuit on a local simulator backend
job_sim = execute(circ, sim_backend)
sim_result = job_sim.result()
# Show the results
print("simulation: ", sim_result)
print(sim_result.get_counts(circ))
except QISKitError as ex:
print('There was an internal Qiskit error. Error = {}'.format(ex))
<|code_end|>
|
credentials failed for qiskit ver 0.6.1
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: 0.6.1
- **Python version**: 3.7.0
- **Operating system**:MAC OSX 10.13.6
### What is the current behavior?
After I acquired fresh token from https://quantumexperience.ng.bluemix.net/qx/account/advanced
IBMQ.load_accounts() fails.
### Steps to reproduce the problem
```
from qiskit import IBMQ
myToken='b6abe11442c9a...'
IBMQ.save_account(myToken)
IBMQ.load_accounts()
```
Results with
```
Traceback (most recent call last):
File "/anaconda3/lib/python3.7/site-packages/qiskit/backends/ibmq/ibmqsingleprovider.py", line 71, in _authenticate
credentials.verify)
File "/anaconda3/lib/python3.7/site-packages/IBMQuantumExperience/IBMQuantumExperience.py", line 478, in __init__
self.req = _Request(token, config=config, verify=verify)
File "/anaconda3/lib/python3.7/site-packages/IBMQuantumExperience/IBMQuantumExperience.py", line 253, in __init__
ntlm_credentials=self.ntlm_credentials)
File "/anaconda3/lib/python3.7/site-packages/IBMQuantumExperience/IBMQuantumExperience.py", line 95, in __init__
self.obtain_token(config=self.config)
File "/anaconda3/lib/python3.7/site-packages/IBMQuantumExperience/IBMQuantumExperience.py", line 159, in obtain_token
raise CredentialsError('error during login: %s' % error_message)
IBMQuantumExperience.IBMQuantumExperience.CredentialsError: error during login: Wrong user or password, check your credentials.
```
### What is the expected behavior?
Would be better if IBMQ.load_accounts() accepted me. All worked well w/ ver 0.5.
### Suggested solutions
|
qiskit/backends/ibmq/credentials/_configrc.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Utilities for reading and writing credentials from and to configuration files.
"""
import os
from ast import literal_eval
from collections import OrderedDict
from configparser import ConfigParser, ParsingError
from qiskit import QISKitError
from .credentials import Credentials
DEFAULT_QISKITRC_FILE = os.path.join(os.path.expanduser("~"),
'.qiskit', 'qiskitrc')
def read_credentials_from_qiskitrc(filename=None):
"""
Read a configuration file and return a dict with its sections.
Args:
filename (str): full path to the qiskitrc file. If `None`, the default
location is used (`HOME/.qiskit/qiskitrc`).
Returns:
dict: dictionary with the contents of the configuration file, with
the form::
{credential_unique_id: Credentials}
Raises:
QISKitError: if the file was not parseable. Please note that this
exception is not raised if the file does not exist (instead, an
empty dict is returned).
"""
filename = filename or DEFAULT_QISKITRC_FILE
config_parser = ConfigParser()
try:
config_parser.read(filename)
except ParsingError as ex:
raise QISKitError(str(ex))
# Build the credentials dictionary.
credentials_dict = OrderedDict()
for name in config_parser.sections():
single_credentials = dict(config_parser.items(name))
# Individually convert keys to their right types.
# TODO: consider generalizing, moving to json configuration or a more
# robust alternative.
if 'proxies' in single_credentials.keys():
single_credentials['proxies'] = literal_eval(
single_credentials['proxies'])
if 'verify' in single_credentials.keys():
single_credentials['verify'] = bool(single_credentials['verify'])
new_credentials = Credentials(**single_credentials)
credentials_dict[new_credentials.unique_id()] = new_credentials
return credentials_dict
def write_qiskit_rc(credentials, filename=None):
"""
Write credentials to the configuration file.
Args:
credentials (dict): dictionary with the credentials, with the form::
{credentials_unique_id: Credentials}
filename (str): full path to the qiskitrc file. If `None`, the default
location is used (`HOME/.qiskit/qiskitrc`).
"""
def _credentials_object_to_dict(obj):
return {key: getattr(obj, key)
for key in ['token', 'url', 'proxies', 'verify']
if getattr(obj, key)}
def _section_name(credentials_):
"""Return a string suitable for use as a unique section name."""
base_name = 'ibmq'
if credentials_.is_ibmq():
base_name = '{}_{}_{}_{}'.format(base_name, *credentials_.unique_id())
return base_name
filename = filename or DEFAULT_QISKITRC_FILE
# Create the directories and the file if not found.
os.makedirs(os.path.dirname(filename), exist_ok=True)
unrolled_credentials = {
_section_name(credentials_object): _credentials_object_to_dict(credentials_object)
for _, credentials_object in credentials.items()
}
# Write the configuration file.
with open(filename, 'w') as config_file:
config_parser = ConfigParser()
config_parser.read_dict(unrolled_credentials)
config_parser.write(config_file)
def store_credentials(credentials, overwrite=False, filename=None):
"""
Store the credentials for a single account in the configuration file.
Args:
credentials (Credentials): credentials instance.
overwrite (bool): overwrite existing credentials.
filename (str): full path to the qiskitrc file. If `None`, the default
location is used (`HOME/.qiskit/qiskitrc`).
Raises:
QISKitError: If credentials already exists and overwrite=False; or if
the account_name could not be assigned.
"""
# Read the current providers stored in the configuration file.
filename = filename or DEFAULT_QISKITRC_FILE
stored_credentials = read_credentials_from_qiskitrc(filename)
if credentials.unique_id() in stored_credentials and not overwrite:
raise QISKitError('Credentials already present and overwrite=False')
# Append and write the credentials to file.
stored_credentials[credentials.unique_id()] = credentials
write_qiskit_rc(stored_credentials, filename)
def remove_credentials(credentials, filename=None):
"""Remove credentials from qiskitrc.
Args:
credentials (Credentials): credentials.
filename (str): full path to the qiskitrc file. If `None`, the default
location is used (`HOME/.qiskit/qiskitrc`).
Raises:
QISKitError: If there is no account with that name on the configuration
file.
"""
# Set the name of the Provider from the class.
stored_credentials = read_credentials_from_qiskitrc(filename)
try:
del stored_credentials[credentials.unique_id()]
except KeyError:
raise QISKitError('The account "%s" does not exist in the '
'configuration file')
write_qiskit_rc(stored_credentials, filename)
<|code_end|>
qiskit/backends/ibmq/credentials/credentials.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Model for representing IBM Q credentials."""
import re
# Regex that matches a IBMQ URL with hub information
REGEX_IBMQ_HUBS = (
'(?P<prefix>http[s]://.+/api)'
'/Hubs/(?P<hub>[^/]+)/Groups/(?P<group>[^/]+)/Projects/(?P<project>[^/]+)'
)
# Template for creating an IBMQ URL with hub information
TEMPLATE_IBMQ_HUBS = '{prefix}/Hubs/{hub}/Groups/{group}/Projects/{project}'
class Credentials(object):
"""IBM Q account credentials.
Note that, by convention, two credentials that have the same hub, group
and token (regardless of other attributes) are considered equivalent.
The `unique_id()` returns the unique identifier.
"""
def __init__(self, token, url, hub=None, group=None, project=None,
proxies=None, verify=True):
"""
Args:
token (str): Quantum Experience or IBMQ API token.
url (str): URL for Quantum Experience or IBMQ.
hub (str): the hub used for IBMQ.
group (str): the group used for IBMQ.
project (str): the project used for IBMQ.
proxies (dict): proxy configuration for the API.
verify (bool): if False, ignores SSL certificates errors
Note:
`hub`, `group` and `project` are stored as attributes for
convenience, but their usage in the API is deprecated. The new-style
URLs (that includes these parameters as part of the url string, and
is automatically set during instantiation) should be used when
communicating with the API.
"""
self.token = token
self.url, self.hub, self.group, self.project = _unify_ibmq_url(
url, hub, group, project)
self.proxies = proxies or {}
self.verify = verify
def is_ibmq(self):
"""Return whether the credentials represent a IBMQ account."""
return all([self.hub, self.group, self.project])
def __eq__(self, other):
return self.__dict__ == other.__dict__
def unique_id(self):
"""Return a value that uniquely identifies these credentials.
By convention, we assume (hub, group, project) is always unique.
"""
return self.hub, self.group, self.project
def _unify_ibmq_url(url, hub=None, group=None, project=None):
"""Return a new-style set of credential values (url and hub parameters).
Args:
url (str): URL for Quantum Experience or IBM Q.
hub (str): the hub used for IBM Q.
group (str): the group used for IBM Q.
project (str): the project used for IBM Q.
Returns:
tuple[url, hub, group, token]:
* url (str): new-style Quantum Experience or IBM Q URL (the hub,
group and project included in the URL.
* hub (str): the hub used for IBM Q.
* group (str): the group used for IBM Q.
* project (str): the project used for IBM Q.
"""
# Check if the URL is "new style", and retrieve embedded parameters from it.
regex_match = re.match(REGEX_IBMQ_HUBS, url, re.IGNORECASE)
if regex_match:
_, hub, group, project = regex_match.groups()
else:
if hub and group and project:
# Assume it is an IBMQ URL, and update the url.
url = TEMPLATE_IBMQ_HUBS.format(prefix=url, hub=hub, group=group,
project=project)
else:
# Cleanup the hub, group and project, without modifying the url.
hub = group = project = None
return url, hub, group, project
<|code_end|>
qiskit/backends/ibmq/ibmqprovider.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Provider for remote IBMQ backends with admin features."""
import warnings
from collections import OrderedDict
from qiskit.backends import BaseProvider
from .credentials._configrc import remove_credentials
from .credentials import (Credentials,
read_credentials_from_qiskitrc, store_credentials, discover_credentials)
from .ibmqaccounterror import IBMQAccountError
from .ibmqsingleprovider import IBMQSingleProvider
QE_URL = 'https://quantumexperience.ng.bluemix.net/api'
class IBMQProvider(BaseProvider):
"""Provider for remote IBMQ backends with admin features.
This class is the entry point for handling backends from IBMQ, allowing
using different accounts.
"""
def __init__(self):
super().__init__()
# dict[credentials_unique_id: IBMQSingleProvider]
# This attribute stores a reference to the different accounts. The
# keys are tuples (hub, group, project), as the convention is that
# that tuple uniquely identifies a set of credentials.
self._accounts = OrderedDict()
def backends(self, name=None, filters=None, **kwargs):
"""Return all backends accessible via IBMQ provider, subject to optional filtering.
Args:
name (str): backend name to filter by
filters (callable): more complex filters, such as lambda functions
e.g. IBMQ.backends(filters=lambda b: b.configuration['n_qubits'] > 5)
kwargs: simple filters specifying a true/false criteria in the
backend configuration or backend status or provider credentials
e.g. IBMQ.backends(n_qubits=5, operational=True, hub='internal')
Returns:
list[IBMQBackend]: list of backends available that match the filter
Raises:
IBMQAccountError: if no account matched the filter.
"""
# pylint: disable=arguments-differ
# Special handling of the credentials filters: match and prune from kwargs
credentials_filter = {}
for key in ['token', 'url', 'hub', 'group', 'project', 'proxies', 'verify']:
if key in kwargs:
credentials_filter[key] = kwargs.pop(key)
providers = [provider for provider in self._accounts.values() if
self._credentials_match_filter(provider.credentials,
credentials_filter)]
# Special handling of the `name` parameter, to support alias resolution.
if name:
aliases = self.aliased_backend_names()
aliases.update(self.deprecated_backend_names())
name = aliases.get(name, name)
# Aggregate the list of filtered backends.
backends = []
for provider in providers:
backends = backends + provider.backends(
name=name, filters=filters, **kwargs)
return backends
@staticmethod
def deprecated_backend_names():
"""Returns deprecated backend names."""
return {
'ibmqx_qasm_simulator': 'ibmq_qasm_simulator',
'ibmqx_hpc_qasm_simulator': 'ibmq_qasm_simulator',
'real': 'ibmqx1'
}
@staticmethod
def aliased_backend_names():
"""Returns aliased backend names."""
return {
'ibmq_5_yorktown': 'ibmqx2',
'ibmq_5_tenerife': 'ibmqx4',
'ibmq_16_rueschlikon': 'ibmqx5',
'ibmq_20_austin': 'QS1_1'
}
def enable_account(self, token, url=QE_URL, **kwargs):
"""Authenticate a new IBMQ account and add for use during this session.
Login into Quantum Experience or IBMQ using the provided credentials,
adding the account to the current session. The account is not stored
in disk.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
"""
credentials = Credentials(token, url, **kwargs)
self._append_account(credentials)
def save_account(self, token, url=QE_URL, **kwargs):
"""Save the account to disk for future use.
Login into Quantum Experience or IBMQ using the provided credentials,
adding the account to the current session. The account is stored in
disk for future use.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
"""
credentials = Credentials(token, url, **kwargs)
# Check if duplicated credentials are already stored. By convention,
# we assume (hub, group, project) is always unique.
stored_credentials = read_credentials_from_qiskitrc()
if credentials.unique_id() in stored_credentials.keys():
warnings.warn('Credentials are already stored.')
else:
store_credentials(credentials)
def active_accounts(self):
"""List all accounts currently in the session.
Returns:
list[dict]: a list with information about the accounts currently
in the session.
"""
information = []
for provider in self._accounts.values():
information.append({
'token': provider.credentials.token,
'url': provider.credentials.url,
})
return information
def stored_accounts(self):
"""List all accounts stored to disk.
Returns:
list[dict]: a list with information about the accounts stored
on disk.
"""
information = []
stored_creds = read_credentials_from_qiskitrc()
for creds in stored_creds:
information.append({
'token': stored_creds[creds].token,
'url': stored_creds[creds].url
})
return information
def load_accounts(self, **kwargs):
"""Load IBMQ accounts found in the system into current session,
subject to optional filtering.
Automatically load the accounts found in the system. This method
looks for credentials in the following locations, in order, and
returns as soon as credentials are found:
1. in the `Qconfig.py` file in the current working directory.
2. in the environment variables.
3. in the `qiskitrc` configuration file
Raises:
IBMQAccountError: if no credentials are found.
"""
for credentials in discover_credentials().values():
if self._credentials_match_filter(credentials, kwargs):
self._append_account(credentials)
if not self._accounts:
raise IBMQAccountError('No IBMQ credentials found on disk.')
def disable_accounts(self, **kwargs):
"""Disable accounts in the current session, subject to optional filtering.
The filter kwargs can be `token`, `url`, `hub`, `group`, `project`.
If no filter is passed, all accounts in the current session will be disabled.
Raises:
IBMQAccountError: if no account matched the filter.
"""
disabled = False
# Try to remove from session.
current_creds = self._accounts.copy()
for creds in current_creds:
credentials = Credentials(current_creds[creds].credentials.token,
current_creds[creds].credentials.url)
if self._credentials_match_filter(credentials, kwargs):
del self._accounts[credentials.unique_id()]
disabled = True
if not disabled:
raise IBMQAccountError('No matching account to disable in current session.')
def delete_accounts(self, **kwargs):
"""Delete saved accounts from disk, subject to optional filtering.
The filter kwargs can be `token`, `url`, `hub`, `group`, `project`.
If no filter is passed, all accounts will be deleted from disk.
Raises:
IBMQAccountError: if no account matched the filter.
"""
deleted = False
# Try to delete from disk.
stored_creds = read_credentials_from_qiskitrc()
for creds in stored_creds:
credentials = Credentials(stored_creds[creds].token,
stored_creds[creds].url)
if self._credentials_match_filter(credentials, kwargs):
remove_credentials(credentials)
deleted = True
if not deleted:
raise IBMQAccountError('No matching account to delete from disk.')
def _append_account(self, credentials):
"""Append an account with the specified credentials to the session.
Args:
credentials (Credentials): set of credentials.
Returns:
IBMQSingleProvider: new single-account provider.
"""
# Check if duplicated credentials are already in use. By convention,
# we assume (hub, group, project) is always unique.
if credentials.unique_id() in self._accounts.keys():
warnings.warn('Credentials are already in use.')
single_provider = IBMQSingleProvider(credentials, self)
self._accounts[credentials.unique_id()] = single_provider
return single_provider
def _credentials_match_filter(self, credentials, filter_dict):
"""Return True if the credentials match a filter.
These filters apply on properties of a Credentials object:
token, url, hub, group, project, proxies, verify
Any other filter has no effect.
Args:
credentials (Credentials): IBMQ credentials object
filter_dict (dict): dictionary of filter conditions
Returns:
bool: True if the credentials meet all the filter conditions
"""
return all(getattr(credentials, key_, None) == value_ for
key_, value_ in filter_dict.items())
<|code_end|>
|
qiskit/backends/ibmq/credentials/_configrc.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Utilities for reading and writing credentials from and to configuration files.
"""
import warnings
import os
from ast import literal_eval
from collections import OrderedDict
from configparser import ConfigParser, ParsingError
from qiskit import QISKitError
from .credentials import Credentials
DEFAULT_QISKITRC_FILE = os.path.join(os.path.expanduser("~"),
'.qiskit', 'qiskitrc')
def read_credentials_from_qiskitrc(filename=None):
"""
Read a configuration file and return a dict with its sections.
Args:
filename (str): full path to the qiskitrc file. If `None`, the default
location is used (`HOME/.qiskit/qiskitrc`).
Returns:
dict: dictionary with the contents of the configuration file, with
the form::
{credential_unique_id: Credentials}
Raises:
QISKitError: if the file was not parseable. Please note that this
exception is not raised if the file does not exist (instead, an
empty dict is returned).
"""
filename = filename or DEFAULT_QISKITRC_FILE
config_parser = ConfigParser()
try:
config_parser.read(filename)
except ParsingError as ex:
raise QISKitError(str(ex))
# Build the credentials dictionary.
credentials_dict = OrderedDict()
for name in config_parser.sections():
single_credentials = dict(config_parser.items(name))
# Individually convert keys to their right types.
# TODO: consider generalizing, moving to json configuration or a more
# robust alternative.
if 'proxies' in single_credentials.keys():
single_credentials['proxies'] = literal_eval(
single_credentials['proxies'])
if 'verify' in single_credentials.keys():
single_credentials['verify'] = bool(single_credentials['verify'])
new_credentials = Credentials(**single_credentials)
credentials_dict[new_credentials.unique_id()] = new_credentials
return credentials_dict
def write_qiskit_rc(credentials, filename=None):
"""
Write credentials to the configuration file.
Args:
credentials (dict): dictionary with the credentials, with the form::
{credentials_unique_id: Credentials}
filename (str): full path to the qiskitrc file. If `None`, the default
location is used (`HOME/.qiskit/qiskitrc`).
"""
def _credentials_object_to_dict(obj):
return {key: getattr(obj, key)
for key in ['token', 'url', 'proxies', 'verify']
if getattr(obj, key)}
def _section_name(credentials_):
"""Return a string suitable for use as a unique section name."""
base_name = 'ibmq'
if credentials_.is_ibmq():
base_name = '{}_{}_{}_{}'.format(base_name, *credentials_.unique_id())
return base_name
filename = filename or DEFAULT_QISKITRC_FILE
# Create the directories and the file if not found.
os.makedirs(os.path.dirname(filename), exist_ok=True)
unrolled_credentials = {
_section_name(credentials_object): _credentials_object_to_dict(credentials_object)
for _, credentials_object in credentials.items()
}
# Write the configuration file.
with open(filename, 'w') as config_file:
config_parser = ConfigParser()
config_parser.read_dict(unrolled_credentials)
config_parser.write(config_file)
def store_credentials(credentials, overwrite=False, filename=None):
"""
Store the credentials for a single account in the configuration file.
Args:
credentials (Credentials): credentials instance.
overwrite (bool): overwrite existing credentials.
filename (str): full path to the qiskitrc file. If `None`, the default
location is used (`HOME/.qiskit/qiskitrc`).
Raises:
QISKitError: if the account_name could not be assigned.
"""
# Read the current providers stored in the configuration file.
filename = filename or DEFAULT_QISKITRC_FILE
stored_credentials = read_credentials_from_qiskitrc(filename)
# Check if duplicated credentials are already stored. By convention,
# we assume (hub, group, project) is always unique.
if credentials.unique_id() in stored_credentials and not overwrite:
warnings.warn('Credentials already present. Set overwrite=True to overwrite.')
return
# Append and write the credentials to file.
stored_credentials[credentials.unique_id()] = credentials
write_qiskit_rc(stored_credentials, filename)
def remove_credentials(credentials, filename=None):
"""Remove credentials from qiskitrc.
Args:
credentials (Credentials): credentials.
filename (str): full path to the qiskitrc file. If `None`, the default
location is used (`HOME/.qiskit/qiskitrc`).
Raises:
QISKitError: If there is no account with that name on the configuration
file.
"""
# Set the name of the Provider from the class.
stored_credentials = read_credentials_from_qiskitrc(filename)
try:
del stored_credentials[credentials.unique_id()]
except KeyError:
raise QISKitError('The account "%s" does not exist in the '
'configuration file')
write_qiskit_rc(stored_credentials, filename)
<|code_end|>
qiskit/backends/ibmq/credentials/credentials.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Model for representing IBM Q credentials."""
import re
# Regex that matches a IBMQ URL with hub information
REGEX_IBMQ_HUBS = (
'(?P<prefix>http[s]://.+/api)'
'/Hubs/(?P<hub>[^/]+)/Groups/(?P<group>[^/]+)/Projects/(?P<project>[^/]+)'
)
# Template for creating an IBMQ URL with hub information
TEMPLATE_IBMQ_HUBS = '{prefix}/Hubs/{hub}/Groups/{group}/Projects/{project}'
class Credentials(object):
"""IBM Q account credentials.
Note that, by convention, two credentials that have the same hub, group
and project (regardless of other attributes) are considered equivalent.
The `unique_id()` returns the unique identifier.
"""
def __init__(self, token, url, hub=None, group=None, project=None,
proxies=None, verify=True):
"""
Args:
token (str): Quantum Experience or IBMQ API token.
url (str): URL for Quantum Experience or IBMQ.
hub (str): the hub used for IBMQ.
group (str): the group used for IBMQ.
project (str): the project used for IBMQ.
proxies (dict): proxy configuration for the API.
verify (bool): if False, ignores SSL certificates errors
Note:
`hub`, `group` and `project` are stored as attributes for
convenience, but their usage in the API is deprecated. The new-style
URLs (that includes these parameters as part of the url string, and
is automatically set during instantiation) should be used when
communicating with the API.
"""
self.token = token
self.url, self.hub, self.group, self.project = _unify_ibmq_url(
url, hub, group, project)
self.proxies = proxies or {}
self.verify = verify
def is_ibmq(self):
"""Return whether the credentials represent a IBMQ account."""
return all([self.hub, self.group, self.project])
def __eq__(self, other):
return self.__dict__ == other.__dict__
def unique_id(self):
"""Return a value that uniquely identifies these credentials.
By convention, we assume (hub, group, project) is always unique.
"""
return self.hub, self.group, self.project
def _unify_ibmq_url(url, hub=None, group=None, project=None):
"""Return a new-style set of credential values (url and hub parameters).
Args:
url (str): URL for Quantum Experience or IBM Q.
hub (str): the hub used for IBM Q.
group (str): the group used for IBM Q.
project (str): the project used for IBM Q.
Returns:
tuple[url, hub, group, token]:
* url (str): new-style Quantum Experience or IBM Q URL (the hub,
group and project included in the URL.
* hub (str): the hub used for IBM Q.
* group (str): the group used for IBM Q.
* project (str): the project used for IBM Q.
"""
# Check if the URL is "new style", and retrieve embedded parameters from it.
regex_match = re.match(REGEX_IBMQ_HUBS, url, re.IGNORECASE)
if regex_match:
_, hub, group, project = regex_match.groups()
else:
if hub and group and project:
# Assume it is an IBMQ URL, and update the url.
url = TEMPLATE_IBMQ_HUBS.format(prefix=url, hub=hub, group=group,
project=project)
else:
# Cleanup the hub, group and project, without modifying the url.
hub = group = project = None
return url, hub, group, project
<|code_end|>
qiskit/backends/ibmq/ibmqprovider.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Provider for remote IBMQ backends with admin features."""
import warnings
from collections import OrderedDict
from qiskit.backends import BaseProvider
from .credentials._configrc import remove_credentials
from .credentials import (Credentials,
read_credentials_from_qiskitrc, store_credentials, discover_credentials)
from .ibmqaccounterror import IBMQAccountError
from .ibmqsingleprovider import IBMQSingleProvider
QE_URL = 'https://quantumexperience.ng.bluemix.net/api'
class IBMQProvider(BaseProvider):
"""Provider for remote IBMQ backends with admin features.
This class is the entry point for handling backends from IBMQ, allowing
using different accounts.
"""
def __init__(self):
super().__init__()
# dict[credentials_unique_id: IBMQSingleProvider]
# This attribute stores a reference to the different accounts. The
# keys are tuples (hub, group, project), as the convention is that
# that tuple uniquely identifies a set of credentials.
self._accounts = OrderedDict()
def backends(self, name=None, filters=None, **kwargs):
"""Return all backends accessible via IBMQ provider, subject to optional filtering.
Args:
name (str): backend name to filter by
filters (callable): more complex filters, such as lambda functions
e.g. IBMQ.backends(filters=lambda b: b.configuration['n_qubits'] > 5)
kwargs: simple filters specifying a true/false criteria in the
backend configuration or backend status or provider credentials
e.g. IBMQ.backends(n_qubits=5, operational=True, hub='internal')
Returns:
list[IBMQBackend]: list of backends available that match the filter
Raises:
IBMQAccountError: if no account matched the filter.
"""
# pylint: disable=arguments-differ
# Special handling of the credentials filters: match and prune from kwargs
credentials_filter = {}
for key in ['token', 'url', 'hub', 'group', 'project', 'proxies', 'verify']:
if key in kwargs:
credentials_filter[key] = kwargs.pop(key)
providers = [provider for provider in self._accounts.values() if
self._credentials_match_filter(provider.credentials,
credentials_filter)]
# Special handling of the `name` parameter, to support alias resolution.
if name:
aliases = self.aliased_backend_names()
aliases.update(self.deprecated_backend_names())
name = aliases.get(name, name)
# Aggregate the list of filtered backends.
backends = []
for provider in providers:
backends = backends + provider.backends(
name=name, filters=filters, **kwargs)
return backends
@staticmethod
def deprecated_backend_names():
"""Returns deprecated backend names."""
return {
'ibmqx_qasm_simulator': 'ibmq_qasm_simulator',
'ibmqx_hpc_qasm_simulator': 'ibmq_qasm_simulator',
'real': 'ibmqx1'
}
@staticmethod
def aliased_backend_names():
"""Returns aliased backend names."""
return {
'ibmq_5_yorktown': 'ibmqx2',
'ibmq_5_tenerife': 'ibmqx4',
'ibmq_16_rueschlikon': 'ibmqx5',
'ibmq_20_austin': 'QS1_1'
}
def enable_account(self, token, url=QE_URL, **kwargs):
"""Authenticate a new IBMQ account and add for use during this session.
Login into Quantum Experience or IBMQ using the provided credentials,
adding the account to the current session. The account is not stored
in disk.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
"""
credentials = Credentials(token, url, **kwargs)
self._append_account(credentials)
def save_account(self, token, url=QE_URL, overwrite=False, **kwargs):
"""Save the account to disk for future use.
Login into Quantum Experience or IBMQ using the provided credentials,
adding the account to the current session. The account is stored in
disk for future use.
Args:
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
overwrite (bool): overwrite existing credentials.
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
"""
credentials = Credentials(token, url, **kwargs)
store_credentials(credentials, overwrite=overwrite)
def active_accounts(self):
"""List all accounts currently in the session.
Returns:
list[dict]: a list with information about the accounts currently
in the session.
"""
information = []
for provider in self._accounts.values():
information.append({
'token': provider.credentials.token,
'url': provider.credentials.url,
})
return information
def stored_accounts(self):
"""List all accounts stored to disk.
Returns:
list[dict]: a list with information about the accounts stored
on disk.
"""
information = []
stored_creds = read_credentials_from_qiskitrc()
for creds in stored_creds:
information.append({
'token': stored_creds[creds].token,
'url': stored_creds[creds].url
})
return information
def load_accounts(self, **kwargs):
"""Load IBMQ accounts found in the system into current session,
subject to optional filtering.
Automatically load the accounts found in the system. This method
looks for credentials in the following locations, in order, and
returns as soon as credentials are found:
1. in the `Qconfig.py` file in the current working directory.
2. in the environment variables.
3. in the `qiskitrc` configuration file
Raises:
IBMQAccountError: if no credentials are found.
"""
for credentials in discover_credentials().values():
if self._credentials_match_filter(credentials, kwargs):
self._append_account(credentials)
if not self._accounts:
raise IBMQAccountError('No IBMQ credentials found on disk.')
def disable_accounts(self, **kwargs):
"""Disable accounts in the current session, subject to optional filtering.
The filter kwargs can be `token`, `url`, `hub`, `group`, `project`.
If no filter is passed, all accounts in the current session will be disabled.
Raises:
IBMQAccountError: if no account matched the filter.
"""
disabled = False
# Try to remove from session.
current_creds = self._accounts.copy()
for creds in current_creds:
credentials = Credentials(current_creds[creds].credentials.token,
current_creds[creds].credentials.url)
if self._credentials_match_filter(credentials, kwargs):
del self._accounts[credentials.unique_id()]
disabled = True
if not disabled:
raise IBMQAccountError('No matching account to disable in current session.')
def delete_accounts(self, **kwargs):
"""Delete saved accounts from disk, subject to optional filtering.
The filter kwargs can be `token`, `url`, `hub`, `group`, `project`.
If no filter is passed, all accounts will be deleted from disk.
Raises:
IBMQAccountError: if no account matched the filter.
"""
deleted = False
# Try to delete from disk.
stored_creds = read_credentials_from_qiskitrc()
for creds in stored_creds:
credentials = Credentials(stored_creds[creds].token,
stored_creds[creds].url)
if self._credentials_match_filter(credentials, kwargs):
remove_credentials(credentials)
deleted = True
if not deleted:
raise IBMQAccountError('No matching account to delete from disk.')
def _append_account(self, credentials):
"""Append an account with the specified credentials to the session.
Args:
credentials (Credentials): set of credentials.
Returns:
IBMQSingleProvider: new single-account provider.
"""
# Check if duplicated credentials are already in use. By convention,
# we assume (hub, group, project) is always unique.
if credentials.unique_id() in self._accounts.keys():
warnings.warn('Credentials are already in use.')
single_provider = IBMQSingleProvider(credentials, self)
self._accounts[credentials.unique_id()] = single_provider
return single_provider
def _credentials_match_filter(self, credentials, filter_dict):
"""Return True if the credentials match a filter.
These filters apply on properties of a Credentials object:
token, url, hub, group, project, proxies, verify
Any other filter has no effect.
Args:
credentials (Credentials): IBMQ credentials object
filter_dict (dict): dictionary of filter conditions
Returns:
bool: True if the credentials meet all the filter conditions
"""
return all(getattr(credentials, key_, None) == value_ for
key_, value_ in filter_dict.items())
<|code_end|>
|
test_qobj_to_circuits_multiple is ocassionally failing
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: latest master
- **Python version**: any
- **Operating system**: any
### What is the current behavior?
When running test_qobj_to_circuits_mutiple we're seeing occasional sporadic failures, like:
https://travis-ci.org/Qiskit/qiskit-terra/jobs/451515130#L2711
It looks like something is getting out of order and that's causing the tests to fail because the lists don't match 100%. We're seeing this mostly in CI, although I was able to reproduce after running `tox -epy37 -- --until-failure` (you can replace 'py37' with the version of python you have installed locally and it will work the same) which ran the tests in a loop until it encountered the failure. I've attached the subunit file from the failed run for reference too: [failure.subunit.gz](https://github.com/Qiskit/qiskit-terra/files/2555411/failure.subunit.gz)
This leads me to believe there is some non-deterministic behavior in the test or function itself. Or there is a cross interaction with another test in the suite (which by switching to running in parallel in #737 would trigger).
### Steps to reproduce the problem
It's not a 100% failure so either run the tests in the loop until it fails, or look at one of the referenced CI failures.
### What is the expected behavior?
The test passes 100% of the time
### Suggested solutions
Figure out what is causing the failure and address it
|
qiskit/dagcircuit/_dagcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Object to represent a quantum circuit as a directed acyclic graph.
The nodes in the graph are either input/output nodes or operation nodes.
The operation nodes are elements of a basis that is part of the circuit.
The QASM definitions of the basis elements are carried with the circuit.
The edges correspond to qubits or bits in the circuit. A directed edge
from node A to node B means that the (qu)bit passes from the output of A
to the input of B. The object's methods allow circuits to be constructed,
composed, and modified. Some natural properties like depth can be computed
directly from the graph.
"""
from collections import OrderedDict
import copy
import itertools
import networkx as nx
import sympy
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QISKitError
from qiskit import _compositegate
from ._dagcircuiterror import DAGCircuitError
class DAGCircuit:
"""
Quantum circuit as a directed acyclic graph.
There are 3 types of nodes in the graph: inputs, outputs, and operations.
The nodes are connected by directed edges that correspond to qubits and
bits.
"""
# pylint: disable=invalid-name
def __init__(self):
"""Create an empty circuit."""
# Circuit name. Generally, this corresponds to the name
# of the QuantumCircuit from which the DAG was generated.
self.name = None
# Map from a wire's name (reg,idx) to a Bool that is True if the
# wire is a classical bit and False if the wire is a qubit.
self.wire_type = OrderedDict()
# Map from wire names (reg,idx) to input nodes of the graph
self.input_map = OrderedDict()
# Map from wire names (reg,idx) to output nodes of the graph
self.output_map = OrderedDict()
# Running count of the total number of nodes
self.node_counter = 0
# Map of named operations in this circuit and their signatures.
# The signature is an integer tuple (nq,nc,np) specifying the
# number of input qubits, input bits, and real parameters.
# The definition is external to the circuit object.
self.basis = OrderedDict()
# Directed multigraph whose nodes are inputs, outputs, or operations.
# Operation nodes have equal in- and out-degrees and carry
# additional data about the operation, including the argument order
# and parameter values.
# Input nodes have out-degree 1 and output nodes have in-degree 1.
# Edges carry wire labels (reg,idx) and each operation has
# corresponding in- and out-edges with the same wire labels.
self.multi_graph = nx.MultiDiGraph()
# Map of qregs to sizes
self.qregs = OrderedDict()
# Map of cregs to sizes
self.cregs = OrderedDict()
# Map of user defined gates to ast nodes defining them
self.gates = OrderedDict()
# Output precision for printing floats
self.prec = 10
# layout of dag quantum registers on the chip
# TODO: rethink this. doesn't seem related to concept of DAG,
# but if we want to be able to generate qobj
# directly from a dag, we need it.
self.layout = []
def get_qubits(self):
"""Return a list of qubits as (qreg, index) pairs."""
return [(k, i) for k, v in self.qregs.items() for i in range(v.size)]
def rename_register(self, regname, newname):
"""Rename a classical or quantum register throughout the circuit.
regname = existing register name string
newname = replacement register name string
"""
if regname == newname:
return
if newname in self.qregs or newname in self.cregs:
raise DAGCircuitError("duplicate register name %s" % newname)
if regname not in self.qregs and regname not in self.cregs:
raise DAGCircuitError("no register named %s" % regname)
iscreg = False
if regname in self.qregs:
self.qregs[newname] = self.qregs[regname]
self.qregs.pop(regname, None)
reg_size = self.qregs[newname].size
if regname in self.cregs:
self.cregs[newname] = self.cregs[regname]
self.cregs.pop(regname, None)
reg_size = self.cregs[newname].size
iscreg = True
for i in range(reg_size):
self.wire_type[(newname, i)] = iscreg
self.wire_type.pop((regname, i), None)
self.input_map[(newname, i)] = self.input_map[(regname, i)]
self.input_map.pop((regname, i), None)
self.output_map[(newname, i)] = self.output_map[(regname, i)]
self.output_map.pop((regname, i), None)
# n node d = data
for _, d in self.multi_graph.nodes(data=True):
if d["type"] == "in" or d["type"] == "out":
if d["name"][0] == regname:
d["name"] = (newname, d["name"][1])
elif d["type"] == "op":
qa = []
for a in d["qargs"]:
if a[0] == regname:
a = (newname, a[1])
qa.append(a)
d["qargs"] = qa
ca = []
for a in d["cargs"]:
if a[0] == regname:
a = (newname, a[1])
ca.append(a)
d["cargs"] = ca
if d["condition"] is not None:
if d["condition"][0] == regname:
d["condition"] = (newname, d["condition"][1])
# eX = edge, d= data
for _, _, d in self.multi_graph.edges(data=True):
if d["name"][0] == regname:
d["name"] = (newname, d["name"][1])
def remove_all_ops_named(self, opname):
"""Remove all operation nodes with the given name."""
for n in self.get_named_nodes(opname):
self._remove_op_node(n)
def fs(self, number):
"""Format a float f as a string with self.prec digits."""
fmt = "{0:0.%snumber}" % self.prec
return fmt.format(number)
def add_qreg(self, qreg):
"""Add all wires in a quantum register."""
if not isinstance(qreg, QuantumRegister):
raise DAGCircuitError("not a QuantumRegister instance.")
if qreg.name in self.qregs:
raise DAGCircuitError("duplicate register %s" % qreg.name)
self.qregs[qreg.name] = qreg
for j in range(qreg.size):
self._add_wire((qreg.name, j))
def add_creg(self, creg):
"""Add all wires in a classical register."""
if not isinstance(creg, ClassicalRegister):
raise DAGCircuitError("not a ClassicalRegister instance.")
if creg.name in self.cregs:
raise DAGCircuitError("duplicate register %s" % creg.name)
self.cregs[creg.name] = creg
for j in range(creg.size):
self._add_wire((creg.name, j), True)
def _add_wire(self, name, isClassical=False):
"""Add a qubit or bit to the circuit.
name is a (string,int) tuple containing register name and index
This adds a pair of in and out nodes connected by an edge.
"""
if name not in self.wire_type:
self.wire_type[name] = isClassical
self.node_counter += 1
self.input_map[name] = self.node_counter
self.node_counter += 1
self.output_map[name] = self.node_counter
in_node = self.input_map[name]
out_node = self.output_map[name]
self.multi_graph.add_edge(in_node, out_node)
self.multi_graph.node[in_node]["type"] = "in"
self.multi_graph.node[out_node]["type"] = "out"
self.multi_graph.node[in_node]["name"] = name
self.multi_graph.node[out_node]["name"] = name
self.multi_graph.adj[in_node][out_node][0]["name"] = name
else:
raise DAGCircuitError("duplicate wire %s" % name)
def add_basis_element(self, name, number_qubits,
number_classical=0, number_parameters=0):
"""Add an operation to the basis.
name is string label for operation
number_qubits is number of qubit arguments
number_classical is number of bit arguments
number_parameters is number of real parameters
The parameters (nq,nc,np) are ignored for the special case
when name = "barrier". The barrier instruction has a variable
number of qubit arguments.
"""
if name not in self.basis:
self.basis[name] = (
number_qubits,
number_classical,
number_parameters)
if name in self.gates:
if self.gates[name]["n_args"] != number_parameters or \
self.gates[name]["n_bits"] != number_qubits or number_classical != 0:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def add_gate_data(self, name, gatedata):
"""Add the definition of a gate.
gatedata is dict with fields:
"print" = True or False
"opaque" = True or False
"n_args" = number of real parameters
"n_bits" = number of qubits
"args" = list of parameter names
"bits" = list of qubit names
"body" = GateBody AST node
"""
if name not in self.gates:
self.gates[name] = gatedata
if name in self.basis:
if self.basis[name][0] != self.gates[name]["n_bits"] or \
self.basis[name][1] != 0 or \
self.basis[name][2] != self.gates[name]["n_args"]:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def _check_basis_data(self, name, qargs, cargs, params):
"""Check the arguments against the data for this operation.
name is a string
qargs is a list of tuples like ("q",0)
cargs is a list of tuples like ("c",0)
params is a list of strings that represent floats
"""
# Check that we have this operation
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
# Check the number of arguments matches the signature
if name in ["barrier"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if params:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
elif name in ["snapshot", "noise", "save", "load"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if not params:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
else:
if len(qargs) != self.basis[name][0]:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if len(cargs) != self.basis[name][1]:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if len(params) != self.basis[name][2]:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
def _check_condition(self, name, condition):
"""Verify that the condition is valid.
name is a string used for error reporting
condition is either None or a tuple (string,int) giving (creg,value)
"""
# Verify creg exists
if condition is not None and condition[0] not in self.cregs:
raise DAGCircuitError("invalid creg in condition for %s" % name)
def _check_bits(self, args, amap, bval):
"""Check the values of a list of (qu)bit arguments.
For each element A of args, check that amap contains A and
self.wire_type[A] equals bval.
args is a list of (regname,idx) tuples
amap is a dictionary keyed on (regname,idx) tuples
bval is boolean
"""
# Check for each wire
for q in args:
if q not in amap:
raise DAGCircuitError("(qu)bit %s not found" % (q,))
if self.wire_type[q] != bval:
raise DAGCircuitError("expected wire type %s for %s"
% (bval, q))
def _bits_in_condition(self, cond):
"""Return a list of bits (regname,idx) in the given condition.
cond is either None or a (regname,int) tuple specifying
a classical if condition.
"""
all_bits = []
if cond is not None:
all_bits.extend([(cond[0], j) for j in range(self.cregs[cond[0]].size)])
return all_bits
def _add_op_node(self, nname, nqargs, ncargs, nparams, ncondition, nop):
"""Add a new operation node to the graph and assign properties.
nname node name
nqargs quantum arguments
ncargs classical arguments
nparams parameters
ncondition classical condition (or None)
nop Instruction instance representing this operation
"""
# Add a new operation node to the graph
self.node_counter += 1
self.multi_graph.add_node(self.node_counter)
# Update that operation node's data
self.multi_graph.node[self.node_counter]["type"] = "op"
self.multi_graph.node[self.node_counter]["name"] = nname
self.multi_graph.node[self.node_counter]["qargs"] = nqargs
self.multi_graph.node[self.node_counter]["cargs"] = ncargs
self.multi_graph.node[self.node_counter]["params"] = nparams
self.multi_graph.node[self.node_counter]["condition"] = ncondition
self.multi_graph.node[self.node_counter]["op"] = nop
def apply_operation_back(self, name, qargs, cargs=None, params=None,
condition=None, op=None):
"""Apply an operation to the output of the circuit.
name is a string
qargs is a list of tuples like ("q",0)
cargs is a list of tuples like ("c",0)
params is a list of symbols that represent numbers
condition is either None or a tuple (string,int) giving (creg,value)
op is an Instruction instance representing this node
"""
cargs = cargs or []
params = params or []
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(name, qargs, cargs, params)
self._check_condition(name, condition)
self._check_bits(qargs, self.output_map, False)
self._check_bits(all_cbits, self.output_map, True)
self._add_op_node(name, qargs, cargs, params, condition, op)
# Add new in-edges from predecessors of the output nodes to the
# operation node while deleting the old in-edges of the output nodes
# and adding new edges from the operation node to each output node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.predecessors(self.output_map[q]))
if len(ie) != 1:
raise QISKitError("output node has multiple in-edges")
self.multi_graph.add_edge(ie[0], self.node_counter, name=q)
self.multi_graph.remove_edge(ie[0], self.output_map[q])
self.multi_graph.add_edge(
self.node_counter, self.output_map[q], name=q)
def apply_operation_front(self, name, qargs, cargs=None, params=None,
condition=None, op=None):
"""Apply an operation to the input of the circuit.
name is a string
qargs is a list of strings like "q[0]"
cargs is a list of strings like "c[0]"
params is a list of strings that represent floats
condition is either None or a tuple (string,int) giving (creg,value)
"""
cargs = cargs or []
params = params or []
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(name, qargs, cargs, params)
self._check_condition(name, condition)
self._check_bits(qargs, self.input_map, False)
self._check_bits(all_cbits, self.input_map, True)
self._add_op_node(name, qargs, cargs, params, condition, op)
# Add new out-edges to successors of the input nodes from the
# operation node while deleting the old out-edges of the input nodes
# and adding new edges to the operation node from each input node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = self.multi_graph.successors(self.input_map[q])
if len(ie) != 1:
raise QISKitError("input node has multiple out-edges")
self.multi_graph.add_edge(self.node_counter, ie[0], name=q)
self.multi_graph.remove_edge(self.input_map[q], ie[0])
self.multi_graph.add_edge(
self.input_map[q], self.node_counter, name=q)
def _make_union_basis(self, input_circuit):
"""Return a new basis map.
The new basis is a copy of self.basis with
new elements of input_circuit.basis added.
input_circuit is a DAGCircuit
"""
union_basis = self.basis.copy()
for g in input_circuit.basis:
if g not in union_basis:
union_basis[g] = input_circuit.basis[g]
if union_basis[g] != input_circuit.basis[g]:
raise DAGCircuitError("incompatible basis")
return union_basis
def _make_union_gates(self, input_circuit):
"""Return a new gates map.
The new gates are a copy of self.gates with
new elements of input_circuit.gates added.
input_circuit is a DAGCircuit
NOTE: gates in input_circuit that are also in self must
be *identical* to the gates in self
"""
union_gates = {}
for k, v in self.gates.items():
union_gates[k] = v
for k, v in input_circuit.gates.items():
if k not in union_gates:
union_gates[k] = v
if union_gates[k]["opaque"] != input_circuit.gates[k]["opaque"] or \
union_gates[k]["n_args"] != input_circuit.gates[k]["n_args"] or \
union_gates[k]["n_bits"] != input_circuit.gates[k]["n_bits"] or \
union_gates[k]["args"] != input_circuit.gates[k]["args"] or \
union_gates[k]["bits"] != input_circuit.gates[k]["bits"]:
raise DAGCircuitError("inequivalent gate definitions for %s"
% k)
return union_gates
def _check_wiremap_registers(self, wire_map, keyregs, valregs,
valreg=True):
"""Check that wiremap neither fragments nor leaves duplicate registers.
1. There are no fragmented registers. A register in keyregs
is fragmented if not all of its (qu)bits are renamed by wire_map.
2. There are no duplicate registers. A register is duplicate if
it appears in both self and keyregs but not in wire_map.
wire_map is a map from (regname,idx) in keyregs to (regname,idx)
in valregs
keyregs is a map from register names to Register objects
valregs is a map from register names to Register objects
valreg is a Bool, if False the method ignores valregs and does not
add regs for bits in the wire_map image that don't appear in valregs
Return the set of regs to add to self
"""
add_regs = set()
reg_frag_chk = {}
for k, v in keyregs.items():
reg_frag_chk[k] = {j: False for j in range(v.size)}
for k in wire_map.keys():
if k[0] in keyregs:
reg_frag_chk[k[0]][k[1]] = True
for k, v in reg_frag_chk.items():
rname = ",".join(map(str, k))
s = set(v.values())
if len(s) == 2:
raise DAGCircuitError("wire_map fragments reg %s" % rname)
elif s == set([False]):
if k in self.qregs or k in self.cregs:
raise DAGCircuitError("unmapped duplicate reg %s" % rname)
else:
# Add registers that appear only in keyregs
add_regs.add(keyregs[k])
else:
if valreg:
# If mapping to a register not in valregs, add it.
# (k,0) exists in wire_map because wire_map doesn't
# fragment k
if not wire_map[(k, 0)][0] in valregs:
size = max(map(lambda x: x[1], filter(lambda x: x[0] == wire_map[(k, 0)][0],
wire_map.values())))
qreg = QuantumRegister(wire_map[(k, 0)][0], size + 1)
add_regs.add(qreg)
return add_regs
def _check_wiremap_validity(self, wire_map, keymap, valmap, input_circuit):
"""Check that the wiremap is consistent.
Check that the wiremap refers to valid wires and that
those wires have consistent types.
wire_map is a map from (regname,idx) in keymap to (regname,idx)
in valmap
keymap is a map whose keys are wire_map keys
valmap is a map whose keys are wire_map values
input_circuit is a DAGCircuit
"""
for k, v in wire_map.items():
kname = ",".join(map(str, k))
vname = ",".join(map(str, v))
if k not in keymap:
raise DAGCircuitError("invalid wire mapping key %s" % kname)
if v not in valmap:
raise DAGCircuitError("invalid wire mapping value %s"
% vname)
if input_circuit.wire_type[k] != self.wire_type[v]:
raise DAGCircuitError("inconsistent wire_map at (%s,%s)"
% (kname, vname))
def _map_condition(self, wire_map, condition):
"""Use the wire_map dict to change the condition tuple's creg name.
wire_map is map from wires to wires
condition is a tuple (reg,int)
Returns the new condition tuple
"""
if condition is None:
n_condition = None
else:
# Map the register name, using fact that registers must not be
# fragmented by the wire_map (this must have been checked
# elsewhere)
bit0 = (condition[0], 0)
n_condition = (wire_map.get(bit0, bit0)[0], condition[1])
return n_condition
def compose_back(self, input_circuit, wire_map=None):
"""Apply the input circuit to the output of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of input qubits of the input circuit are mapped
to a subset of output qubits of this circuit.
wire_map[input_qubit_to_input_circuit] = output_qubit_of_self
"""
wire_map = wire_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map for duplicate values
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_wiremap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.input_map,
self.output_map, input_circuit)
# Compose
self.basis = union_basis
self.gates = union_gates
for node in nx.topological_sort(input_circuit.multi_graph):
nd = input_circuit.multi_graph.node[node]
if nd["type"] == "in":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["name"], nd["name"])
# the mapped wire should already exist
if m_name not in self.output_map:
raise QISKitError("wire (%s,%d) not in self" % (m_name[0], m_name[1]))
if nd["name"] not in input_circuit.wire_type:
raise QISKitError("inconsistent wire_type for (%s,%d) in input_circuit"
% (nd["name"][0], nd["name"][1]))
elif nd["type"] == "out":
# ignore output nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: wire_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x), nd["cargs"]))
self.apply_operation_back(nd["name"], m_qargs, m_cargs,
nd["params"], condition, nd["op"])
else:
raise QISKitError("bad node type %s" % nd["type"])
def compose_front(self, input_circuit, wire_map=None):
"""Apply the input circuit to the input of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of output qubits of the input circuit are mapped
to a subset of input qubits of
this circuit.
"""
wire_map = wire_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_wiremap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.output_map,
self.input_map, input_circuit)
# Compose
self.basis = union_basis
self.gates = union_gates
for n in reversed(list(nx.topological_sort(input_circuit.multi_graph))):
nd = input_circuit.multi_graph.node[n]
if nd["type"] == "out":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["name"], nd["name"])
# the mapped wire should already exist
if m_name not in self.input_map:
raise QISKitError("wire (%s,%d) not in self" % (m_name[0], m_name[1]))
if nd["name"] not in input_circuit.wire_type:
raise QISKitError(
"inconsistent wire_type for (%s,%d) in input_circuit"
% (nd["name"][0], nd["name"][1]))
elif nd["type"] == "in":
# ignore input nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: wire_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x), nd["cargs"]))
self.apply_operation_front(nd["name"], m_qargs, m_cargs,
nd["params"], condition, nd["op"])
else:
raise QISKitError("bad node type %s" % nd["type"])
def size(self):
"""Return the number of operations."""
return self.multi_graph.order() - 2 * len(self.wire_type)
def depth(self):
"""Return the circuit depth."""
if not nx.is_directed_acyclic_graph(self.multi_graph):
raise QISKitError("not a DAG")
return nx.dag_longest_path_length(self.multi_graph) - 1
def width(self):
"""Return the total number of qubits used by the circuit."""
return len(self.wire_type) - self.num_cbits()
def num_cbits(self):
"""Return the total number of bits used by the circuit."""
return list(self.wire_type.values()).count(True)
def num_tensor_factors(self):
"""Compute how many components the circuit can decompose into."""
return nx.number_weakly_connected_components(self.multi_graph)
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.gates[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.gates[name]["n_args"] > 0:
out += "(" + ",".join(self.gates[name]["args"]) + ")"
out += " " + ",".join(self.gates[name]["bits"])
if self.gates[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.gates[name]["body"].qasm() + "}"
return out
def qasm(self, decls_only=False, add_swap=False,
no_decls=False, qeflag=False, aliases=None, eval_symbols=False):
"""Return a string containing QASM for this circuit.
if qeflag is True, add a line to include "qelib1.inc"
and only generate gate code for gates not in qelib1.
if eval_symbols is True, evaluate all symbolic
expressions to their floating point representation.
if no_decls is True, only print the instructions.
if aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
if decls_only is True, only print the declarations.
if add_swap is True, add the definition of swap in terms of
cx if necessary.
"""
# TODO: some of the input flags are not needed anymore
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
# Write top matter
if no_decls:
out = ""
else:
printed_gates = []
out = "OPENQASM 2.0;\n"
if qeflag:
out += "include \"qelib1.inc\";\n"
for k, v in sorted(qregdata.items()):
out += "qreg %s[%d];\n" % (k, v.size)
for k, v in sorted(self.cregs.items()):
out += "creg %s[%d];\n" % (k, v.size)
omit = ["U", "CX", "measure", "reset", "barrier"]
# TODO: dagcircuit shouldn't know about extensions
if qeflag:
qelib = ["u3", "u2", "u1", "cx", "id", "x", "y", "z", "h",
"s", "sdg", "t", "tdg", "cz", "cy", "ccx", "cu1",
"cu3", "swap", "cswap", "u0", "rx", "ry", "rz",
"ch", "crz", "rzz"]
omit.extend(qelib)
printed_gates.extend(qelib)
simulator_instructions = ["snapshot", "save", "load", "noise", "wait"]
omit.extend(simulator_instructions)
for k in self.basis.keys():
if k not in omit:
if not self.gates[k]["opaque"]:
calls = self.gates[k]["body"].calls()
for c in calls:
if c not in printed_gates:
out += self._gate_string(c) + "\n"
printed_gates.append(c)
if k not in printed_gates:
out += self._gate_string(k) + "\n"
printed_gates.append(k)
if add_swap and not qeflag and "cx" not in self.basis:
out += "gate cx a,b { CX a,b; }\n"
if add_swap and "swap" not in self.basis:
out += "gate swap a,b { cx a,b; cx b,a; cx a,b; }\n"
# Write the instructions
if not decls_only:
for n in nx.lexicographical_topological_sort(self.multi_graph):
nd = self.multi_graph.node[n]
if nd["type"] == "op":
if nd["condition"] is not None:
out += "if(%s==%d) " \
% (nd["condition"][0], nd["condition"][1])
if not nd["cargs"]:
nm = nd["name"]
if aliases:
qarglist = map(lambda x: aliases[x], nd["qargs"])
else:
qarglist = nd["qargs"]
qarg = ",".join(map(lambda x: "%s[%d]" % (x[0], x[1]),
qarglist))
if nd["params"]:
if eval_symbols:
param = ",".join(map(lambda x: str(sympy.N(x)),
nd["params"]))
else:
param = ",".join(map(lambda x: x.replace("**", "^"),
map(str, nd["params"])))
out += "%s(%s) %s;\n" % (nm, param, qarg)
else:
out += "%s %s;\n" % (nm, qarg)
else:
if nd["name"] == "measure":
if len(nd["cargs"]) != 1 or len(nd["qargs"]) != 1 \
or nd["params"]:
raise QISKitError("bad node data")
qname = nd["qargs"][0][0]
qindex = nd["qargs"][0][1]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
out += "measure %s[%d] -> %s[%d];\n" \
% (qname,
qindex,
nd["cargs"][0][0],
nd["cargs"][0][1])
else:
raise QISKitError("bad node data")
return out
def _check_wires_list(self, wires, name, input_circuit, condition=None):
"""Check that a list of wires satisfies some conditions.
wires = list of (register_name, index) tuples
name = name of operation
input_circuit = replacement circuit for operation
condition = None or (creg_name, value) if this instance of the
operation is classically controlled
The wires give an order for (qu)bits in the input circuit
that is replacing the named operation.
- no duplicate names
- correct length for named operation
- elements are wires of input_circuit
Raises an exception otherwise.
"""
if len(set(wires)) != len(wires):
raise DAGCircuitError("duplicate wires")
wire_tot = self.basis[name][0] + self.basis[name][1]
if condition is not None:
wire_tot += self.cregs[condition[0]].size
if len(wires) != wire_tot:
raise DAGCircuitError("expected %d wires, got %d"
% (wire_tot, len(wires)))
for w in wires:
if w not in input_circuit.wire_type:
raise DAGCircuitError("wire (%s,%d) not in input circuit"
% (w[0], w[1]))
def _make_pred_succ_maps(self, n):
"""Return predecessor and successor dictionaries.
These map from wire names to predecessor and successor
nodes for the operation node n in self.multi_graph.
"""
pred_map = {e[2]['name']: e[0] for e in
self.multi_graph.in_edges(nbunch=n, data=True)}
succ_map = {e[2]['name']: e[1] for e in
self.multi_graph.out_edges(nbunch=n, data=True)}
return pred_map, succ_map
def _full_pred_succ_maps(self, pred_map, succ_map, input_circuit,
wire_map):
"""Map all wires of the input circuit.
Map all wires of the input circuit to predecessor and
successor nodes in self, keyed on wires in self.
pred_map, succ_map dicts come from _make_pred_succ_maps
input_circuit is the input circuit
wire_map is the wire map from wires of input_circuit to wires of self
returns full_pred_map, full_succ_map
"""
full_pred_map = {}
full_succ_map = {}
for w in input_circuit.input_map:
# If w is wire mapped, find the corresponding predecessor
# of the node
if w in wire_map:
full_pred_map[wire_map[w]] = pred_map[wire_map[w]]
full_succ_map[wire_map[w]] = succ_map[wire_map[w]]
else:
# Otherwise, use the corresponding output nodes of self
# and compute the predecessor.
full_succ_map[w] = self.output_map[w]
full_pred_map[w] = self.multi_graph.predecessors(
self.output_map[w])[0]
if len(list(self.multi_graph.predecessors(self.output_map[w]))) != 1:
raise QISKitError(
"too many predecessors for (%s,%d) output node" % (w[0], w[1])
)
return full_pred_map, full_succ_map
def node_nums_in_topological_order(self):
"""
Returns the nodes (their ids) in topological order.
Returns:
List(int): The list of node numbers in topological order
"""
return nx.topological_sort(self.multi_graph)
def substitute_circuit_all(self, name, input_circuit, wires=None):
"""Replace every occurrence of named operation with input_circuit."""
# TODO: rewrite this method to call substitute_circuit_one
wires = wires or None
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
self._check_wires_list(wires, name, input_circuit)
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: ("", 0) for w in wires}
add_qregs = self._check_wiremap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Iterate through the nodes of self and replace the selected nodes
# by iterating through the input_circuit, constructing and
# checking the validity of the wire_map for each replacement
# NOTE: We do not replace conditioned gates. One way to implement
# this later is to add or update the conditions of each gate
# that we add from the input_circuit.
self.basis = union_basis
self.gates = union_gates
for n in self.node_nums_in_topological_order():
nd = self.multi_graph.node[n]
if nd["type"] == "op" and nd["name"] == name:
if nd["condition"] is None:
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"], nd["cargs"]]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map, input_circuit)
pred_map, succ_map = self._make_pred_succ_maps(n)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(n)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map,
md["condition"])
m_qargs = [wire_map.get(x, x) for x in md["qargs0"]]
m_cargs = [wire_map.get(x, x) for x in md["cargs0"]]
self._add_op_node(md["name"], m_qargs, m_cargs,
md["params"], condition, md["op"])
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter, name=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w], full_succ_map[w],
name=w)
o_pred = list(self.multi_graph.predecessors(
self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise QISKitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise QISKitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(
p[0], self.output_map[w])
def substitute_circuit_one(self, node, input_circuit, wires=None):
"""Replace one node with input_circuit.
node is a reference to a node of self.multi_graph of type "op"
input_circuit is a DAGCircuit
"""
wires = wires or None
nd = self.multi_graph.node[node]
name = nd["name"]
self._check_wires_list(wires, name, input_circuit, nd["condition"])
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: ("", 0) for w in wires}
add_qregs = self._check_wiremap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Replace the node by iterating through the input_circuit.
# Constructing and checking the validity of the wire_map.
# If a gate is conditioned, we expect the replacement subcircuit
# to depend on those control bits as well.
self.basis = union_basis
self.gates = union_gates
if nd["type"] != "op":
raise DAGCircuitError("expected node type \"op\", got %s"
% nd["type"])
condition_bit_list = self._bits_in_condition(nd["condition"])
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"],
nd["cargs"],
condition_bit_list]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map, input_circuit)
pred_map, succ_map = self._make_pred_succ_maps(node)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(node)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map, md["condition"])
m_qargs = list(map(lambda x: wire_map.get(x, x),
md["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x),
md["cargs"]))
self._add_op_node(md["name"], m_qargs, m_cargs,
md["params"], condition, md["op"])
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter,
name=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(
full_pred_map[w], full_succ_map[w], name=w)
o_pred = list(self.multi_graph.predecessors(self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise QISKitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise QISKitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(p[0], self.output_map[w])
def get_named_nodes(self, name):
"""Get the set of "op" node ids with the given name."""
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
# We need to instantiate the full list now because the underlying multi_graph
# may change when users iterate over the named nodes.
return {node_id for node_id, data in self.multi_graph.nodes(data=True)
if data["type"] == "op" and data["name"] == name}
def _remove_op_node(self, n):
"""Remove an operation node n.
Add edges from predecessors to successors.
"""
pred_map, succ_map = self._make_pred_succ_maps(n)
self.multi_graph.remove_node(n)
for w in pred_map.keys():
self.multi_graph.add_edge(pred_map[w], succ_map[w], name=w)
def remove_ancestors_of(self, node):
"""Remove all of the ancestor operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
# TODO: probably better to do all at once using
# multi_graph.remove_nodes_from; same for related functions ...
for n in anc:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_descendants_of(self, node):
"""Remove all of the descendant operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
for n in dec:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nonancestors_of(self, node):
"""Remove all of the non-ancestors operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(anc))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nondescendants_of(self, node):
"""Remove all of the non-descendants operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(dec))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def layers(self):
"""Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit.
A layer is a circuit whose gates act on disjoint qubits, i.e.
a layer has depth 1. The total number of layers equals the
circuit depth d. The layers are indexed from 0 to d-1 with the
earliest layer at index 0. The layers are constructed using a
greedy algorithm. Each returned layer is a dict containing
{"graph": circuit graph, "partition": list of qubit lists}.
TODO: Gates that use the same cbits will end up in different
layers as this is currently implemented. This may not be
the desired behavior.
"""
graph_layers = self.multigraph_layers()
try:
next(graph_layers) # Remove input nodes
except StopIteration:
return
def nodes_data(nodes):
"""Construct full nodes from just node ids."""
return ((node_id, self.multi_graph.nodes[node_id]) for node_id in nodes)
for graph_layer in graph_layers:
# Get the op nodes from the layer, removing any input and output nodes.
op_nodes = [node for node in nodes_data(graph_layer) if node[1]["type"] == "op"]
# Stop yielding once there are no more op_nodes in a layer.
if not op_nodes:
return
# Construct a shallow copy of self
new_layer = copy.copy(self)
new_layer.multi_graph = nx.MultiDiGraph()
new_layer.multi_graph.add_nodes_from(nodes_data(self.input_map.values()))
new_layer.multi_graph.add_nodes_from(nodes_data(self.output_map.values()))
# The quantum registers that have an operation in this layer.
support_list = [
op_node[1]["qargs"]
for op_node in op_nodes
if op_node[1]["name"] not in {"barrier", "snapshot", "save", "load", "noise"}
]
new_layer.multi_graph.add_nodes_from(op_nodes)
# Now add the edges to the multi_graph
# By default we just wire inputs to the outputs.
wires = {self.input_map[register]: self.output_map[register]
for register in self.wire_type}
# Wire inputs to op nodes, and op nodes to outputs.
for op_node in op_nodes:
args = self._bits_in_condition(op_node[1]["condition"]) \
+ op_node[1]["cargs"] + op_node[1]["qargs"]
arg_ids = (self.input_map[arg] for arg in args) # map from ("q",0) to node id.
for arg_id in arg_ids:
wires[arg_id], wires[op_node[0]] = op_node[0], wires[arg_id]
# Add wiring to/from the operations and between unused inputs & outputs.
new_layer.multi_graph.add_edges_from(wires.items())
yield {"graph": new_layer, "partition": support_list}
def serial_layers(self):
"""Yield a layer for all gates of this circuit.
A serial layer is a circuit with one gate. The layers have the
same structure as in layers().
"""
for n in self.node_nums_in_topological_order():
nxt_nd = self.multi_graph.node[n]
if nxt_nd["type"] == "op":
new_layer = DAGCircuit()
for qreg in self.qregs.values():
new_layer.add_qreg(qreg)
for creg in self.cregs.values():
new_layer.add_creg(creg)
new_layer.basis = self.basis.copy()
new_layer.gates = self.gates.copy()
# Save the support of the operation we add to the layer
support_list = []
# Operation data
qa = copy.copy(nxt_nd["qargs"])
ca = copy.copy(nxt_nd["cargs"])
pa = copy.copy(nxt_nd["params"])
co = copy.copy(nxt_nd["condition"])
op = copy.copy(nxt_nd["op"])
_ = self._bits_in_condition(co)
# Add node to new_layer
new_layer.apply_operation_back(nxt_nd["name"],
qa, ca, pa, co, op)
# Add operation to partition
if nxt_nd["name"] not in ["barrier",
"snapshot", "save", "load", "noise"]:
# support_list.append(list(set(qa) | set(ca) | set(cob)))
support_list.append(list(qa))
l_dict = {"graph": new_layer, "partition": support_list}
yield l_dict
def multigraph_layers(self):
"""Yield layers of the multigraph."""
predecessor_count = dict() # Dict[node, predecessors not visited]
cur_layer = [node for node in self.input_map.values()]
yield cur_layer
next_layer = []
while cur_layer:
for node in cur_layer:
# Count multiedges with multiplicity.
for successor in self.multi_graph.successors(node):
multiplicity = self.multi_graph.number_of_edges(node, successor)
if successor in predecessor_count:
predecessor_count[successor] -= multiplicity
else:
predecessor_count[successor] = \
self.multi_graph.in_degree(successor) - multiplicity
if predecessor_count[successor] == 0:
next_layer.append(successor)
del predecessor_count[successor]
yield next_layer
cur_layer = next_layer
next_layer = []
def collect_runs(self, namelist):
"""Return a set of runs of "op" nodes with the given names.
For example, "... h q[0]; cx q[0],q[1]; cx q[0],q[1]; h q[1]; .."
would produce the tuple of cx nodes as an element of the set returned
from a call to collect_runs(["cx"]). If instead the cx nodes were
"cx q[0],q[1]; cx q[1],q[0];", the method would still return the
pair in a tuple. The namelist can contain names that are not
in the circuit's basis.
Nodes must have only one successor to continue the run.
"""
group_list = []
# Iterate through the nodes of self in topological order
# and form tuples containing sequences of gates
# on the same qubit(s).
ts = list(self.node_nums_in_topological_order())
nodes_seen = dict(zip(ts, [False] * len(ts)))
for node in ts:
nd = self.multi_graph.node[node]
if nd["type"] == "op" and nd["name"] in namelist \
and not nodes_seen[node]:
group = [node]
nodes_seen[node] = True
s = list(self.multi_graph.successors(node))
while len(s) == 1 and \
self.multi_graph.node[s[0]]["type"] == "op" and \
self.multi_graph.node[s[0]]["name"] in namelist:
group.append(s[0])
nodes_seen[s[0]] = True
s = list(self.multi_graph.successors(s[0]))
if len(group) > 1:
group_list.append(tuple(group))
return set(group_list)
def count_ops(self):
"""Count the occurrences of operation names.
Returns a dictionary of counts keyed on the operation name.
"""
op_dict = {}
for node in self.node_nums_in_topological_order():
nd = self.multi_graph.node[node]
name = nd["name"]
if nd["type"] == "op":
if name not in op_dict:
op_dict[name] = 1
else:
op_dict[name] += 1
return op_dict
def properties(self):
"""Return a dictionary of circuit properties."""
summary = {"size": self.size(),
"depth": self.depth(),
"width": self.width(),
"bits": self.num_cbits(),
"factors": self.num_tensor_factors(),
"operations": self.count_ops()}
return summary
@staticmethod
def fromQuantumCircuit(circuit, expand_gates=True):
"""Build a ``DAGCircuit`` object from a ``QuantumCircuit``.
Args:
circuit (QuantumCircuit): the input circuit.
expand_gates (bool): if ``False``, none of the gates are expanded,
i.e. the gates that are defined in the circuit are included in
the DAG basis.
Return:
DAGCircuit: the DAG representing the input circuit.
"""
dagcircuit = DAGCircuit()
dagcircuit.name = circuit.name
for register in circuit.qregs:
dagcircuit.add_qreg(register)
for register in circuit.cregs:
dagcircuit.add_creg(register)
# Add user gate definitions
for name, data in circuit.definitions.items():
dagcircuit.add_basis_element(name, data["n_bits"], 0,
data["n_args"])
dagcircuit.add_gate_data(name, data)
# Add instructions
builtins = {
"U": ["U", 1, 0, 3],
"CX": ["CX", 2, 0, 0],
"measure": ["measure", 1, 1, 0],
"reset": ["reset", 1, 0, 0],
"barrier": ["barrier", -1, 0, 0]
}
# Add simulator instructions
simulator_instructions = {
"snapshot": ["snapshot", -1, 0, 1],
"save": ["save", -1, 0, 1],
"load": ["load", -1, 0, 1],
"noise": ["noise", -1, 0, 1]
}
for main_instruction in circuit.data:
# TODO: generate definitions and nodes for CompositeGates,
# for now simply drop their instructions into the DAG
instruction_list = []
is_composite = isinstance(main_instruction,
_compositegate.CompositeGate)
if is_composite and expand_gates:
instruction_list = main_instruction.instruction_list()
else:
instruction_list.append(main_instruction)
for instruction in instruction_list:
# Add OpenQASM built-in gates on demand
if instruction.name in builtins:
dagcircuit.add_basis_element(*builtins[instruction.name])
# Add simulator extension instructions
if instruction.name in simulator_instructions:
dagcircuit.add_basis_element(*simulator_instructions[instruction.name])
# Separate classical arguments to measurements
if instruction.name == "measure":
qargs = [(instruction.qargs[0][0].name, instruction.qargs[0][1])]
cargs = [(instruction.cargs[0][0].name, instruction.cargs[0][1])]
else:
qargs = list(map(lambda x: (x[0].name, x[1]), instruction.qargs))
cargs = []
# Get arguments for classical control (if any)
if instruction.control is None:
control = None
else:
control = (instruction.control[0].name, instruction.control[1])
if is_composite and not expand_gates:
is_inverse = instruction.inverse_flag
name = instruction.name if not is_inverse else instruction.inverse_name
else:
name = instruction.name
dagcircuit.apply_operation_back(name, qargs, cargs,
instruction.param,
control, instruction)
return dagcircuit
<|code_end|>
|
qiskit/dagcircuit/_dagcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Object to represent a quantum circuit as a directed acyclic graph.
The nodes in the graph are either input/output nodes or operation nodes.
The operation nodes are elements of a basis that is part of the circuit.
The QASM definitions of the basis elements are carried with the circuit.
The edges correspond to qubits or bits in the circuit. A directed edge
from node A to node B means that the (qu)bit passes from the output of A
to the input of B. The object's methods allow circuits to be constructed,
composed, and modified. Some natural properties like depth can be computed
directly from the graph.
"""
from collections import OrderedDict
import copy
import itertools
import networkx as nx
import sympy
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QISKitError
from qiskit import _compositegate
from ._dagcircuiterror import DAGCircuitError
class DAGCircuit:
"""
Quantum circuit as a directed acyclic graph.
There are 3 types of nodes in the graph: inputs, outputs, and operations.
The nodes are connected by directed edges that correspond to qubits and
bits.
"""
# pylint: disable=invalid-name
def __init__(self):
"""Create an empty circuit."""
# Circuit name. Generally, this corresponds to the name
# of the QuantumCircuit from which the DAG was generated.
self.name = None
# Map from a wire's name (reg,idx) to a Bool that is True if the
# wire is a classical bit and False if the wire is a qubit.
self.wire_type = OrderedDict()
# Map from wire names (reg,idx) to input nodes of the graph
self.input_map = OrderedDict()
# Map from wire names (reg,idx) to output nodes of the graph
self.output_map = OrderedDict()
# Running count of the total number of nodes
self.node_counter = 0
# Map of named operations in this circuit and their signatures.
# The signature is an integer tuple (nq,nc,np) specifying the
# number of input qubits, input bits, and real parameters.
# The definition is external to the circuit object.
self.basis = OrderedDict()
# Directed multigraph whose nodes are inputs, outputs, or operations.
# Operation nodes have equal in- and out-degrees and carry
# additional data about the operation, including the argument order
# and parameter values.
# Input nodes have out-degree 1 and output nodes have in-degree 1.
# Edges carry wire labels (reg,idx) and each operation has
# corresponding in- and out-edges with the same wire labels.
self.multi_graph = nx.MultiDiGraph()
# Map of qregs to sizes
self.qregs = OrderedDict()
# Map of cregs to sizes
self.cregs = OrderedDict()
# Map of user defined gates to ast nodes defining them
self.gates = OrderedDict()
# Output precision for printing floats
self.prec = 10
# layout of dag quantum registers on the chip
# TODO: rethink this. doesn't seem related to concept of DAG,
# but if we want to be able to generate qobj
# directly from a dag, we need it.
self.layout = []
def get_qubits(self):
"""Return a list of qubits as (qreg, index) pairs."""
return [(k, i) for k, v in self.qregs.items() for i in range(v.size)]
def rename_register(self, regname, newname):
"""Rename a classical or quantum register throughout the circuit.
regname = existing register name string
newname = replacement register name string
"""
if regname == newname:
return
if newname in self.qregs or newname in self.cregs:
raise DAGCircuitError("duplicate register name %s" % newname)
if regname not in self.qregs and regname not in self.cregs:
raise DAGCircuitError("no register named %s" % regname)
iscreg = False
if regname in self.qregs:
self.qregs[newname] = self.qregs[regname]
self.qregs.pop(regname, None)
reg_size = self.qregs[newname].size
if regname in self.cregs:
self.cregs[newname] = self.cregs[regname]
self.cregs.pop(regname, None)
reg_size = self.cregs[newname].size
iscreg = True
for i in range(reg_size):
self.wire_type[(newname, i)] = iscreg
self.wire_type.pop((regname, i), None)
self.input_map[(newname, i)] = self.input_map[(regname, i)]
self.input_map.pop((regname, i), None)
self.output_map[(newname, i)] = self.output_map[(regname, i)]
self.output_map.pop((regname, i), None)
# n node d = data
for _, d in self.multi_graph.nodes(data=True):
if d["type"] == "in" or d["type"] == "out":
if d["name"][0] == regname:
d["name"] = (newname, d["name"][1])
elif d["type"] == "op":
qa = []
for a in d["qargs"]:
if a[0] == regname:
a = (newname, a[1])
qa.append(a)
d["qargs"] = qa
ca = []
for a in d["cargs"]:
if a[0] == regname:
a = (newname, a[1])
ca.append(a)
d["cargs"] = ca
if d["condition"] is not None:
if d["condition"][0] == regname:
d["condition"] = (newname, d["condition"][1])
# eX = edge, d= data
for _, _, d in self.multi_graph.edges(data=True):
if d["name"][0] == regname:
d["name"] = (newname, d["name"][1])
def remove_all_ops_named(self, opname):
"""Remove all operation nodes with the given name."""
for n in self.get_named_nodes(opname):
self._remove_op_node(n)
def fs(self, number):
"""Format a float f as a string with self.prec digits."""
fmt = "{0:0.%snumber}" % self.prec
return fmt.format(number)
def add_qreg(self, qreg):
"""Add all wires in a quantum register."""
if not isinstance(qreg, QuantumRegister):
raise DAGCircuitError("not a QuantumRegister instance.")
if qreg.name in self.qregs:
raise DAGCircuitError("duplicate register %s" % qreg.name)
self.qregs[qreg.name] = qreg
for j in range(qreg.size):
self._add_wire((qreg.name, j))
def add_creg(self, creg):
"""Add all wires in a classical register."""
if not isinstance(creg, ClassicalRegister):
raise DAGCircuitError("not a ClassicalRegister instance.")
if creg.name in self.cregs:
raise DAGCircuitError("duplicate register %s" % creg.name)
self.cregs[creg.name] = creg
for j in range(creg.size):
self._add_wire((creg.name, j), True)
def _add_wire(self, name, isClassical=False):
"""Add a qubit or bit to the circuit.
name is a (string,int) tuple containing register name and index
This adds a pair of in and out nodes connected by an edge.
"""
if name not in self.wire_type:
self.wire_type[name] = isClassical
self.node_counter += 1
self.input_map[name] = self.node_counter
self.node_counter += 1
self.output_map[name] = self.node_counter
in_node = self.input_map[name]
out_node = self.output_map[name]
self.multi_graph.add_edge(in_node, out_node)
self.multi_graph.node[in_node]["type"] = "in"
self.multi_graph.node[out_node]["type"] = "out"
self.multi_graph.node[in_node]["name"] = name
self.multi_graph.node[out_node]["name"] = name
self.multi_graph.adj[in_node][out_node][0]["name"] = name
else:
raise DAGCircuitError("duplicate wire %s" % name)
def add_basis_element(self, name, number_qubits,
number_classical=0, number_parameters=0):
"""Add an operation to the basis.
name is string label for operation
number_qubits is number of qubit arguments
number_classical is number of bit arguments
number_parameters is number of real parameters
The parameters (nq,nc,np) are ignored for the special case
when name = "barrier". The barrier instruction has a variable
number of qubit arguments.
"""
if name not in self.basis:
self.basis[name] = (
number_qubits,
number_classical,
number_parameters)
if name in self.gates:
if self.gates[name]["n_args"] != number_parameters or \
self.gates[name]["n_bits"] != number_qubits or number_classical != 0:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def add_gate_data(self, name, gatedata):
"""Add the definition of a gate.
gatedata is dict with fields:
"print" = True or False
"opaque" = True or False
"n_args" = number of real parameters
"n_bits" = number of qubits
"args" = list of parameter names
"bits" = list of qubit names
"body" = GateBody AST node
"""
if name not in self.gates:
self.gates[name] = gatedata
if name in self.basis:
if self.basis[name][0] != self.gates[name]["n_bits"] or \
self.basis[name][1] != 0 or \
self.basis[name][2] != self.gates[name]["n_args"]:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def _check_basis_data(self, name, qargs, cargs, params):
"""Check the arguments against the data for this operation.
name is a string
qargs is a list of tuples like ("q",0)
cargs is a list of tuples like ("c",0)
params is a list of strings that represent floats
"""
# Check that we have this operation
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
# Check the number of arguments matches the signature
if name in ["barrier"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if params:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
elif name in ["snapshot", "noise", "save", "load"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if not params:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
else:
if len(qargs) != self.basis[name][0]:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if len(cargs) != self.basis[name][1]:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if len(params) != self.basis[name][2]:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
def _check_condition(self, name, condition):
"""Verify that the condition is valid.
name is a string used for error reporting
condition is either None or a tuple (string,int) giving (creg,value)
"""
# Verify creg exists
if condition is not None and condition[0] not in self.cregs:
raise DAGCircuitError("invalid creg in condition for %s" % name)
def _check_bits(self, args, amap, bval):
"""Check the values of a list of (qu)bit arguments.
For each element A of args, check that amap contains A and
self.wire_type[A] equals bval.
args is a list of (regname,idx) tuples
amap is a dictionary keyed on (regname,idx) tuples
bval is boolean
"""
# Check for each wire
for q in args:
if q not in amap:
raise DAGCircuitError("(qu)bit %s not found" % (q,))
if self.wire_type[q] != bval:
raise DAGCircuitError("expected wire type %s for %s"
% (bval, q))
def _bits_in_condition(self, cond):
"""Return a list of bits (regname,idx) in the given condition.
cond is either None or a (regname,int) tuple specifying
a classical if condition.
"""
all_bits = []
if cond is not None:
all_bits.extend([(cond[0], j) for j in range(self.cregs[cond[0]].size)])
return all_bits
def _add_op_node(self, nname, nqargs, ncargs, nparams, ncondition, nop):
"""Add a new operation node to the graph and assign properties.
nname node name
nqargs quantum arguments
ncargs classical arguments
nparams parameters
ncondition classical condition (or None)
nop Instruction instance representing this operation
"""
# Add a new operation node to the graph
self.node_counter += 1
self.multi_graph.add_node(self.node_counter)
# Update that operation node's data
self.multi_graph.node[self.node_counter]["type"] = "op"
self.multi_graph.node[self.node_counter]["name"] = nname
self.multi_graph.node[self.node_counter]["qargs"] = nqargs
self.multi_graph.node[self.node_counter]["cargs"] = ncargs
self.multi_graph.node[self.node_counter]["params"] = nparams
self.multi_graph.node[self.node_counter]["condition"] = ncondition
self.multi_graph.node[self.node_counter]["op"] = nop
def apply_operation_back(self, name, qargs, cargs=None, params=None,
condition=None, op=None):
"""Apply an operation to the output of the circuit.
name is a string
qargs is a list of tuples like ("q",0)
cargs is a list of tuples like ("c",0)
params is a list of symbols that represent numbers
condition is either None or a tuple (string,int) giving (creg,value)
op is an Instruction instance representing this node
"""
cargs = cargs or []
params = params or []
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(name, qargs, cargs, params)
self._check_condition(name, condition)
self._check_bits(qargs, self.output_map, False)
self._check_bits(all_cbits, self.output_map, True)
self._add_op_node(name, qargs, cargs, params, condition, op)
# Add new in-edges from predecessors of the output nodes to the
# operation node while deleting the old in-edges of the output nodes
# and adding new edges from the operation node to each output node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.predecessors(self.output_map[q]))
if len(ie) != 1:
raise QISKitError("output node has multiple in-edges")
self.multi_graph.add_edge(ie[0], self.node_counter, name=q)
self.multi_graph.remove_edge(ie[0], self.output_map[q])
self.multi_graph.add_edge(
self.node_counter, self.output_map[q], name=q)
def apply_operation_front(self, name, qargs, cargs=None, params=None,
condition=None, op=None):
"""Apply an operation to the input of the circuit.
name is a string
qargs is a list of strings like "q[0]"
cargs is a list of strings like "c[0]"
params is a list of strings that represent floats
condition is either None or a tuple (string,int) giving (creg,value)
"""
cargs = cargs or []
params = params or []
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(name, qargs, cargs, params)
self._check_condition(name, condition)
self._check_bits(qargs, self.input_map, False)
self._check_bits(all_cbits, self.input_map, True)
self._add_op_node(name, qargs, cargs, params, condition, op)
# Add new out-edges to successors of the input nodes from the
# operation node while deleting the old out-edges of the input nodes
# and adding new edges to the operation node from each input node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = self.multi_graph.successors(self.input_map[q])
if len(ie) != 1:
raise QISKitError("input node has multiple out-edges")
self.multi_graph.add_edge(self.node_counter, ie[0], name=q)
self.multi_graph.remove_edge(self.input_map[q], ie[0])
self.multi_graph.add_edge(
self.input_map[q], self.node_counter, name=q)
def _make_union_basis(self, input_circuit):
"""Return a new basis map.
The new basis is a copy of self.basis with
new elements of input_circuit.basis added.
input_circuit is a DAGCircuit
"""
union_basis = self.basis.copy()
for g in input_circuit.basis:
if g not in union_basis:
union_basis[g] = input_circuit.basis[g]
if union_basis[g] != input_circuit.basis[g]:
raise DAGCircuitError("incompatible basis")
return union_basis
def _make_union_gates(self, input_circuit):
"""Return a new gates map.
The new gates are a copy of self.gates with
new elements of input_circuit.gates added.
input_circuit is a DAGCircuit
NOTE: gates in input_circuit that are also in self must
be *identical* to the gates in self
"""
union_gates = {}
for k, v in self.gates.items():
union_gates[k] = v
for k, v in input_circuit.gates.items():
if k not in union_gates:
union_gates[k] = v
if union_gates[k]["opaque"] != input_circuit.gates[k]["opaque"] or \
union_gates[k]["n_args"] != input_circuit.gates[k]["n_args"] or \
union_gates[k]["n_bits"] != input_circuit.gates[k]["n_bits"] or \
union_gates[k]["args"] != input_circuit.gates[k]["args"] or \
union_gates[k]["bits"] != input_circuit.gates[k]["bits"]:
raise DAGCircuitError("inequivalent gate definitions for %s"
% k)
return union_gates
def _check_wiremap_registers(self, wire_map, keyregs, valregs,
valreg=True):
"""Check that wiremap neither fragments nor leaves duplicate registers.
1. There are no fragmented registers. A register in keyregs
is fragmented if not all of its (qu)bits are renamed by wire_map.
2. There are no duplicate registers. A register is duplicate if
it appears in both self and keyregs but not in wire_map.
wire_map is a map from (regname,idx) in keyregs to (regname,idx)
in valregs
keyregs is a map from register names to Register objects
valregs is a map from register names to Register objects
valreg is a Bool, if False the method ignores valregs and does not
add regs for bits in the wire_map image that don't appear in valregs
Return the set of regs to add to self
"""
add_regs = set()
reg_frag_chk = {}
for k, v in keyregs.items():
reg_frag_chk[k] = {j: False for j in range(v.size)}
for k in wire_map.keys():
if k[0] in keyregs:
reg_frag_chk[k[0]][k[1]] = True
for k, v in reg_frag_chk.items():
rname = ",".join(map(str, k))
s = set(v.values())
if len(s) == 2:
raise DAGCircuitError("wire_map fragments reg %s" % rname)
elif s == set([False]):
if k in self.qregs or k in self.cregs:
raise DAGCircuitError("unmapped duplicate reg %s" % rname)
else:
# Add registers that appear only in keyregs
add_regs.add(keyregs[k])
else:
if valreg:
# If mapping to a register not in valregs, add it.
# (k,0) exists in wire_map because wire_map doesn't
# fragment k
if not wire_map[(k, 0)][0] in valregs:
size = max(map(lambda x: x[1], filter(lambda x: x[0] == wire_map[(k, 0)][0],
wire_map.values())))
qreg = QuantumRegister(wire_map[(k, 0)][0], size + 1)
add_regs.add(qreg)
return add_regs
def _check_wiremap_validity(self, wire_map, keymap, valmap, input_circuit):
"""Check that the wiremap is consistent.
Check that the wiremap refers to valid wires and that
those wires have consistent types.
wire_map is a map from (regname,idx) in keymap to (regname,idx)
in valmap
keymap is a map whose keys are wire_map keys
valmap is a map whose keys are wire_map values
input_circuit is a DAGCircuit
"""
for k, v in wire_map.items():
kname = ",".join(map(str, k))
vname = ",".join(map(str, v))
if k not in keymap:
raise DAGCircuitError("invalid wire mapping key %s" % kname)
if v not in valmap:
raise DAGCircuitError("invalid wire mapping value %s"
% vname)
if input_circuit.wire_type[k] != self.wire_type[v]:
raise DAGCircuitError("inconsistent wire_map at (%s,%s)"
% (kname, vname))
def _map_condition(self, wire_map, condition):
"""Use the wire_map dict to change the condition tuple's creg name.
wire_map is map from wires to wires
condition is a tuple (reg,int)
Returns the new condition tuple
"""
if condition is None:
n_condition = None
else:
# Map the register name, using fact that registers must not be
# fragmented by the wire_map (this must have been checked
# elsewhere)
bit0 = (condition[0], 0)
n_condition = (wire_map.get(bit0, bit0)[0], condition[1])
return n_condition
def compose_back(self, input_circuit, wire_map=None):
"""Apply the input circuit to the output of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of input qubits of the input circuit are mapped
to a subset of output qubits of this circuit.
wire_map[input_qubit_to_input_circuit] = output_qubit_of_self
"""
wire_map = wire_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map for duplicate values
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_wiremap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.input_map,
self.output_map, input_circuit)
# Compose
self.basis = union_basis
self.gates = union_gates
for node in nx.topological_sort(input_circuit.multi_graph):
nd = input_circuit.multi_graph.node[node]
if nd["type"] == "in":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["name"], nd["name"])
# the mapped wire should already exist
if m_name not in self.output_map:
raise QISKitError("wire (%s,%d) not in self" % (m_name[0], m_name[1]))
if nd["name"] not in input_circuit.wire_type:
raise QISKitError("inconsistent wire_type for (%s,%d) in input_circuit"
% (nd["name"][0], nd["name"][1]))
elif nd["type"] == "out":
# ignore output nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: wire_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x), nd["cargs"]))
self.apply_operation_back(nd["name"], m_qargs, m_cargs,
nd["params"], condition, nd["op"])
else:
raise QISKitError("bad node type %s" % nd["type"])
def compose_front(self, input_circuit, wire_map=None):
"""Apply the input circuit to the input of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of output qubits of the input circuit are mapped
to a subset of input qubits of
this circuit.
"""
wire_map = wire_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_wiremap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.output_map,
self.input_map, input_circuit)
# Compose
self.basis = union_basis
self.gates = union_gates
for n in reversed(list(nx.topological_sort(input_circuit.multi_graph))):
nd = input_circuit.multi_graph.node[n]
if nd["type"] == "out":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["name"], nd["name"])
# the mapped wire should already exist
if m_name not in self.input_map:
raise QISKitError("wire (%s,%d) not in self" % (m_name[0], m_name[1]))
if nd["name"] not in input_circuit.wire_type:
raise QISKitError(
"inconsistent wire_type for (%s,%d) in input_circuit"
% (nd["name"][0], nd["name"][1]))
elif nd["type"] == "in":
# ignore input nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: wire_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x), nd["cargs"]))
self.apply_operation_front(nd["name"], m_qargs, m_cargs,
nd["params"], condition, nd["op"])
else:
raise QISKitError("bad node type %s" % nd["type"])
def size(self):
"""Return the number of operations."""
return self.multi_graph.order() - 2 * len(self.wire_type)
def depth(self):
"""Return the circuit depth."""
if not nx.is_directed_acyclic_graph(self.multi_graph):
raise QISKitError("not a DAG")
return nx.dag_longest_path_length(self.multi_graph) - 1
def width(self):
"""Return the total number of qubits used by the circuit."""
return len(self.wire_type) - self.num_cbits()
def num_cbits(self):
"""Return the total number of bits used by the circuit."""
return list(self.wire_type.values()).count(True)
def num_tensor_factors(self):
"""Compute how many components the circuit can decompose into."""
return nx.number_weakly_connected_components(self.multi_graph)
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.gates[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.gates[name]["n_args"] > 0:
out += "(" + ",".join(self.gates[name]["args"]) + ")"
out += " " + ",".join(self.gates[name]["bits"])
if self.gates[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.gates[name]["body"].qasm() + "}"
return out
def qasm(self, decls_only=False, add_swap=False,
no_decls=False, qeflag=False, aliases=None, eval_symbols=False):
"""Return a string containing QASM for this circuit.
if qeflag is True, add a line to include "qelib1.inc"
and only generate gate code for gates not in qelib1.
if eval_symbols is True, evaluate all symbolic
expressions to their floating point representation.
if no_decls is True, only print the instructions.
if aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
if decls_only is True, only print the declarations.
if add_swap is True, add the definition of swap in terms of
cx if necessary.
"""
# TODO: some of the input flags are not needed anymore
# Rename qregs if necessary
if aliases:
qregdata = OrderedDict()
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
# Write top matter
if no_decls:
out = ""
else:
printed_gates = []
out = "OPENQASM 2.0;\n"
if qeflag:
out += "include \"qelib1.inc\";\n"
for k, v in qregdata.items():
out += "qreg %s[%d];\n" % (k, v.size)
for k, v in self.cregs.items():
out += "creg %s[%d];\n" % (k, v.size)
omit = ["U", "CX", "measure", "reset", "barrier"]
# TODO: dagcircuit shouldn't know about extensions
if qeflag:
qelib = ["u3", "u2", "u1", "cx", "id", "x", "y", "z", "h",
"s", "sdg", "t", "tdg", "cz", "cy", "ccx", "cu1",
"cu3", "swap", "cswap", "u0", "rx", "ry", "rz",
"ch", "crz", "rzz"]
omit.extend(qelib)
printed_gates.extend(qelib)
simulator_instructions = ["snapshot", "save", "load", "noise", "wait"]
omit.extend(simulator_instructions)
for k in self.basis.keys():
if k not in omit:
if not self.gates[k]["opaque"]:
calls = self.gates[k]["body"].calls()
for c in calls:
if c not in printed_gates:
out += self._gate_string(c) + "\n"
printed_gates.append(c)
if k not in printed_gates:
out += self._gate_string(k) + "\n"
printed_gates.append(k)
if add_swap and not qeflag and "cx" not in self.basis:
out += "gate cx a,b { CX a,b; }\n"
if add_swap and "swap" not in self.basis:
out += "gate swap a,b { cx a,b; cx b,a; cx a,b; }\n"
# Write the instructions
if not decls_only:
for n in nx.lexicographical_topological_sort(self.multi_graph):
nd = self.multi_graph.node[n]
if nd["type"] == "op":
if nd["condition"] is not None:
out += "if(%s==%d) " \
% (nd["condition"][0], nd["condition"][1])
if not nd["cargs"]:
nm = nd["name"]
if aliases:
qarglist = map(lambda x: aliases[x], nd["qargs"])
else:
qarglist = nd["qargs"]
qarg = ",".join(map(lambda x: "%s[%d]" % (x[0], x[1]),
qarglist))
if nd["params"]:
if eval_symbols:
param = ",".join(map(lambda x: str(sympy.N(x)),
nd["params"]))
else:
param = ",".join(map(lambda x: x.replace("**", "^"),
map(str, nd["params"])))
out += "%s(%s) %s;\n" % (nm, param, qarg)
else:
out += "%s %s;\n" % (nm, qarg)
else:
if nd["name"] == "measure":
if len(nd["cargs"]) != 1 or len(nd["qargs"]) != 1 \
or nd["params"]:
raise QISKitError("bad node data")
qname = nd["qargs"][0][0]
qindex = nd["qargs"][0][1]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
out += "measure %s[%d] -> %s[%d];\n" \
% (qname,
qindex,
nd["cargs"][0][0],
nd["cargs"][0][1])
else:
raise QISKitError("bad node data")
return out
def _check_wires_list(self, wires, name, input_circuit, condition=None):
"""Check that a list of wires satisfies some conditions.
wires = list of (register_name, index) tuples
name = name of operation
input_circuit = replacement circuit for operation
condition = None or (creg_name, value) if this instance of the
operation is classically controlled
The wires give an order for (qu)bits in the input circuit
that is replacing the named operation.
- no duplicate names
- correct length for named operation
- elements are wires of input_circuit
Raises an exception otherwise.
"""
if len(set(wires)) != len(wires):
raise DAGCircuitError("duplicate wires")
wire_tot = self.basis[name][0] + self.basis[name][1]
if condition is not None:
wire_tot += self.cregs[condition[0]].size
if len(wires) != wire_tot:
raise DAGCircuitError("expected %d wires, got %d"
% (wire_tot, len(wires)))
for w in wires:
if w not in input_circuit.wire_type:
raise DAGCircuitError("wire (%s,%d) not in input circuit"
% (w[0], w[1]))
def _make_pred_succ_maps(self, n):
"""Return predecessor and successor dictionaries.
These map from wire names to predecessor and successor
nodes for the operation node n in self.multi_graph.
"""
pred_map = {e[2]['name']: e[0] for e in
self.multi_graph.in_edges(nbunch=n, data=True)}
succ_map = {e[2]['name']: e[1] for e in
self.multi_graph.out_edges(nbunch=n, data=True)}
return pred_map, succ_map
def _full_pred_succ_maps(self, pred_map, succ_map, input_circuit,
wire_map):
"""Map all wires of the input circuit.
Map all wires of the input circuit to predecessor and
successor nodes in self, keyed on wires in self.
pred_map, succ_map dicts come from _make_pred_succ_maps
input_circuit is the input circuit
wire_map is the wire map from wires of input_circuit to wires of self
returns full_pred_map, full_succ_map
"""
full_pred_map = {}
full_succ_map = {}
for w in input_circuit.input_map:
# If w is wire mapped, find the corresponding predecessor
# of the node
if w in wire_map:
full_pred_map[wire_map[w]] = pred_map[wire_map[w]]
full_succ_map[wire_map[w]] = succ_map[wire_map[w]]
else:
# Otherwise, use the corresponding output nodes of self
# and compute the predecessor.
full_succ_map[w] = self.output_map[w]
full_pred_map[w] = self.multi_graph.predecessors(
self.output_map[w])[0]
if len(list(self.multi_graph.predecessors(self.output_map[w]))) != 1:
raise QISKitError(
"too many predecessors for (%s,%d) output node" % (w[0], w[1])
)
return full_pred_map, full_succ_map
def node_nums_in_topological_order(self):
"""
Returns the nodes (their ids) in topological order.
Returns:
List(int): The list of node numbers in topological order
"""
return nx.topological_sort(self.multi_graph)
def substitute_circuit_all(self, name, input_circuit, wires=None):
"""Replace every occurrence of named operation with input_circuit."""
# TODO: rewrite this method to call substitute_circuit_one
wires = wires or None
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
self._check_wires_list(wires, name, input_circuit)
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: ("", 0) for w in wires}
add_qregs = self._check_wiremap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Iterate through the nodes of self and replace the selected nodes
# by iterating through the input_circuit, constructing and
# checking the validity of the wire_map for each replacement
# NOTE: We do not replace conditioned gates. One way to implement
# this later is to add or update the conditions of each gate
# that we add from the input_circuit.
self.basis = union_basis
self.gates = union_gates
for n in self.node_nums_in_topological_order():
nd = self.multi_graph.node[n]
if nd["type"] == "op" and nd["name"] == name:
if nd["condition"] is None:
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"], nd["cargs"]]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map, input_circuit)
pred_map, succ_map = self._make_pred_succ_maps(n)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(n)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map,
md["condition"])
m_qargs = [wire_map.get(x, x) for x in md["qargs0"]]
m_cargs = [wire_map.get(x, x) for x in md["cargs0"]]
self._add_op_node(md["name"], m_qargs, m_cargs,
md["params"], condition, md["op"])
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter, name=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w], full_succ_map[w],
name=w)
o_pred = list(self.multi_graph.predecessors(
self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise QISKitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise QISKitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(
p[0], self.output_map[w])
def substitute_circuit_one(self, node, input_circuit, wires=None):
"""Replace one node with input_circuit.
node is a reference to a node of self.multi_graph of type "op"
input_circuit is a DAGCircuit
"""
wires = wires or None
nd = self.multi_graph.node[node]
name = nd["name"]
self._check_wires_list(wires, name, input_circuit, nd["condition"])
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: ("", 0) for w in wires}
add_qregs = self._check_wiremap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Replace the node by iterating through the input_circuit.
# Constructing and checking the validity of the wire_map.
# If a gate is conditioned, we expect the replacement subcircuit
# to depend on those control bits as well.
self.basis = union_basis
self.gates = union_gates
if nd["type"] != "op":
raise DAGCircuitError("expected node type \"op\", got %s"
% nd["type"])
condition_bit_list = self._bits_in_condition(nd["condition"])
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"],
nd["cargs"],
condition_bit_list]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map, input_circuit)
pred_map, succ_map = self._make_pred_succ_maps(node)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(node)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map, md["condition"])
m_qargs = list(map(lambda x: wire_map.get(x, x),
md["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x),
md["cargs"]))
self._add_op_node(md["name"], m_qargs, m_cargs,
md["params"], condition, md["op"])
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter,
name=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(
full_pred_map[w], full_succ_map[w], name=w)
o_pred = list(self.multi_graph.predecessors(self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise QISKitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise QISKitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(p[0], self.output_map[w])
def get_named_nodes(self, name):
"""Get the set of "op" node ids with the given name."""
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
# We need to instantiate the full list now because the underlying multi_graph
# may change when users iterate over the named nodes.
return {node_id for node_id, data in self.multi_graph.nodes(data=True)
if data["type"] == "op" and data["name"] == name}
def _remove_op_node(self, n):
"""Remove an operation node n.
Add edges from predecessors to successors.
"""
pred_map, succ_map = self._make_pred_succ_maps(n)
self.multi_graph.remove_node(n)
for w in pred_map.keys():
self.multi_graph.add_edge(pred_map[w], succ_map[w], name=w)
def remove_ancestors_of(self, node):
"""Remove all of the ancestor operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
# TODO: probably better to do all at once using
# multi_graph.remove_nodes_from; same for related functions ...
for n in anc:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_descendants_of(self, node):
"""Remove all of the descendant operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
for n in dec:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nonancestors_of(self, node):
"""Remove all of the non-ancestors operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(anc))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nondescendants_of(self, node):
"""Remove all of the non-descendants operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(dec))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def layers(self):
"""Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit.
A layer is a circuit whose gates act on disjoint qubits, i.e.
a layer has depth 1. The total number of layers equals the
circuit depth d. The layers are indexed from 0 to d-1 with the
earliest layer at index 0. The layers are constructed using a
greedy algorithm. Each returned layer is a dict containing
{"graph": circuit graph, "partition": list of qubit lists}.
TODO: Gates that use the same cbits will end up in different
layers as this is currently implemented. This may not be
the desired behavior.
"""
graph_layers = self.multigraph_layers()
try:
next(graph_layers) # Remove input nodes
except StopIteration:
return
def nodes_data(nodes):
"""Construct full nodes from just node ids."""
return ((node_id, self.multi_graph.nodes[node_id]) for node_id in nodes)
for graph_layer in graph_layers:
# Get the op nodes from the layer, removing any input and output nodes.
op_nodes = [node for node in nodes_data(graph_layer) if node[1]["type"] == "op"]
# Stop yielding once there are no more op_nodes in a layer.
if not op_nodes:
return
# Construct a shallow copy of self
new_layer = copy.copy(self)
new_layer.multi_graph = nx.MultiDiGraph()
new_layer.multi_graph.add_nodes_from(nodes_data(self.input_map.values()))
new_layer.multi_graph.add_nodes_from(nodes_data(self.output_map.values()))
# The quantum registers that have an operation in this layer.
support_list = [
op_node[1]["qargs"]
for op_node in op_nodes
if op_node[1]["name"] not in {"barrier", "snapshot", "save", "load", "noise"}
]
new_layer.multi_graph.add_nodes_from(op_nodes)
# Now add the edges to the multi_graph
# By default we just wire inputs to the outputs.
wires = {self.input_map[register]: self.output_map[register]
for register in self.wire_type}
# Wire inputs to op nodes, and op nodes to outputs.
for op_node in op_nodes:
args = self._bits_in_condition(op_node[1]["condition"]) \
+ op_node[1]["cargs"] + op_node[1]["qargs"]
arg_ids = (self.input_map[arg] for arg in args) # map from ("q",0) to node id.
for arg_id in arg_ids:
wires[arg_id], wires[op_node[0]] = op_node[0], wires[arg_id]
# Add wiring to/from the operations and between unused inputs & outputs.
new_layer.multi_graph.add_edges_from(wires.items())
yield {"graph": new_layer, "partition": support_list}
def serial_layers(self):
"""Yield a layer for all gates of this circuit.
A serial layer is a circuit with one gate. The layers have the
same structure as in layers().
"""
for n in self.node_nums_in_topological_order():
nxt_nd = self.multi_graph.node[n]
if nxt_nd["type"] == "op":
new_layer = DAGCircuit()
for qreg in self.qregs.values():
new_layer.add_qreg(qreg)
for creg in self.cregs.values():
new_layer.add_creg(creg)
new_layer.basis = self.basis.copy()
new_layer.gates = self.gates.copy()
# Save the support of the operation we add to the layer
support_list = []
# Operation data
qa = copy.copy(nxt_nd["qargs"])
ca = copy.copy(nxt_nd["cargs"])
pa = copy.copy(nxt_nd["params"])
co = copy.copy(nxt_nd["condition"])
op = copy.copy(nxt_nd["op"])
_ = self._bits_in_condition(co)
# Add node to new_layer
new_layer.apply_operation_back(nxt_nd["name"],
qa, ca, pa, co, op)
# Add operation to partition
if nxt_nd["name"] not in ["barrier",
"snapshot", "save", "load", "noise"]:
# support_list.append(list(set(qa) | set(ca) | set(cob)))
support_list.append(list(qa))
l_dict = {"graph": new_layer, "partition": support_list}
yield l_dict
def multigraph_layers(self):
"""Yield layers of the multigraph."""
predecessor_count = dict() # Dict[node, predecessors not visited]
cur_layer = [node for node in self.input_map.values()]
yield cur_layer
next_layer = []
while cur_layer:
for node in cur_layer:
# Count multiedges with multiplicity.
for successor in self.multi_graph.successors(node):
multiplicity = self.multi_graph.number_of_edges(node, successor)
if successor in predecessor_count:
predecessor_count[successor] -= multiplicity
else:
predecessor_count[successor] = \
self.multi_graph.in_degree(successor) - multiplicity
if predecessor_count[successor] == 0:
next_layer.append(successor)
del predecessor_count[successor]
yield next_layer
cur_layer = next_layer
next_layer = []
def collect_runs(self, namelist):
"""Return a set of runs of "op" nodes with the given names.
For example, "... h q[0]; cx q[0],q[1]; cx q[0],q[1]; h q[1]; .."
would produce the tuple of cx nodes as an element of the set returned
from a call to collect_runs(["cx"]). If instead the cx nodes were
"cx q[0],q[1]; cx q[1],q[0];", the method would still return the
pair in a tuple. The namelist can contain names that are not
in the circuit's basis.
Nodes must have only one successor to continue the run.
"""
group_list = []
# Iterate through the nodes of self in topological order
# and form tuples containing sequences of gates
# on the same qubit(s).
ts = list(self.node_nums_in_topological_order())
nodes_seen = dict(zip(ts, [False] * len(ts)))
for node in ts:
nd = self.multi_graph.node[node]
if nd["type"] == "op" and nd["name"] in namelist \
and not nodes_seen[node]:
group = [node]
nodes_seen[node] = True
s = list(self.multi_graph.successors(node))
while len(s) == 1 and \
self.multi_graph.node[s[0]]["type"] == "op" and \
self.multi_graph.node[s[0]]["name"] in namelist:
group.append(s[0])
nodes_seen[s[0]] = True
s = list(self.multi_graph.successors(s[0]))
if len(group) > 1:
group_list.append(tuple(group))
return set(group_list)
def count_ops(self):
"""Count the occurrences of operation names.
Returns a dictionary of counts keyed on the operation name.
"""
op_dict = {}
for node in self.node_nums_in_topological_order():
nd = self.multi_graph.node[node]
name = nd["name"]
if nd["type"] == "op":
if name not in op_dict:
op_dict[name] = 1
else:
op_dict[name] += 1
return op_dict
def properties(self):
"""Return a dictionary of circuit properties."""
summary = {"size": self.size(),
"depth": self.depth(),
"width": self.width(),
"bits": self.num_cbits(),
"factors": self.num_tensor_factors(),
"operations": self.count_ops()}
return summary
@staticmethod
def fromQuantumCircuit(circuit, expand_gates=True):
"""Build a ``DAGCircuit`` object from a ``QuantumCircuit``.
Args:
circuit (QuantumCircuit): the input circuit.
expand_gates (bool): if ``False``, none of the gates are expanded,
i.e. the gates that are defined in the circuit are included in
the DAG basis.
Return:
DAGCircuit: the DAG representing the input circuit.
"""
dagcircuit = DAGCircuit()
dagcircuit.name = circuit.name
for register in circuit.qregs:
dagcircuit.add_qreg(register)
for register in circuit.cregs:
dagcircuit.add_creg(register)
# Add user gate definitions
for name, data in circuit.definitions.items():
dagcircuit.add_basis_element(name, data["n_bits"], 0,
data["n_args"])
dagcircuit.add_gate_data(name, data)
# Add instructions
builtins = {
"U": ["U", 1, 0, 3],
"CX": ["CX", 2, 0, 0],
"measure": ["measure", 1, 1, 0],
"reset": ["reset", 1, 0, 0],
"barrier": ["barrier", -1, 0, 0]
}
# Add simulator instructions
simulator_instructions = {
"snapshot": ["snapshot", -1, 0, 1],
"save": ["save", -1, 0, 1],
"load": ["load", -1, 0, 1],
"noise": ["noise", -1, 0, 1]
}
for main_instruction in circuit.data:
# TODO: generate definitions and nodes for CompositeGates,
# for now simply drop their instructions into the DAG
instruction_list = []
is_composite = isinstance(main_instruction,
_compositegate.CompositeGate)
if is_composite and expand_gates:
instruction_list = main_instruction.instruction_list()
else:
instruction_list.append(main_instruction)
for instruction in instruction_list:
# Add OpenQASM built-in gates on demand
if instruction.name in builtins:
dagcircuit.add_basis_element(*builtins[instruction.name])
# Add simulator extension instructions
if instruction.name in simulator_instructions:
dagcircuit.add_basis_element(*simulator_instructions[instruction.name])
# Separate classical arguments to measurements
if instruction.name == "measure":
qargs = [(instruction.qargs[0][0].name, instruction.qargs[0][1])]
cargs = [(instruction.cargs[0][0].name, instruction.cargs[0][1])]
else:
qargs = list(map(lambda x: (x[0].name, x[1]), instruction.qargs))
cargs = []
# Get arguments for classical control (if any)
if instruction.control is None:
control = None
else:
control = (instruction.control[0].name, instruction.control[1])
if is_composite and not expand_gates:
is_inverse = instruction.inverse_flag
name = instruction.name if not is_inverse else instruction.inverse_name
else:
name = instruction.name
dagcircuit.apply_operation_back(name, qargs, cargs,
instruction.param,
control, instruction)
return dagcircuit
<|code_end|>
|
A check_map analysis pass is needed
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
In https://github.com/Qiskit/qiskit-terra/pull/1270#issuecomment-439951585 @ajavadia raised the need to have a pass to check if a circuit is compatible with a coupling map.
|
qiskit/dagcircuit/_dagcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Object to represent a quantum circuit as a directed acyclic graph.
The nodes in the graph are either input/output nodes or operation nodes.
The operation nodes are elements of a basis that is part of the circuit.
The QASM definitions of the basis elements are carried with the circuit.
The edges correspond to qubits or bits in the circuit. A directed edge
from node A to node B means that the (qu)bit passes from the output of A
to the input of B. The object's methods allow circuits to be constructed,
composed, and modified. Some natural properties like depth can be computed
directly from the graph.
"""
from collections import OrderedDict
import copy
import itertools
import networkx as nx
import sympy
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QISKitError
from qiskit import _compositegate
from ._dagcircuiterror import DAGCircuitError
class DAGCircuit:
"""
Quantum circuit as a directed acyclic graph.
There are 3 types of nodes in the graph: inputs, outputs, and operations.
The nodes are connected by directed edges that correspond to qubits and
bits.
"""
# pylint: disable=invalid-name
def __init__(self):
"""Create an empty circuit."""
# Circuit name. Generally, this corresponds to the name
# of the QuantumCircuit from which the DAG was generated.
self.name = None
# Map from a wire's name (reg,idx) to a Bool that is True if the
# wire is a classical bit and False if the wire is a qubit.
self.wire_type = OrderedDict()
# Map from wire names (reg,idx) to input nodes of the graph
self.input_map = OrderedDict()
# Map from wire names (reg,idx) to output nodes of the graph
self.output_map = OrderedDict()
# Running count of the total number of nodes
self.node_counter = 0
# Map of named operations in this circuit and their signatures.
# The signature is an integer tuple (nq,nc,np) specifying the
# number of input qubits, input bits, and real parameters.
# The definition is external to the circuit object.
self.basis = OrderedDict()
# Directed multigraph whose nodes are inputs, outputs, or operations.
# Operation nodes have equal in- and out-degrees and carry
# additional data about the operation, including the argument order
# and parameter values.
# Input nodes have out-degree 1 and output nodes have in-degree 1.
# Edges carry wire labels (reg,idx) and each operation has
# corresponding in- and out-edges with the same wire labels.
self.multi_graph = nx.MultiDiGraph()
# Map of qregs to sizes
self.qregs = OrderedDict()
# Map of cregs to sizes
self.cregs = OrderedDict()
# Map of user defined gates to ast nodes defining them
self.gates = OrderedDict()
# Output precision for printing floats
self.prec = 10
# layout of dag quantum registers on the chip
# TODO: rethink this. doesn't seem related to concept of DAG,
# but if we want to be able to generate qobj
# directly from a dag, we need it.
self.layout = []
def get_qubits(self):
"""Return a list of qubits as (qreg, index) pairs."""
return [(k, i) for k, v in self.qregs.items() for i in range(v.size)]
def rename_register(self, regname, newname):
"""Rename a classical or quantum register throughout the circuit.
regname = existing register name string
newname = replacement register name string
"""
if regname == newname:
return
if newname in self.qregs or newname in self.cregs:
raise DAGCircuitError("duplicate register name %s" % newname)
if regname not in self.qregs and regname not in self.cregs:
raise DAGCircuitError("no register named %s" % regname)
iscreg = False
if regname in self.qregs:
self.qregs[newname] = self.qregs[regname]
self.qregs.pop(regname, None)
reg_size = self.qregs[newname].size
if regname in self.cregs:
self.cregs[newname] = self.cregs[regname]
self.cregs.pop(regname, None)
reg_size = self.cregs[newname].size
iscreg = True
for i in range(reg_size):
self.wire_type[(newname, i)] = iscreg
self.wire_type.pop((regname, i), None)
self.input_map[(newname, i)] = self.input_map[(regname, i)]
self.input_map.pop((regname, i), None)
self.output_map[(newname, i)] = self.output_map[(regname, i)]
self.output_map.pop((regname, i), None)
# n node d = data
for _, d in self.multi_graph.nodes(data=True):
if d["type"] == "in" or d["type"] == "out":
if d["name"][0] == regname:
d["name"] = (newname, d["name"][1])
elif d["type"] == "op":
qa = []
for a in d["qargs"]:
if a[0] == regname:
a = (newname, a[1])
qa.append(a)
d["qargs"] = qa
ca = []
for a in d["cargs"]:
if a[0] == regname:
a = (newname, a[1])
ca.append(a)
d["cargs"] = ca
if d["condition"] is not None:
if d["condition"][0] == regname:
d["condition"] = (newname, d["condition"][1])
# eX = edge, d= data
for _, _, d in self.multi_graph.edges(data=True):
if d["name"][0] == regname:
d["name"] = (newname, d["name"][1])
def remove_all_ops_named(self, opname):
"""Remove all operation nodes with the given name."""
for n in self.get_named_nodes(opname):
self._remove_op_node(n)
def fs(self, number):
"""Format a float f as a string with self.prec digits."""
fmt = "{0:0.%snumber}" % self.prec
return fmt.format(number)
def add_qreg(self, qreg):
"""Add all wires in a quantum register."""
if not isinstance(qreg, QuantumRegister):
raise DAGCircuitError("not a QuantumRegister instance.")
if qreg.name in self.qregs:
raise DAGCircuitError("duplicate register %s" % qreg.name)
self.qregs[qreg.name] = qreg
for j in range(qreg.size):
self._add_wire((qreg.name, j))
def add_creg(self, creg):
"""Add all wires in a classical register."""
if not isinstance(creg, ClassicalRegister):
raise DAGCircuitError("not a ClassicalRegister instance.")
if creg.name in self.cregs:
raise DAGCircuitError("duplicate register %s" % creg.name)
self.cregs[creg.name] = creg
for j in range(creg.size):
self._add_wire((creg.name, j), True)
def _add_wire(self, name, isClassical=False):
"""Add a qubit or bit to the circuit.
name is a (string,int) tuple containing register name and index
This adds a pair of in and out nodes connected by an edge.
"""
if name not in self.wire_type:
self.wire_type[name] = isClassical
self.node_counter += 1
self.input_map[name] = self.node_counter
self.node_counter += 1
self.output_map[name] = self.node_counter
in_node = self.input_map[name]
out_node = self.output_map[name]
self.multi_graph.add_edge(in_node, out_node)
self.multi_graph.node[in_node]["type"] = "in"
self.multi_graph.node[out_node]["type"] = "out"
self.multi_graph.node[in_node]["name"] = name
self.multi_graph.node[out_node]["name"] = name
self.multi_graph.adj[in_node][out_node][0]["name"] = name
else:
raise DAGCircuitError("duplicate wire %s" % name)
def add_basis_element(self, name, number_qubits,
number_classical=0, number_parameters=0):
"""Add an operation to the basis.
name is string label for operation
number_qubits is number of qubit arguments
number_classical is number of bit arguments
number_parameters is number of real parameters
The parameters (nq,nc,np) are ignored for the special case
when name = "barrier". The barrier instruction has a variable
number of qubit arguments.
"""
if name not in self.basis:
self.basis[name] = (
number_qubits,
number_classical,
number_parameters)
if name in self.gates:
if self.gates[name]["n_args"] != number_parameters or \
self.gates[name]["n_bits"] != number_qubits or number_classical != 0:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def add_gate_data(self, name, gatedata):
"""Add the definition of a gate.
gatedata is dict with fields:
"print" = True or False
"opaque" = True or False
"n_args" = number of real parameters
"n_bits" = number of qubits
"args" = list of parameter names
"bits" = list of qubit names
"body" = GateBody AST node
"""
if name not in self.gates:
self.gates[name] = gatedata
if name in self.basis:
if self.basis[name][0] != self.gates[name]["n_bits"] or \
self.basis[name][1] != 0 or \
self.basis[name][2] != self.gates[name]["n_args"]:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def _check_basis_data(self, name, qargs, cargs, params):
"""Check the arguments against the data for this operation.
name is a string
qargs is a list of tuples like ("q",0)
cargs is a list of tuples like ("c",0)
params is a list of strings that represent floats
"""
# Check that we have this operation
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
# Check the number of arguments matches the signature
if name in ["barrier"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if params:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
elif name in ["snapshot", "noise", "save", "load"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if not params:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
else:
if len(qargs) != self.basis[name][0]:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if len(cargs) != self.basis[name][1]:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if len(params) != self.basis[name][2]:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
def _check_condition(self, name, condition):
"""Verify that the condition is valid.
name is a string used for error reporting
condition is either None or a tuple (string,int) giving (creg,value)
"""
# Verify creg exists
if condition is not None and condition[0] not in self.cregs:
raise DAGCircuitError("invalid creg in condition for %s" % name)
def _check_bits(self, args, amap, bval):
"""Check the values of a list of (qu)bit arguments.
For each element A of args, check that amap contains A and
self.wire_type[A] equals bval.
args is a list of (regname,idx) tuples
amap is a dictionary keyed on (regname,idx) tuples
bval is boolean
"""
# Check for each wire
for q in args:
if q not in amap:
raise DAGCircuitError("(qu)bit %s not found" % (q,))
if self.wire_type[q] != bval:
raise DAGCircuitError("expected wire type %s for %s"
% (bval, q))
def _bits_in_condition(self, cond):
"""Return a list of bits (regname,idx) in the given condition.
cond is either None or a (regname,int) tuple specifying
a classical if condition.
"""
all_bits = []
if cond is not None:
all_bits.extend([(cond[0], j) for j in range(self.cregs[cond[0]].size)])
return all_bits
def _add_op_node(self, nname, nqargs, ncargs, nparams, ncondition, nop):
"""Add a new operation node to the graph and assign properties.
nname node name
nqargs quantum arguments
ncargs classical arguments
nparams parameters
ncondition classical condition (or None)
nop Instruction instance representing this operation
"""
# Add a new operation node to the graph
self.node_counter += 1
self.multi_graph.add_node(self.node_counter)
# Update that operation node's data
self.multi_graph.node[self.node_counter]["type"] = "op"
self.multi_graph.node[self.node_counter]["name"] = nname
self.multi_graph.node[self.node_counter]["qargs"] = nqargs
self.multi_graph.node[self.node_counter]["cargs"] = ncargs
self.multi_graph.node[self.node_counter]["params"] = nparams
self.multi_graph.node[self.node_counter]["condition"] = ncondition
self.multi_graph.node[self.node_counter]["op"] = nop
def apply_operation_back(self, name, qargs, cargs=None, params=None,
condition=None, op=None):
"""Apply an operation to the output of the circuit.
name is a string
qargs is a list of tuples like ("q",0)
cargs is a list of tuples like ("c",0)
params is a list of symbols that represent numbers
condition is either None or a tuple (string,int) giving (creg,value)
op is an Instruction instance representing this node
"""
cargs = cargs or []
params = params or []
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(name, qargs, cargs, params)
self._check_condition(name, condition)
self._check_bits(qargs, self.output_map, False)
self._check_bits(all_cbits, self.output_map, True)
self._add_op_node(name, qargs, cargs, params, condition, op)
# Add new in-edges from predecessors of the output nodes to the
# operation node while deleting the old in-edges of the output nodes
# and adding new edges from the operation node to each output node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.predecessors(self.output_map[q]))
if len(ie) != 1:
raise QISKitError("output node has multiple in-edges")
self.multi_graph.add_edge(ie[0], self.node_counter, name=q)
self.multi_graph.remove_edge(ie[0], self.output_map[q])
self.multi_graph.add_edge(
self.node_counter, self.output_map[q], name=q)
def apply_operation_front(self, name, qargs, cargs=None, params=None,
condition=None, op=None):
"""Apply an operation to the input of the circuit.
name is a string
qargs is a list of strings like "q[0]"
cargs is a list of strings like "c[0]"
params is a list of strings that represent floats
condition is either None or a tuple (string,int) giving (creg,value)
"""
cargs = cargs or []
params = params or []
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(name, qargs, cargs, params)
self._check_condition(name, condition)
self._check_bits(qargs, self.input_map, False)
self._check_bits(all_cbits, self.input_map, True)
self._add_op_node(name, qargs, cargs, params, condition, op)
# Add new out-edges to successors of the input nodes from the
# operation node while deleting the old out-edges of the input nodes
# and adding new edges to the operation node from each input node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = self.multi_graph.successors(self.input_map[q])
if len(ie) != 1:
raise QISKitError("input node has multiple out-edges")
self.multi_graph.add_edge(self.node_counter, ie[0], name=q)
self.multi_graph.remove_edge(self.input_map[q], ie[0])
self.multi_graph.add_edge(
self.input_map[q], self.node_counter, name=q)
def _make_union_basis(self, input_circuit):
"""Return a new basis map.
The new basis is a copy of self.basis with
new elements of input_circuit.basis added.
input_circuit is a DAGCircuit
"""
union_basis = self.basis.copy()
for g in input_circuit.basis:
if g not in union_basis:
union_basis[g] = input_circuit.basis[g]
if union_basis[g] != input_circuit.basis[g]:
raise DAGCircuitError("incompatible basis")
return union_basis
def _make_union_gates(self, input_circuit):
"""Return a new gates map.
The new gates are a copy of self.gates with
new elements of input_circuit.gates added.
input_circuit is a DAGCircuit
NOTE: gates in input_circuit that are also in self must
be *identical* to the gates in self
"""
union_gates = {}
for k, v in self.gates.items():
union_gates[k] = v
for k, v in input_circuit.gates.items():
if k not in union_gates:
union_gates[k] = v
if union_gates[k]["opaque"] != input_circuit.gates[k]["opaque"] or \
union_gates[k]["n_args"] != input_circuit.gates[k]["n_args"] or \
union_gates[k]["n_bits"] != input_circuit.gates[k]["n_bits"] or \
union_gates[k]["args"] != input_circuit.gates[k]["args"] or \
union_gates[k]["bits"] != input_circuit.gates[k]["bits"]:
raise DAGCircuitError("inequivalent gate definitions for %s"
% k)
return union_gates
def _check_wiremap_registers(self, wire_map, keyregs, valregs,
valreg=True):
"""Check that wiremap neither fragments nor leaves duplicate registers.
1. There are no fragmented registers. A register in keyregs
is fragmented if not all of its (qu)bits are renamed by wire_map.
2. There are no duplicate registers. A register is duplicate if
it appears in both self and keyregs but not in wire_map.
wire_map is a map from (regname,idx) in keyregs to (regname,idx)
in valregs
keyregs is a map from register names to Register objects
valregs is a map from register names to Register objects
valreg is a Bool, if False the method ignores valregs and does not
add regs for bits in the wire_map image that don't appear in valregs
Return the set of regs to add to self
"""
add_regs = set()
reg_frag_chk = {}
for k, v in keyregs.items():
reg_frag_chk[k] = {j: False for j in range(v.size)}
for k in wire_map.keys():
if k[0] in keyregs:
reg_frag_chk[k[0]][k[1]] = True
for k, v in reg_frag_chk.items():
rname = ",".join(map(str, k))
s = set(v.values())
if len(s) == 2:
raise DAGCircuitError("wire_map fragments reg %s" % rname)
elif s == set([False]):
if k in self.qregs or k in self.cregs:
raise DAGCircuitError("unmapped duplicate reg %s" % rname)
else:
# Add registers that appear only in keyregs
add_regs.add(keyregs[k])
else:
if valreg:
# If mapping to a register not in valregs, add it.
# (k,0) exists in wire_map because wire_map doesn't
# fragment k
if not wire_map[(k, 0)][0] in valregs:
size = max(map(lambda x: x[1], filter(lambda x: x[0] == wire_map[(k, 0)][0],
wire_map.values())))
qreg = QuantumRegister(wire_map[(k, 0)][0], size + 1)
add_regs.add(qreg)
return add_regs
def _check_wiremap_validity(self, wire_map, keymap, valmap, input_circuit):
"""Check that the wiremap is consistent.
Check that the wiremap refers to valid wires and that
those wires have consistent types.
wire_map is a map from (regname,idx) in keymap to (regname,idx)
in valmap
keymap is a map whose keys are wire_map keys
valmap is a map whose keys are wire_map values
input_circuit is a DAGCircuit
"""
for k, v in wire_map.items():
kname = ",".join(map(str, k))
vname = ",".join(map(str, v))
if k not in keymap:
raise DAGCircuitError("invalid wire mapping key %s" % kname)
if v not in valmap:
raise DAGCircuitError("invalid wire mapping value %s"
% vname)
if input_circuit.wire_type[k] != self.wire_type[v]:
raise DAGCircuitError("inconsistent wire_map at (%s,%s)"
% (kname, vname))
def _map_condition(self, wire_map, condition):
"""Use the wire_map dict to change the condition tuple's creg name.
wire_map is map from wires to wires
condition is a tuple (reg,int)
Returns the new condition tuple
"""
if condition is None:
n_condition = None
else:
# Map the register name, using fact that registers must not be
# fragmented by the wire_map (this must have been checked
# elsewhere)
bit0 = (condition[0], 0)
n_condition = (wire_map.get(bit0, bit0)[0], condition[1])
return n_condition
def compose_back(self, input_circuit, wire_map=None):
"""Apply the input circuit to the output of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of input qubits of the input circuit are mapped
to a subset of output qubits of this circuit.
wire_map[input_qubit_to_input_circuit] = output_qubit_of_self
"""
wire_map = wire_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map for duplicate values
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_wiremap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.input_map,
self.output_map, input_circuit)
# Compose
self.basis = union_basis
self.gates = union_gates
for node in nx.topological_sort(input_circuit.multi_graph):
nd = input_circuit.multi_graph.node[node]
if nd["type"] == "in":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["name"], nd["name"])
# the mapped wire should already exist
if m_name not in self.output_map:
raise QISKitError("wire (%s,%d) not in self" % (m_name[0], m_name[1]))
if nd["name"] not in input_circuit.wire_type:
raise QISKitError("inconsistent wire_type for (%s,%d) in input_circuit"
% (nd["name"][0], nd["name"][1]))
elif nd["type"] == "out":
# ignore output nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: wire_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x), nd["cargs"]))
self.apply_operation_back(nd["name"], m_qargs, m_cargs,
nd["params"], condition, nd["op"])
else:
raise QISKitError("bad node type %s" % nd["type"])
def compose_front(self, input_circuit, wire_map=None):
"""Apply the input circuit to the input of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of output qubits of the input circuit are mapped
to a subset of input qubits of
this circuit.
"""
wire_map = wire_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_wiremap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.output_map,
self.input_map, input_circuit)
# Compose
self.basis = union_basis
self.gates = union_gates
for n in reversed(list(nx.topological_sort(input_circuit.multi_graph))):
nd = input_circuit.multi_graph.node[n]
if nd["type"] == "out":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["name"], nd["name"])
# the mapped wire should already exist
if m_name not in self.input_map:
raise QISKitError("wire (%s,%d) not in self" % (m_name[0], m_name[1]))
if nd["name"] not in input_circuit.wire_type:
raise QISKitError(
"inconsistent wire_type for (%s,%d) in input_circuit"
% (nd["name"][0], nd["name"][1]))
elif nd["type"] == "in":
# ignore input nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: wire_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x), nd["cargs"]))
self.apply_operation_front(nd["name"], m_qargs, m_cargs,
nd["params"], condition, nd["op"])
else:
raise QISKitError("bad node type %s" % nd["type"])
def size(self):
"""Return the number of operations."""
return self.multi_graph.order() - 2 * len(self.wire_type)
def depth(self):
"""Return the circuit depth."""
if not nx.is_directed_acyclic_graph(self.multi_graph):
raise QISKitError("not a DAG")
return nx.dag_longest_path_length(self.multi_graph) - 1
def width(self):
"""Return the total number of qubits used by the circuit."""
return len(self.wire_type) - self.num_cbits()
def num_cbits(self):
"""Return the total number of bits used by the circuit."""
return list(self.wire_type.values()).count(True)
def num_tensor_factors(self):
"""Compute how many components the circuit can decompose into."""
return nx.number_weakly_connected_components(self.multi_graph)
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.gates[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.gates[name]["n_args"] > 0:
out += "(" + ",".join(self.gates[name]["args"]) + ")"
out += " " + ",".join(self.gates[name]["bits"])
if self.gates[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.gates[name]["body"].qasm() + "}"
return out
def qasm(self, decls_only=False, add_swap=False,
no_decls=False, qeflag=False, aliases=None, eval_symbols=False):
"""Return a string containing QASM for this circuit.
if qeflag is True, add a line to include "qelib1.inc"
and only generate gate code for gates not in qelib1.
if eval_symbols is True, evaluate all symbolic
expressions to their floating point representation.
if no_decls is True, only print the instructions.
if aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
if decls_only is True, only print the declarations.
if add_swap is True, add the definition of swap in terms of
cx if necessary.
"""
# TODO: some of the input flags are not needed anymore
# Rename qregs if necessary
if aliases:
qregdata = OrderedDict()
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
# Write top matter
if no_decls:
out = ""
else:
printed_gates = []
out = "OPENQASM 2.0;\n"
if qeflag:
out += "include \"qelib1.inc\";\n"
for k, v in qregdata.items():
out += "qreg %s[%d];\n" % (k, v.size)
for k, v in self.cregs.items():
out += "creg %s[%d];\n" % (k, v.size)
omit = ["U", "CX", "measure", "reset", "barrier"]
# TODO: dagcircuit shouldn't know about extensions
if qeflag:
qelib = ["u3", "u2", "u1", "cx", "id", "x", "y", "z", "h",
"s", "sdg", "t", "tdg", "cz", "cy", "ccx", "cu1",
"cu3", "swap", "cswap", "u0", "rx", "ry", "rz",
"ch", "crz", "rzz"]
omit.extend(qelib)
printed_gates.extend(qelib)
simulator_instructions = ["snapshot", "save", "load", "noise", "wait"]
omit.extend(simulator_instructions)
for k in self.basis.keys():
if k not in omit:
if not self.gates[k]["opaque"]:
calls = self.gates[k]["body"].calls()
for c in calls:
if c not in printed_gates:
out += self._gate_string(c) + "\n"
printed_gates.append(c)
if k not in printed_gates:
out += self._gate_string(k) + "\n"
printed_gates.append(k)
if add_swap and not qeflag and "cx" not in self.basis:
out += "gate cx a,b { CX a,b; }\n"
if add_swap and "swap" not in self.basis:
out += "gate swap a,b { cx a,b; cx b,a; cx a,b; }\n"
# Write the instructions
if not decls_only:
for n in nx.lexicographical_topological_sort(self.multi_graph):
nd = self.multi_graph.node[n]
if nd["type"] == "op":
if nd["condition"] is not None:
out += "if(%s==%d) " \
% (nd["condition"][0], nd["condition"][1])
if not nd["cargs"]:
nm = nd["name"]
if aliases:
qarglist = map(lambda x: aliases[x], nd["qargs"])
else:
qarglist = nd["qargs"]
qarg = ",".join(map(lambda x: "%s[%d]" % (x[0], x[1]),
qarglist))
if nd["params"]:
if eval_symbols:
param = ",".join(map(lambda x: str(sympy.N(x)),
nd["params"]))
else:
param = ",".join(map(lambda x: x.replace("**", "^"),
map(str, nd["params"])))
out += "%s(%s) %s;\n" % (nm, param, qarg)
else:
out += "%s %s;\n" % (nm, qarg)
else:
if nd["name"] == "measure":
if len(nd["cargs"]) != 1 or len(nd["qargs"]) != 1 \
or nd["params"]:
raise QISKitError("bad node data")
qname = nd["qargs"][0][0]
qindex = nd["qargs"][0][1]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
out += "measure %s[%d] -> %s[%d];\n" \
% (qname,
qindex,
nd["cargs"][0][0],
nd["cargs"][0][1])
else:
raise QISKitError("bad node data")
return out
def _check_wires_list(self, wires, name, input_circuit, condition=None):
"""Check that a list of wires satisfies some conditions.
wires = list of (register_name, index) tuples
name = name of operation
input_circuit = replacement circuit for operation
condition = None or (creg_name, value) if this instance of the
operation is classically controlled
The wires give an order for (qu)bits in the input circuit
that is replacing the named operation.
- no duplicate names
- correct length for named operation
- elements are wires of input_circuit
Raises an exception otherwise.
"""
if len(set(wires)) != len(wires):
raise DAGCircuitError("duplicate wires")
wire_tot = self.basis[name][0] + self.basis[name][1]
if condition is not None:
wire_tot += self.cregs[condition[0]].size
if len(wires) != wire_tot:
raise DAGCircuitError("expected %d wires, got %d"
% (wire_tot, len(wires)))
for w in wires:
if w not in input_circuit.wire_type:
raise DAGCircuitError("wire (%s,%d) not in input circuit"
% (w[0], w[1]))
def _make_pred_succ_maps(self, n):
"""Return predecessor and successor dictionaries.
These map from wire names to predecessor and successor
nodes for the operation node n in self.multi_graph.
"""
pred_map = {e[2]['name']: e[0] for e in
self.multi_graph.in_edges(nbunch=n, data=True)}
succ_map = {e[2]['name']: e[1] for e in
self.multi_graph.out_edges(nbunch=n, data=True)}
return pred_map, succ_map
def _full_pred_succ_maps(self, pred_map, succ_map, input_circuit,
wire_map):
"""Map all wires of the input circuit.
Map all wires of the input circuit to predecessor and
successor nodes in self, keyed on wires in self.
pred_map, succ_map dicts come from _make_pred_succ_maps
input_circuit is the input circuit
wire_map is the wire map from wires of input_circuit to wires of self
returns full_pred_map, full_succ_map
"""
full_pred_map = {}
full_succ_map = {}
for w in input_circuit.input_map:
# If w is wire mapped, find the corresponding predecessor
# of the node
if w in wire_map:
full_pred_map[wire_map[w]] = pred_map[wire_map[w]]
full_succ_map[wire_map[w]] = succ_map[wire_map[w]]
else:
# Otherwise, use the corresponding output nodes of self
# and compute the predecessor.
full_succ_map[w] = self.output_map[w]
full_pred_map[w] = self.multi_graph.predecessors(
self.output_map[w])[0]
if len(list(self.multi_graph.predecessors(self.output_map[w]))) != 1:
raise QISKitError(
"too many predecessors for (%s,%d) output node" % (w[0], w[1])
)
return full_pred_map, full_succ_map
def node_nums_in_topological_order(self):
"""
Returns the nodes (their ids) in topological order.
Returns:
List(int): The list of node numbers in topological order
"""
return nx.topological_sort(self.multi_graph)
def substitute_circuit_all(self, name, input_circuit, wires=None):
"""Replace every occurrence of named operation with input_circuit."""
# TODO: rewrite this method to call substitute_circuit_one
wires = wires or None
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
self._check_wires_list(wires, name, input_circuit)
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: ("", 0) for w in wires}
add_qregs = self._check_wiremap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Iterate through the nodes of self and replace the selected nodes
# by iterating through the input_circuit, constructing and
# checking the validity of the wire_map for each replacement
# NOTE: We do not replace conditioned gates. One way to implement
# this later is to add or update the conditions of each gate
# that we add from the input_circuit.
self.basis = union_basis
self.gates = union_gates
for n in self.node_nums_in_topological_order():
nd = self.multi_graph.node[n]
if nd["type"] == "op" and nd["name"] == name:
if nd["condition"] is None:
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"], nd["cargs"]]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map, input_circuit)
pred_map, succ_map = self._make_pred_succ_maps(n)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(n)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map,
md["condition"])
m_qargs = [wire_map.get(x, x) for x in md["qargs0"]]
m_cargs = [wire_map.get(x, x) for x in md["cargs0"]]
self._add_op_node(md["name"], m_qargs, m_cargs,
md["params"], condition, md["op"])
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter, name=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w], full_succ_map[w],
name=w)
o_pred = list(self.multi_graph.predecessors(
self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise QISKitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise QISKitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(
p[0], self.output_map[w])
def substitute_circuit_one(self, node, input_circuit, wires=None):
"""Replace one node with input_circuit.
node is a reference to a node of self.multi_graph of type "op"
input_circuit is a DAGCircuit
"""
wires = wires or None
nd = self.multi_graph.node[node]
name = nd["name"]
self._check_wires_list(wires, name, input_circuit, nd["condition"])
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: ("", 0) for w in wires}
add_qregs = self._check_wiremap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Replace the node by iterating through the input_circuit.
# Constructing and checking the validity of the wire_map.
# If a gate is conditioned, we expect the replacement subcircuit
# to depend on those control bits as well.
self.basis = union_basis
self.gates = union_gates
if nd["type"] != "op":
raise DAGCircuitError("expected node type \"op\", got %s"
% nd["type"])
condition_bit_list = self._bits_in_condition(nd["condition"])
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"],
nd["cargs"],
condition_bit_list]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map, input_circuit)
pred_map, succ_map = self._make_pred_succ_maps(node)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(node)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map, md["condition"])
m_qargs = list(map(lambda x: wire_map.get(x, x),
md["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x),
md["cargs"]))
self._add_op_node(md["name"], m_qargs, m_cargs,
md["params"], condition, md["op"])
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter,
name=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(
full_pred_map[w], full_succ_map[w], name=w)
o_pred = list(self.multi_graph.predecessors(self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise QISKitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise QISKitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(p[0], self.output_map[w])
def get_named_nodes(self, name):
"""Get the set of "op" node ids with the given name."""
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
# We need to instantiate the full list now because the underlying multi_graph
# may change when users iterate over the named nodes.
return {node_id for node_id, data in self.multi_graph.nodes(data=True)
if data["type"] == "op" and data["name"] == name}
def _remove_op_node(self, n):
"""Remove an operation node n.
Add edges from predecessors to successors.
"""
pred_map, succ_map = self._make_pred_succ_maps(n)
self.multi_graph.remove_node(n)
for w in pred_map.keys():
self.multi_graph.add_edge(pred_map[w], succ_map[w], name=w)
def remove_ancestors_of(self, node):
"""Remove all of the ancestor operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
# TODO: probably better to do all at once using
# multi_graph.remove_nodes_from; same for related functions ...
for n in anc:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_descendants_of(self, node):
"""Remove all of the descendant operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
for n in dec:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nonancestors_of(self, node):
"""Remove all of the non-ancestors operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(anc))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nondescendants_of(self, node):
"""Remove all of the non-descendants operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(dec))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def layers(self):
"""Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit.
A layer is a circuit whose gates act on disjoint qubits, i.e.
a layer has depth 1. The total number of layers equals the
circuit depth d. The layers are indexed from 0 to d-1 with the
earliest layer at index 0. The layers are constructed using a
greedy algorithm. Each returned layer is a dict containing
{"graph": circuit graph, "partition": list of qubit lists}.
TODO: Gates that use the same cbits will end up in different
layers as this is currently implemented. This may not be
the desired behavior.
"""
graph_layers = self.multigraph_layers()
try:
next(graph_layers) # Remove input nodes
except StopIteration:
return
def nodes_data(nodes):
"""Construct full nodes from just node ids."""
return ((node_id, self.multi_graph.nodes[node_id]) for node_id in nodes)
for graph_layer in graph_layers:
# Get the op nodes from the layer, removing any input and output nodes.
op_nodes = [node for node in nodes_data(graph_layer) if node[1]["type"] == "op"]
# Stop yielding once there are no more op_nodes in a layer.
if not op_nodes:
return
# Construct a shallow copy of self
new_layer = copy.copy(self)
new_layer.multi_graph = nx.MultiDiGraph()
new_layer.multi_graph.add_nodes_from(nodes_data(self.input_map.values()))
new_layer.multi_graph.add_nodes_from(nodes_data(self.output_map.values()))
# The quantum registers that have an operation in this layer.
support_list = [
op_node[1]["qargs"]
for op_node in op_nodes
if op_node[1]["name"] not in {"barrier", "snapshot", "save", "load", "noise"}
]
new_layer.multi_graph.add_nodes_from(op_nodes)
# Now add the edges to the multi_graph
# By default we just wire inputs to the outputs.
wires = {self.input_map[register]: self.output_map[register]
for register in self.wire_type}
# Wire inputs to op nodes, and op nodes to outputs.
for op_node in op_nodes:
args = self._bits_in_condition(op_node[1]["condition"]) \
+ op_node[1]["cargs"] + op_node[1]["qargs"]
arg_ids = (self.input_map[arg] for arg in args) # map from ("q",0) to node id.
for arg_id in arg_ids:
wires[arg_id], wires[op_node[0]] = op_node[0], wires[arg_id]
# Add wiring to/from the operations and between unused inputs & outputs.
new_layer.multi_graph.add_edges_from(wires.items())
yield {"graph": new_layer, "partition": support_list}
def serial_layers(self):
"""Yield a layer for all gates of this circuit.
A serial layer is a circuit with one gate. The layers have the
same structure as in layers().
"""
for n in self.node_nums_in_topological_order():
nxt_nd = self.multi_graph.node[n]
if nxt_nd["type"] == "op":
new_layer = DAGCircuit()
for qreg in self.qregs.values():
new_layer.add_qreg(qreg)
for creg in self.cregs.values():
new_layer.add_creg(creg)
new_layer.basis = self.basis.copy()
new_layer.gates = self.gates.copy()
# Save the support of the operation we add to the layer
support_list = []
# Operation data
qa = copy.copy(nxt_nd["qargs"])
ca = copy.copy(nxt_nd["cargs"])
pa = copy.copy(nxt_nd["params"])
co = copy.copy(nxt_nd["condition"])
op = copy.copy(nxt_nd["op"])
_ = self._bits_in_condition(co)
# Add node to new_layer
new_layer.apply_operation_back(nxt_nd["name"],
qa, ca, pa, co, op)
# Add operation to partition
if nxt_nd["name"] not in ["barrier",
"snapshot", "save", "load", "noise"]:
# support_list.append(list(set(qa) | set(ca) | set(cob)))
support_list.append(list(qa))
l_dict = {"graph": new_layer, "partition": support_list}
yield l_dict
def multigraph_layers(self):
"""Yield layers of the multigraph."""
predecessor_count = dict() # Dict[node, predecessors not visited]
cur_layer = [node for node in self.input_map.values()]
yield cur_layer
next_layer = []
while cur_layer:
for node in cur_layer:
# Count multiedges with multiplicity.
for successor in self.multi_graph.successors(node):
multiplicity = self.multi_graph.number_of_edges(node, successor)
if successor in predecessor_count:
predecessor_count[successor] -= multiplicity
else:
predecessor_count[successor] = \
self.multi_graph.in_degree(successor) - multiplicity
if predecessor_count[successor] == 0:
next_layer.append(successor)
del predecessor_count[successor]
yield next_layer
cur_layer = next_layer
next_layer = []
def collect_runs(self, namelist):
"""Return a set of runs of "op" nodes with the given names.
For example, "... h q[0]; cx q[0],q[1]; cx q[0],q[1]; h q[1]; .."
would produce the tuple of cx nodes as an element of the set returned
from a call to collect_runs(["cx"]). If instead the cx nodes were
"cx q[0],q[1]; cx q[1],q[0];", the method would still return the
pair in a tuple. The namelist can contain names that are not
in the circuit's basis.
Nodes must have only one successor to continue the run.
"""
group_list = []
# Iterate through the nodes of self in topological order
# and form tuples containing sequences of gates
# on the same qubit(s).
ts = list(self.node_nums_in_topological_order())
nodes_seen = dict(zip(ts, [False] * len(ts)))
for node in ts:
nd = self.multi_graph.node[node]
if nd["type"] == "op" and nd["name"] in namelist \
and not nodes_seen[node]:
group = [node]
nodes_seen[node] = True
s = list(self.multi_graph.successors(node))
while len(s) == 1 and \
self.multi_graph.node[s[0]]["type"] == "op" and \
self.multi_graph.node[s[0]]["name"] in namelist:
group.append(s[0])
nodes_seen[s[0]] = True
s = list(self.multi_graph.successors(s[0]))
if len(group) > 1:
group_list.append(tuple(group))
return set(group_list)
def count_ops(self):
"""Count the occurrences of operation names.
Returns a dictionary of counts keyed on the operation name.
"""
op_dict = {}
for node in self.node_nums_in_topological_order():
nd = self.multi_graph.node[node]
name = nd["name"]
if nd["type"] == "op":
if name not in op_dict:
op_dict[name] = 1
else:
op_dict[name] += 1
return op_dict
def properties(self):
"""Return a dictionary of circuit properties."""
summary = {"size": self.size(),
"depth": self.depth(),
"width": self.width(),
"bits": self.num_cbits(),
"factors": self.num_tensor_factors(),
"operations": self.count_ops()}
return summary
@staticmethod
def fromQuantumCircuit(circuit, expand_gates=True):
"""Build a ``DAGCircuit`` object from a ``QuantumCircuit``.
Args:
circuit (QuantumCircuit): the input circuit.
expand_gates (bool): if ``False``, none of the gates are expanded,
i.e. the gates that are defined in the circuit are included in
the DAG basis.
Return:
DAGCircuit: the DAG representing the input circuit.
"""
dagcircuit = DAGCircuit()
dagcircuit.name = circuit.name
for register in circuit.qregs:
dagcircuit.add_qreg(register)
for register in circuit.cregs:
dagcircuit.add_creg(register)
# Add user gate definitions
for name, data in circuit.definitions.items():
dagcircuit.add_basis_element(name, data["n_bits"], 0,
data["n_args"])
dagcircuit.add_gate_data(name, data)
# Add instructions
builtins = {
"U": ["U", 1, 0, 3],
"CX": ["CX", 2, 0, 0],
"measure": ["measure", 1, 1, 0],
"reset": ["reset", 1, 0, 0],
"barrier": ["barrier", -1, 0, 0]
}
# Add simulator instructions
simulator_instructions = {
"snapshot": ["snapshot", -1, 0, 1],
"save": ["save", -1, 0, 1],
"load": ["load", -1, 0, 1],
"noise": ["noise", -1, 0, 1]
}
for main_instruction in circuit.data:
# TODO: generate definitions and nodes for CompositeGates,
# for now simply drop their instructions into the DAG
instruction_list = []
is_composite = isinstance(main_instruction,
_compositegate.CompositeGate)
if is_composite and expand_gates:
instruction_list = main_instruction.instruction_list()
else:
instruction_list.append(main_instruction)
for instruction in instruction_list:
# Add OpenQASM built-in gates on demand
if instruction.name in builtins:
dagcircuit.add_basis_element(*builtins[instruction.name])
# Add simulator extension instructions
if instruction.name in simulator_instructions:
dagcircuit.add_basis_element(*simulator_instructions[instruction.name])
# Separate classical arguments to measurements
if instruction.name == "measure":
qargs = [(instruction.qargs[0][0].name, instruction.qargs[0][1])]
cargs = [(instruction.cargs[0][0].name, instruction.cargs[0][1])]
else:
qargs = list(map(lambda x: (x[0].name, x[1]), instruction.qargs))
cargs = []
# Get arguments for classical control (if any)
if instruction.control is None:
control = None
else:
control = (instruction.control[0].name, instruction.control[1])
if is_composite and not expand_gates:
is_inverse = instruction.inverse_flag
name = instruction.name if not is_inverse else instruction.inverse_name
else:
name = instruction.name
dagcircuit.apply_operation_back(name, qargs, cargs,
instruction.param,
control, instruction)
return dagcircuit
<|code_end|>
qiskit/transpiler/passes/__init__.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Utils for transpiler."""
from .cx_cancellation import CXCancellation
from .fixed_point import FixedPoint
<|code_end|>
qiskit/transpiler/passes/check_map.py
<|code_start|><|code_end|>
|
qiskit/dagcircuit/_dagcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Object to represent a quantum circuit as a directed acyclic graph.
The nodes in the graph are either input/output nodes or operation nodes.
The operation nodes are elements of a basis that is part of the circuit.
The QASM definitions of the basis elements are carried with the circuit.
The edges correspond to qubits or bits in the circuit. A directed edge
from node A to node B means that the (qu)bit passes from the output of A
to the input of B. The object's methods allow circuits to be constructed,
composed, and modified. Some natural properties like depth can be computed
directly from the graph.
"""
from collections import OrderedDict
import copy
import itertools
import networkx as nx
import sympy
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QISKitError
from qiskit import _compositegate
from ._dagcircuiterror import DAGCircuitError
class DAGCircuit:
"""
Quantum circuit as a directed acyclic graph.
There are 3 types of nodes in the graph: inputs, outputs, and operations.
The nodes are connected by directed edges that correspond to qubits and
bits.
"""
# pylint: disable=invalid-name
def __init__(self):
"""Create an empty circuit."""
# Circuit name. Generally, this corresponds to the name
# of the QuantumCircuit from which the DAG was generated.
self.name = None
# Map from a wire's name (reg,idx) to a Bool that is True if the
# wire is a classical bit and False if the wire is a qubit.
self.wire_type = OrderedDict()
# Map from wire names (reg,idx) to input nodes of the graph
self.input_map = OrderedDict()
# Map from wire names (reg,idx) to output nodes of the graph
self.output_map = OrderedDict()
# Running count of the total number of nodes
self.node_counter = 0
# Map of named operations in this circuit and their signatures.
# The signature is an integer tuple (nq,nc,np) specifying the
# number of input qubits, input bits, and real parameters.
# The definition is external to the circuit object.
self.basis = OrderedDict()
# Directed multigraph whose nodes are inputs, outputs, or operations.
# Operation nodes have equal in- and out-degrees and carry
# additional data about the operation, including the argument order
# and parameter values.
# Input nodes have out-degree 1 and output nodes have in-degree 1.
# Edges carry wire labels (reg,idx) and each operation has
# corresponding in- and out-edges with the same wire labels.
self.multi_graph = nx.MultiDiGraph()
# Map of qregs to sizes
self.qregs = OrderedDict()
# Map of cregs to sizes
self.cregs = OrderedDict()
# Map of user defined gates to ast nodes defining them
self.gates = OrderedDict()
# Output precision for printing floats
self.prec = 10
# layout of dag quantum registers on the chip
# TODO: rethink this. doesn't seem related to concept of DAG,
# but if we want to be able to generate qobj
# directly from a dag, we need it.
self.layout = []
def get_qubits(self):
"""Return a list of qubits as (qreg, index) pairs."""
return [(k, i) for k, v in self.qregs.items() for i in range(v.size)]
def rename_register(self, regname, newname):
"""Rename a classical or quantum register throughout the circuit.
regname = existing register name string
newname = replacement register name string
"""
if regname == newname:
return
if newname in self.qregs or newname in self.cregs:
raise DAGCircuitError("duplicate register name %s" % newname)
if regname not in self.qregs and regname not in self.cregs:
raise DAGCircuitError("no register named %s" % regname)
iscreg = False
if regname in self.qregs:
self.qregs[newname] = self.qregs[regname]
self.qregs.pop(regname, None)
reg_size = self.qregs[newname].size
if regname in self.cregs:
self.cregs[newname] = self.cregs[regname]
self.cregs.pop(regname, None)
reg_size = self.cregs[newname].size
iscreg = True
for i in range(reg_size):
self.wire_type[(newname, i)] = iscreg
self.wire_type.pop((regname, i), None)
self.input_map[(newname, i)] = self.input_map[(regname, i)]
self.input_map.pop((regname, i), None)
self.output_map[(newname, i)] = self.output_map[(regname, i)]
self.output_map.pop((regname, i), None)
# n node d = data
for _, d in self.multi_graph.nodes(data=True):
if d["type"] == "in" or d["type"] == "out":
if d["name"][0] == regname:
d["name"] = (newname, d["name"][1])
elif d["type"] == "op":
qa = []
for a in d["qargs"]:
if a[0] == regname:
a = (newname, a[1])
qa.append(a)
d["qargs"] = qa
ca = []
for a in d["cargs"]:
if a[0] == regname:
a = (newname, a[1])
ca.append(a)
d["cargs"] = ca
if d["condition"] is not None:
if d["condition"][0] == regname:
d["condition"] = (newname, d["condition"][1])
# eX = edge, d= data
for _, _, d in self.multi_graph.edges(data=True):
if d["name"][0] == regname:
d["name"] = (newname, d["name"][1])
def remove_all_ops_named(self, opname):
"""Remove all operation nodes with the given name."""
for n in self.get_named_nodes(opname):
self._remove_op_node(n)
def fs(self, number):
"""Format a float f as a string with self.prec digits."""
fmt = "{0:0.%snumber}" % self.prec
return fmt.format(number)
def add_qreg(self, qreg):
"""Add all wires in a quantum register."""
if not isinstance(qreg, QuantumRegister):
raise DAGCircuitError("not a QuantumRegister instance.")
if qreg.name in self.qregs:
raise DAGCircuitError("duplicate register %s" % qreg.name)
self.qregs[qreg.name] = qreg
for j in range(qreg.size):
self._add_wire((qreg.name, j))
def add_creg(self, creg):
"""Add all wires in a classical register."""
if not isinstance(creg, ClassicalRegister):
raise DAGCircuitError("not a ClassicalRegister instance.")
if creg.name in self.cregs:
raise DAGCircuitError("duplicate register %s" % creg.name)
self.cregs[creg.name] = creg
for j in range(creg.size):
self._add_wire((creg.name, j), True)
def _add_wire(self, name, isClassical=False):
"""Add a qubit or bit to the circuit.
name is a (string,int) tuple containing register name and index
This adds a pair of in and out nodes connected by an edge.
"""
if name not in self.wire_type:
self.wire_type[name] = isClassical
self.node_counter += 1
self.input_map[name] = self.node_counter
self.node_counter += 1
self.output_map[name] = self.node_counter
in_node = self.input_map[name]
out_node = self.output_map[name]
self.multi_graph.add_edge(in_node, out_node)
self.multi_graph.node[in_node]["type"] = "in"
self.multi_graph.node[out_node]["type"] = "out"
self.multi_graph.node[in_node]["name"] = name
self.multi_graph.node[out_node]["name"] = name
self.multi_graph.adj[in_node][out_node][0]["name"] = name
else:
raise DAGCircuitError("duplicate wire %s" % name)
def add_basis_element(self, name, number_qubits,
number_classical=0, number_parameters=0):
"""Add an operation to the basis.
name is string label for operation
number_qubits is number of qubit arguments
number_classical is number of bit arguments
number_parameters is number of real parameters
The parameters (nq,nc,np) are ignored for the special case
when name = "barrier". The barrier instruction has a variable
number of qubit arguments.
"""
if name not in self.basis:
self.basis[name] = (
number_qubits,
number_classical,
number_parameters)
if name in self.gates:
if self.gates[name]["n_args"] != number_parameters or \
self.gates[name]["n_bits"] != number_qubits or number_classical != 0:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def add_gate_data(self, name, gatedata):
"""Add the definition of a gate.
gatedata is dict with fields:
"print" = True or False
"opaque" = True or False
"n_args" = number of real parameters
"n_bits" = number of qubits
"args" = list of parameter names
"bits" = list of qubit names
"body" = GateBody AST node
"""
if name not in self.gates:
self.gates[name] = gatedata
if name in self.basis:
if self.basis[name][0] != self.gates[name]["n_bits"] or \
self.basis[name][1] != 0 or \
self.basis[name][2] != self.gates[name]["n_args"]:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def _check_basis_data(self, name, qargs, cargs, params):
"""Check the arguments against the data for this operation.
name is a string
qargs is a list of tuples like ("q",0)
cargs is a list of tuples like ("c",0)
params is a list of strings that represent floats
"""
# Check that we have this operation
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
# Check the number of arguments matches the signature
if name in ["barrier"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if params:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
elif name in ["snapshot", "noise", "save", "load"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if not params:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
else:
if len(qargs) != self.basis[name][0]:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if len(cargs) != self.basis[name][1]:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if len(params) != self.basis[name][2]:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
def _check_condition(self, name, condition):
"""Verify that the condition is valid.
name is a string used for error reporting
condition is either None or a tuple (string,int) giving (creg,value)
"""
# Verify creg exists
if condition is not None and condition[0] not in self.cregs:
raise DAGCircuitError("invalid creg in condition for %s" % name)
def _check_bits(self, args, amap, bval):
"""Check the values of a list of (qu)bit arguments.
For each element A of args, check that amap contains A and
self.wire_type[A] equals bval.
args is a list of (regname,idx) tuples
amap is a dictionary keyed on (regname,idx) tuples
bval is boolean
"""
# Check for each wire
for q in args:
if q not in amap:
raise DAGCircuitError("(qu)bit %s not found" % (q,))
if self.wire_type[q] != bval:
raise DAGCircuitError("expected wire type %s for %s"
% (bval, q))
def _bits_in_condition(self, cond):
"""Return a list of bits (regname,idx) in the given condition.
cond is either None or a (regname,int) tuple specifying
a classical if condition.
"""
all_bits = []
if cond is not None:
all_bits.extend([(cond[0], j) for j in range(self.cregs[cond[0]].size)])
return all_bits
def _add_op_node(self, nname, nqargs, ncargs, nparams, ncondition, nop):
"""Add a new operation node to the graph and assign properties.
nname node name
nqargs quantum arguments
ncargs classical arguments
nparams parameters
ncondition classical condition (or None)
nop Instruction instance representing this operation
"""
# Add a new operation node to the graph
self.node_counter += 1
self.multi_graph.add_node(self.node_counter)
# Update that operation node's data
self.multi_graph.node[self.node_counter]["type"] = "op"
self.multi_graph.node[self.node_counter]["name"] = nname
self.multi_graph.node[self.node_counter]["qargs"] = nqargs
self.multi_graph.node[self.node_counter]["cargs"] = ncargs
self.multi_graph.node[self.node_counter]["params"] = nparams
self.multi_graph.node[self.node_counter]["condition"] = ncondition
self.multi_graph.node[self.node_counter]["op"] = nop
def apply_operation_back(self, name, qargs, cargs=None, params=None,
condition=None, op=None):
"""Apply an operation to the output of the circuit.
name is a string
qargs is a list of tuples like ("q",0)
cargs is a list of tuples like ("c",0)
params is a list of symbols that represent numbers
condition is either None or a tuple (string,int) giving (creg,value)
op is an Instruction instance representing this node
"""
cargs = cargs or []
params = params or []
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(name, qargs, cargs, params)
self._check_condition(name, condition)
self._check_bits(qargs, self.output_map, False)
self._check_bits(all_cbits, self.output_map, True)
self._add_op_node(name, qargs, cargs, params, condition, op)
# Add new in-edges from predecessors of the output nodes to the
# operation node while deleting the old in-edges of the output nodes
# and adding new edges from the operation node to each output node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.predecessors(self.output_map[q]))
if len(ie) != 1:
raise QISKitError("output node has multiple in-edges")
self.multi_graph.add_edge(ie[0], self.node_counter, name=q)
self.multi_graph.remove_edge(ie[0], self.output_map[q])
self.multi_graph.add_edge(
self.node_counter, self.output_map[q], name=q)
def apply_operation_front(self, name, qargs, cargs=None, params=None,
condition=None, op=None):
"""Apply an operation to the input of the circuit.
name is a string
qargs is a list of strings like "q[0]"
cargs is a list of strings like "c[0]"
params is a list of strings that represent floats
condition is either None or a tuple (string,int) giving (creg,value)
"""
cargs = cargs or []
params = params or []
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(name, qargs, cargs, params)
self._check_condition(name, condition)
self._check_bits(qargs, self.input_map, False)
self._check_bits(all_cbits, self.input_map, True)
self._add_op_node(name, qargs, cargs, params, condition, op)
# Add new out-edges to successors of the input nodes from the
# operation node while deleting the old out-edges of the input nodes
# and adding new edges to the operation node from each input node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = self.multi_graph.successors(self.input_map[q])
if len(ie) != 1:
raise QISKitError("input node has multiple out-edges")
self.multi_graph.add_edge(self.node_counter, ie[0], name=q)
self.multi_graph.remove_edge(self.input_map[q], ie[0])
self.multi_graph.add_edge(
self.input_map[q], self.node_counter, name=q)
def _make_union_basis(self, input_circuit):
"""Return a new basis map.
The new basis is a copy of self.basis with
new elements of input_circuit.basis added.
input_circuit is a DAGCircuit
"""
union_basis = self.basis.copy()
for g in input_circuit.basis:
if g not in union_basis:
union_basis[g] = input_circuit.basis[g]
if union_basis[g] != input_circuit.basis[g]:
raise DAGCircuitError("incompatible basis")
return union_basis
def _make_union_gates(self, input_circuit):
"""Return a new gates map.
The new gates are a copy of self.gates with
new elements of input_circuit.gates added.
input_circuit is a DAGCircuit
NOTE: gates in input_circuit that are also in self must
be *identical* to the gates in self
"""
union_gates = {}
for k, v in self.gates.items():
union_gates[k] = v
for k, v in input_circuit.gates.items():
if k not in union_gates:
union_gates[k] = v
if union_gates[k]["opaque"] != input_circuit.gates[k]["opaque"] or \
union_gates[k]["n_args"] != input_circuit.gates[k]["n_args"] or \
union_gates[k]["n_bits"] != input_circuit.gates[k]["n_bits"] or \
union_gates[k]["args"] != input_circuit.gates[k]["args"] or \
union_gates[k]["bits"] != input_circuit.gates[k]["bits"]:
raise DAGCircuitError("inequivalent gate definitions for %s"
% k)
return union_gates
def _check_wiremap_registers(self, wire_map, keyregs, valregs,
valreg=True):
"""Check that wiremap neither fragments nor leaves duplicate registers.
1. There are no fragmented registers. A register in keyregs
is fragmented if not all of its (qu)bits are renamed by wire_map.
2. There are no duplicate registers. A register is duplicate if
it appears in both self and keyregs but not in wire_map.
wire_map is a map from (regname,idx) in keyregs to (regname,idx)
in valregs
keyregs is a map from register names to Register objects
valregs is a map from register names to Register objects
valreg is a Bool, if False the method ignores valregs and does not
add regs for bits in the wire_map image that don't appear in valregs
Return the set of regs to add to self
"""
add_regs = set()
reg_frag_chk = {}
for k, v in keyregs.items():
reg_frag_chk[k] = {j: False for j in range(v.size)}
for k in wire_map.keys():
if k[0] in keyregs:
reg_frag_chk[k[0]][k[1]] = True
for k, v in reg_frag_chk.items():
rname = ",".join(map(str, k))
s = set(v.values())
if len(s) == 2:
raise DAGCircuitError("wire_map fragments reg %s" % rname)
elif s == set([False]):
if k in self.qregs or k in self.cregs:
raise DAGCircuitError("unmapped duplicate reg %s" % rname)
else:
# Add registers that appear only in keyregs
add_regs.add(keyregs[k])
else:
if valreg:
# If mapping to a register not in valregs, add it.
# (k,0) exists in wire_map because wire_map doesn't
# fragment k
if not wire_map[(k, 0)][0] in valregs:
size = max(map(lambda x: x[1], filter(lambda x: x[0] == wire_map[(k, 0)][0],
wire_map.values())))
qreg = QuantumRegister(wire_map[(k, 0)][0], size + 1)
add_regs.add(qreg)
return add_regs
def _check_wiremap_validity(self, wire_map, keymap, valmap, input_circuit):
"""Check that the wiremap is consistent.
Check that the wiremap refers to valid wires and that
those wires have consistent types.
wire_map is a map from (regname,idx) in keymap to (regname,idx)
in valmap
keymap is a map whose keys are wire_map keys
valmap is a map whose keys are wire_map values
input_circuit is a DAGCircuit
"""
for k, v in wire_map.items():
kname = ",".join(map(str, k))
vname = ",".join(map(str, v))
if k not in keymap:
raise DAGCircuitError("invalid wire mapping key %s" % kname)
if v not in valmap:
raise DAGCircuitError("invalid wire mapping value %s"
% vname)
if input_circuit.wire_type[k] != self.wire_type[v]:
raise DAGCircuitError("inconsistent wire_map at (%s,%s)"
% (kname, vname))
def _map_condition(self, wire_map, condition):
"""Use the wire_map dict to change the condition tuple's creg name.
wire_map is map from wires to wires
condition is a tuple (reg,int)
Returns the new condition tuple
"""
if condition is None:
n_condition = None
else:
# Map the register name, using fact that registers must not be
# fragmented by the wire_map (this must have been checked
# elsewhere)
bit0 = (condition[0], 0)
n_condition = (wire_map.get(bit0, bit0)[0], condition[1])
return n_condition
def compose_back(self, input_circuit, wire_map=None):
"""Apply the input circuit to the output of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of input qubits of the input circuit are mapped
to a subset of output qubits of this circuit.
wire_map[input_qubit_to_input_circuit] = output_qubit_of_self
"""
wire_map = wire_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map for duplicate values
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_wiremap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.input_map,
self.output_map, input_circuit)
# Compose
self.basis = union_basis
self.gates = union_gates
for node in nx.topological_sort(input_circuit.multi_graph):
nd = input_circuit.multi_graph.node[node]
if nd["type"] == "in":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["name"], nd["name"])
# the mapped wire should already exist
if m_name not in self.output_map:
raise QISKitError("wire (%s,%d) not in self" % (m_name[0], m_name[1]))
if nd["name"] not in input_circuit.wire_type:
raise QISKitError("inconsistent wire_type for (%s,%d) in input_circuit"
% (nd["name"][0], nd["name"][1]))
elif nd["type"] == "out":
# ignore output nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: wire_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x), nd["cargs"]))
self.apply_operation_back(nd["name"], m_qargs, m_cargs,
nd["params"], condition, nd["op"])
else:
raise QISKitError("bad node type %s" % nd["type"])
def compose_front(self, input_circuit, wire_map=None):
"""Apply the input circuit to the input of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of output qubits of the input circuit are mapped
to a subset of input qubits of
this circuit.
"""
wire_map = wire_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_wiremap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.output_map,
self.input_map, input_circuit)
# Compose
self.basis = union_basis
self.gates = union_gates
for n in reversed(list(nx.topological_sort(input_circuit.multi_graph))):
nd = input_circuit.multi_graph.node[n]
if nd["type"] == "out":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["name"], nd["name"])
# the mapped wire should already exist
if m_name not in self.input_map:
raise QISKitError("wire (%s,%d) not in self" % (m_name[0], m_name[1]))
if nd["name"] not in input_circuit.wire_type:
raise QISKitError(
"inconsistent wire_type for (%s,%d) in input_circuit"
% (nd["name"][0], nd["name"][1]))
elif nd["type"] == "in":
# ignore input nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: wire_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x), nd["cargs"]))
self.apply_operation_front(nd["name"], m_qargs, m_cargs,
nd["params"], condition, nd["op"])
else:
raise QISKitError("bad node type %s" % nd["type"])
def size(self):
"""Return the number of operations."""
return self.multi_graph.order() - 2 * len(self.wire_type)
def depth(self):
"""Return the circuit depth."""
if not nx.is_directed_acyclic_graph(self.multi_graph):
raise QISKitError("not a DAG")
return nx.dag_longest_path_length(self.multi_graph) - 1
def width(self):
"""Return the total number of qubits used by the circuit."""
return len(self.wire_type) - self.num_cbits()
def num_cbits(self):
"""Return the total number of bits used by the circuit."""
return list(self.wire_type.values()).count(True)
def num_tensor_factors(self):
"""Compute how many components the circuit can decompose into."""
return nx.number_weakly_connected_components(self.multi_graph)
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.gates[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.gates[name]["n_args"] > 0:
out += "(" + ",".join(self.gates[name]["args"]) + ")"
out += " " + ",".join(self.gates[name]["bits"])
if self.gates[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.gates[name]["body"].qasm() + "}"
return out
def qasm(self, decls_only=False, add_swap=False,
no_decls=False, qeflag=False, aliases=None, eval_symbols=False):
"""Return a string containing QASM for this circuit.
if qeflag is True, add a line to include "qelib1.inc"
and only generate gate code for gates not in qelib1.
if eval_symbols is True, evaluate all symbolic
expressions to their floating point representation.
if no_decls is True, only print the instructions.
if aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
if decls_only is True, only print the declarations.
if add_swap is True, add the definition of swap in terms of
cx if necessary.
"""
# TODO: some of the input flags are not needed anymore
# Rename qregs if necessary
if aliases:
qregdata = OrderedDict()
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
# Write top matter
if no_decls:
out = ""
else:
printed_gates = []
out = "OPENQASM 2.0;\n"
if qeflag:
out += "include \"qelib1.inc\";\n"
for k, v in qregdata.items():
out += "qreg %s[%d];\n" % (k, v.size)
for k, v in self.cregs.items():
out += "creg %s[%d];\n" % (k, v.size)
omit = ["U", "CX", "measure", "reset", "barrier"]
# TODO: dagcircuit shouldn't know about extensions
if qeflag:
qelib = ["u3", "u2", "u1", "cx", "id", "x", "y", "z", "h",
"s", "sdg", "t", "tdg", "cz", "cy", "ccx", "cu1",
"cu3", "swap", "cswap", "u0", "rx", "ry", "rz",
"ch", "crz", "rzz"]
omit.extend(qelib)
printed_gates.extend(qelib)
simulator_instructions = ["snapshot", "save", "load", "noise", "wait"]
omit.extend(simulator_instructions)
for k in self.basis.keys():
if k not in omit:
if not self.gates[k]["opaque"]:
calls = self.gates[k]["body"].calls()
for c in calls:
if c not in printed_gates:
out += self._gate_string(c) + "\n"
printed_gates.append(c)
if k not in printed_gates:
out += self._gate_string(k) + "\n"
printed_gates.append(k)
if add_swap and not qeflag and "cx" not in self.basis:
out += "gate cx a,b { CX a,b; }\n"
if add_swap and "swap" not in self.basis:
out += "gate swap a,b { cx a,b; cx b,a; cx a,b; }\n"
# Write the instructions
if not decls_only:
for n in nx.lexicographical_topological_sort(self.multi_graph):
nd = self.multi_graph.node[n]
if nd["type"] == "op":
if nd["condition"] is not None:
out += "if(%s==%d) " \
% (nd["condition"][0], nd["condition"][1])
if not nd["cargs"]:
nm = nd["name"]
if aliases:
qarglist = map(lambda x: aliases[x], nd["qargs"])
else:
qarglist = nd["qargs"]
qarg = ",".join(map(lambda x: "%s[%d]" % (x[0], x[1]),
qarglist))
if nd["params"]:
if eval_symbols:
param = ",".join(map(lambda x: str(sympy.N(x)),
nd["params"]))
else:
param = ",".join(map(lambda x: x.replace("**", "^"),
map(str, nd["params"])))
out += "%s(%s) %s;\n" % (nm, param, qarg)
else:
out += "%s %s;\n" % (nm, qarg)
else:
if nd["name"] == "measure":
if len(nd["cargs"]) != 1 or len(nd["qargs"]) != 1 \
or nd["params"]:
raise QISKitError("bad node data")
qname = nd["qargs"][0][0]
qindex = nd["qargs"][0][1]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
out += "measure %s[%d] -> %s[%d];\n" \
% (qname,
qindex,
nd["cargs"][0][0],
nd["cargs"][0][1])
else:
raise QISKitError("bad node data")
return out
def _check_wires_list(self, wires, name, input_circuit, condition=None):
"""Check that a list of wires satisfies some conditions.
wires = list of (register_name, index) tuples
name = name of operation
input_circuit = replacement circuit for operation
condition = None or (creg_name, value) if this instance of the
operation is classically controlled
The wires give an order for (qu)bits in the input circuit
that is replacing the named operation.
- no duplicate names
- correct length for named operation
- elements are wires of input_circuit
Raises an exception otherwise.
"""
if len(set(wires)) != len(wires):
raise DAGCircuitError("duplicate wires")
wire_tot = self.basis[name][0] + self.basis[name][1]
if condition is not None:
wire_tot += self.cregs[condition[0]].size
if len(wires) != wire_tot:
raise DAGCircuitError("expected %d wires, got %d"
% (wire_tot, len(wires)))
for w in wires:
if w not in input_circuit.wire_type:
raise DAGCircuitError("wire (%s,%d) not in input circuit"
% (w[0], w[1]))
def _make_pred_succ_maps(self, n):
"""Return predecessor and successor dictionaries.
These map from wire names to predecessor and successor
nodes for the operation node n in self.multi_graph.
"""
pred_map = {e[2]['name']: e[0] for e in
self.multi_graph.in_edges(nbunch=n, data=True)}
succ_map = {e[2]['name']: e[1] for e in
self.multi_graph.out_edges(nbunch=n, data=True)}
return pred_map, succ_map
def _full_pred_succ_maps(self, pred_map, succ_map, input_circuit,
wire_map):
"""Map all wires of the input circuit.
Map all wires of the input circuit to predecessor and
successor nodes in self, keyed on wires in self.
pred_map, succ_map dicts come from _make_pred_succ_maps
input_circuit is the input circuit
wire_map is the wire map from wires of input_circuit to wires of self
returns full_pred_map, full_succ_map
"""
full_pred_map = {}
full_succ_map = {}
for w in input_circuit.input_map:
# If w is wire mapped, find the corresponding predecessor
# of the node
if w in wire_map:
full_pred_map[wire_map[w]] = pred_map[wire_map[w]]
full_succ_map[wire_map[w]] = succ_map[wire_map[w]]
else:
# Otherwise, use the corresponding output nodes of self
# and compute the predecessor.
full_succ_map[w] = self.output_map[w]
full_pred_map[w] = self.multi_graph.predecessors(
self.output_map[w])[0]
if len(list(self.multi_graph.predecessors(self.output_map[w]))) != 1:
raise QISKitError(
"too many predecessors for (%s,%d) output node" % (w[0], w[1])
)
return full_pred_map, full_succ_map
def node_nums_in_topological_order(self):
"""
Returns the nodes (their ids) in topological order.
Returns:
List(int): The list of node numbers in topological order
"""
return nx.topological_sort(self.multi_graph)
def substitute_circuit_all(self, name, input_circuit, wires=None):
"""Replace every occurrence of named operation with input_circuit."""
# TODO: rewrite this method to call substitute_circuit_one
wires = wires or None
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
self._check_wires_list(wires, name, input_circuit)
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: ("", 0) for w in wires}
add_qregs = self._check_wiremap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Iterate through the nodes of self and replace the selected nodes
# by iterating through the input_circuit, constructing and
# checking the validity of the wire_map for each replacement
# NOTE: We do not replace conditioned gates. One way to implement
# this later is to add or update the conditions of each gate
# that we add from the input_circuit.
self.basis = union_basis
self.gates = union_gates
for n in self.node_nums_in_topological_order():
nd = self.multi_graph.node[n]
if nd["type"] == "op" and nd["name"] == name:
if nd["condition"] is None:
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"], nd["cargs"]]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map, input_circuit)
pred_map, succ_map = self._make_pred_succ_maps(n)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(n)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map,
md["condition"])
m_qargs = [wire_map.get(x, x) for x in md["qargs0"]]
m_cargs = [wire_map.get(x, x) for x in md["cargs0"]]
self._add_op_node(md["name"], m_qargs, m_cargs,
md["params"], condition, md["op"])
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter, name=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w], full_succ_map[w],
name=w)
o_pred = list(self.multi_graph.predecessors(
self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise QISKitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise QISKitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(
p[0], self.output_map[w])
def substitute_circuit_one(self, node, input_circuit, wires=None):
"""Replace one node with input_circuit.
node is a reference to a node of self.multi_graph of type "op"
input_circuit is a DAGCircuit
"""
wires = wires or None
nd = self.multi_graph.node[node]
name = nd["name"]
self._check_wires_list(wires, name, input_circuit, nd["condition"])
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: ("", 0) for w in wires}
add_qregs = self._check_wiremap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Replace the node by iterating through the input_circuit.
# Constructing and checking the validity of the wire_map.
# If a gate is conditioned, we expect the replacement subcircuit
# to depend on those control bits as well.
self.basis = union_basis
self.gates = union_gates
if nd["type"] != "op":
raise DAGCircuitError("expected node type \"op\", got %s"
% nd["type"])
condition_bit_list = self._bits_in_condition(nd["condition"])
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"],
nd["cargs"],
condition_bit_list]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map, input_circuit)
pred_map, succ_map = self._make_pred_succ_maps(node)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(node)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map, md["condition"])
m_qargs = list(map(lambda x: wire_map.get(x, x),
md["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x),
md["cargs"]))
self._add_op_node(md["name"], m_qargs, m_cargs,
md["params"], condition, md["op"])
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter,
name=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(
full_pred_map[w], full_succ_map[w], name=w)
o_pred = list(self.multi_graph.predecessors(self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise QISKitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise QISKitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(p[0], self.output_map[w])
def get_named_nodes(self, name):
"""Get the set of "op" node ids with the given name."""
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
# We need to instantiate the full list now because the underlying multi_graph
# may change when users iterate over the named nodes.
return {node_id for node_id, data in self.multi_graph.nodes(data=True)
if data["type"] == "op" and data["name"] == name}
def get_cnot_nodes(self):
"""Get the set of Cnot."""
cx_names = ['cx', 'CX']
cxs_nodes = []
for cx_name in cx_names:
if cx_name in self.basis:
for cx_id in self.get_named_nodes(cx_name):
cxs_nodes.append(self.multi_graph.node[cx_id])
return cxs_nodes
def _remove_op_node(self, n):
"""Remove an operation node n.
Add edges from predecessors to successors.
"""
pred_map, succ_map = self._make_pred_succ_maps(n)
self.multi_graph.remove_node(n)
for w in pred_map.keys():
self.multi_graph.add_edge(pred_map[w], succ_map[w], name=w)
def remove_ancestors_of(self, node):
"""Remove all of the ancestor operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
# TODO: probably better to do all at once using
# multi_graph.remove_nodes_from; same for related functions ...
for n in anc:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_descendants_of(self, node):
"""Remove all of the descendant operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
for n in dec:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nonancestors_of(self, node):
"""Remove all of the non-ancestors operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(anc))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nondescendants_of(self, node):
"""Remove all of the non-descendants operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(dec))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def layers(self):
"""Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit.
A layer is a circuit whose gates act on disjoint qubits, i.e.
a layer has depth 1. The total number of layers equals the
circuit depth d. The layers are indexed from 0 to d-1 with the
earliest layer at index 0. The layers are constructed using a
greedy algorithm. Each returned layer is a dict containing
{"graph": circuit graph, "partition": list of qubit lists}.
TODO: Gates that use the same cbits will end up in different
layers as this is currently implemented. This may not be
the desired behavior.
"""
graph_layers = self.multigraph_layers()
try:
next(graph_layers) # Remove input nodes
except StopIteration:
return
def nodes_data(nodes):
"""Construct full nodes from just node ids."""
return ((node_id, self.multi_graph.nodes[node_id]) for node_id in nodes)
for graph_layer in graph_layers:
# Get the op nodes from the layer, removing any input and output nodes.
op_nodes = [node for node in nodes_data(graph_layer) if node[1]["type"] == "op"]
# Stop yielding once there are no more op_nodes in a layer.
if not op_nodes:
return
# Construct a shallow copy of self
new_layer = copy.copy(self)
new_layer.multi_graph = nx.MultiDiGraph()
new_layer.multi_graph.add_nodes_from(nodes_data(self.input_map.values()))
new_layer.multi_graph.add_nodes_from(nodes_data(self.output_map.values()))
# The quantum registers that have an operation in this layer.
support_list = [
op_node[1]["qargs"]
for op_node in op_nodes
if op_node[1]["name"] not in {"barrier", "snapshot", "save", "load", "noise"}
]
new_layer.multi_graph.add_nodes_from(op_nodes)
# Now add the edges to the multi_graph
# By default we just wire inputs to the outputs.
wires = {self.input_map[register]: self.output_map[register]
for register in self.wire_type}
# Wire inputs to op nodes, and op nodes to outputs.
for op_node in op_nodes:
args = self._bits_in_condition(op_node[1]["condition"]) \
+ op_node[1]["cargs"] + op_node[1]["qargs"]
arg_ids = (self.input_map[arg] for arg in args) # map from ("q",0) to node id.
for arg_id in arg_ids:
wires[arg_id], wires[op_node[0]] = op_node[0], wires[arg_id]
# Add wiring to/from the operations and between unused inputs & outputs.
new_layer.multi_graph.add_edges_from(wires.items())
yield {"graph": new_layer, "partition": support_list}
def serial_layers(self):
"""Yield a layer for all gates of this circuit.
A serial layer is a circuit with one gate. The layers have the
same structure as in layers().
"""
for n in self.node_nums_in_topological_order():
nxt_nd = self.multi_graph.node[n]
if nxt_nd["type"] == "op":
new_layer = DAGCircuit()
for qreg in self.qregs.values():
new_layer.add_qreg(qreg)
for creg in self.cregs.values():
new_layer.add_creg(creg)
new_layer.basis = self.basis.copy()
new_layer.gates = self.gates.copy()
# Save the support of the operation we add to the layer
support_list = []
# Operation data
qa = copy.copy(nxt_nd["qargs"])
ca = copy.copy(nxt_nd["cargs"])
pa = copy.copy(nxt_nd["params"])
co = copy.copy(nxt_nd["condition"])
op = copy.copy(nxt_nd["op"])
_ = self._bits_in_condition(co)
# Add node to new_layer
new_layer.apply_operation_back(nxt_nd["name"],
qa, ca, pa, co, op)
# Add operation to partition
if nxt_nd["name"] not in ["barrier",
"snapshot", "save", "load", "noise"]:
# support_list.append(list(set(qa) | set(ca) | set(cob)))
support_list.append(list(qa))
l_dict = {"graph": new_layer, "partition": support_list}
yield l_dict
def multigraph_layers(self):
"""Yield layers of the multigraph."""
predecessor_count = dict() # Dict[node, predecessors not visited]
cur_layer = [node for node in self.input_map.values()]
yield cur_layer
next_layer = []
while cur_layer:
for node in cur_layer:
# Count multiedges with multiplicity.
for successor in self.multi_graph.successors(node):
multiplicity = self.multi_graph.number_of_edges(node, successor)
if successor in predecessor_count:
predecessor_count[successor] -= multiplicity
else:
predecessor_count[successor] = \
self.multi_graph.in_degree(successor) - multiplicity
if predecessor_count[successor] == 0:
next_layer.append(successor)
del predecessor_count[successor]
yield next_layer
cur_layer = next_layer
next_layer = []
def collect_runs(self, namelist):
"""Return a set of runs of "op" nodes with the given names.
For example, "... h q[0]; cx q[0],q[1]; cx q[0],q[1]; h q[1]; .."
would produce the tuple of cx nodes as an element of the set returned
from a call to collect_runs(["cx"]). If instead the cx nodes were
"cx q[0],q[1]; cx q[1],q[0];", the method would still return the
pair in a tuple. The namelist can contain names that are not
in the circuit's basis.
Nodes must have only one successor to continue the run.
"""
group_list = []
# Iterate through the nodes of self in topological order
# and form tuples containing sequences of gates
# on the same qubit(s).
ts = list(self.node_nums_in_topological_order())
nodes_seen = dict(zip(ts, [False] * len(ts)))
for node in ts:
nd = self.multi_graph.node[node]
if nd["type"] == "op" and nd["name"] in namelist \
and not nodes_seen[node]:
group = [node]
nodes_seen[node] = True
s = list(self.multi_graph.successors(node))
while len(s) == 1 and \
self.multi_graph.node[s[0]]["type"] == "op" and \
self.multi_graph.node[s[0]]["name"] in namelist:
group.append(s[0])
nodes_seen[s[0]] = True
s = list(self.multi_graph.successors(s[0]))
if len(group) > 1:
group_list.append(tuple(group))
return set(group_list)
def count_ops(self):
"""Count the occurrences of operation names.
Returns a dictionary of counts keyed on the operation name.
"""
op_dict = {}
for node in self.node_nums_in_topological_order():
nd = self.multi_graph.node[node]
name = nd["name"]
if nd["type"] == "op":
if name not in op_dict:
op_dict[name] = 1
else:
op_dict[name] += 1
return op_dict
def properties(self):
"""Return a dictionary of circuit properties."""
summary = {"size": self.size(),
"depth": self.depth(),
"width": self.width(),
"bits": self.num_cbits(),
"factors": self.num_tensor_factors(),
"operations": self.count_ops()}
return summary
@staticmethod
def fromQuantumCircuit(circuit, expand_gates=True):
"""Build a ``DAGCircuit`` object from a ``QuantumCircuit``.
Args:
circuit (QuantumCircuit): the input circuit.
expand_gates (bool): if ``False``, none of the gates are expanded,
i.e. the gates that are defined in the circuit are included in
the DAG basis.
Return:
DAGCircuit: the DAG representing the input circuit.
"""
dagcircuit = DAGCircuit()
dagcircuit.name = circuit.name
for register in circuit.qregs:
dagcircuit.add_qreg(register)
for register in circuit.cregs:
dagcircuit.add_creg(register)
# Add user gate definitions
for name, data in circuit.definitions.items():
dagcircuit.add_basis_element(name, data["n_bits"], 0,
data["n_args"])
dagcircuit.add_gate_data(name, data)
# Add instructions
builtins = {
"U": ["U", 1, 0, 3],
"CX": ["CX", 2, 0, 0],
"measure": ["measure", 1, 1, 0],
"reset": ["reset", 1, 0, 0],
"barrier": ["barrier", -1, 0, 0]
}
# Add simulator instructions
simulator_instructions = {
"snapshot": ["snapshot", -1, 0, 1],
"save": ["save", -1, 0, 1],
"load": ["load", -1, 0, 1],
"noise": ["noise", -1, 0, 1]
}
for main_instruction in circuit.data:
# TODO: generate definitions and nodes for CompositeGates,
# for now simply drop their instructions into the DAG
instruction_list = []
is_composite = isinstance(main_instruction,
_compositegate.CompositeGate)
if is_composite and expand_gates:
instruction_list = main_instruction.instruction_list()
else:
instruction_list.append(main_instruction)
for instruction in instruction_list:
# Add OpenQASM built-in gates on demand
if instruction.name in builtins:
dagcircuit.add_basis_element(*builtins[instruction.name])
# Add simulator extension instructions
if instruction.name in simulator_instructions:
dagcircuit.add_basis_element(*simulator_instructions[instruction.name])
# Separate classical arguments to measurements
if instruction.name == "measure":
qargs = [(instruction.qargs[0][0].name, instruction.qargs[0][1])]
cargs = [(instruction.cargs[0][0].name, instruction.cargs[0][1])]
else:
qargs = list(map(lambda x: (x[0].name, x[1]), instruction.qargs))
cargs = []
# Get arguments for classical control (if any)
if instruction.control is None:
control = None
else:
control = (instruction.control[0].name, instruction.control[1])
if is_composite and not expand_gates:
is_inverse = instruction.inverse_flag
name = instruction.name if not is_inverse else instruction.inverse_name
else:
name = instruction.name
dagcircuit.apply_operation_back(name, qargs, cargs,
instruction.param,
control, instruction)
return dagcircuit
<|code_end|>
qiskit/transpiler/passes/__init__.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Utils for transpiler."""
from .cx_cancellation import CXCancellation
from .fixed_point import FixedPoint
from .check_map import CheckMap
<|code_end|>
qiskit/transpiler/passes/check_map.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
This pass checks if a DAG is mapped to a coupling map.
"""
from qiskit.transpiler._basepasses import AnalysisPass
from qiskit.mapper import Layout
class CheckMap(AnalysisPass):
"""
Checks if a DAGCircuit is mapped to `coupling_map`.
"""
def __init__(self, coupling_map, initial_layout=None):
"""
Checks if a DAGCircuit is mapped to `coupling_map`.
Args:
coupling_map (Coupling): Directed graph represented a coupling map.
initial_layout (Layout): The initial layout of the DAG to analyze.
"""
super().__init__()
self.layout = initial_layout
self.coupling_map = coupling_map
def run(self, dag):
"""
If `dag` is mapped to coupling_map, the property `is_mapped` is
set to True (or to False otherwise).
Args:
dag (DAGCircuit): DAG to map.
"""
if self.layout is None:
self.layout = Layout()
for qreg in dag.qregs.values():
self.layout.add_register(qreg)
self.property_set['is_mapped'] = None
for layer in dag.serial_layers():
subdag = layer['graph']
for a_cx in subdag.get_cnot_nodes():
physical_q0 = ('q', self.layout[a_cx['op'].qargs[0]])
physical_q1 = ('q', self.layout[a_cx['op'].qargs[1]])
if self.coupling_map.distance(physical_q0, physical_q1) != 1:
self.property_set['is_mapped'] = False
return
self.property_set['is_mapped'] = True
<|code_end|>
|
Bug in drawing conditionals in latex and matplotlib
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
After #1278 and #1276, the latex and matplotlib have a bug in drawing conditional gates:
This code:
```python
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(3, 'q')
c = ClassicalRegister(1, 'c')
circ = QuantumCircuit(q, c)
circ.u2(1.57, 0.7, q[0])
circ.measure(q[0], c[0])
circ.u1(0.1, q[1]).c_if(c, 1)
circ.draw(output='latex')
```
was drawn correctly before these 2 recent PR merges:

but with this patch the conditional vertical wire is gone:

This is also an issue with the mpl drawer:

But the text drawer is fine:
```
q_2: |0>──────────────────────────────
┌─────────┐
q_1: |0>───────────────────┤ U1(0.1) ├
┌──────────────┐┌─┐└────┬────┘
q_0: |0>┤ U2(1.57,0.7) ├┤M├─────┼─────
└──────────────┘└╥┘┌────┴────┐
c_0: 0 ═════════════════╩═╡ = 1 ╞
└─────────┘
```
|
qiskit/tools/visualization/_latex.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""latex circuit visualization backends."""
import collections
import io
import itertools
import json
import math
import operator
import re
import numpy as np
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _qcstyle
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, qregs, cregs, ops, scale, style=None,
plot_barriers=True, reverse_bits=False):
"""
Args:
qregs (list): A list of tuples for the quantum registers
cregs (list): A list of tuples for the classical registers
ops (list): A list of dicts where each entry is a operation from
the circuit.
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
"""
# style sheet
self._style = _qcstyle.QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.ops = ops
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
self.reverse_bits = reverse_bits
self.plot_barriers = plot_barriers
#################################
self.qregs = collections.OrderedDict(_get_register_specs(qregs))
self.qubit_list = qregs
self.ordered_regs = qregs + cregs
self.cregs = collections.OrderedDict(_get_register_specs(cregs))
self.clbit_list = cregs
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = io.StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\' + '\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
VisualizationError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.ops:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's',
'sdg', 't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy',
'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image
# scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['params']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float, str(arg))
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
if len(op['cargs']) != 1 or len(op['qargs']) != 1:
raise _error.VisualizationError("bad operation record")
if 'conditional' in op:
raise _error.VisualizationError(
'conditional measures currently not supported.')
qindex = self._get_qubit_index(op['qargs'][0])
cindex = self._get_clbit_index(op['cargs'][0])
qname, qindex = self.total_2_register_index(
qindex, self.qregs)
cname, cindex = self.total_2_register_index(
cindex, self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op:
raise _error.VisualizationError(
'conditional reset currently not supported.')
qindex = self._get_qubit_index(op['qargs'][0])
qname, qindex = self.total_2_register_index(
qindex, self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
raise _error.VisualizationError("bad node data")
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns + 1, math.ceil(sum_column_widths) + 4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet
# (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def _get_qubit_index(self, qubit):
"""Get the index number for a quantum bit
Args:
qubit (tuple): The tuple of the bit of the form
(register_name, bit_number)
Returns:
int: The index in the bit list
Raises:
VisualizationError: If the bit isn't found
"""
for i, bit in enumerate(self.qubit_list):
if qubit == bit:
qindex = i
break
else:
raise _error.VisualizationError(
"unable to find bit for operation")
return qindex
def _get_clbit_index(self, clbit):
"""Get the index number for a classical bit
Args:
clbit (tuple): The tuple of the bit of the form
(register_name, bit_number)
Returns:
int: The index in the bit list
Raises:
VisualizationError: If the bit isn't found
"""
for i, bit in enumerate(self.clbit_list):
if clbit == bit:
cindex = i
break
else:
raise _error.VisualizationError(
"unable to find bit for operation")
return cindex
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above
example, index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.ops):
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(int(op['conditional']['val'], 16),
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier', 'snapshot', 'load',
'save', 'noise']:
nm = op['name']
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'conditional' in op:
mask = int(op['conditional']['mask'], 16)
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["params"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["params"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["params"][0], op["params"][1])
elif nm == "u3":
self._latex[pos_1][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["params"][0],
op["params"][1],
op["params"][2]))
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["params"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["params"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["params"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["params"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["params"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["params"][0], op["params"][1])
elif nm == "u3":
self._latex[pos_1][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["params"][0],
op["params"][1],
op["params"][2]))
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["params"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["params"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["params"][0])
elif nm == "reset":
self._latex[pos_1][columns] = (
"\\push{\\rule{.6em}{0em}\\ket{0}\\"
"rule{.2em}{0em}} \\qw")
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'conditional' in op:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["params"][0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["params"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["params"][0],
op["params"][1],
op["params"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["params"][0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["params"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["params"][0],
op["params"][1],
op["params"][2]))
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'conditional' in op:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-0.65em]{')
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(
pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-0.65em]{')
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(
pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
if (len(op['cargs']) != 1
or len(op['qargs']) != 1
or op['params']):
raise _error.VisualizationError("bad operation record")
if 'conditional' in op:
raise _error.VisualizationError(
"If controlled measures currently not supported.")
qindex = self._get_qubit_index(op['qargs'][0])
cindex = self._get_clbit_index(op['cargs'][0])
qname, qindex = self.total_2_register_index(
qindex, self.qregs)
cname, cindex = self.total_2_register_index(
cindex, self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise _error.VisualizationError(
'Error during Latex building: %s' % str(e))
elif op['name'] in ["barrier", 'snapshot', 'load', 'save',
'noise']:
if self.plot_barriers:
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qargs']) - 1
self._latex[start][columns] += " \\barrier{" + str(
span) + "}"
else:
raise _error.VisualizationError("bad node data")
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
return origin - 1
def _get_register_specs(bit_labels):
"""Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = itertools.groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
<|code_end|>
qiskit/tools/visualization/_matplotlib.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""mpl circuit visualization backend."""
import collections
import fractions
import itertools
import json
import logging
import math
import numpy as np
try:
from matplotlib import patches
from matplotlib import pyplot as plt
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _qcstyle
from qiskit.tools.visualization import _utils
logger = logging.getLogger(__name__)
Register = collections.namedtuple('Register', 'name index')
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
scale=1.0, style=None, plot_barriers=True,
reverse_bits=False):
if not HAS_MATPLOTLIB:
raise ImportError('The class MatplotlibDrawer needs matplotlib. '
'Run "pip install matplotlib" before.')
self._ast = None
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = collections.OrderedDict()
self._creg_dict = collections.OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = _qcstyle.QCStyle()
self.plot_barriers = plot_barriers
self.reverse_bits = reverse_bits
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False,
labelleft=False, labelright=False)
def parse_circuit(self, circuit):
qregs, cregs, ops = _utils._get_instructions(
circuit, reversebits=self.reverse_bits)
self._registers(cregs, qregs)
self._ops = ops
def _registers(self, creg, qreg):
# NOTE: formats of clbit and qubit are different!
self._creg = []
for e in creg:
self._creg.append(Register(name=e[0], index=e[1]))
self._qreg = []
for e in qreg:
self._qreg.append(Register(name=e[0], index=e[1]))
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(
xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center',
va='center', fontsize=self._style.fs,
color=self._style.gt, clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.sc, clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7,
height=HIG * 0.7, theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID],
[qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy + 0.35 * WID], lc=self._style.cc,
ls=self._style.cline)
arrowhead = patches.Polygon(((cx - 0.20 * WID, cy + 0.35 * WID),
(cx + 0.20 * WID, cy + 0.35 * WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'],
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
plt.close(self.figure)
return self.figure
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(itertools.zip_longest(
self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
self._cond['n_lines'] += 1
idx += 1
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left',
va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc,
ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(
itertools.zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qargs' in op.keys():
q_idxs = []
for qarg in op['qargs']:
for index, reg in self._qreg_dict.items():
if (reg['group'] == qarg[0] and
reg['index'] == qarg[1]):
q_idxs.append(index)
break
else:
q_idxs = []
# get creg index
if 'cargs' in op.keys():
c_idxs = []
for carg in op['cargs']:
for index, reg in self._creg_dict.items():
if (reg['group'] == carg[0] and
reg['index'] == carg[1]):
c_idxs.append(index)
break
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or 'conditional' in op.keys() or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied),
max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(
this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] in [
'barrier', 'snapshot', 'load', 'save',
'noise'] and not self.plot_barriers:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg coordinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'conditional' in op.keys():
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for
ii in self._creg_dict]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
mask = int(op['conditional']['mask'], 16)
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
val = int(op['conditional']['val'], 16)
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, op['conditional']['val'])
self._line(qreg_t, creg_b, lc=self._style.cc,
ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] in ['barrier', 'snapshot', 'load', 'save',
'noise']:
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self.plot_barriers:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise _error.VisualizationError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (
self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.tc, clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if math.isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if math.isclose(math.fmod(abs_val, 1.0),
0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
if 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if math.isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return fractions.Fraction(i, j)
return None
<|code_end|>
|
qiskit/tools/visualization/_latex.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""latex circuit visualization backends."""
import collections
import io
import itertools
import json
import math
import operator
import re
import numpy as np
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _qcstyle
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, qregs, cregs, ops, scale, style=None,
plot_barriers=True, reverse_bits=False):
"""
Args:
qregs (list): A list of tuples for the quantum registers
cregs (list): A list of tuples for the classical registers
ops (list): A list of dicts where each entry is a operation from
the circuit.
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
"""
# style sheet
self._style = _qcstyle.QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.ops = ops
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
self.reverse_bits = reverse_bits
self.plot_barriers = plot_barriers
#################################
self.qregs = collections.OrderedDict(_get_register_specs(qregs))
self.qubit_list = qregs
self.ordered_regs = qregs + cregs
self.cregs = collections.OrderedDict(_get_register_specs(cregs))
self.clbit_list = cregs
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = io.StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\' + '\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
VisualizationError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.ops:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's',
'sdg', 't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy',
'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image
# scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['params']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float, str(arg))
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
if len(op['cargs']) != 1 or len(op['qargs']) != 1:
raise _error.VisualizationError("bad operation record")
if 'condition' in op and op['condition']:
raise _error.VisualizationError(
'conditional measures currently not supported.')
qindex = self._get_qubit_index(op['qargs'][0])
cindex = self._get_clbit_index(op['cargs'][0])
qname, qindex = self.total_2_register_index(
qindex, self.qregs)
cname, cindex = self.total_2_register_index(
cindex, self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op and op['condition']:
raise _error.VisualizationError(
'conditional reset currently not supported.')
qindex = self._get_qubit_index(op['qargs'][0])
qname, qindex = self.total_2_register_index(
qindex, self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
raise _error.VisualizationError("bad node data")
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns + 1, math.ceil(sum_column_widths) + 4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet
# (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def _get_qubit_index(self, qubit):
"""Get the index number for a quantum bit
Args:
qubit (tuple): The tuple of the bit of the form
(register_name, bit_number)
Returns:
int: The index in the bit list
Raises:
VisualizationError: If the bit isn't found
"""
for i, bit in enumerate(self.qubit_list):
if qubit == bit:
qindex = i
break
else:
raise _error.VisualizationError(
"unable to find bit for operation")
return qindex
def _get_clbit_index(self, clbit):
"""Get the index number for a classical bit
Args:
clbit (tuple): The tuple of the bit of the form
(register_name, bit_number)
Returns:
int: The index in the bit list
Raises:
VisualizationError: If the bit isn't found
"""
for i, bit in enumerate(self.clbit_list):
if clbit == bit:
cindex = i
break
else:
raise _error.VisualizationError(
"unable to find bit for operation")
return cindex
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above
example, index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _get_mask(self, creg_name):
mask = 0
for index, cbit in enumerate(self.clbit_list):
if creg_name == cbit[0]:
mask |= (1 << index)
return mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.ops):
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(op['condition'][1],
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier', 'snapshot', 'load',
'save', 'noise']:
nm = op['name']
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["params"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["params"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["params"][0], op["params"][1])
elif nm == "u3":
self._latex[pos_1][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["params"][0],
op["params"][1],
op["params"][2]))
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["params"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["params"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["params"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["params"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["params"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["params"][0], op["params"][1])
elif nm == "u3":
self._latex[pos_1][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["params"][0],
op["params"][1],
op["params"][2]))
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["params"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["params"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["params"][0])
elif nm == "reset":
self._latex[pos_1][columns] = (
"\\push{\\rule{.6em}{0em}\\ket{0}\\"
"rule{.2em}{0em}} \\qw")
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'condition' in op and op['condition']:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["params"][0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["params"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["params"][0],
op["params"][1],
op["params"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["params"][0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["params"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["params"][0],
op["params"][1],
op["params"][2]))
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'condition' in op and op['condition']:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-0.65em]{')
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(
pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-0.65em]{')
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(
pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
if (len(op['cargs']) != 1
or len(op['qargs']) != 1
or op['params']):
raise _error.VisualizationError("bad operation record")
if 'condition' in op and op['condition']:
raise _error.VisualizationError(
"If controlled measures currently not supported.")
qindex = self._get_qubit_index(op['qargs'][0])
cindex = self._get_clbit_index(op['cargs'][0])
qname, qindex = self.total_2_register_index(
qindex, self.qregs)
cname, cindex = self.total_2_register_index(
cindex, self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise _error.VisualizationError(
'Error during Latex building: %s' % str(e))
elif op['name'] in ["barrier", 'snapshot', 'load', 'save',
'noise']:
if self.plot_barriers:
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qargs']) - 1
self._latex[start][columns] += " \\barrier{" + str(
span) + "}"
else:
raise _error.VisualizationError("bad node data")
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
return origin - 1
def _get_register_specs(bit_labels):
"""Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = itertools.groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
<|code_end|>
qiskit/tools/visualization/_matplotlib.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""mpl circuit visualization backend."""
import collections
import fractions
import itertools
import json
import logging
import math
import numpy as np
try:
from matplotlib import patches
from matplotlib import pyplot as plt
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _qcstyle
from qiskit.tools.visualization import _utils
logger = logging.getLogger(__name__)
Register = collections.namedtuple('Register', 'name index')
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
scale=1.0, style=None, plot_barriers=True,
reverse_bits=False):
if not HAS_MATPLOTLIB:
raise ImportError('The class MatplotlibDrawer needs matplotlib. '
'Run "pip install matplotlib" before.')
self._ast = None
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = collections.OrderedDict()
self._creg_dict = collections.OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = _qcstyle.QCStyle()
self.plot_barriers = plot_barriers
self.reverse_bits = reverse_bits
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False,
labelleft=False, labelright=False)
def parse_circuit(self, circuit):
qregs, cregs, ops = _utils._get_instructions(
circuit, reversebits=self.reverse_bits)
self._registers(cregs, qregs)
self._ops = ops
def _registers(self, creg, qreg):
# NOTE: formats of clbit and qubit are different!
self._creg = []
for e in creg:
self._creg.append(Register(name=e[0], index=e[1]))
self._qreg = []
for e in qreg:
self._qreg.append(Register(name=e[0], index=e[1]))
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(
xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center',
va='center', fontsize=self._style.fs,
color=self._style.gt, clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.sc, clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7,
height=HIG * 0.7, theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID],
[qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy + 0.35 * WID], lc=self._style.cc,
ls=self._style.cline)
arrowhead = patches.Polygon(((cx - 0.20 * WID, cy + 0.35 * WID),
(cx + 0.20 * WID, cy + 0.35 * WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'],
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
plt.close(self.figure)
return self.figure
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(itertools.zip_longest(
self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
self._cond['n_lines'] += 1
idx += 1
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left',
va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc,
ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(
itertools.zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qargs' in op.keys():
q_idxs = []
for qarg in op['qargs']:
for index, reg in self._qreg_dict.items():
if (reg['group'] == qarg[0] and
reg['index'] == qarg[1]):
q_idxs.append(index)
break
else:
q_idxs = []
# get creg index
if 'cargs' in op.keys():
c_idxs = []
for carg in op['cargs']:
for index, reg in self._creg_dict.items():
if (reg['group'] == carg[0] and
reg['index'] == carg[1]):
c_idxs.append(index)
break
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or (
'condition' in op.keys() and op['condition']) or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied),
max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(
this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] in [
'barrier', 'snapshot', 'load', 'save',
'noise'] and not self.plot_barriers:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg coordinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'params' in op.keys():
param = self.param_parse(op['params'], self._style.pimode)
else:
param = None
# conditional gate
if 'condition' in op.keys() and op['condition']:
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for
ii in self._creg_dict]
mask = 0
for index, cbit in enumerate(self._creg):
if cbit.name == op['condition'][0]:
mask |= (1 << index)
val = op['condition'][1]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, hex(val))
self._line(qreg_t, creg_b, lc=self._style.cc,
ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] in ['barrier', 'snapshot', 'load', 'save',
'noise']:
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self.plot_barriers:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise _error.VisualizationError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (
self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.tc, clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if math.isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if math.isclose(math.fmod(abs_val, 1.0),
0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
if 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if math.isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return fractions.Fraction(i, j)
return None
<|code_end|>
|
_has_connection('https://qvisualization.mybluemix.net/', port=443) returns False
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Information
- **Qiskit Terra version**: master
- **Python version**: 3.7
- **Operating system**: OSX
### What is the current behavior?
Interactive visualizations do not work because `_has_connection('https://qvisualization.mybluemix.net/', port=443)` is returning `False`.
### Steps to reproduce the problem
Try it.
### What is the expected behavior?
### Suggested solutions
|
qiskit/tools/visualization/__init__.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""Main Qiskit visualization methods."""
import sys
from qiskit._util import _has_connection
from ._circuit_visualization import circuit_drawer, plot_circuit, generate_latex_source, \
latex_circuit_drawer, matplotlib_circuit_drawer, _text_circuit_drawer, qx_color_scheme
from ._error import VisualizationError
from ._matplotlib import HAS_MATPLOTLIB
from ._dag_visualization import dag_drawer
if HAS_MATPLOTLIB:
from matplotlib import pyplot as plt
else:
plt = None
_MSG = 'The function %s needs matplotlib. Run "pip install matplotlib" before.'
INTERACTIVE = False
if ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
if _has_connection('https://qvisualization.mybluemix.net/', 443):
INTERACTIVE = True
def plot_state(rho, method='city', filename=None, options=None, mode=None,
show=False):
"""Plot a quantum state.
This function provides several methods to plot a quantum state. There are
two rendering backends either done in python using matplotlib or using js
in a jupyter notebook using an externally hosted graphing library. To use
the js you need to be running in jupyter and have network connectivity to
the external server where the js library is hosted.
Args:
rho (ndarray): statevector or density matrix representation of a
quantum state
method (str): The plotting method to use. Valid choices are:
- 'city': Plots the cityscape, two 3d bargraphs of the mixed state
rho) of the quantum state. This is the default.
- 'paulivec': Plot the paulivec representation, a bar graph of the
mixed state rho over the pauli matrices, of a quantum
state
- 'qsphere': Plot the qsphere representation of the quantum state
- 'bloch': Plot the bloch vector for each qubit in the quantum state
- 'wigner': Plot the equal angle slice spin Wigner function of an
arbitrary quantum state.
filename (str): If using the `mpl` mode save the output visualization
as an image file to this path
options (dict): An dict with options for visualization in `interactive`
mode. The valid fields are:
- width (int): graph horizontal size, must be specified with
height to have an effect
- height (integer): graph vertical size, must be specified with
width to have an effect
- slider (bool): activate slider (only used for the `paulivec`
method)
mode (str): The visualization mode to use, either `mpl` or
`interactive`. Interactive requires running in jupyter and external
network connectivity to work. By default this will use `mpl` unless
you are running in jupyter and you have external connectivity.
show (bool): If set to true the rendered image will open in a new
window (mpl only)
Returns:
None: If used in interactive mode there is no return
matplotlib.Figure: If used in mpl mode the matplotlib.Figure of the
histogram will be returned.
Raises:
VisualizationError: If invalid mode is specified
ImportError: If matplotlib is used but it's not installed or configured
"""
fig = None
if not mode:
if INTERACTIVE:
from .interactive._iplot_state import iplot_state
iplot_state(rho, method=method, options=options)
elif HAS_MATPLOTLIB:
from ._state_visualization import plot_state as plot
fig = plot(rho, method=method, filename=filename, show=show)
else:
raise ImportError(_MSG % "plot_state")
else:
if mode == 'interactive':
from .interactive._iplot_state import iplot_state
iplot_state(rho, method=method, options=options)
elif mode == 'mpl':
if HAS_MATPLOTLIB:
from ._state_visualization import plot_state as plot
fig = plot(rho, method=method, filename=filename, show=show)
else:
raise ImportError(_MSG % "plot_state")
else:
raise VisualizationError(
"Invalid mode: %s, valid choices are 'interactive' or 'mpl'")
if HAS_MATPLOTLIB:
if fig:
plt.close(fig)
return fig
def plot_histogram(data, number_to_keep=None, legend=None, options=None,
filename=None, mode=None, show=False):
"""Plot a histogram of the measurement counts
There are two rendering backends either done in python using matplotlib or
using js in a jupyter notebook using an externally hosted graphing library.
To use the js you need to be running in jupyter and have network
connectivity to the external server where the js library is hosted.
Args:
data (list or dict): This is either a list of dictionaries or a
single dictionary containing the values to represent (ex
{'001': 139})
number_to_keep (int): DEPRECATED the number of terms to plot and rest
is made into a single bar called other values
legend(list): A list of strings to use for labels of the data.
The number of entries must match the length of data (if data is a
list or 1 if it's a dict)
filename (str): If using the `mpl` mode save the output visualization
as an image file to this path
options (dict): An dict with options for use for the visualization.
Valid keys are:
- width (integer): graph horizontal size, must be specified with
height to have an effect
- height (integer): graph vertical size, must be specified with
width to have an effect
- number_to_keep (integer): groups max values
- show_legend (bool): show legend of graph content
- sort (string): Could be 'asc' or 'desc'
- slider (bool): activate slider (`interactive` mode only)
mode (str): The visualization mode to use, either `mpl` or
`interactive`. Interactive requires running in jupyter and external
network connectivity to work. By default this will use `mpl` unless
you are running in jupyter and you have external connectivity.
show (bool): If set to true the rendered image will open in a new
window (mpl only)
Returns:
None: If used in interactive mode there is no return
matplotlib.Figure: If used in mpl mode the matplotlib.Figure of the
histogram will be returned.
Raises:
VisualizationError: If invalid mode is specified
ImportError: If matplotlib is used but it's not installed or configured
"""
fig = None
if not mode:
if INTERACTIVE:
from .interactive._iplot_histogram import iplot_histogram
iplot_histogram(data, number_to_keep=number_to_keep, legend=legend,
options=options)
elif HAS_MATPLOTLIB:
from ._counts_visualization import plot_histogram as plot
fig = plot(data, number_to_keep=number_to_keep, legend=legend,
options=options, show=show)
else:
raise ImportError(_MSG % "plot_histogram")
else:
if mode == 'interactive':
from .interactive._iplot_histogram import iplot_histogram
iplot_histogram(data, number_to_keep=number_to_keep, legend=legend,
options=options)
elif mode == 'mpl':
if HAS_MATPLOTLIB:
from ._counts_visualization import plot_histogram as plot
fig = plot(data, number_to_keep=number_to_keep, legend=legend,
options=options, filename=filename, show=show)
else:
raise ImportError(_MSG % "plot_histogram")
else:
raise VisualizationError(
"Invalid mode: %s, valid choices are 'interactive' or 'mpl'")
if HAS_MATPLOTLIB:
if fig:
plt.close(fig)
return fig
def plot_bloch_vector(bloch, title="", filename=None, show=False):
"""Plot the Bloch sphere.
Plot a sphere, axes, the Bloch vector, and its projections onto each axis.
Args:
bloch (list[double]): array of three elements where [<x>, <y>,<z>]
title (str): a string that represents the plot title
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
show (bool): If set to true the rendered image will open in a new
window
Returns:
matplotlib.Figure: The figure of the rendered bloch sphere
Raises:
ImportError: If matplotlib is not installed or configured
"""
if not HAS_MATPLOTLIB:
raise ImportError(_MSG % "plot_bloch_vector")
else:
from ._bloch import Bloch
B = Bloch()
B.add_vectors(bloch)
B.render(title=title)
fig = B.fig
if filename:
plt.savefig(filename)
elif show:
plt.show()
plt.close(fig)
return fig
<|code_end|>
|
qiskit/tools/visualization/__init__.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""Main Qiskit visualization methods."""
import sys
from qiskit._util import _has_connection
from ._circuit_visualization import circuit_drawer, plot_circuit, generate_latex_source, \
latex_circuit_drawer, matplotlib_circuit_drawer, _text_circuit_drawer, qx_color_scheme
from ._error import VisualizationError
from ._matplotlib import HAS_MATPLOTLIB
from ._dag_visualization import dag_drawer
if HAS_MATPLOTLIB:
from matplotlib import pyplot as plt
else:
plt = None
_MSG = 'The function %s needs matplotlib. Run "pip install matplotlib" before.'
INTERACTIVE = False
if ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
if _has_connection('qvisualization.mybluemix.net', 443):
INTERACTIVE = True
def plot_state(rho, method='city', filename=None, options=None, mode=None,
show=False):
"""Plot a quantum state.
This function provides several methods to plot a quantum state. There are
two rendering backends either done in python using matplotlib or using js
in a jupyter notebook using an externally hosted graphing library. To use
the js you need to be running in jupyter and have network connectivity to
the external server where the js library is hosted.
Args:
rho (ndarray): statevector or density matrix representation of a
quantum state
method (str): The plotting method to use. Valid choices are:
- 'city': Plots the cityscape, two 3d bargraphs of the mixed state
rho) of the quantum state. This is the default.
- 'paulivec': Plot the paulivec representation, a bar graph of the
mixed state rho over the pauli matrices, of a quantum
state
- 'qsphere': Plot the qsphere representation of the quantum state
- 'bloch': Plot the bloch vector for each qubit in the quantum state
- 'wigner': Plot the equal angle slice spin Wigner function of an
arbitrary quantum state.
filename (str): If using the `mpl` mode save the output visualization
as an image file to this path
options (dict): An dict with options for visualization in `interactive`
mode. The valid fields are:
- width (int): graph horizontal size, must be specified with
height to have an effect
- height (integer): graph vertical size, must be specified with
width to have an effect
- slider (bool): activate slider (only used for the `paulivec`
method)
mode (str): The visualization mode to use, either `mpl` or
`interactive`. Interactive requires running in jupyter and external
network connectivity to work. By default this will use `mpl` unless
you are running in jupyter and you have external connectivity.
show (bool): If set to true the rendered image will open in a new
window (mpl only)
Returns:
None: If used in interactive mode there is no return
matplotlib.Figure: If used in mpl mode the matplotlib.Figure of the
histogram will be returned.
Raises:
VisualizationError: If invalid mode is specified
ImportError: If matplotlib is used but it's not installed or configured
"""
fig = None
if not mode:
if INTERACTIVE:
from .interactive._iplot_state import iplot_state
iplot_state(rho, method=method, options=options)
elif HAS_MATPLOTLIB:
from ._state_visualization import plot_state as plot
fig = plot(rho, method=method, filename=filename, show=show)
else:
raise ImportError(_MSG % "plot_state")
else:
if mode == 'interactive':
from .interactive._iplot_state import iplot_state
iplot_state(rho, method=method, options=options)
elif mode == 'mpl':
if HAS_MATPLOTLIB:
from ._state_visualization import plot_state as plot
fig = plot(rho, method=method, filename=filename, show=show)
else:
raise ImportError(_MSG % "plot_state")
else:
raise VisualizationError(
"Invalid mode: %s, valid choices are 'interactive' or 'mpl'")
if HAS_MATPLOTLIB:
if fig:
plt.close(fig)
return fig
def plot_histogram(data, number_to_keep=None, legend=None, options=None,
filename=None, mode=None, show=False):
"""Plot a histogram of the measurement counts
There are two rendering backends either done in python using matplotlib or
using js in a jupyter notebook using an externally hosted graphing library.
To use the js you need to be running in jupyter and have network
connectivity to the external server where the js library is hosted.
Args:
data (list or dict): This is either a list of dictionaries or a
single dictionary containing the values to represent (ex
{'001': 139})
number_to_keep (int): DEPRECATED the number of terms to plot and rest
is made into a single bar called other values
legend(list): A list of strings to use for labels of the data.
The number of entries must match the length of data (if data is a
list or 1 if it's a dict)
filename (str): If using the `mpl` mode save the output visualization
as an image file to this path
options (dict): An dict with options for use for the visualization.
Valid keys are:
- width (integer): graph horizontal size, must be specified with
height to have an effect
- height (integer): graph vertical size, must be specified with
width to have an effect
- number_to_keep (integer): groups max values
- show_legend (bool): show legend of graph content
- sort (string): Could be 'asc' or 'desc'
- slider (bool): activate slider (`interactive` mode only)
mode (str): The visualization mode to use, either `mpl` or
`interactive`. Interactive requires running in jupyter and external
network connectivity to work. By default this will use `mpl` unless
you are running in jupyter and you have external connectivity.
show (bool): If set to true the rendered image will open in a new
window (mpl only)
Returns:
None: If used in interactive mode there is no return
matplotlib.Figure: If used in mpl mode the matplotlib.Figure of the
histogram will be returned.
Raises:
VisualizationError: If invalid mode is specified
ImportError: If matplotlib is used but it's not installed or configured
"""
fig = None
if not mode:
if INTERACTIVE:
from .interactive._iplot_histogram import iplot_histogram
iplot_histogram(data, number_to_keep=number_to_keep, legend=legend,
options=options)
elif HAS_MATPLOTLIB:
from ._counts_visualization import plot_histogram as plot
fig = plot(data, number_to_keep=number_to_keep, legend=legend,
options=options, show=show)
else:
raise ImportError(_MSG % "plot_histogram")
else:
if mode == 'interactive':
from .interactive._iplot_histogram import iplot_histogram
iplot_histogram(data, number_to_keep=number_to_keep, legend=legend,
options=options)
elif mode == 'mpl':
if HAS_MATPLOTLIB:
from ._counts_visualization import plot_histogram as plot
fig = plot(data, number_to_keep=number_to_keep, legend=legend,
options=options, filename=filename, show=show)
else:
raise ImportError(_MSG % "plot_histogram")
else:
raise VisualizationError(
"Invalid mode: %s, valid choices are 'interactive' or 'mpl'")
if HAS_MATPLOTLIB:
if fig:
plt.close(fig)
return fig
def plot_bloch_vector(bloch, title="", filename=None, show=False):
"""Plot the Bloch sphere.
Plot a sphere, axes, the Bloch vector, and its projections onto each axis.
Args:
bloch (list[double]): array of three elements where [<x>, <y>,<z>]
title (str): a string that represents the plot title
filename (str): the output file to save the plot as. If specified it
will save and exit and not open up the plot in a new window.
show (bool): If set to true the rendered image will open in a new
window
Returns:
matplotlib.Figure: The figure of the rendered bloch sphere
Raises:
ImportError: If matplotlib is not installed or configured
"""
if not HAS_MATPLOTLIB:
raise ImportError(_MSG % "plot_bloch_vector")
else:
from ._bloch import Bloch
B = Bloch()
B.add_vectors(bloch)
B.render(title=title)
fig = B.fig
if filename:
plt.savefig(filename)
elif show:
plt.show()
plt.close(fig)
return fig
<|code_end|>
|
conditional bug
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: 0.7
- **Python version**: 3.6
- **Operating system**: Mac
### What is the current behavior?
qobj without mapping
```
QobjItem(name='h', params=[], qubits=[1], texparams=[])
QobjItem(name='cx', params=[], qubits=[1, 2], texparams=[])
QobjItem(name='u3', params=[0.3, 0.2, 0.1], qubits=[0], texparams=['0.3', '0.2', '0.1'])
QobjItem(name='barrier', qubits=[0, 1, 2])
QobjItem(name='cx', params=[], qubits=[0, 1], texparams=[])
QobjItem(clbits=[1], memory=[1], name='measure', qubits=[1])
QobjItem(name='h', params=[], qubits=[0], texparams=[])
QobjItem(clbits=[0], memory=[0], name='measure', qubits=[0])
QobjItem(name='barrier', qubits=[0, 1, 2])
QobjItem(conditional=QobjItem(mask='0x1', type='equals', val='0x1'), name='z', params=[], qubits=[2], texparams=[])
QobjItem(conditional=QobjItem(mask='0x2', type='equals', val='0x1'), name='x', params=[], qubits=[2], texparams=[])
QobjItem(clbits=[2], memory=[2], name='measure', qubits=[2])
```
Output
```
{'0 0 0': 269, '0 0 1': 251, '0 1 0': 254, '0 1 1': 229, '1 0 0': 5, '1 0 1': 5, '1 1 0': 6, '1 1 1': 5}
```
Qobj after mapping to a coupling map
```
QobjItem(name='u2', params=[0.0, 3.141592653589793], qubits=[1], texparams=['0', '\\pi'])
QobjItem(name='cx', params=[], qubits=[1, 2], texparams=[])
QobjItem(name='u3', params=[0.3, 0.2, 0.1], qubits=[0], texparams=['0.3', '0.2', '0.1'])
QobjItem(name='barrier', qubits=[0, 1, 2])
QobjItem(name='cx', params=[], qubits=[0, 1], texparams=[])
QobjItem(name='u2', params=[0.0, 3.141592653589793], qubits=[0], texparams=['0', '\\pi'])
QobjItem(name='barrier', qubits=[0, 1, 2])
QobjItem(conditional=QobjItem(mask='0x1', type='equals', val='0x1'), name='u1', params=[3.141592653589793], qubits=[2], texparams=['\\pi'])
QobjItem(clbits=[0], memory=[0], name='measure', qubits=[0])
QobjItem(conditional=QobjItem(mask='0x2', type='equals', val='0x1'), name='u3', params=[3.141592653589793, 0.0, 3.141592653589793], qubits=[2], texparams=['\\pi', '0', '\\pi'])
QobjItem(clbits=[1], memory=[1], name='measure', qubits=[1])
QobjItem(clbits=[2], memory=[2], name='measure', qubits=[2])
```
output
```
{'0 0 0': 233, '0 0 1': 253, '0 1 0': 3, '0 1 1': 8, '1 0 0': 2, '1 0 1': 7, '1 1 0': 252, '1 1 1': 266}
```
The error is the measurements are passing through the conditional.
### Steps to reproduce the problem
Run the example teleport
### What is the expected behavior?
outcoumes should be the same
### Suggested solutions
Debug the mapper pass
NOTE you may need to look after #1284 is merged as there was another error with the qubits randomly changing position in the circuit.
|
examples/python/teleport.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Quantum teleportation example.
Note: if you have only cloned the Qiskit repository but not
used `pip install`, the examples only work from the root directory.
"""
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import compile, Aer
###############################################################
# Set the backend name and coupling map.
###############################################################
coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]]
backend = Aer.get_backend("qasm_simulator")
###############################################################
# Make a quantum program for quantum teleportation.
###############################################################
q = QuantumRegister(3, "q")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
c2 = ClassicalRegister(1, "c2")
qc = QuantumCircuit(q, c0, c1, c2, name="teleport")
# Prepare an initial state
qc.u3(0.3, 0.2, 0.1, q[0])
# Prepare a Bell pair
qc.h(q[1])
qc.cx(q[1], q[2])
# Barrier following state preparation
qc.barrier(q)
# Measure in the Bell basis
qc.cx(q[0], q[1])
qc.h(q[0])
qc.measure(q[0], c0[0])
qc.measure(q[1], c1[0])
# Apply a correction
qc.barrier(q)
qc.z(q[2]).c_if(c0, 1)
qc.x(q[2]).c_if(c1, 1)
qc.measure(q[2], c2[0])
###############################################################
# Execute.
# Experiment does not support feedback, so we use the simulator
###############################################################
# First version: not mapped
initial_layout = {("q", 0): ("q", 0), ("q", 1): ("q", 1),
("q", 2): ("q", 2)}
qobj = compile(qc, backend=backend, coupling_map=None, shots=1024, initial_layout=initial_layout)
job = backend.run(qobj)
qobj_exp = qobj.experiments[0]
print(qobj_exp.header.qubit_labels)
print(qobj_exp.header.compiled_circuit_qasm)
print(qobj_exp.header.clbit_labels)
for i in qobj_exp.instructions:
print(i)
result = job.result()
print(result)
print(result.get_counts(qc))
# Second version: mapped to 2x8 array coupling graph
qobj = compile(qc, backend=backend, coupling_map=coupling_map, shots=1024,initial_layout=initial_layout)
qobj_exp = qobj.experiments[0]
print(qobj_exp.header.qubit_labels)
qobj_exp.header.compiled_circuit_qasm = ""
print(qobj_exp.header.compiled_circuit_qasm)
print(qobj_exp.header.clbit_labels)
for i in qobj_exp.instructions:
print(i)
job = backend.run(qobj)
result = job.result()
print(result)
print(result.get_counts(qc))
# Both versions should give the same distribution<|code_end|>
qiskit/mapper/_mapping.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name, inconsistent-return-statements
"""
Layout module to assist with mapping circuit qubits onto physical qubits.
"""
import logging
import pprint
import sys
import networkx as nx
import numpy as np
import sympy
from sympy import Number as N
from qiskit.qasm import _node as node
from qiskit.mapper import MapperError
from qiskit.dagcircuit import DAGCircuit
from qiskit.dagcircuit._dagcircuiterror import DAGCircuitError
from qiskit.unrollers._dagunroller import DagUnroller
from qiskit.unrollers._dagbackend import DAGBackend
from qiskit.mapper._quaternion import quaternion_from_euler
from qiskit import QuantumRegister
logger = logging.getLogger(__name__)
# Notes:
# Measurements may occur and be followed by swaps that result in repeated
# measurement of the same qubit. Near-term experiments cannot implement
# these circuits, so we may need to modify the algorithm.
# It can happen that a swap in a deeper layer can be removed by permuting
# qubits in the layout. We don't do this.
# It can happen that initial swaps can be removed or partly simplified
# because the initial state is zero. We don't do this.
cx_data = {
"opaque": False,
"n_args": 0,
"n_bits": 2,
"args": [],
"bits": ["c", "t"],
# gate cx c,t { CX c,t; }
"body": node.GateBody([
node.Cnot([
node.Id("c", 0, ""),
node.Id("t", 0, "")
])
])
}
swap_data = {
"opaque": False,
"n_args": 0,
"n_bits": 2,
"args": [],
"bits": ["a", "b"],
# gate swap a,b { cx a,b; cx b,a; cx a,b; }
"body": node.GateBody([
node.CustomUnitary([
node.Id("cx", 0, ""),
node.PrimaryList([
node.Id("a", 0, ""),
node.Id("b", 0, "")
])
]),
node.CustomUnitary([
node.Id("cx", 0, ""),
node.PrimaryList([
node.Id("b", 0, ""),
node.Id("a", 0, "")
])
]),
node.CustomUnitary([
node.Id("cx", 0, ""),
node.PrimaryList([
node.Id("a", 0, ""),
node.Id("b", 0, "")
])
])
])
}
u2_data = {
"opaque": False,
"n_args": 2,
"n_bits": 1,
"args": ["phi", "lambda"],
"bits": ["q"],
# gate u2(phi,lambda) q { U(pi/2,phi,lambda) q; }
"body": node.GateBody([
node.UniversalUnitary([
node.ExpressionList([
node.BinaryOp([
node.BinaryOperator('/'),
node.Real(sympy.pi),
node.Int(2)
]),
node.Id("phi", 0, ""),
node.Id("lambda", 0, "")
]),
node.Id("q", 0, "")
])
])
}
h_data = {
"opaque": False,
"n_args": 0,
"n_bits": 1,
"args": [],
"bits": ["a"],
# gate h a { u2(0,pi) a; }
"body": node.GateBody([
node.CustomUnitary([
node.Id("u2", 0, ""),
node.ExpressionList([
node.Int(0),
node.Real(sympy.pi)
]),
node.PrimaryList([
node.Id("a", 0, "")
])
])
])
}
def layer_permutation(layer_partition, layout, qubit_subset, coupling, trials,
seed=None):
"""Find a swap circuit that implements a permutation for this layer.
The goal is to swap qubits such that qubits in the same two-qubit gates
are adjacent.
Based on Sergey Bravyi's algorithm.
The layer_partition is a list of (qu)bit lists and each qubit is a
tuple (qreg, index).
The layout is a dict mapping qubits in the circuit to qubits in the
coupling graph and represents the current positions of the data.
The qubit_subset is the subset of qubits in the coupling graph that
we have chosen to map into.
The coupling is a CouplingGraph.
TRIALS is the number of attempts the randomized algorithm makes.
Returns: success_flag, best_circ, best_d, best_layout, trivial_flag
If success_flag is True, then best_circ contains a DAGCircuit with
the swap circuit, best_d contains the depth of the swap circuit, and
best_layout contains the new positions of the data qubits after the
swap circuit has been applied. The trivial_flag is set if the layer
has no multi-qubit gates.
"""
if seed is not None:
np.random.seed(seed)
logger.debug("layer_permutation: ----- enter -----")
logger.debug("layer_permutation: layer_partition = %s",
pprint.pformat(layer_partition))
logger.debug("layer_permutation: layout = %s",
pprint.pformat(layout))
logger.debug("layer_permutation: qubit_subset = %s",
pprint.pformat(qubit_subset))
logger.debug("layer_permutation: trials = %s", trials)
rev_layout = {b: a for a, b in layout.items()}
gates = []
for layer in layer_partition:
if len(layer) > 2:
raise MapperError("Layer contains >2 qubit gates")
elif len(layer) == 2:
gates.append(tuple(layer))
logger.debug("layer_permutation: gates = %s", pprint.pformat(gates))
# Find layout maximum index
layout_max_index = max(map(lambda x: x[1]+1, layout.values()))
# Can we already apply the gates?
dist = sum([coupling.distance(layout[g[0]],
layout[g[1]]) for g in gates])
logger.debug("layer_permutation: dist = %s", dist)
if dist == len(gates):
logger.debug("layer_permutation: done already")
logger.debug("layer_permutation: ----- exit -----")
circ = DAGCircuit()
circ.add_qreg(QuantumRegister(layout_max_index, "q"))
circ.add_basis_element("CX", 2)
circ.add_basis_element("cx", 2)
circ.add_basis_element("swap", 2)
circ.add_gate_data("cx", cx_data)
circ.add_gate_data("swap", swap_data)
return True, circ, 0, layout, bool(gates)
# Begin loop over trials of randomized algorithm
n = coupling.size()
best_d = sys.maxsize # initialize best depth
best_circ = None # initialize best swap circuit
best_layout = None # initialize best final layout
for trial in range(trials):
logger.debug("layer_permutation: trial %s", trial)
trial_layout = layout.copy()
rev_trial_layout = rev_layout.copy()
# SWAP circuit constructed this trial
trial_circ = DAGCircuit()
trial_circ.add_qreg(QuantumRegister(layout_max_index, "q"))
# Compute Sergey's randomized distance
xi = {}
for i in coupling.get_qubits():
xi[i] = {}
for i in coupling.get_qubits():
for j in coupling.get_qubits():
scale = 1 + np.random.normal(0, 1 / n)
xi[i][j] = scale * coupling.distance(i, j) ** 2
xi[j][i] = xi[i][j]
# Loop over depths d up to a max depth of 2n+1
d = 1
# Circuit for this swap slice
circ = DAGCircuit()
circ.add_qreg(QuantumRegister(layout_max_index, "q"))
circ.add_basis_element("CX", 2)
circ.add_basis_element("cx", 2)
circ.add_basis_element("swap", 2)
circ.add_gate_data("cx", cx_data)
circ.add_gate_data("swap", swap_data)
# Identity wire-map for composing the circuits
identity_wire_map = {('q', j): ('q', j) for j in range(layout_max_index)}
while d < 2 * n + 1:
# Set of available qubits
qubit_set = set(qubit_subset)
# While there are still qubits available
while qubit_set:
# Compute the objective function
min_cost = sum([xi[trial_layout[g[0]]][trial_layout[g[1]]]
for g in gates])
# Try to decrease objective function
progress_made = False
# Loop over edges of coupling graph
for e in coupling.get_edges():
# Are the qubits available?
if e[0] in qubit_set and e[1] in qubit_set:
# Try this edge to reduce the cost
new_layout = trial_layout.copy()
new_layout[rev_trial_layout[e[0]]] = e[1]
new_layout[rev_trial_layout[e[1]]] = e[0]
rev_new_layout = rev_trial_layout.copy()
rev_new_layout[e[0]] = rev_trial_layout[e[1]]
rev_new_layout[e[1]] = rev_trial_layout[e[0]]
# Compute the objective function
new_cost = sum([xi[new_layout[g[0]]][new_layout[g[1]]]
for g in gates])
# Record progress if we succceed
if new_cost < min_cost:
logger.debug("layer_permutation: progress! "
"min_cost = %s", min_cost)
progress_made = True
min_cost = new_cost
opt_layout = new_layout
rev_opt_layout = rev_new_layout
opt_edge = e
# Were there any good choices?
if progress_made:
qubit_set.remove(opt_edge[0])
qubit_set.remove(opt_edge[1])
trial_layout = opt_layout
rev_trial_layout = rev_opt_layout
circ.apply_operation_back("swap", [(opt_edge[0][0],
opt_edge[0][1]),
(opt_edge[1][0],
opt_edge[1][1])])
logger.debug("layer_permutation: chose pair %s",
pprint.pformat(opt_edge))
else:
break
# We have either run out of qubits or failed to improve
# Compute the coupling graph distance
dist = sum([coupling.distance(trial_layout[g[0]],
trial_layout[g[1]]) for g in gates])
logger.debug("layer_permutation: dist = %s", dist)
# If all gates can be applied now, we are finished
# Otherwise we need to consider a deeper swap circuit
if dist == len(gates):
logger.debug("layer_permutation: all can be applied now")
trial_circ.compose_back(circ, identity_wire_map)
break
# Increment the depth
d += 1
logger.debug("layer_permutation: increment depth to %s", d)
# Either we have succeeded at some depth d < dmax or failed
dist = sum([coupling.distance(trial_layout[g[0]],
trial_layout[g[1]]) for g in gates])
logger.debug("layer_permutation: dist = %s", dist)
if dist == len(gates):
if d < best_d:
logger.debug("layer_permutation: got circuit with depth %s", d)
best_circ = trial_circ
best_layout = trial_layout
best_d = min(best_d, d)
if best_circ is None:
logger.debug("layer_permutation: failed!")
logger.debug("layer_permutation: ----- exit -----")
return False, None, None, None, False
logger.debug("layer_permutation: done")
logger.debug("layer_permutation: ----- exit -----")
return True, best_circ, best_d, best_layout, False
def direction_mapper(circuit_graph, coupling_graph):
"""Change the direction of CNOT gates to conform to CouplingGraph.
circuit_graph = input DAGCircuit
coupling_graph = corresponding CouplingGraph
Adds "h" to the circuit basis.
Returns a DAGCircuit object containing a circuit equivalent to
circuit_graph but with CNOT gate directions matching the edges
of coupling_graph. Raises an exception if the circuit_graph
does not conform to the coupling_graph.
"""
if "cx" not in circuit_graph.basis:
return circuit_graph
if circuit_graph.basis["cx"] != (2, 0, 0):
raise MapperError("cx gate has unexpected signature %s" %
circuit_graph.basis["cx"])
flipped_cx_circuit = DAGCircuit()
flipped_cx_circuit.add_qreg(QuantumRegister(2, "q"))
flipped_cx_circuit.add_basis_element("CX", 2)
flipped_cx_circuit.add_basis_element("U", 1, 0, 3)
flipped_cx_circuit.add_basis_element("cx", 2)
flipped_cx_circuit.add_basis_element("u2", 1, 0, 2)
flipped_cx_circuit.add_basis_element("h", 1)
flipped_cx_circuit.add_gate_data("cx", cx_data)
flipped_cx_circuit.add_gate_data("u2", u2_data)
flipped_cx_circuit.add_gate_data("h", h_data)
flipped_cx_circuit.apply_operation_back("h", [("q", 0)])
flipped_cx_circuit.apply_operation_back("h", [("q", 1)])
flipped_cx_circuit.apply_operation_back("cx", [("q", 1), ("q", 0)])
flipped_cx_circuit.apply_operation_back("h", [("q", 0)])
flipped_cx_circuit.apply_operation_back("h", [("q", 1)])
cg_edges = coupling_graph.get_edges()
for cx_node in circuit_graph.get_named_nodes("cx"):
nd = circuit_graph.multi_graph.node[cx_node]
cxedge = tuple(nd["qargs"])
if cxedge in cg_edges:
logger.debug("cx %s[%d], %s[%d] -- OK",
cxedge[0][0], cxedge[0][1],
cxedge[1][0], cxedge[1][1])
continue
elif (cxedge[1], cxedge[0]) in cg_edges:
circuit_graph.substitute_circuit_one(cx_node,
flipped_cx_circuit,
wires=[("q", 0), ("q", 1)])
logger.debug("cx %s[%d], %s[%d] -FLIP",
cxedge[0][0], cxedge[0][1],
cxedge[1][0], cxedge[1][1])
else:
raise MapperError("circuit incompatible with CouplingGraph: "
"cx on %s" % pprint.pformat(cxedge))
return circuit_graph
def swap_mapper_layer_update(i, first_layer, best_layout, best_d,
best_circ, layer_list):
"""Update the QASM string for an iteration of swap_mapper.
i = layer number
first_layer = True if this is the first layer with multi-qubit gates
best_layout = layout returned from swap algorithm
best_d = depth returned from swap algorithm
best_circ = swap circuit returned from swap algorithm
layer_list = list of circuit objects for each layer
Return DAGCircuit object to append to the output DAGCircuit.
"""
layout = best_layout
layout_max_index = max(map(lambda x: x[1]+1, layout.values()))
dagcircuit_output = DAGCircuit()
dagcircuit_output.add_qreg(QuantumRegister(layout_max_index, "q"))
# Identity wire-map for composing the circuits
identity_wire_map = {('q', j): ('q', j) for j in range(layout_max_index)}
# If this is the first layer with multi-qubit gates,
# output all layers up to this point and ignore any
# swap gates. Set the initial layout.
if first_layer:
logger.debug("update_qasm_and_layout: first multi-qubit gate layer")
# Output all layers up to this point
for j in range(i + 1):
dagcircuit_output.compose_back(layer_list[j]["graph"], layout)
# Otherwise, we output the current layer and the associated swap gates.
else:
# Output any swaps
if best_d > 0:
logger.debug("update_qasm_and_layout: swaps in this layer, "
"depth %d", best_d)
dagcircuit_output.compose_back(best_circ, identity_wire_map)
else:
logger.debug("update_qasm_and_layout: no swaps in this layer")
# Output this layer
dagcircuit_output.compose_back(layer_list[i]["graph"], layout)
return dagcircuit_output
def swap_mapper(circuit_graph, coupling_graph,
initial_layout=None,
basis="cx,u1,u2,u3,id", trials=20, seed=None):
"""Map a DAGCircuit onto a CouplingGraph using swap gates.
Args:
circuit_graph (DAGCircuit): input DAG circuit
coupling_graph (CouplingGraph): coupling graph to map onto
initial_layout (dict): dict from qubits of circuit_graph to qubits
of coupling_graph (optional)
basis (str): basis string specifying basis of output DAGCircuit
trials (int): number of trials.
seed (int): initial seed.
Returns:
DAGCircuit: object containing a circuit equivalent to
circuit_graph that respects couplings in coupling_graph, and
a layout dict mapping qubits of circuit_graph into qubits
of coupling_graph. The layout may differ from the initial_layout
if the first layer of gates cannot be executed on the
initial_layout. Finally, returned is the final layer qubit
permutation that is needed to add measurements back in.
Raises:
MapperError: if there was any error during the mapping or with the
parameters.
"""
if circuit_graph.width() > coupling_graph.size():
raise MapperError("Not enough qubits in CouplingGraph")
# Schedule the input circuit
layerlist = list(circuit_graph.layers())
logger.debug("schedule:")
for i, v in enumerate(layerlist):
logger.debug(" %d: %s", i, v["partition"])
if initial_layout is not None:
# Check the input layout
circ_qubits = circuit_graph.get_qubits()
coup_qubits = coupling_graph.get_qubits()
qubit_subset = []
for k, v in initial_layout.items():
qubit_subset.append(v)
if k not in circ_qubits:
raise MapperError("initial_layout qubit %s[%d] not in input "
"DAGCircuit" % (k[0], k[1]))
if v not in coup_qubits:
raise MapperError("initial_layout qubit %s[%d] not in input "
"CouplingGraph" % (v[0], v[1]))
else:
# Supply a default layout
qubit_subset = coupling_graph.get_qubits()
qubit_subset = qubit_subset[0:circuit_graph.width()]
initial_layout = {a: b for a, b in
zip(circuit_graph.get_qubits(), qubit_subset)}
# Find swap circuit to preceed to each layer of input circuit
layout = initial_layout.copy()
layout_max_index = max(map(lambda x: x[1]+1, layout.values()))
# Construct an empty DAGCircuit with one qreg "q"
# and the same set of cregs as the input circuit
dagcircuit_output = DAGCircuit()
dagcircuit_output.name = circuit_graph.name
dagcircuit_output.add_qreg(QuantumRegister(layout_max_index, "q"))
for creg in circuit_graph.cregs.values():
dagcircuit_output.add_creg(creg)
# Make a trivial wire mapping between the subcircuits
# returned by swap_mapper_layer_update and the circuit
# we are building
identity_wire_map = {}
for j in range(layout_max_index):
identity_wire_map[("q", j)] = ("q", j)
for creg in circuit_graph.cregs.values():
for j in range(creg.size):
identity_wire_map[(creg.name, j)] = (creg.name, j)
first_layer = True # True until first layer is output
logger.debug("initial_layout = %s", layout)
# Iterate over layers
for i, layer in enumerate(layerlist):
# Attempt to find a permutation for this layer
success_flag, best_circ, best_d, best_layout, trivial_flag \
= layer_permutation(layer["partition"], layout,
qubit_subset, coupling_graph, trials, seed)
logger.debug("swap_mapper: layer %d", i)
logger.debug("swap_mapper: success_flag=%s,best_d=%s,trivial_flag=%s",
success_flag, str(best_d), trivial_flag)
# If this fails, try one gate at a time in this layer
if not success_flag:
logger.debug("swap_mapper: failed, layer %d, "
"retrying sequentially", i)
serial_layerlist = list(layer["graph"].serial_layers())
# Go through each gate in the layer
for j, serial_layer in enumerate(serial_layerlist):
success_flag, best_circ, best_d, best_layout, trivial_flag \
= layer_permutation(serial_layer["partition"],
layout, qubit_subset, coupling_graph,
trials, seed)
logger.debug("swap_mapper: layer %d, sublayer %d", i, j)
logger.debug("swap_mapper: success_flag=%s,best_d=%s,"
"trivial_flag=%s",
success_flag, str(best_d), trivial_flag)
# Give up if we fail again
if not success_flag:
raise MapperError("swap_mapper failed: " +
"layer %d, sublayer %d" % (i, j) +
", \"%s\"" %
serial_layer["graph"].qasm(
no_decls=True,
aliases=layout))
# If this layer is only single-qubit gates,
# and we have yet to see multi-qubit gates,
# continue to the next inner iteration
if trivial_flag and first_layer:
logger.debug("swap_mapper: skip to next sublayer")
continue
# Update the record of qubit positions for each inner iteration
layout = best_layout
# Update the QASM
dagcircuit_output.compose_back(
swap_mapper_layer_update(j,
first_layer,
best_layout,
best_d,
best_circ,
serial_layerlist),
identity_wire_map)
# Update initial layout
if first_layer:
initial_layout = layout
first_layer = False
else:
# Update the record of qubit positions for each iteration
layout = best_layout
# Update the QASM
dagcircuit_output.compose_back(
swap_mapper_layer_update(i,
first_layer,
best_layout,
best_d,
best_circ,
layerlist),
identity_wire_map)
# Update initial layout
if first_layer:
initial_layout = layout
first_layer = False
# This is the final layout that we need to correctly replace
# any measurements that needed to be removed before the swap
last_layout = layout
# If first_layer is still set, the circuit only has single-qubit gates
# so we can use the initial layout to output the entire circuit
if first_layer:
layout = initial_layout
for i, layer in enumerate(layerlist):
dagcircuit_output.compose_back(layer["graph"], layout)
# Parse openqasm_output into DAGCircuit object
dag_unrolled = DagUnroller(dagcircuit_output,
DAGBackend(basis.split(",")))
dagcircuit_output = dag_unrolled.expand_gates()
return dagcircuit_output, initial_layout, last_layout
def yzy_to_zyz(xi, theta1, theta2, eps=1e-9):
"""Express a Y.Z.Y single qubit gate as a Z.Y.Z gate.
Solve the equation
.. math::
Ry(theta1).Rz(xi).Ry(theta2) = Rz(phi).Ry(theta).Rz(lambda)
for theta, phi, and lambda.
Return a solution theta, phi, and lambda.
"""
Q = quaternion_from_euler([theta1, xi, theta2], 'yzy')
euler = Q.to_zyz()
P = quaternion_from_euler(euler, 'zyz')
# output order different than rotation order
out_angles = (euler[1], euler[0], euler[2])
abs_inner = abs(P.data.dot(Q.data))
if not np.allclose(abs_inner, 1, eps):
logger.debug("xi=%s", xi)
logger.debug("theta1=%s", theta1)
logger.debug("theta2=%s", theta2)
logger.debug("solutions=%s", out_angles)
logger.debug("abs_inner=%s", abs_inner)
raise MapperError('YZY and ZYZ angles do not give same rotation matrix.')
return out_angles
def compose_u3(theta1, phi1, lambda1, theta2, phi2, lambda2):
"""Return a triple theta, phi, lambda for the product.
u3(theta, phi, lambda)
= u3(theta1, phi1, lambda1).u3(theta2, phi2, lambda2)
= Rz(phi1).Ry(theta1).Rz(lambda1+phi2).Ry(theta2).Rz(lambda2)
= Rz(phi1).Rz(phi').Ry(theta').Rz(lambda').Rz(lambda2)
= u3(theta', phi1 + phi', lambda2 + lambda')
Return theta, phi, lambda.
"""
# Careful with the factor of two in yzy_to_zyz
thetap, phip, lambdap = yzy_to_zyz((lambda1 + phi2),
theta1, theta2)
(theta, phi, lamb) = (thetap, phi1 + phip, lambda2 + lambdap)
return (theta, phi, lamb)
def cx_cancellation(circuit):
"""Cancel back-to-back "cx" gates in circuit."""
runs = circuit.collect_runs(["cx"])
for run in runs:
# Partition the run into chunks with equal gate arguments
partition = []
chunk = []
for i in range(len(run) - 1):
chunk.append(run[i])
qargs0 = circuit.multi_graph.node[run[i]]["qargs"]
qargs1 = circuit.multi_graph.node[run[i + 1]]["qargs"]
if qargs0 != qargs1:
partition.append(chunk)
chunk = []
chunk.append(run[-1])
partition.append(chunk)
# Simplify each chunk in the partition
for chunk in partition:
if len(chunk) % 2 == 0:
for n in chunk:
circuit._remove_op_node(n)
else:
for n in chunk[1:]:
circuit._remove_op_node(n)
def optimize_1q_gates(circuit):
"""Simplify runs of single qubit gates in the QX basis.
Return a new circuit that has been optimized.
"""
qx_basis = ["u1", "u2", "u3", "cx", "id"]
dag_unroller = DagUnroller(circuit, DAGBackend(qx_basis))
unrolled = dag_unroller.expand_gates()
runs = unrolled.collect_runs(["u1", "u2", "u3", "id"])
for run in runs:
qname = unrolled.multi_graph.node[run[0]]["qargs"][0]
right_name = "u1"
right_parameters = (N(0), N(0), N(0)) # (theta, phi, lambda)
for current_node in run:
nd = unrolled.multi_graph.node[current_node]
left_name = nd["name"]
if (nd["condition"] is not None
or len(nd["qargs"]) != 1
or nd["qargs"][0] != qname
or left_name not in ["u1", "u2", "u3", "id"]):
raise MapperError("internal error")
if left_name == "u1":
left_parameters = (N(0), N(0), nd["params"][0])
elif left_name == "u2":
left_parameters = (sympy.pi / 2, nd["params"][0], nd["params"][1])
elif left_name == "u3":
left_parameters = tuple(nd["params"])
else:
left_name = "u1" # replace id with u1
left_parameters = (N(0), N(0), N(0))
# Compose gates
name_tuple = (left_name, right_name)
if name_tuple == ("u1", "u1"):
# u1(lambda1) * u1(lambda2) = u1(lambda1 + lambda2)
right_parameters = (N(0), N(0), right_parameters[2] +
left_parameters[2])
elif name_tuple == ("u1", "u2"):
# u1(lambda1) * u2(phi2, lambda2) = u2(phi2 + lambda1, lambda2)
right_parameters = (sympy.pi / 2, right_parameters[1] +
left_parameters[2], right_parameters[2])
elif name_tuple == ("u2", "u1"):
# u2(phi1, lambda1) * u1(lambda2) = u2(phi1, lambda1 + lambda2)
right_name = "u2"
right_parameters = (sympy.pi / 2, left_parameters[1],
right_parameters[2] + left_parameters[2])
elif name_tuple == ("u1", "u3"):
# u1(lambda1) * u3(theta2, phi2, lambda2) =
# u3(theta2, phi2 + lambda1, lambda2)
right_parameters = (right_parameters[0], right_parameters[1] +
left_parameters[2], right_parameters[2])
elif name_tuple == ("u3", "u1"):
# u3(theta1, phi1, lambda1) * u1(lambda2) =
# u3(theta1, phi1, lambda1 + lambda2)
right_name = "u3"
right_parameters = (left_parameters[0], left_parameters[1],
right_parameters[2] + left_parameters[2])
elif name_tuple == ("u2", "u2"):
# Using Ry(pi/2).Rz(2*lambda).Ry(pi/2) =
# Rz(pi/2).Ry(pi-2*lambda).Rz(pi/2),
# u2(phi1, lambda1) * u2(phi2, lambda2) =
# u3(pi - lambda1 - phi2, phi1 + pi/2, lambda2 + pi/2)
right_name = "u3"
right_parameters = (sympy.pi - left_parameters[2] -
right_parameters[1], left_parameters[1] +
sympy.pi / 2, right_parameters[2] +
sympy.pi / 2)
elif name_tuple[1] == "nop":
right_name = left_name
right_parameters = left_parameters
else:
# For composing u3's or u2's with u3's, use
# u2(phi, lambda) = u3(pi/2, phi, lambda)
# together with the qiskit.mapper.compose_u3 method.
right_name = "u3"
# Evaluate the symbolic expressions for efficiency
left_parameters = tuple(map(lambda x: x.evalf(), list(left_parameters)))
right_parameters = tuple(map(lambda x: x.evalf(), list(right_parameters)))
right_parameters = compose_u3(left_parameters[0],
left_parameters[1],
left_parameters[2],
right_parameters[0],
right_parameters[1],
right_parameters[2])
# Why evalf()? This program:
# OPENQASM 2.0;
# include "qelib1.inc";
# qreg q[2];
# creg c[2];
# u3(0.518016983430947*pi,1.37051598592907*pi,1.36816383603222*pi) q[0];
# u3(1.69867232277986*pi,0.371448347747471*pi,0.461117217930936*pi) q[0];
# u3(0.294319836336836*pi,0.450325871124225*pi,1.46804720442555*pi) q[0];
# measure q -> c;
# took >630 seconds (did not complete) to optimize without
# calling evalf() at all, 19 seconds to optimize calling
# evalf() AFTER compose_u3, and 1 second to optimize
# calling evalf() BEFORE compose_u3.
# 1. Here down, when we simplify, we add f(theta) to lambda to
# correct the global phase when f(theta) is 2*pi. This isn't
# necessary but the other steps preserve the global phase, so
# we continue in that manner.
# 2. The final step will remove Z rotations by 2*pi.
# 3. Note that is_zero is true only if the expression is exactly
# zero. If the input expressions have already been evaluated
# then these final simplifications will not occur.
# TODO After we refactor, we should have separate passes for
# exact and approximate rewriting.
# Y rotation is 0 mod 2*pi, so the gate is a u1
if (right_parameters[0] % (2 * sympy.pi)).is_zero \
and right_name != "u1":
right_name = "u1"
right_parameters = (0, 0, right_parameters[1] +
right_parameters[2] +
right_parameters[0])
# Y rotation is pi/2 or -pi/2 mod 2*pi, so the gate is a u2
if right_name == "u3":
# theta = pi/2 + 2*k*pi
if ((right_parameters[0] - sympy.pi / 2) % (2 * sympy.pi)).is_zero:
right_name = "u2"
right_parameters = (sympy.pi / 2, right_parameters[1],
right_parameters[2] +
(right_parameters[0] - sympy.pi / 2))
# theta = -pi/2 + 2*k*pi
if ((right_parameters[0] + sympy.pi / 2) % (2 * sympy.pi)).is_zero:
right_name = "u2"
right_parameters = (sympy.pi / 2, right_parameters[1] +
sympy.pi, right_parameters[2] -
sympy.pi + (right_parameters[0] +
sympy.pi / 2))
# u1 and lambda is 0 mod 2*pi so gate is nop (up to a global phase)
if right_name == "u1" and (right_parameters[2] % (2 * sympy.pi)).is_zero:
right_name = "nop"
# Simplify the symbolic parameters
right_parameters = tuple(map(sympy.simplify, list(right_parameters)))
# Replace the data of the first node in the run
new_params = []
if right_name == "u1":
new_params = [right_parameters[2]]
if right_name == "u2":
new_params = [right_parameters[1], right_parameters[2]]
if right_name == "u3":
new_params = list(right_parameters)
nx.set_node_attributes(unrolled.multi_graph, name='name',
values={run[0]: right_name})
# params is a list of sympy symbols
nx.set_node_attributes(unrolled.multi_graph, name='params',
values={run[0]: new_params})
# Delete the other nodes in the run
for current_node in run[1:]:
unrolled._remove_op_node(current_node)
if right_name == "nop":
unrolled._remove_op_node(run[0])
return unrolled
def remove_last_measurements(dag_circuit, perform_remove=True):
"""Removes all measurements that occur as the last operation
on a given qubit for a DAG circuit. Measurements that are followed by
additional gates are untouched.
This operation is done in-place on the input DAG circuit if perform_pop=True.
Parameters:
dag_circuit (qiskit.dagcircuit._dagcircuit.DAGCircuit): DAG circuit.
perform_remove (bool): Whether to perform removal, or just return node list.
Returns:
list: List of all measurements that were removed.
"""
removed_meas = []
try:
meas_nodes = dag_circuit.get_named_nodes('measure')
except DAGCircuitError:
return removed_meas
for idx in meas_nodes:
_, succ_map = dag_circuit._make_pred_succ_maps(idx)
if len(succ_map) == 2:
# All succesors of the measurement are outputs, one for qubit and one for cbit
# (As opposed to more gates being applied), and it is safe to remove the
# measurement node and add it back after the swap mapper is done.
removed_meas.append(dag_circuit.multi_graph.node[idx])
if perform_remove:
dag_circuit._remove_op_node(idx)
return removed_meas
def return_last_measurements(dag_circuit, removed_meas, final_layout):
"""Returns the measurements to a quantum circuit, removed by
`remove_last_measurements` after the swap mapper is finished.
This operation is done in-place on the input DAG circuit.
Parameters:
dag_circuit (qiskit.dagcircuit._dagcircuit.DAGCircuit): DAG circuit.
removed_meas (list): List of measurements previously removed.
final_layout (dict): Qubit layout after swap mapping.
"""
if any(removed_meas) and 'measure' not in dag_circuit.basis.keys():
dag_circuit.add_basis_element("measure", 1, 1, 0)
for meas in removed_meas:
new_q_label = final_layout[meas['qargs'][0]]
dag_circuit.apply_operation_back(name='measure', qargs=[new_q_label],
cargs=meas['cargs'])
<|code_end|>
|
examples/python/teleport.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Quantum teleportation example.
Note: if you have only cloned the Qiskit repository but not
used `pip install`, the examples only work from the root directory.
"""
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import compile, Aer
###############################################################
# Set the backend name and coupling map.
###############################################################
coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]]
backend = Aer.get_backend("qasm_simulator")
###############################################################
# Make a quantum program for quantum teleportation.
###############################################################
q = QuantumRegister(3, "q")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
c2 = ClassicalRegister(1, "c2")
qc = QuantumCircuit(q, c0, c1, c2, name="teleport")
# Prepare an initial state
qc.u3(0.3, 0.2, 0.1, q[0])
# Prepare a Bell pair
qc.h(q[1])
qc.cx(q[1], q[2])
# Barrier following state preparation
qc.barrier(q)
# Measure in the Bell basis
qc.cx(q[0], q[1])
qc.h(q[0])
qc.measure(q[0], c0[0])
qc.measure(q[1], c1[0])
# Apply a correction
qc.barrier(q)
qc.z(q[2]).c_if(c0, 1)
qc.x(q[2]).c_if(c1, 1)
qc.measure(q[2], c2[0])
###############################################################
# Execute.
# Experiment does not support feedback, so we use the simulator
###############################################################
# First version: not mapped
initial_layout = {("q", 0): ("q", 0), ("q", 1): ("q", 1),
("q", 2): ("q", 2)}
qobj = compile(qc, backend=backend, coupling_map=None, shots=1024, initial_layout=initial_layout)
job = backend.run(qobj)
qobj_exp = qobj.experiments[0]
result = job.result()
print(result)
print(result.get_counts(qc))
# Second version: mapped to 2x8 array coupling graph
qobj = compile(qc, backend=backend, coupling_map=coupling_map, shots=1024,initial_layout=initial_layout)
qobj_exp = qobj.experiments[0]
qobj_exp.header.compiled_circuit_qasm = ""
job = backend.run(qobj)
result = job.result()
print(result)
print(result.get_counts(qc))
# Both versions should give the same distribution
<|code_end|>
qiskit/mapper/_mapping.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name, inconsistent-return-statements
"""
Layout module to assist with mapping circuit qubits onto physical qubits.
"""
import logging
import pprint
import sys
import networkx as nx
import numpy as np
import sympy
from sympy import Number as N
from qiskit.qasm import _node as node
from qiskit.mapper import MapperError
from qiskit.dagcircuit import DAGCircuit
from qiskit.dagcircuit._dagcircuiterror import DAGCircuitError
from qiskit.unrollers._dagunroller import DagUnroller
from qiskit.unrollers._dagbackend import DAGBackend
from qiskit.mapper._quaternion import quaternion_from_euler
from qiskit import QuantumRegister
logger = logging.getLogger(__name__)
# Notes:
# Measurements may occur and be followed by swaps that result in repeated
# measurement of the same qubit. Near-term experiments cannot implement
# these circuits, so we may need to modify the algorithm.
# It can happen that a swap in a deeper layer can be removed by permuting
# qubits in the layout. We don't do this.
# It can happen that initial swaps can be removed or partly simplified
# because the initial state is zero. We don't do this.
cx_data = {
"opaque": False,
"n_args": 0,
"n_bits": 2,
"args": [],
"bits": ["c", "t"],
# gate cx c,t { CX c,t; }
"body": node.GateBody([
node.Cnot([
node.Id("c", 0, ""),
node.Id("t", 0, "")
])
])
}
swap_data = {
"opaque": False,
"n_args": 0,
"n_bits": 2,
"args": [],
"bits": ["a", "b"],
# gate swap a,b { cx a,b; cx b,a; cx a,b; }
"body": node.GateBody([
node.CustomUnitary([
node.Id("cx", 0, ""),
node.PrimaryList([
node.Id("a", 0, ""),
node.Id("b", 0, "")
])
]),
node.CustomUnitary([
node.Id("cx", 0, ""),
node.PrimaryList([
node.Id("b", 0, ""),
node.Id("a", 0, "")
])
]),
node.CustomUnitary([
node.Id("cx", 0, ""),
node.PrimaryList([
node.Id("a", 0, ""),
node.Id("b", 0, "")
])
])
])
}
u2_data = {
"opaque": False,
"n_args": 2,
"n_bits": 1,
"args": ["phi", "lambda"],
"bits": ["q"],
# gate u2(phi,lambda) q { U(pi/2,phi,lambda) q; }
"body": node.GateBody([
node.UniversalUnitary([
node.ExpressionList([
node.BinaryOp([
node.BinaryOperator('/'),
node.Real(sympy.pi),
node.Int(2)
]),
node.Id("phi", 0, ""),
node.Id("lambda", 0, "")
]),
node.Id("q", 0, "")
])
])
}
h_data = {
"opaque": False,
"n_args": 0,
"n_bits": 1,
"args": [],
"bits": ["a"],
# gate h a { u2(0,pi) a; }
"body": node.GateBody([
node.CustomUnitary([
node.Id("u2", 0, ""),
node.ExpressionList([
node.Int(0),
node.Real(sympy.pi)
]),
node.PrimaryList([
node.Id("a", 0, "")
])
])
])
}
def layer_permutation(layer_partition, layout, qubit_subset, coupling, trials,
seed=None):
"""Find a swap circuit that implements a permutation for this layer.
The goal is to swap qubits such that qubits in the same two-qubit gates
are adjacent.
Based on Sergey Bravyi's algorithm.
The layer_partition is a list of (qu)bit lists and each qubit is a
tuple (qreg, index).
The layout is a dict mapping qubits in the circuit to qubits in the
coupling graph and represents the current positions of the data.
The qubit_subset is the subset of qubits in the coupling graph that
we have chosen to map into.
The coupling is a CouplingGraph.
TRIALS is the number of attempts the randomized algorithm makes.
Returns: success_flag, best_circ, best_d, best_layout, trivial_flag
If success_flag is True, then best_circ contains a DAGCircuit with
the swap circuit, best_d contains the depth of the swap circuit, and
best_layout contains the new positions of the data qubits after the
swap circuit has been applied. The trivial_flag is set if the layer
has no multi-qubit gates.
"""
if seed is not None:
np.random.seed(seed)
logger.debug("layer_permutation: ----- enter -----")
logger.debug("layer_permutation: layer_partition = %s",
pprint.pformat(layer_partition))
logger.debug("layer_permutation: layout = %s",
pprint.pformat(layout))
logger.debug("layer_permutation: qubit_subset = %s",
pprint.pformat(qubit_subset))
logger.debug("layer_permutation: trials = %s", trials)
rev_layout = {b: a for a, b in layout.items()}
gates = []
for layer in layer_partition:
if len(layer) > 2:
raise MapperError("Layer contains >2 qubit gates")
elif len(layer) == 2:
gates.append(tuple(layer))
logger.debug("layer_permutation: gates = %s", pprint.pformat(gates))
# Find layout maximum index
layout_max_index = max(map(lambda x: x[1]+1, layout.values()))
# Can we already apply the gates?
dist = sum([coupling.distance(layout[g[0]],
layout[g[1]]) for g in gates])
logger.debug("layer_permutation: dist = %s", dist)
if dist == len(gates):
logger.debug("layer_permutation: done already")
logger.debug("layer_permutation: ----- exit -----")
circ = DAGCircuit()
circ.add_qreg(QuantumRegister(layout_max_index, "q"))
circ.add_basis_element("CX", 2)
circ.add_basis_element("cx", 2)
circ.add_basis_element("swap", 2)
circ.add_gate_data("cx", cx_data)
circ.add_gate_data("swap", swap_data)
return True, circ, 0, layout, bool(gates)
# Begin loop over trials of randomized algorithm
n = coupling.size()
best_d = sys.maxsize # initialize best depth
best_circ = None # initialize best swap circuit
best_layout = None # initialize best final layout
for trial in range(trials):
logger.debug("layer_permutation: trial %s", trial)
trial_layout = layout.copy()
rev_trial_layout = rev_layout.copy()
# SWAP circuit constructed this trial
trial_circ = DAGCircuit()
trial_circ.add_qreg(QuantumRegister(layout_max_index, "q"))
# Compute Sergey's randomized distance
xi = {}
for i in coupling.get_qubits():
xi[i] = {}
for i in coupling.get_qubits():
for j in coupling.get_qubits():
scale = 1 + np.random.normal(0, 1 / n)
xi[i][j] = scale * coupling.distance(i, j) ** 2
xi[j][i] = xi[i][j]
# Loop over depths d up to a max depth of 2n+1
d = 1
# Circuit for this swap slice
circ = DAGCircuit()
circ.add_qreg(QuantumRegister(layout_max_index, "q"))
circ.add_basis_element("CX", 2)
circ.add_basis_element("cx", 2)
circ.add_basis_element("swap", 2)
circ.add_gate_data("cx", cx_data)
circ.add_gate_data("swap", swap_data)
# Identity wire-map for composing the circuits
identity_wire_map = {('q', j): ('q', j) for j in range(layout_max_index)}
while d < 2 * n + 1:
# Set of available qubits
qubit_set = set(qubit_subset)
# While there are still qubits available
while qubit_set:
# Compute the objective function
min_cost = sum([xi[trial_layout[g[0]]][trial_layout[g[1]]]
for g in gates])
# Try to decrease objective function
progress_made = False
# Loop over edges of coupling graph
for e in coupling.get_edges():
# Are the qubits available?
if e[0] in qubit_set and e[1] in qubit_set:
# Try this edge to reduce the cost
new_layout = trial_layout.copy()
new_layout[rev_trial_layout[e[0]]] = e[1]
new_layout[rev_trial_layout[e[1]]] = e[0]
rev_new_layout = rev_trial_layout.copy()
rev_new_layout[e[0]] = rev_trial_layout[e[1]]
rev_new_layout[e[1]] = rev_trial_layout[e[0]]
# Compute the objective function
new_cost = sum([xi[new_layout[g[0]]][new_layout[g[1]]]
for g in gates])
# Record progress if we succceed
if new_cost < min_cost:
logger.debug("layer_permutation: progress! "
"min_cost = %s", min_cost)
progress_made = True
min_cost = new_cost
opt_layout = new_layout
rev_opt_layout = rev_new_layout
opt_edge = e
# Were there any good choices?
if progress_made:
qubit_set.remove(opt_edge[0])
qubit_set.remove(opt_edge[1])
trial_layout = opt_layout
rev_trial_layout = rev_opt_layout
circ.apply_operation_back("swap", [(opt_edge[0][0],
opt_edge[0][1]),
(opt_edge[1][0],
opt_edge[1][1])])
logger.debug("layer_permutation: chose pair %s",
pprint.pformat(opt_edge))
else:
break
# We have either run out of qubits or failed to improve
# Compute the coupling graph distance
dist = sum([coupling.distance(trial_layout[g[0]],
trial_layout[g[1]]) for g in gates])
logger.debug("layer_permutation: dist = %s", dist)
# If all gates can be applied now, we are finished
# Otherwise we need to consider a deeper swap circuit
if dist == len(gates):
logger.debug("layer_permutation: all can be applied now")
trial_circ.compose_back(circ, identity_wire_map)
break
# Increment the depth
d += 1
logger.debug("layer_permutation: increment depth to %s", d)
# Either we have succeeded at some depth d < dmax or failed
dist = sum([coupling.distance(trial_layout[g[0]],
trial_layout[g[1]]) for g in gates])
logger.debug("layer_permutation: dist = %s", dist)
if dist == len(gates):
if d < best_d:
logger.debug("layer_permutation: got circuit with depth %s", d)
best_circ = trial_circ
best_layout = trial_layout
best_d = min(best_d, d)
if best_circ is None:
logger.debug("layer_permutation: failed!")
logger.debug("layer_permutation: ----- exit -----")
return False, None, None, None, False
logger.debug("layer_permutation: done")
logger.debug("layer_permutation: ----- exit -----")
return True, best_circ, best_d, best_layout, False
def direction_mapper(circuit_graph, coupling_graph):
"""Change the direction of CNOT gates to conform to CouplingGraph.
circuit_graph = input DAGCircuit
coupling_graph = corresponding CouplingGraph
Adds "h" to the circuit basis.
Returns a DAGCircuit object containing a circuit equivalent to
circuit_graph but with CNOT gate directions matching the edges
of coupling_graph. Raises an exception if the circuit_graph
does not conform to the coupling_graph.
"""
if "cx" not in circuit_graph.basis:
return circuit_graph
if circuit_graph.basis["cx"] != (2, 0, 0):
raise MapperError("cx gate has unexpected signature %s" %
circuit_graph.basis["cx"])
flipped_cx_circuit = DAGCircuit()
flipped_cx_circuit.add_qreg(QuantumRegister(2, "q"))
flipped_cx_circuit.add_basis_element("CX", 2)
flipped_cx_circuit.add_basis_element("U", 1, 0, 3)
flipped_cx_circuit.add_basis_element("cx", 2)
flipped_cx_circuit.add_basis_element("u2", 1, 0, 2)
flipped_cx_circuit.add_basis_element("h", 1)
flipped_cx_circuit.add_gate_data("cx", cx_data)
flipped_cx_circuit.add_gate_data("u2", u2_data)
flipped_cx_circuit.add_gate_data("h", h_data)
flipped_cx_circuit.apply_operation_back("h", [("q", 0)])
flipped_cx_circuit.apply_operation_back("h", [("q", 1)])
flipped_cx_circuit.apply_operation_back("cx", [("q", 1), ("q", 0)])
flipped_cx_circuit.apply_operation_back("h", [("q", 0)])
flipped_cx_circuit.apply_operation_back("h", [("q", 1)])
cg_edges = coupling_graph.get_edges()
for cx_node in circuit_graph.get_named_nodes("cx"):
nd = circuit_graph.multi_graph.node[cx_node]
cxedge = tuple(nd["qargs"])
if cxedge in cg_edges:
logger.debug("cx %s[%d], %s[%d] -- OK",
cxedge[0][0], cxedge[0][1],
cxedge[1][0], cxedge[1][1])
continue
elif (cxedge[1], cxedge[0]) in cg_edges:
circuit_graph.substitute_circuit_one(cx_node,
flipped_cx_circuit,
wires=[("q", 0), ("q", 1)])
logger.debug("cx %s[%d], %s[%d] -FLIP",
cxedge[0][0], cxedge[0][1],
cxedge[1][0], cxedge[1][1])
else:
raise MapperError("circuit incompatible with CouplingGraph: "
"cx on %s" % pprint.pformat(cxedge))
return circuit_graph
def swap_mapper_layer_update(i, first_layer, best_layout, best_d,
best_circ, layer_list):
"""Update the QASM string for an iteration of swap_mapper.
i = layer number
first_layer = True if this is the first layer with multi-qubit gates
best_layout = layout returned from swap algorithm
best_d = depth returned from swap algorithm
best_circ = swap circuit returned from swap algorithm
layer_list = list of circuit objects for each layer
Return DAGCircuit object to append to the output DAGCircuit.
"""
layout = best_layout
layout_max_index = max(map(lambda x: x[1]+1, layout.values()))
dagcircuit_output = DAGCircuit()
dagcircuit_output.add_qreg(QuantumRegister(layout_max_index, "q"))
# Identity wire-map for composing the circuits
identity_wire_map = {('q', j): ('q', j) for j in range(layout_max_index)}
# If this is the first layer with multi-qubit gates,
# output all layers up to this point and ignore any
# swap gates. Set the initial layout.
if first_layer:
logger.debug("update_qasm_and_layout: first multi-qubit gate layer")
# Output all layers up to this point
for j in range(i + 1):
dagcircuit_output.compose_back(layer_list[j]["graph"], layout)
# Otherwise, we output the current layer and the associated swap gates.
else:
# Output any swaps
if best_d > 0:
logger.debug("update_qasm_and_layout: swaps in this layer, "
"depth %d", best_d)
dagcircuit_output.compose_back(best_circ, identity_wire_map)
else:
logger.debug("update_qasm_and_layout: no swaps in this layer")
# Output this layer
dagcircuit_output.compose_back(layer_list[i]["graph"], layout)
return dagcircuit_output
def swap_mapper(circuit_graph, coupling_graph,
initial_layout=None,
basis="cx,u1,u2,u3,id", trials=20, seed=None):
"""Map a DAGCircuit onto a CouplingGraph using swap gates.
Args:
circuit_graph (DAGCircuit): input DAG circuit
coupling_graph (CouplingGraph): coupling graph to map onto
initial_layout (dict): dict from qubits of circuit_graph to qubits
of coupling_graph (optional)
basis (str): basis string specifying basis of output DAGCircuit
trials (int): number of trials.
seed (int): initial seed.
Returns:
DAGCircuit: object containing a circuit equivalent to
circuit_graph that respects couplings in coupling_graph, and
a layout dict mapping qubits of circuit_graph into qubits
of coupling_graph. The layout may differ from the initial_layout
if the first layer of gates cannot be executed on the
initial_layout. Finally, returned is the final layer qubit
permutation that is needed to add measurements back in.
Raises:
MapperError: if there was any error during the mapping or with the
parameters.
"""
if circuit_graph.width() > coupling_graph.size():
raise MapperError("Not enough qubits in CouplingGraph")
# Schedule the input circuit
layerlist = list(circuit_graph.layers())
logger.debug("schedule:")
for i, v in enumerate(layerlist):
logger.debug(" %d: %s", i, v["partition"])
if initial_layout is not None:
# Check the input layout
circ_qubits = circuit_graph.get_qubits()
coup_qubits = coupling_graph.get_qubits()
qubit_subset = []
for k, v in initial_layout.items():
qubit_subset.append(v)
if k not in circ_qubits:
raise MapperError("initial_layout qubit %s[%d] not in input "
"DAGCircuit" % (k[0], k[1]))
if v not in coup_qubits:
raise MapperError("initial_layout qubit %s[%d] not in input "
"CouplingGraph" % (v[0], v[1]))
else:
# Supply a default layout
qubit_subset = coupling_graph.get_qubits()
qubit_subset = qubit_subset[0:circuit_graph.width()]
initial_layout = {a: b for a, b in
zip(circuit_graph.get_qubits(), qubit_subset)}
# Find swap circuit to preceed to each layer of input circuit
layout = initial_layout.copy()
layout_max_index = max(map(lambda x: x[1]+1, layout.values()))
# Construct an empty DAGCircuit with one qreg "q"
# and the same set of cregs as the input circuit
dagcircuit_output = DAGCircuit()
dagcircuit_output.name = circuit_graph.name
dagcircuit_output.add_qreg(QuantumRegister(layout_max_index, "q"))
for creg in circuit_graph.cregs.values():
dagcircuit_output.add_creg(creg)
# Make a trivial wire mapping between the subcircuits
# returned by swap_mapper_layer_update and the circuit
# we are building
identity_wire_map = {}
for j in range(layout_max_index):
identity_wire_map[("q", j)] = ("q", j)
for creg in circuit_graph.cregs.values():
for j in range(creg.size):
identity_wire_map[(creg.name, j)] = (creg.name, j)
first_layer = True # True until first layer is output
logger.debug("initial_layout = %s", layout)
# Iterate over layers
for i, layer in enumerate(layerlist):
# Attempt to find a permutation for this layer
success_flag, best_circ, best_d, best_layout, trivial_flag \
= layer_permutation(layer["partition"], layout,
qubit_subset, coupling_graph, trials, seed)
logger.debug("swap_mapper: layer %d", i)
logger.debug("swap_mapper: success_flag=%s,best_d=%s,trivial_flag=%s",
success_flag, str(best_d), trivial_flag)
# If this fails, try one gate at a time in this layer
if not success_flag:
logger.debug("swap_mapper: failed, layer %d, "
"retrying sequentially", i)
serial_layerlist = list(layer["graph"].serial_layers())
# Go through each gate in the layer
for j, serial_layer in enumerate(serial_layerlist):
success_flag, best_circ, best_d, best_layout, trivial_flag \
= layer_permutation(serial_layer["partition"],
layout, qubit_subset, coupling_graph,
trials, seed)
logger.debug("swap_mapper: layer %d, sublayer %d", i, j)
logger.debug("swap_mapper: success_flag=%s,best_d=%s,"
"trivial_flag=%s",
success_flag, str(best_d), trivial_flag)
# Give up if we fail again
if not success_flag:
raise MapperError("swap_mapper failed: " +
"layer %d, sublayer %d" % (i, j) +
", \"%s\"" %
serial_layer["graph"].qasm(
no_decls=True,
aliases=layout))
# If this layer is only single-qubit gates,
# and we have yet to see multi-qubit gates,
# continue to the next inner iteration
if trivial_flag and first_layer:
logger.debug("swap_mapper: skip to next sublayer")
continue
# Update the record of qubit positions for each inner iteration
layout = best_layout
# Update the QASM
dagcircuit_output.compose_back(
swap_mapper_layer_update(j,
first_layer,
best_layout,
best_d,
best_circ,
serial_layerlist),
identity_wire_map)
# Update initial layout
if first_layer:
initial_layout = layout
first_layer = False
else:
# Update the record of qubit positions for each iteration
layout = best_layout
# Update the QASM
dagcircuit_output.compose_back(
swap_mapper_layer_update(i,
first_layer,
best_layout,
best_d,
best_circ,
layerlist),
identity_wire_map)
# Update initial layout
if first_layer:
initial_layout = layout
first_layer = False
# This is the final layout that we need to correctly replace
# any measurements that needed to be removed before the swap
last_layout = layout
# If first_layer is still set, the circuit only has single-qubit gates
# so we can use the initial layout to output the entire circuit
if first_layer:
layout = initial_layout
for i, layer in enumerate(layerlist):
dagcircuit_output.compose_back(layer["graph"], layout)
# Parse openqasm_output into DAGCircuit object
dag_unrolled = DagUnroller(dagcircuit_output,
DAGBackend(basis.split(",")))
dagcircuit_output = dag_unrolled.expand_gates()
return dagcircuit_output, initial_layout, last_layout
def yzy_to_zyz(xi, theta1, theta2, eps=1e-9):
"""Express a Y.Z.Y single qubit gate as a Z.Y.Z gate.
Solve the equation
.. math::
Ry(theta1).Rz(xi).Ry(theta2) = Rz(phi).Ry(theta).Rz(lambda)
for theta, phi, and lambda.
Return a solution theta, phi, and lambda.
"""
Q = quaternion_from_euler([theta1, xi, theta2], 'yzy')
euler = Q.to_zyz()
P = quaternion_from_euler(euler, 'zyz')
# output order different than rotation order
out_angles = (euler[1], euler[0], euler[2])
abs_inner = abs(P.data.dot(Q.data))
if not np.allclose(abs_inner, 1, eps):
logger.debug("xi=%s", xi)
logger.debug("theta1=%s", theta1)
logger.debug("theta2=%s", theta2)
logger.debug("solutions=%s", out_angles)
logger.debug("abs_inner=%s", abs_inner)
raise MapperError('YZY and ZYZ angles do not give same rotation matrix.')
return out_angles
def compose_u3(theta1, phi1, lambda1, theta2, phi2, lambda2):
"""Return a triple theta, phi, lambda for the product.
u3(theta, phi, lambda)
= u3(theta1, phi1, lambda1).u3(theta2, phi2, lambda2)
= Rz(phi1).Ry(theta1).Rz(lambda1+phi2).Ry(theta2).Rz(lambda2)
= Rz(phi1).Rz(phi').Ry(theta').Rz(lambda').Rz(lambda2)
= u3(theta', phi1 + phi', lambda2 + lambda')
Return theta, phi, lambda.
"""
# Careful with the factor of two in yzy_to_zyz
thetap, phip, lambdap = yzy_to_zyz((lambda1 + phi2),
theta1, theta2)
(theta, phi, lamb) = (thetap, phi1 + phip, lambda2 + lambdap)
return (theta, phi, lamb)
def cx_cancellation(circuit):
"""Cancel back-to-back "cx" gates in circuit."""
runs = circuit.collect_runs(["cx"])
for run in runs:
# Partition the run into chunks with equal gate arguments
partition = []
chunk = []
for i in range(len(run) - 1):
chunk.append(run[i])
qargs0 = circuit.multi_graph.node[run[i]]["qargs"]
qargs1 = circuit.multi_graph.node[run[i + 1]]["qargs"]
if qargs0 != qargs1:
partition.append(chunk)
chunk = []
chunk.append(run[-1])
partition.append(chunk)
# Simplify each chunk in the partition
for chunk in partition:
if len(chunk) % 2 == 0:
for n in chunk:
circuit._remove_op_node(n)
else:
for n in chunk[1:]:
circuit._remove_op_node(n)
def optimize_1q_gates(circuit):
"""Simplify runs of single qubit gates in the QX basis.
Return a new circuit that has been optimized.
"""
qx_basis = ["u1", "u2", "u3", "cx", "id"]
dag_unroller = DagUnroller(circuit, DAGBackend(qx_basis))
unrolled = dag_unroller.expand_gates()
runs = unrolled.collect_runs(["u1", "u2", "u3", "id"])
for run in runs:
qname = unrolled.multi_graph.node[run[0]]["qargs"][0]
right_name = "u1"
right_parameters = (N(0), N(0), N(0)) # (theta, phi, lambda)
for current_node in run:
nd = unrolled.multi_graph.node[current_node]
left_name = nd["name"]
if (nd["condition"] is not None
or len(nd["qargs"]) != 1
or nd["qargs"][0] != qname
or left_name not in ["u1", "u2", "u3", "id"]):
raise MapperError("internal error")
if left_name == "u1":
left_parameters = (N(0), N(0), nd["params"][0])
elif left_name == "u2":
left_parameters = (sympy.pi / 2, nd["params"][0], nd["params"][1])
elif left_name == "u3":
left_parameters = tuple(nd["params"])
else:
left_name = "u1" # replace id with u1
left_parameters = (N(0), N(0), N(0))
# Compose gates
name_tuple = (left_name, right_name)
if name_tuple == ("u1", "u1"):
# u1(lambda1) * u1(lambda2) = u1(lambda1 + lambda2)
right_parameters = (N(0), N(0), right_parameters[2] +
left_parameters[2])
elif name_tuple == ("u1", "u2"):
# u1(lambda1) * u2(phi2, lambda2) = u2(phi2 + lambda1, lambda2)
right_parameters = (sympy.pi / 2, right_parameters[1] +
left_parameters[2], right_parameters[2])
elif name_tuple == ("u2", "u1"):
# u2(phi1, lambda1) * u1(lambda2) = u2(phi1, lambda1 + lambda2)
right_name = "u2"
right_parameters = (sympy.pi / 2, left_parameters[1],
right_parameters[2] + left_parameters[2])
elif name_tuple == ("u1", "u3"):
# u1(lambda1) * u3(theta2, phi2, lambda2) =
# u3(theta2, phi2 + lambda1, lambda2)
right_parameters = (right_parameters[0], right_parameters[1] +
left_parameters[2], right_parameters[2])
elif name_tuple == ("u3", "u1"):
# u3(theta1, phi1, lambda1) * u1(lambda2) =
# u3(theta1, phi1, lambda1 + lambda2)
right_name = "u3"
right_parameters = (left_parameters[0], left_parameters[1],
right_parameters[2] + left_parameters[2])
elif name_tuple == ("u2", "u2"):
# Using Ry(pi/2).Rz(2*lambda).Ry(pi/2) =
# Rz(pi/2).Ry(pi-2*lambda).Rz(pi/2),
# u2(phi1, lambda1) * u2(phi2, lambda2) =
# u3(pi - lambda1 - phi2, phi1 + pi/2, lambda2 + pi/2)
right_name = "u3"
right_parameters = (sympy.pi - left_parameters[2] -
right_parameters[1], left_parameters[1] +
sympy.pi / 2, right_parameters[2] +
sympy.pi / 2)
elif name_tuple[1] == "nop":
right_name = left_name
right_parameters = left_parameters
else:
# For composing u3's or u2's with u3's, use
# u2(phi, lambda) = u3(pi/2, phi, lambda)
# together with the qiskit.mapper.compose_u3 method.
right_name = "u3"
# Evaluate the symbolic expressions for efficiency
left_parameters = tuple(map(lambda x: x.evalf(), list(left_parameters)))
right_parameters = tuple(map(lambda x: x.evalf(), list(right_parameters)))
right_parameters = compose_u3(left_parameters[0],
left_parameters[1],
left_parameters[2],
right_parameters[0],
right_parameters[1],
right_parameters[2])
# Why evalf()? This program:
# OPENQASM 2.0;
# include "qelib1.inc";
# qreg q[2];
# creg c[2];
# u3(0.518016983430947*pi,1.37051598592907*pi,1.36816383603222*pi) q[0];
# u3(1.69867232277986*pi,0.371448347747471*pi,0.461117217930936*pi) q[0];
# u3(0.294319836336836*pi,0.450325871124225*pi,1.46804720442555*pi) q[0];
# measure q -> c;
# took >630 seconds (did not complete) to optimize without
# calling evalf() at all, 19 seconds to optimize calling
# evalf() AFTER compose_u3, and 1 second to optimize
# calling evalf() BEFORE compose_u3.
# 1. Here down, when we simplify, we add f(theta) to lambda to
# correct the global phase when f(theta) is 2*pi. This isn't
# necessary but the other steps preserve the global phase, so
# we continue in that manner.
# 2. The final step will remove Z rotations by 2*pi.
# 3. Note that is_zero is true only if the expression is exactly
# zero. If the input expressions have already been evaluated
# then these final simplifications will not occur.
# TODO After we refactor, we should have separate passes for
# exact and approximate rewriting.
# Y rotation is 0 mod 2*pi, so the gate is a u1
if (right_parameters[0] % (2 * sympy.pi)).is_zero \
and right_name != "u1":
right_name = "u1"
right_parameters = (0, 0, right_parameters[1] +
right_parameters[2] +
right_parameters[0])
# Y rotation is pi/2 or -pi/2 mod 2*pi, so the gate is a u2
if right_name == "u3":
# theta = pi/2 + 2*k*pi
if ((right_parameters[0] - sympy.pi / 2) % (2 * sympy.pi)).is_zero:
right_name = "u2"
right_parameters = (sympy.pi / 2, right_parameters[1],
right_parameters[2] +
(right_parameters[0] - sympy.pi / 2))
# theta = -pi/2 + 2*k*pi
if ((right_parameters[0] + sympy.pi / 2) % (2 * sympy.pi)).is_zero:
right_name = "u2"
right_parameters = (sympy.pi / 2, right_parameters[1] +
sympy.pi, right_parameters[2] -
sympy.pi + (right_parameters[0] +
sympy.pi / 2))
# u1 and lambda is 0 mod 2*pi so gate is nop (up to a global phase)
if right_name == "u1" and (right_parameters[2] % (2 * sympy.pi)).is_zero:
right_name = "nop"
# Simplify the symbolic parameters
right_parameters = tuple(map(sympy.simplify, list(right_parameters)))
# Replace the data of the first node in the run
new_params = []
if right_name == "u1":
new_params = [right_parameters[2]]
if right_name == "u2":
new_params = [right_parameters[1], right_parameters[2]]
if right_name == "u3":
new_params = list(right_parameters)
nx.set_node_attributes(unrolled.multi_graph, name='name',
values={run[0]: right_name})
# params is a list of sympy symbols
nx.set_node_attributes(unrolled.multi_graph, name='params',
values={run[0]: new_params})
# Delete the other nodes in the run
for current_node in run[1:]:
unrolled._remove_op_node(current_node)
if right_name == "nop":
unrolled._remove_op_node(run[0])
return unrolled
def remove_last_measurements(dag_circuit, perform_remove=True):
"""Removes all measurements that occur as the last operation
on a given qubit for a DAG circuit. Measurements that are followed by
additional gates are untouched.
This operation is done in-place on the input DAG circuit if perform_pop=True.
Parameters:
dag_circuit (qiskit.dagcircuit._dagcircuit.DAGCircuit): DAG circuit.
perform_remove (bool): Whether to perform removal, or just return node list.
Returns:
list: List of all measurements that were removed.
"""
removed_meas = []
try:
meas_nodes = dag_circuit.get_named_nodes('measure')
except DAGCircuitError:
return removed_meas
for idx in meas_nodes:
_, succ_map = dag_circuit._make_pred_succ_maps(idx)
if len(succ_map) == 2 and all([dag_circuit.multi_graph.node[n]["type"] == "out"
for n in succ_map.values()]):
# All succesors of the measurement are outputs, one for qubit and one for cbit
# (As opposed to more gates being applied), and it is safe to remove the
# measurement node and add it back after the swap mapper is done.
removed_meas.append(dag_circuit.multi_graph.node[idx])
if perform_remove:
dag_circuit._remove_op_node(idx)
return removed_meas
def return_last_measurements(dag_circuit, removed_meas, final_layout):
"""Returns the measurements to a quantum circuit, removed by
`remove_last_measurements` after the swap mapper is finished.
This operation is done in-place on the input DAG circuit.
Parameters:
dag_circuit (qiskit.dagcircuit._dagcircuit.DAGCircuit): DAG circuit.
removed_meas (list): List of measurements previously removed.
final_layout (dict): Qubit layout after swap mapping.
"""
if any(removed_meas) and 'measure' not in dag_circuit.basis.keys():
dag_circuit.add_basis_element("measure", 1, 1, 0)
for meas in removed_meas:
new_q_label = final_layout[meas['qargs'][0]]
dag_circuit.apply_operation_back(name='measure', qargs=[new_q_label],
cargs=meas['cargs'])
<|code_end|>
|
Latex visualizer confuses the qubits when measurement
### Informations
- **Qiskit Terra version**: master
### What is the current behavior?
The following code generates the following image:
```Python
q = QuantumRegister(3, 'q')
c = ClassicalRegister(1, 'c')
circ_py = QuantumCircuit(q, c)
circ_py.measure(q[0], c[0])
circ_py.z(q[1]).c_if(c, 1)
circ_py.draw(output='latex').show()
```

### What is the expected behavior?
The measurement should be on `q_0`, not on `q_2`
|
qiskit/tools/visualization/_latex.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""latex circuit visualization backends."""
import collections
import io
import itertools
import json
import math
import operator
import re
import numpy as np
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _qcstyle
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, qregs, cregs, ops, scale, style=None,
plot_barriers=True, reverse_bits=False):
"""
Args:
qregs (list): A list of tuples for the quantum registers
cregs (list): A list of tuples for the classical registers
ops (list): A list of dicts where each entry is a operation from
the circuit.
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
"""
# style sheet
self._style = _qcstyle.QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.ops = ops
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
self.reverse_bits = reverse_bits
self.plot_barriers = plot_barriers
#################################
self.qregs = collections.OrderedDict(_get_register_specs(qregs))
self.qubit_list = qregs
self.ordered_regs = qregs + cregs
self.cregs = collections.OrderedDict(_get_register_specs(cregs))
self.clbit_list = cregs
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = io.StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\' + '\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
VisualizationError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.ops:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's',
'sdg', 't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy',
'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image
# scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['params']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float, str(arg))
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
if len(op['cargs']) != 1 or len(op['qargs']) != 1:
raise _error.VisualizationError("bad operation record")
if 'condition' in op and op['condition']:
raise _error.VisualizationError(
'conditional measures currently not supported.')
qindex = self._get_qubit_index(op['qargs'][0])
cindex = self._get_clbit_index(op['cargs'][0])
qname, qindex = self.total_2_register_index(
qindex, self.qregs)
cname, cindex = self.total_2_register_index(
cindex, self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op and op['condition']:
raise _error.VisualizationError(
'conditional reset currently not supported.')
qindex = self._get_qubit_index(op['qargs'][0])
qname, qindex = self.total_2_register_index(
qindex, self.qregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
raise _error.VisualizationError("bad node data")
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns + 1, math.ceil(sum_column_widths) + 4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet
# (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def _get_qubit_index(self, qubit):
"""Get the index number for a quantum bit
Args:
qubit (tuple): The tuple of the bit of the form
(register_name, bit_number)
Returns:
int: The index in the bit list
Raises:
VisualizationError: If the bit isn't found
"""
for i, bit in enumerate(self.qubit_list):
if qubit == bit:
qindex = i
break
else:
raise _error.VisualizationError(
"unable to find bit for operation")
return qindex
def _get_clbit_index(self, clbit):
"""Get the index number for a classical bit
Args:
clbit (tuple): The tuple of the bit of the form
(register_name, bit_number)
Returns:
int: The index in the bit list
Raises:
VisualizationError: If the bit isn't found
"""
for i, bit in enumerate(self.clbit_list):
if clbit == bit:
cindex = i
break
else:
raise _error.VisualizationError(
"unable to find bit for operation")
return cindex
def total_2_register_index(self, index, registers):
"""Get register name for qubit index.
This function uses the self.qregs ordered dictionary, which looks like
{'qr1': 2, 'qr2', 3}
to get the register name for the total qubit index. For the above
example, index in [0,1] returns 'qr1' and index in [2,4] returns 'qr2'.
Args:
index (int): total qubit index among all quantum registers
registers (OrderedDict): OrderedDict as described above.
Returns:
str: name of register associated with qubit index.
Raises:
ValueError: if the qubit index lies outside the range of qubit
registers.
"""
count = 0
for name, size in registers.items():
if count + size > index:
return name, index - count
else:
count += size
raise ValueError('qubit index lies outside range of qubit registers')
def _get_mask(self, creg_name):
mask = 0
for index, cbit in enumerate(self.clbit_list):
if creg_name == cbit[0]:
mask |= (1 << index)
return mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.ops):
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(op['condition'][1],
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier', 'snapshot', 'load',
'save', 'noise']:
nm = op['name']
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["params"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["params"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["params"][0], op["params"][1])
elif nm == "u3":
self._latex[pos_1][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["params"][0],
op["params"][1],
op["params"][2]))
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["params"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["params"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["params"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["params"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["params"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["params"][0], op["params"][1])
elif nm == "u3":
self._latex[pos_1][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["params"][0],
op["params"][1],
op["params"][2]))
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["params"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["params"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["params"][0])
elif nm == "reset":
self._latex[pos_1][columns] = (
"\\push{\\rule{.6em}{0em}\\ket{0}\\"
"rule{.2em}{0em}} \\qw")
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'condition' in op and op['condition']:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["params"][0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["params"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["params"][0],
op["params"][1],
op["params"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["params"][0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["params"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["params"][0],
op["params"][1],
op["params"][2]))
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'condition' in op and op['condition']:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-0.65em]{')
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(
pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-0.65em]{')
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(
pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
if (len(op['cargs']) != 1
or len(op['qargs']) != 1
or op['params']):
raise _error.VisualizationError("bad operation record")
if 'condition' in op and op['condition']:
raise _error.VisualizationError(
"If controlled measures currently not supported.")
qindex = self._get_qubit_index(op['qargs'][0])
cindex = self._get_clbit_index(op['cargs'][0])
qname, qindex = self.total_2_register_index(
qindex, self.qregs)
cname, cindex = self.total_2_register_index(
cindex, self.cregs)
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise _error.VisualizationError(
'Error during Latex building: %s' % str(e))
elif op['name'] in ["barrier", 'snapshot', 'load', 'save',
'noise']:
if self.plot_barriers:
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qargs']) - 1
self._latex[start][columns] += " \\barrier{" + str(
span) + "}"
else:
raise _error.VisualizationError("bad node data")
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
return origin - 1
def _get_register_specs(bit_labels):
"""Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = itertools.groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
<|code_end|>
|
qiskit/tools/visualization/_latex.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""latex circuit visualization backends."""
import collections
import io
import itertools
import json
import math
import operator
import re
import numpy as np
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _qcstyle
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for QISKit.
"""
def __init__(self, qregs, cregs, ops, scale, style=None,
plot_barriers=True, reverse_bits=False):
"""
Args:
qregs (list): A list of tuples for the quantum registers
cregs (list): A list of tuples for the classical registers
ops (list): A list of dicts where each entry is a operation from
the circuit.
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
"""
# style sheet
self._style = _qcstyle.QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.ops = ops
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
self.reverse_bits = reverse_bits
self.plot_barriers = plot_barriers
#################################
self.qregs = collections.OrderedDict(_get_register_specs(qregs))
self.qubit_list = qregs
self.ordered_regs = qregs + cregs
self.cregs = collections.OrderedDict(_get_register_specs(cregs))
self.clbit_list = cregs
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = io.StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\' + '\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0] + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0] + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
VisualizationError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.ops:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's',
'sdg', 't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy',
'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image
# scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['params']:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float, str(arg))
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
if len(op['cargs']) != 1 or len(op['qargs']) != 1:
raise _error.VisualizationError("bad operation record")
if 'condition' in op and op['condition']:
raise _error.VisualizationError(
'conditional measures currently not supported.')
qname, qindex = op['qargs'][0]
cname, cindex = op['cargs'][0]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op and op['condition']:
raise _error.VisualizationError(
'conditional reset currently not supported.')
qname, qindex = op['qargs'][0]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
raise _error.VisualizationError("bad node data")
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns + 1, math.ceil(sum_column_widths) + 4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet
# (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def _get_mask(self, creg_name):
mask = 0
for index, cbit in enumerate(self.clbit_list):
if creg_name == cbit[0]:
mask |= (1 << index)
return mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.ops):
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(op['condition'][1],
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier', 'snapshot', 'load',
'save', 'noise']:
nm = op['name']
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["params"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["params"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["params"][0], op["params"][1])
elif nm == "u3":
self._latex[pos_1][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["params"][0],
op["params"][1],
op["params"][2]))
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["params"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["params"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["params"][0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["params"][0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["params"][0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["params"][0], op["params"][1])
elif nm == "u3":
self._latex[pos_1][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["params"][0],
op["params"][1],
op["params"][2]))
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["params"][0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["params"][0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["params"][0])
elif nm == "reset":
self._latex[pos_1][columns] = (
"\\push{\\rule{.6em}{0em}\\ket{0}\\"
"rule{.2em}{0em}} \\qw")
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'condition' in op and op['condition']:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["params"][0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["params"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["params"][0],
op["params"][1],
op["params"][2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["params"][0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["params"][0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["params"][0],
op["params"][1],
op["params"][2]))
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'condition' in op and op['condition']:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-0.65em]{')
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(
pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-0.65em]{')
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(
pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
if (len(op['cargs']) != 1
or len(op['qargs']) != 1
or op['params']):
raise _error.VisualizationError("bad operation record")
if 'condition' in op and op['condition']:
raise _error.VisualizationError(
"If controlled measures currently not supported.")
qname, qindex = op['qargs'][0]
cname, cindex = op['cargs'][0]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise _error.VisualizationError(
'Error during Latex building: %s' % str(e))
elif op['name'] in ["barrier", 'snapshot', 'load', 'save',
'noise']:
if self.plot_barriers:
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
span = len(op['qargs']) - 1
self._latex[start][columns] += " \\barrier{" + str(
span) + "}"
else:
raise _error.VisualizationError("bad node data")
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
return origin - 1
def _get_register_specs(bit_labels):
"""Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = itertools.groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
<|code_end|>
|
Dag equality
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
A method to check if two dags are the same.
#1363 and #1349 are holding this up
|
qiskit/dagcircuit/_dagcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Object to represent a quantum circuit as a directed acyclic graph.
The nodes in the graph are either input/output nodes or operation nodes.
The operation nodes are elements of a basis that is part of the circuit.
The QASM definitions of the basis elements are carried with the circuit.
The edges correspond to qubits or bits in the circuit. A directed edge
from node A to node B means that the (qu)bit passes from the output of A
to the input of B. The object's methods allow circuits to be constructed,
composed, and modified. Some natural properties like depth can be computed
directly from the graph.
"""
from collections import OrderedDict
import copy
import itertools
import networkx as nx
import sympy
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QISKitError
from qiskit import _compositegate
from ._dagcircuiterror import DAGCircuitError
class DAGCircuit:
"""
Quantum circuit as a directed acyclic graph.
There are 3 types of nodes in the graph: inputs, outputs, and operations.
The nodes are connected by directed edges that correspond to qubits and
bits.
"""
# pylint: disable=invalid-name
def __init__(self):
"""Create an empty circuit."""
# Circuit name. Generally, this corresponds to the name
# of the QuantumCircuit from which the DAG was generated.
self.name = None
# Map from a wire's name (reg,idx) to a Bool that is True if the
# wire is a classical bit and False if the wire is a qubit.
self.wire_type = OrderedDict()
# Map from wire names (reg,idx) to input nodes of the graph
self.input_map = OrderedDict()
# Map from wire names (reg,idx) to output nodes of the graph
self.output_map = OrderedDict()
# Running count of the total number of nodes
self.node_counter = 0
# Map of named operations in this circuit and their signatures.
# The signature is an integer tuple (nq,nc,np) specifying the
# number of input qubits, input bits, and real parameters.
# The definition is external to the circuit object.
self.basis = OrderedDict()
# Directed multigraph whose nodes are inputs, outputs, or operations.
# Operation nodes have equal in- and out-degrees and carry
# additional data about the operation, including the argument order
# and parameter values.
# Input nodes have out-degree 1 and output nodes have in-degree 1.
# Edges carry wire labels (reg,idx) and each operation has
# corresponding in- and out-edges with the same wire labels.
self.multi_graph = nx.MultiDiGraph()
# Map of qregs to sizes
self.qregs = OrderedDict()
# Map of cregs to sizes
self.cregs = OrderedDict()
# Map of user defined gates to ast nodes defining them
self.gates = OrderedDict()
# Output precision for printing floats
self.prec = 10
# layout of dag quantum registers on the chip
# TODO: rethink this. doesn't seem related to concept of DAG,
# but if we want to be able to generate qobj
# directly from a dag, we need it.
self.layout = []
def get_qubits(self):
"""Return a list of qubits as (qreg, index) pairs."""
return [(k, i) for k, v in self.qregs.items() for i in range(v.size)]
def rename_register(self, regname, newname):
"""Rename a classical or quantum register throughout the circuit.
regname = existing register name string
newname = replacement register name string
"""
if regname == newname:
return
if newname in self.qregs or newname in self.cregs:
raise DAGCircuitError("duplicate register name %s" % newname)
if regname not in self.qregs and regname not in self.cregs:
raise DAGCircuitError("no register named %s" % regname)
iscreg = False
if regname in self.qregs:
self.qregs[newname] = self.qregs[regname]
self.qregs.pop(regname, None)
reg_size = self.qregs[newname].size
if regname in self.cregs:
self.cregs[newname] = self.cregs[regname]
self.cregs.pop(regname, None)
reg_size = self.cregs[newname].size
iscreg = True
for i in range(reg_size):
self.wire_type[(newname, i)] = iscreg
self.wire_type.pop((regname, i), None)
self.input_map[(newname, i)] = self.input_map[(regname, i)]
self.input_map.pop((regname, i), None)
self.output_map[(newname, i)] = self.output_map[(regname, i)]
self.output_map.pop((regname, i), None)
# n node d = data
for _, d in self.multi_graph.nodes(data=True):
if d["type"] == "in" or d["type"] == "out":
if d["name"][0] == regname:
d["name"] = (newname, d["name"][1])
elif d["type"] == "op":
qa = []
for a in d["qargs"]:
if a[0] == regname:
a = (newname, a[1])
qa.append(a)
d["qargs"] = qa
ca = []
for a in d["cargs"]:
if a[0] == regname:
a = (newname, a[1])
ca.append(a)
d["cargs"] = ca
if d["condition"] is not None:
if d["condition"][0] == regname:
d["condition"] = (newname, d["condition"][1])
# eX = edge, d= data
for _, _, d in self.multi_graph.edges(data=True):
if d["name"][0] == regname:
d["name"] = (newname, d["name"][1])
def remove_all_ops_named(self, opname):
"""Remove all operation nodes with the given name."""
for n in self.get_named_nodes(opname):
self._remove_op_node(n)
def fs(self, number):
"""Format a float f as a string with self.prec digits."""
fmt = "{0:0.%snumber}" % self.prec
return fmt.format(number)
def add_qreg(self, qreg):
"""Add all wires in a quantum register."""
if not isinstance(qreg, QuantumRegister):
raise DAGCircuitError("not a QuantumRegister instance.")
if qreg.name in self.qregs:
raise DAGCircuitError("duplicate register %s" % qreg.name)
self.qregs[qreg.name] = qreg
for j in range(qreg.size):
self._add_wire((qreg.name, j))
def add_creg(self, creg):
"""Add all wires in a classical register."""
if not isinstance(creg, ClassicalRegister):
raise DAGCircuitError("not a ClassicalRegister instance.")
if creg.name in self.cregs:
raise DAGCircuitError("duplicate register %s" % creg.name)
self.cregs[creg.name] = creg
for j in range(creg.size):
self._add_wire((creg.name, j), True)
def _add_wire(self, name, isClassical=False):
"""Add a qubit or bit to the circuit.
name is a (string,int) tuple containing register name and index
This adds a pair of in and out nodes connected by an edge.
"""
if name not in self.wire_type:
self.wire_type[name] = isClassical
self.node_counter += 1
self.input_map[name] = self.node_counter
self.node_counter += 1
self.output_map[name] = self.node_counter
in_node = self.input_map[name]
out_node = self.output_map[name]
self.multi_graph.add_edge(in_node, out_node)
self.multi_graph.node[in_node]["type"] = "in"
self.multi_graph.node[out_node]["type"] = "out"
self.multi_graph.node[in_node]["name"] = name
self.multi_graph.node[out_node]["name"] = name
self.multi_graph.adj[in_node][out_node][0]["name"] = name
else:
raise DAGCircuitError("duplicate wire %s" % name)
def add_basis_element(self, name, number_qubits,
number_classical=0, number_parameters=0):
"""Add an operation to the basis.
name is string label for operation
number_qubits is number of qubit arguments
number_classical is number of bit arguments
number_parameters is number of real parameters
The parameters (nq,nc,np) are ignored for the special case
when name = "barrier". The barrier instruction has a variable
number of qubit arguments.
"""
if name not in self.basis:
self.basis[name] = (
number_qubits,
number_classical,
number_parameters)
if name in self.gates:
if self.gates[name]["n_args"] != number_parameters or \
self.gates[name]["n_bits"] != number_qubits or number_classical != 0:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def add_gate_data(self, name, gatedata):
"""Add the definition of a gate.
gatedata is dict with fields:
"print" = True or False
"opaque" = True or False
"n_args" = number of real parameters
"n_bits" = number of qubits
"args" = list of parameter names
"bits" = list of qubit names
"body" = GateBody AST node
"""
if name not in self.gates:
self.gates[name] = gatedata
if name in self.basis:
if self.basis[name][0] != self.gates[name]["n_bits"] or \
self.basis[name][1] != 0 or \
self.basis[name][2] != self.gates[name]["n_args"]:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def _check_basis_data(self, name, qargs, cargs, params):
"""Check the arguments against the data for this operation.
name is a string
qargs is a list of tuples like ("q",0)
cargs is a list of tuples like ("c",0)
params is a list of strings that represent floats
"""
# Check that we have this operation
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
# Check the number of arguments matches the signature
if name in ["barrier"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if params:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
elif name in ["snapshot", "noise", "save", "load"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if not params:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
else:
if len(qargs) != self.basis[name][0]:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if len(cargs) != self.basis[name][1]:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if len(params) != self.basis[name][2]:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
def _check_condition(self, name, condition):
"""Verify that the condition is valid.
name is a string used for error reporting
condition is either None or a tuple (string,int) giving (creg,value)
"""
# Verify creg exists
if condition is not None and condition[0] not in self.cregs:
raise DAGCircuitError("invalid creg in condition for %s" % name)
def _check_bits(self, args, amap, bval):
"""Check the values of a list of (qu)bit arguments.
For each element A of args, check that amap contains A and
self.wire_type[A] equals bval.
args is a list of (regname,idx) tuples
amap is a dictionary keyed on (regname,idx) tuples
bval is boolean
"""
# Check for each wire
for q in args:
if q not in amap:
raise DAGCircuitError("(qu)bit %s not found" % (q,))
if self.wire_type[q] != bval:
raise DAGCircuitError("expected wire type %s for %s"
% (bval, q))
def _bits_in_condition(self, cond):
"""Return a list of bits (regname,idx) in the given condition.
cond is either None or a (regname,int) tuple specifying
a classical if condition.
"""
all_bits = []
if cond is not None:
all_bits.extend([(cond[0], j) for j in range(self.cregs[cond[0]].size)])
return all_bits
def _add_op_node(self, nname, nqargs, ncargs, nparams, ncondition, nop):
"""Add a new operation node to the graph and assign properties.
nname node name
nqargs quantum arguments
ncargs classical arguments
nparams parameters
ncondition classical condition (or None)
nop Instruction instance representing this operation
"""
# Add a new operation node to the graph
self.node_counter += 1
self.multi_graph.add_node(self.node_counter)
# Update that operation node's data
self.multi_graph.node[self.node_counter]["type"] = "op"
self.multi_graph.node[self.node_counter]["name"] = nname
self.multi_graph.node[self.node_counter]["qargs"] = nqargs
self.multi_graph.node[self.node_counter]["cargs"] = ncargs
self.multi_graph.node[self.node_counter]["params"] = nparams
self.multi_graph.node[self.node_counter]["condition"] = ncondition
self.multi_graph.node[self.node_counter]["op"] = nop
def apply_operation_back(self, name, qargs, cargs=None, params=None,
condition=None, op=None):
"""Apply an operation to the output of the circuit.
name is a string
qargs is a list of tuples like ("q",0)
cargs is a list of tuples like ("c",0)
params is a list of symbols that represent numbers
condition is either None or a tuple (string,int) giving (creg,value)
op is an Instruction instance representing this node
"""
cargs = cargs or []
params = params or []
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(name, qargs, cargs, params)
self._check_condition(name, condition)
self._check_bits(qargs, self.output_map, False)
self._check_bits(all_cbits, self.output_map, True)
self._add_op_node(name, qargs, cargs, params, condition, op)
# Add new in-edges from predecessors of the output nodes to the
# operation node while deleting the old in-edges of the output nodes
# and adding new edges from the operation node to each output node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.predecessors(self.output_map[q]))
if len(ie) != 1:
raise QISKitError("output node has multiple in-edges")
self.multi_graph.add_edge(ie[0], self.node_counter, name=q)
self.multi_graph.remove_edge(ie[0], self.output_map[q])
self.multi_graph.add_edge(
self.node_counter, self.output_map[q], name=q)
def apply_operation_front(self, name, qargs, cargs=None, params=None,
condition=None, op=None):
"""Apply an operation to the input of the circuit.
name is a string
qargs is a list of strings like "q[0]"
cargs is a list of strings like "c[0]"
params is a list of strings that represent floats
condition is either None or a tuple (string,int) giving (creg,value)
"""
cargs = cargs or []
params = params or []
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(name, qargs, cargs, params)
self._check_condition(name, condition)
self._check_bits(qargs, self.input_map, False)
self._check_bits(all_cbits, self.input_map, True)
self._add_op_node(name, qargs, cargs, params, condition, op)
# Add new out-edges to successors of the input nodes from the
# operation node while deleting the old out-edges of the input nodes
# and adding new edges to the operation node from each input node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = self.multi_graph.successors(self.input_map[q])
if len(ie) != 1:
raise QISKitError("input node has multiple out-edges")
self.multi_graph.add_edge(self.node_counter, ie[0], name=q)
self.multi_graph.remove_edge(self.input_map[q], ie[0])
self.multi_graph.add_edge(
self.input_map[q], self.node_counter, name=q)
def _make_union_basis(self, input_circuit):
"""Return a new basis map.
The new basis is a copy of self.basis with
new elements of input_circuit.basis added.
input_circuit is a DAGCircuit
"""
union_basis = self.basis.copy()
for g in input_circuit.basis:
if g not in union_basis:
union_basis[g] = input_circuit.basis[g]
if union_basis[g] != input_circuit.basis[g]:
raise DAGCircuitError("incompatible basis")
return union_basis
def _make_union_gates(self, input_circuit):
"""Return a new gates map.
The new gates are a copy of self.gates with
new elements of input_circuit.gates added.
input_circuit is a DAGCircuit
NOTE: gates in input_circuit that are also in self must
be *identical* to the gates in self
"""
union_gates = {}
for k, v in self.gates.items():
union_gates[k] = v
for k, v in input_circuit.gates.items():
if k not in union_gates:
union_gates[k] = v
if union_gates[k]["opaque"] != input_circuit.gates[k]["opaque"] or \
union_gates[k]["n_args"] != input_circuit.gates[k]["n_args"] or \
union_gates[k]["n_bits"] != input_circuit.gates[k]["n_bits"] or \
union_gates[k]["args"] != input_circuit.gates[k]["args"] or \
union_gates[k]["bits"] != input_circuit.gates[k]["bits"]:
raise DAGCircuitError("inequivalent gate definitions for %s"
% k)
return union_gates
def _check_wiremap_registers(self, wire_map, keyregs, valregs,
valreg=True):
"""Check that wiremap neither fragments nor leaves duplicate registers.
1. There are no fragmented registers. A register in keyregs
is fragmented if not all of its (qu)bits are renamed by wire_map.
2. There are no duplicate registers. A register is duplicate if
it appears in both self and keyregs but not in wire_map.
wire_map is a map from (regname,idx) in keyregs to (regname,idx)
in valregs
keyregs is a map from register names to Register objects
valregs is a map from register names to Register objects
valreg is a Bool, if False the method ignores valregs and does not
add regs for bits in the wire_map image that don't appear in valregs
Return the set of regs to add to self
"""
add_regs = set()
reg_frag_chk = {}
for k, v in keyregs.items():
reg_frag_chk[k] = {j: False for j in range(v.size)}
for k in wire_map.keys():
if k[0] in keyregs:
reg_frag_chk[k[0]][k[1]] = True
for k, v in reg_frag_chk.items():
rname = ",".join(map(str, k))
s = set(v.values())
if len(s) == 2:
raise DAGCircuitError("wire_map fragments reg %s" % rname)
elif s == set([False]):
if k in self.qregs or k in self.cregs:
raise DAGCircuitError("unmapped duplicate reg %s" % rname)
else:
# Add registers that appear only in keyregs
add_regs.add(keyregs[k])
else:
if valreg:
# If mapping to a register not in valregs, add it.
# (k,0) exists in wire_map because wire_map doesn't
# fragment k
if not wire_map[(k, 0)][0] in valregs:
size = max(map(lambda x: x[1], filter(lambda x: x[0] == wire_map[(k, 0)][0],
wire_map.values())))
qreg = QuantumRegister(wire_map[(k, 0)][0], size + 1)
add_regs.add(qreg)
return add_regs
def _check_wiremap_validity(self, wire_map, keymap, valmap, input_circuit):
"""Check that the wiremap is consistent.
Check that the wiremap refers to valid wires and that
those wires have consistent types.
wire_map is a map from (regname,idx) in keymap to (regname,idx)
in valmap
keymap is a map whose keys are wire_map keys
valmap is a map whose keys are wire_map values
input_circuit is a DAGCircuit
"""
for k, v in wire_map.items():
kname = ",".join(map(str, k))
vname = ",".join(map(str, v))
if k not in keymap:
raise DAGCircuitError("invalid wire mapping key %s" % kname)
if v not in valmap:
raise DAGCircuitError("invalid wire mapping value %s"
% vname)
if input_circuit.wire_type[k] != self.wire_type[v]:
raise DAGCircuitError("inconsistent wire_map at (%s,%s)"
% (kname, vname))
def _map_condition(self, wire_map, condition):
"""Use the wire_map dict to change the condition tuple's creg name.
wire_map is map from wires to wires
condition is a tuple (reg,int)
Returns the new condition tuple
"""
if condition is None:
n_condition = None
else:
# Map the register name, using fact that registers must not be
# fragmented by the wire_map (this must have been checked
# elsewhere)
bit0 = (condition[0], 0)
n_condition = (wire_map.get(bit0, bit0)[0], condition[1])
return n_condition
def compose_back(self, input_circuit, wire_map=None):
"""Apply the input circuit to the output of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of input qubits of the input circuit are mapped
to a subset of output qubits of this circuit.
wire_map[input_qubit_to_input_circuit] = output_qubit_of_self
"""
wire_map = wire_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map for duplicate values
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_wiremap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.input_map,
self.output_map, input_circuit)
# Compose
self.basis = union_basis
self.gates = union_gates
for node in nx.topological_sort(input_circuit.multi_graph):
nd = input_circuit.multi_graph.node[node]
if nd["type"] == "in":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["name"], nd["name"])
# the mapped wire should already exist
if m_name not in self.output_map:
raise QISKitError("wire (%s,%d) not in self" % (m_name[0], m_name[1]))
if nd["name"] not in input_circuit.wire_type:
raise QISKitError("inconsistent wire_type for (%s,%d) in input_circuit"
% (nd["name"][0], nd["name"][1]))
elif nd["type"] == "out":
# ignore output nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: wire_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x), nd["cargs"]))
self.apply_operation_back(nd["name"], m_qargs, m_cargs,
nd["params"], condition, nd["op"])
else:
raise QISKitError("bad node type %s" % nd["type"])
def compose_front(self, input_circuit, wire_map=None):
"""Apply the input circuit to the input of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of output qubits of the input circuit are mapped
to a subset of input qubits of
this circuit.
"""
wire_map = wire_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_wiremap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.output_map,
self.input_map, input_circuit)
# Compose
self.basis = union_basis
self.gates = union_gates
for n in reversed(list(nx.topological_sort(input_circuit.multi_graph))):
nd = input_circuit.multi_graph.node[n]
if nd["type"] == "out":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["name"], nd["name"])
# the mapped wire should already exist
if m_name not in self.input_map:
raise QISKitError("wire (%s,%d) not in self" % (m_name[0], m_name[1]))
if nd["name"] not in input_circuit.wire_type:
raise QISKitError(
"inconsistent wire_type for (%s,%d) in input_circuit"
% (nd["name"][0], nd["name"][1]))
elif nd["type"] == "in":
# ignore input nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: wire_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x), nd["cargs"]))
self.apply_operation_front(nd["name"], m_qargs, m_cargs,
nd["params"], condition, nd["op"])
else:
raise QISKitError("bad node type %s" % nd["type"])
def size(self):
"""Return the number of operations."""
return self.multi_graph.order() - 2 * len(self.wire_type)
def depth(self):
"""Return the circuit depth."""
if not nx.is_directed_acyclic_graph(self.multi_graph):
raise QISKitError("not a DAG")
return nx.dag_longest_path_length(self.multi_graph) - 1
def width(self):
"""Return the total number of qubits used by the circuit."""
return len(self.wire_type) - self.num_cbits()
def num_cbits(self):
"""Return the total number of bits used by the circuit."""
return list(self.wire_type.values()).count(True)
def num_tensor_factors(self):
"""Compute how many components the circuit can decompose into."""
return nx.number_weakly_connected_components(self.multi_graph)
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.gates[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.gates[name]["n_args"] > 0:
out += "(" + ",".join(self.gates[name]["args"]) + ")"
out += " " + ",".join(self.gates[name]["bits"])
if self.gates[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.gates[name]["body"].qasm() + "}"
return out
def qasm(self, decls_only=False, add_swap=False,
no_decls=False, qeflag=False, aliases=None, eval_symbols=False):
"""Return a string containing QASM for this circuit.
if qeflag is True, add a line to include "qelib1.inc"
and only generate gate code for gates not in qelib1.
if eval_symbols is True, evaluate all symbolic
expressions to their floating point representation.
if no_decls is True, only print the instructions.
if aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
if decls_only is True, only print the declarations.
if add_swap is True, add the definition of swap in terms of
cx if necessary.
"""
# TODO: some of the input flags are not needed anymore
# Rename qregs if necessary
if aliases:
qregdata = OrderedDict()
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
# Write top matter
if no_decls:
out = ""
else:
printed_gates = []
out = "OPENQASM 2.0;\n"
if qeflag:
out += "include \"qelib1.inc\";\n"
for k, v in qregdata.items():
out += "qreg %s[%d];\n" % (k, v.size)
for k, v in self.cregs.items():
out += "creg %s[%d];\n" % (k, v.size)
omit = ["U", "CX", "measure", "reset", "barrier"]
# TODO: dagcircuit shouldn't know about extensions
if qeflag:
qelib = ["u3", "u2", "u1", "cx", "id", "x", "y", "z", "h",
"s", "sdg", "t", "tdg", "cz", "cy", "ccx", "cu1",
"cu3", "swap", "cswap", "u0", "rx", "ry", "rz",
"ch", "crz", "rzz"]
omit.extend(qelib)
printed_gates.extend(qelib)
simulator_instructions = ["snapshot", "save", "load", "noise", "wait"]
omit.extend(simulator_instructions)
for k in self.basis.keys():
if k not in omit:
if not self.gates[k]["opaque"]:
calls = self.gates[k]["body"].calls()
for c in calls:
if c not in printed_gates:
out += self._gate_string(c) + "\n"
printed_gates.append(c)
if k not in printed_gates:
out += self._gate_string(k) + "\n"
printed_gates.append(k)
if add_swap and not qeflag and "cx" not in self.basis:
out += "gate cx a,b { CX a,b; }\n"
if add_swap and "swap" not in self.basis:
out += "gate swap a,b { cx a,b; cx b,a; cx a,b; }\n"
# Write the instructions
if not decls_only:
for n in nx.lexicographical_topological_sort(self.multi_graph):
nd = self.multi_graph.node[n]
if nd["type"] == "op":
if nd["condition"] is not None:
out += "if(%s==%d) " \
% (nd["condition"][0], nd["condition"][1])
if not nd["cargs"]:
nm = nd["name"]
if aliases:
qarglist = map(lambda x: aliases[x], nd["qargs"])
else:
qarglist = nd["qargs"]
qarg = ",".join(map(lambda x: "%s[%d]" % (x[0], x[1]),
qarglist))
if nd["params"]:
if eval_symbols:
param = ",".join(map(lambda x: str(sympy.N(x)),
nd["params"]))
else:
param = ",".join(map(lambda x: x.replace("**", "^"),
map(str, nd["params"])))
out += "%s(%s) %s;\n" % (nm, param, qarg)
else:
out += "%s %s;\n" % (nm, qarg)
else:
if nd["name"] == "measure":
if len(nd["cargs"]) != 1 or len(nd["qargs"]) != 1 \
or nd["params"]:
raise QISKitError("bad node data")
qname = nd["qargs"][0][0]
qindex = nd["qargs"][0][1]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
out += "measure %s[%d] -> %s[%d];\n" \
% (qname,
qindex,
nd["cargs"][0][0],
nd["cargs"][0][1])
else:
raise QISKitError("bad node data")
return out
def _check_wires_list(self, wires, name, input_circuit, condition=None):
"""Check that a list of wires satisfies some conditions.
wires = list of (register_name, index) tuples
name = name of operation
input_circuit = replacement circuit for operation
condition = None or (creg_name, value) if this instance of the
operation is classically controlled
The wires give an order for (qu)bits in the input circuit
that is replacing the named operation.
- no duplicate names
- correct length for named operation
- elements are wires of input_circuit
Raises an exception otherwise.
"""
if len(set(wires)) != len(wires):
raise DAGCircuitError("duplicate wires")
wire_tot = self.basis[name][0] + self.basis[name][1]
if condition is not None:
wire_tot += self.cregs[condition[0]].size
if len(wires) != wire_tot:
raise DAGCircuitError("expected %d wires, got %d"
% (wire_tot, len(wires)))
for w in wires:
if w not in input_circuit.wire_type:
raise DAGCircuitError("wire (%s,%d) not in input circuit"
% (w[0], w[1]))
def _make_pred_succ_maps(self, n):
"""Return predecessor and successor dictionaries.
These map from wire names to predecessor and successor
nodes for the operation node n in self.multi_graph.
"""
pred_map = {e[2]['name']: e[0] for e in
self.multi_graph.in_edges(nbunch=n, data=True)}
succ_map = {e[2]['name']: e[1] for e in
self.multi_graph.out_edges(nbunch=n, data=True)}
return pred_map, succ_map
def _full_pred_succ_maps(self, pred_map, succ_map, input_circuit,
wire_map):
"""Map all wires of the input circuit.
Map all wires of the input circuit to predecessor and
successor nodes in self, keyed on wires in self.
pred_map, succ_map dicts come from _make_pred_succ_maps
input_circuit is the input circuit
wire_map is the wire map from wires of input_circuit to wires of self
returns full_pred_map, full_succ_map
"""
full_pred_map = {}
full_succ_map = {}
for w in input_circuit.input_map:
# If w is wire mapped, find the corresponding predecessor
# of the node
if w in wire_map:
full_pred_map[wire_map[w]] = pred_map[wire_map[w]]
full_succ_map[wire_map[w]] = succ_map[wire_map[w]]
else:
# Otherwise, use the corresponding output nodes of self
# and compute the predecessor.
full_succ_map[w] = self.output_map[w]
full_pred_map[w] = self.multi_graph.predecessors(
self.output_map[w])[0]
if len(list(self.multi_graph.predecessors(self.output_map[w]))) != 1:
raise QISKitError(
"too many predecessors for (%s,%d) output node" % (w[0], w[1])
)
return full_pred_map, full_succ_map
def node_nums_in_topological_order(self):
"""
Returns the nodes (their ids) in topological order.
Returns:
List(int): The list of node numbers in topological order
"""
return nx.topological_sort(self.multi_graph)
def substitute_circuit_all(self, name, input_circuit, wires=None):
"""Replace every occurrence of named operation with input_circuit."""
# TODO: rewrite this method to call substitute_circuit_one
wires = wires or None
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
self._check_wires_list(wires, name, input_circuit)
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: ("", 0) for w in wires}
add_qregs = self._check_wiremap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Iterate through the nodes of self and replace the selected nodes
# by iterating through the input_circuit, constructing and
# checking the validity of the wire_map for each replacement
# NOTE: We do not replace conditioned gates. One way to implement
# this later is to add or update the conditions of each gate
# that we add from the input_circuit.
self.basis = union_basis
self.gates = union_gates
for n in self.node_nums_in_topological_order():
nd = self.multi_graph.node[n]
if nd["type"] == "op" and nd["name"] == name:
if nd["condition"] is None:
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"], nd["cargs"]]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map, input_circuit)
pred_map, succ_map = self._make_pred_succ_maps(n)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(n)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map,
md["condition"])
m_qargs = [wire_map.get(x, x) for x in md["qargs0"]]
m_cargs = [wire_map.get(x, x) for x in md["cargs0"]]
self._add_op_node(md["name"], m_qargs, m_cargs,
md["params"], condition, md["op"])
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter, name=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w], full_succ_map[w],
name=w)
o_pred = list(self.multi_graph.predecessors(
self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise QISKitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise QISKitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(
p[0], self.output_map[w])
def substitute_circuit_one(self, node, input_circuit, wires=None):
"""Replace one node with input_circuit.
node is a reference to a node of self.multi_graph of type "op"
input_circuit is a DAGCircuit
"""
wires = wires or None
nd = self.multi_graph.node[node]
name = nd["name"]
self._check_wires_list(wires, name, input_circuit, nd["condition"])
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: ("", 0) for w in wires}
add_qregs = self._check_wiremap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Replace the node by iterating through the input_circuit.
# Constructing and checking the validity of the wire_map.
# If a gate is conditioned, we expect the replacement subcircuit
# to depend on those control bits as well.
self.basis = union_basis
self.gates = union_gates
if nd["type"] != "op":
raise DAGCircuitError("expected node type \"op\", got %s"
% nd["type"])
condition_bit_list = self._bits_in_condition(nd["condition"])
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"],
nd["cargs"],
condition_bit_list]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map, input_circuit)
pred_map, succ_map = self._make_pred_succ_maps(node)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(node)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map, md["condition"])
m_qargs = list(map(lambda x: wire_map.get(x, x),
md["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x),
md["cargs"]))
self._add_op_node(md["name"], m_qargs, m_cargs,
md["params"], condition, md["op"])
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter,
name=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(
full_pred_map[w], full_succ_map[w], name=w)
o_pred = list(self.multi_graph.predecessors(self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise QISKitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise QISKitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(p[0], self.output_map[w])
def get_named_nodes(self, name):
"""Get the set of "op" node ids with the given name."""
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
# We need to instantiate the full list now because the underlying multi_graph
# may change when users iterate over the named nodes.
return {node_id for node_id, data in self.multi_graph.nodes(data=True)
if data["type"] == "op" and data["name"] == name}
def get_cnot_nodes(self):
"""Get the set of Cnot."""
cx_names = ['cx', 'CX']
cxs_nodes = []
for cx_name in cx_names:
if cx_name in self.basis:
for cx_id in self.get_named_nodes(cx_name):
cxs_nodes.append(self.multi_graph.node[cx_id])
return cxs_nodes
def _remove_op_node(self, n):
"""Remove an operation node n.
Add edges from predecessors to successors.
"""
pred_map, succ_map = self._make_pred_succ_maps(n)
self.multi_graph.remove_node(n)
for w in pred_map.keys():
self.multi_graph.add_edge(pred_map[w], succ_map[w], name=w)
def remove_ancestors_of(self, node):
"""Remove all of the ancestor operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
# TODO: probably better to do all at once using
# multi_graph.remove_nodes_from; same for related functions ...
for n in anc:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_descendants_of(self, node):
"""Remove all of the descendant operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
for n in dec:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nonancestors_of(self, node):
"""Remove all of the non-ancestors operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(anc))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nondescendants_of(self, node):
"""Remove all of the non-descendants operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(dec))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def layers(self):
"""Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit.
A layer is a circuit whose gates act on disjoint qubits, i.e.
a layer has depth 1. The total number of layers equals the
circuit depth d. The layers are indexed from 0 to d-1 with the
earliest layer at index 0. The layers are constructed using a
greedy algorithm. Each returned layer is a dict containing
{"graph": circuit graph, "partition": list of qubit lists}.
TODO: Gates that use the same cbits will end up in different
layers as this is currently implemented. This may not be
the desired behavior.
"""
graph_layers = self.multigraph_layers()
try:
next(graph_layers) # Remove input nodes
except StopIteration:
return
def nodes_data(nodes):
"""Construct full nodes from just node ids."""
return ((node_id, self.multi_graph.nodes[node_id]) for node_id in nodes)
for graph_layer in graph_layers:
# Get the op nodes from the layer, removing any input and output nodes.
op_nodes = [node for node in nodes_data(graph_layer) if node[1]["type"] == "op"]
# Stop yielding once there are no more op_nodes in a layer.
if not op_nodes:
return
# Construct a shallow copy of self
new_layer = copy.copy(self)
new_layer.multi_graph = nx.MultiDiGraph()
new_layer.multi_graph.add_nodes_from(nodes_data(self.input_map.values()))
new_layer.multi_graph.add_nodes_from(nodes_data(self.output_map.values()))
# The quantum registers that have an operation in this layer.
support_list = [
op_node[1]["qargs"]
for op_node in op_nodes
if op_node[1]["name"] not in {"barrier", "snapshot", "save", "load", "noise"}
]
new_layer.multi_graph.add_nodes_from(op_nodes)
# Now add the edges to the multi_graph
# By default we just wire inputs to the outputs.
wires = {self.input_map[register]: self.output_map[register]
for register in self.wire_type}
# Wire inputs to op nodes, and op nodes to outputs.
for op_node in op_nodes:
args = self._bits_in_condition(op_node[1]["condition"]) \
+ op_node[1]["cargs"] + op_node[1]["qargs"]
arg_ids = (self.input_map[arg] for arg in args) # map from ("q",0) to node id.
for arg_id in arg_ids:
wires[arg_id], wires[op_node[0]] = op_node[0], wires[arg_id]
# Add wiring to/from the operations and between unused inputs & outputs.
new_layer.multi_graph.add_edges_from(wires.items())
yield {"graph": new_layer, "partition": support_list}
def serial_layers(self):
"""Yield a layer for all gates of this circuit.
A serial layer is a circuit with one gate. The layers have the
same structure as in layers().
"""
for n in self.node_nums_in_topological_order():
nxt_nd = self.multi_graph.node[n]
if nxt_nd["type"] == "op":
new_layer = DAGCircuit()
for qreg in self.qregs.values():
new_layer.add_qreg(qreg)
for creg in self.cregs.values():
new_layer.add_creg(creg)
new_layer.basis = self.basis.copy()
new_layer.gates = self.gates.copy()
# Save the support of the operation we add to the layer
support_list = []
# Operation data
qa = copy.copy(nxt_nd["qargs"])
ca = copy.copy(nxt_nd["cargs"])
pa = copy.copy(nxt_nd["params"])
co = copy.copy(nxt_nd["condition"])
op = copy.copy(nxt_nd["op"])
_ = self._bits_in_condition(co)
# Add node to new_layer
new_layer.apply_operation_back(nxt_nd["name"],
qa, ca, pa, co, op)
# Add operation to partition
if nxt_nd["name"] not in ["barrier",
"snapshot", "save", "load", "noise"]:
# support_list.append(list(set(qa) | set(ca) | set(cob)))
support_list.append(list(qa))
l_dict = {"graph": new_layer, "partition": support_list}
yield l_dict
def multigraph_layers(self):
"""Yield layers of the multigraph."""
predecessor_count = dict() # Dict[node, predecessors not visited]
cur_layer = [node for node in self.input_map.values()]
yield cur_layer
next_layer = []
while cur_layer:
for node in cur_layer:
# Count multiedges with multiplicity.
for successor in self.multi_graph.successors(node):
multiplicity = self.multi_graph.number_of_edges(node, successor)
if successor in predecessor_count:
predecessor_count[successor] -= multiplicity
else:
predecessor_count[successor] = \
self.multi_graph.in_degree(successor) - multiplicity
if predecessor_count[successor] == 0:
next_layer.append(successor)
del predecessor_count[successor]
yield next_layer
cur_layer = next_layer
next_layer = []
def collect_runs(self, namelist):
"""Return a set of runs of "op" nodes with the given names.
For example, "... h q[0]; cx q[0],q[1]; cx q[0],q[1]; h q[1]; .."
would produce the tuple of cx nodes as an element of the set returned
from a call to collect_runs(["cx"]). If instead the cx nodes were
"cx q[0],q[1]; cx q[1],q[0];", the method would still return the
pair in a tuple. The namelist can contain names that are not
in the circuit's basis.
Nodes must have only one successor to continue the run.
"""
group_list = []
# Iterate through the nodes of self in topological order
# and form tuples containing sequences of gates
# on the same qubit(s).
ts = list(self.node_nums_in_topological_order())
nodes_seen = dict(zip(ts, [False] * len(ts)))
for node in ts:
nd = self.multi_graph.node[node]
if nd["type"] == "op" and nd["name"] in namelist \
and not nodes_seen[node]:
group = [node]
nodes_seen[node] = True
s = list(self.multi_graph.successors(node))
while len(s) == 1 and \
self.multi_graph.node[s[0]]["type"] == "op" and \
self.multi_graph.node[s[0]]["name"] in namelist:
group.append(s[0])
nodes_seen[s[0]] = True
s = list(self.multi_graph.successors(s[0]))
if len(group) > 1:
group_list.append(tuple(group))
return set(group_list)
def count_ops(self):
"""Count the occurrences of operation names.
Returns a dictionary of counts keyed on the operation name.
"""
op_dict = {}
for node in self.node_nums_in_topological_order():
nd = self.multi_graph.node[node]
name = nd["name"]
if nd["type"] == "op":
if name not in op_dict:
op_dict[name] = 1
else:
op_dict[name] += 1
return op_dict
def properties(self):
"""Return a dictionary of circuit properties."""
summary = {"size": self.size(),
"depth": self.depth(),
"width": self.width(),
"bits": self.num_cbits(),
"factors": self.num_tensor_factors(),
"operations": self.count_ops()}
return summary
@staticmethod
def fromQuantumCircuit(circuit, expand_gates=True):
"""Build a ``DAGCircuit`` object from a ``QuantumCircuit``.
Args:
circuit (QuantumCircuit): the input circuit.
expand_gates (bool): if ``False``, none of the gates are expanded,
i.e. the gates that are defined in the circuit are included in
the DAG basis.
Return:
DAGCircuit: the DAG representing the input circuit.
"""
dagcircuit = DAGCircuit()
dagcircuit.name = circuit.name
for register in circuit.qregs:
dagcircuit.add_qreg(register)
for register in circuit.cregs:
dagcircuit.add_creg(register)
# Add user gate definitions
for name, data in circuit.definitions.items():
dagcircuit.add_basis_element(name, data["n_bits"], 0,
data["n_args"])
dagcircuit.add_gate_data(name, data)
# Add instructions
builtins = {
"U": ["U", 1, 0, 3],
"CX": ["CX", 2, 0, 0],
"measure": ["measure", 1, 1, 0],
"reset": ["reset", 1, 0, 0],
"barrier": ["barrier", -1, 0, 0]
}
# Add simulator instructions
simulator_instructions = {
"snapshot": ["snapshot", -1, 0, 1],
"save": ["save", -1, 0, 1],
"load": ["load", -1, 0, 1],
"noise": ["noise", -1, 0, 1]
}
for main_instruction in circuit.data:
# TODO: generate definitions and nodes for CompositeGates,
# for now simply drop their instructions into the DAG
instruction_list = []
is_composite = isinstance(main_instruction,
_compositegate.CompositeGate)
if is_composite and expand_gates:
instruction_list = main_instruction.instruction_list()
else:
instruction_list.append(main_instruction)
for instruction in instruction_list:
# Add OpenQASM built-in gates on demand
if instruction.name in builtins:
dagcircuit.add_basis_element(*builtins[instruction.name])
# Add simulator extension instructions
if instruction.name in simulator_instructions:
dagcircuit.add_basis_element(*simulator_instructions[instruction.name])
# Separate classical arguments to measurements
if instruction.name == "measure":
qargs = [(instruction.qargs[0][0].name, instruction.qargs[0][1])]
cargs = [(instruction.cargs[0][0].name, instruction.cargs[0][1])]
else:
qargs = list(map(lambda x: (x[0].name, x[1]), instruction.qargs))
cargs = []
# Get arguments for classical control (if any)
if instruction.control is None:
control = None
else:
control = (instruction.control[0].name, instruction.control[1])
if is_composite and not expand_gates:
is_inverse = instruction.inverse_flag
name = instruction.name if not is_inverse else instruction.inverse_name
else:
name = instruction.name
dagcircuit.apply_operation_back(name, qargs, cargs,
instruction.param,
control, instruction)
return dagcircuit
<|code_end|>
|
qiskit/dagcircuit/_dagcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Object to represent a quantum circuit as a directed acyclic graph.
The nodes in the graph are either input/output nodes or operation nodes.
The operation nodes are elements of a basis that is part of the circuit.
The QASM definitions of the basis elements are carried with the circuit.
The edges correspond to qubits or bits in the circuit. A directed edge
from node A to node B means that the (qu)bit passes from the output of A
to the input of B. The object's methods allow circuits to be constructed,
composed, and modified. Some natural properties like depth can be computed
directly from the graph.
"""
from collections import OrderedDict
import copy
import itertools
import networkx as nx
import sympy
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QISKitError
from qiskit import _compositegate
from ._dagcircuiterror import DAGCircuitError
class DAGCircuit:
"""
Quantum circuit as a directed acyclic graph.
There are 3 types of nodes in the graph: inputs, outputs, and operations.
The nodes are connected by directed edges that correspond to qubits and
bits.
"""
# pylint: disable=invalid-name
def __init__(self):
"""Create an empty circuit."""
# Circuit name. Generally, this corresponds to the name
# of the QuantumCircuit from which the DAG was generated.
self.name = None
# Map from a wire's name (reg,idx) to a Bool that is True if the
# wire is a classical bit and False if the wire is a qubit.
self.wire_type = OrderedDict()
# Map from wire names (reg,idx) to input nodes of the graph
self.input_map = OrderedDict()
# Map from wire names (reg,idx) to output nodes of the graph
self.output_map = OrderedDict()
# Running count of the total number of nodes
self.node_counter = 0
# Map of named operations in this circuit and their signatures.
# The signature is an integer tuple (nq,nc,np) specifying the
# number of input qubits, input bits, and real parameters.
# The definition is external to the circuit object.
self.basis = OrderedDict()
# Directed multigraph whose nodes are inputs, outputs, or operations.
# Operation nodes have equal in- and out-degrees and carry
# additional data about the operation, including the argument order
# and parameter values.
# Input nodes have out-degree 1 and output nodes have in-degree 1.
# Edges carry wire labels (reg,idx) and each operation has
# corresponding in- and out-edges with the same wire labels.
self.multi_graph = nx.MultiDiGraph()
# Map of qregs to sizes
self.qregs = OrderedDict()
# Map of cregs to sizes
self.cregs = OrderedDict()
# Map of user defined gates to ast nodes defining them
self.gates = OrderedDict()
# Output precision for printing floats
self.prec = 10
# layout of dag quantum registers on the chip
# TODO: rethink this. doesn't seem related to concept of DAG,
# but if we want to be able to generate qobj
# directly from a dag, we need it.
self.layout = []
def get_qubits(self):
"""Return a list of qubits as (qreg, index) pairs."""
return [(k, i) for k, v in self.qregs.items() for i in range(v.size)]
def rename_register(self, regname, newname):
"""Rename a classical or quantum register throughout the circuit.
regname = existing register name string
newname = replacement register name string
"""
if regname == newname:
return
if newname in self.qregs or newname in self.cregs:
raise DAGCircuitError("duplicate register name %s" % newname)
if regname not in self.qregs and regname not in self.cregs:
raise DAGCircuitError("no register named %s" % regname)
iscreg = False
if regname in self.qregs:
self.qregs[newname] = self.qregs[regname]
self.qregs.pop(regname, None)
reg_size = self.qregs[newname].size
if regname in self.cregs:
self.cregs[newname] = self.cregs[regname]
self.cregs.pop(regname, None)
reg_size = self.cregs[newname].size
iscreg = True
for i in range(reg_size):
self.wire_type[(newname, i)] = iscreg
self.wire_type.pop((regname, i), None)
self.input_map[(newname, i)] = self.input_map[(regname, i)]
self.input_map.pop((regname, i), None)
self.output_map[(newname, i)] = self.output_map[(regname, i)]
self.output_map.pop((regname, i), None)
# n node d = data
for _, d in self.multi_graph.nodes(data=True):
if d["type"] == "in" or d["type"] == "out":
if d["name"][0] == regname:
d["name"] = (newname, d["name"][1])
elif d["type"] == "op":
qa = []
for a in d["qargs"]:
if a[0] == regname:
a = (newname, a[1])
qa.append(a)
d["qargs"] = qa
ca = []
for a in d["cargs"]:
if a[0] == regname:
a = (newname, a[1])
ca.append(a)
d["cargs"] = ca
if d["condition"] is not None:
if d["condition"][0] == regname:
d["condition"] = (newname, d["condition"][1])
# eX = edge, d= data
for _, _, d in self.multi_graph.edges(data=True):
if d["name"][0] == regname:
d["name"] = (newname, d["name"][1])
def remove_all_ops_named(self, opname):
"""Remove all operation nodes with the given name."""
for n in self.get_named_nodes(opname):
self._remove_op_node(n)
def fs(self, number):
"""Format a float f as a string with self.prec digits."""
fmt = "{0:0.%snumber}" % self.prec
return fmt.format(number)
def add_qreg(self, qreg):
"""Add all wires in a quantum register."""
if not isinstance(qreg, QuantumRegister):
raise DAGCircuitError("not a QuantumRegister instance.")
if qreg.name in self.qregs:
raise DAGCircuitError("duplicate register %s" % qreg.name)
self.qregs[qreg.name] = qreg
for j in range(qreg.size):
self._add_wire((qreg.name, j))
def add_creg(self, creg):
"""Add all wires in a classical register."""
if not isinstance(creg, ClassicalRegister):
raise DAGCircuitError("not a ClassicalRegister instance.")
if creg.name in self.cregs:
raise DAGCircuitError("duplicate register %s" % creg.name)
self.cregs[creg.name] = creg
for j in range(creg.size):
self._add_wire((creg.name, j), True)
def _add_wire(self, name, isClassical=False):
"""Add a qubit or bit to the circuit.
name is a (string,int) tuple containing register name and index
This adds a pair of in and out nodes connected by an edge.
"""
if name not in self.wire_type:
self.wire_type[name] = isClassical
self.node_counter += 1
self.input_map[name] = self.node_counter
self.node_counter += 1
self.output_map[name] = self.node_counter
in_node = self.input_map[name]
out_node = self.output_map[name]
self.multi_graph.add_edge(in_node, out_node)
self.multi_graph.node[in_node]["type"] = "in"
self.multi_graph.node[out_node]["type"] = "out"
self.multi_graph.node[in_node]["name"] = name
self.multi_graph.node[out_node]["name"] = name
self.multi_graph.adj[in_node][out_node][0]["name"] = name
else:
raise DAGCircuitError("duplicate wire %s" % name)
def add_basis_element(self, name, number_qubits,
number_classical=0, number_parameters=0):
"""Add an operation to the basis.
name is string label for operation
number_qubits is number of qubit arguments
number_classical is number of bit arguments
number_parameters is number of real parameters
The parameters (nq,nc,np) are ignored for the special case
when name = "barrier". The barrier instruction has a variable
number of qubit arguments.
"""
if name not in self.basis:
self.basis[name] = (
number_qubits,
number_classical,
number_parameters)
if name in self.gates:
if self.gates[name]["n_args"] != number_parameters or \
self.gates[name]["n_bits"] != number_qubits or number_classical != 0:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def add_gate_data(self, name, gatedata):
"""Add the definition of a gate.
gatedata is dict with fields:
"print" = True or False
"opaque" = True or False
"n_args" = number of real parameters
"n_bits" = number of qubits
"args" = list of parameter names
"bits" = list of qubit names
"body" = GateBody AST node
"""
if name not in self.gates:
self.gates[name] = gatedata
if name in self.basis:
if self.basis[name][0] != self.gates[name]["n_bits"] or \
self.basis[name][1] != 0 or \
self.basis[name][2] != self.gates[name]["n_args"]:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def _check_basis_data(self, name, qargs, cargs, params):
"""Check the arguments against the data for this operation.
name is a string
qargs is a list of tuples like ("q",0)
cargs is a list of tuples like ("c",0)
params is a list of strings that represent floats
"""
# Check that we have this operation
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
# Check the number of arguments matches the signature
if name in ["barrier"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if params:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
elif name in ["snapshot", "noise", "save", "load"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if not params:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
else:
if len(qargs) != self.basis[name][0]:
raise DAGCircuitError("incorrect number of qubits for %s"
% name)
if len(cargs) != self.basis[name][1]:
raise DAGCircuitError("incorrect number of bits for %s"
% name)
if len(params) != self.basis[name][2]:
raise DAGCircuitError("incorrect number of parameters for %s"
% name)
def _check_condition(self, name, condition):
"""Verify that the condition is valid.
name is a string used for error reporting
condition is either None or a tuple (string,int) giving (creg,value)
"""
# Verify creg exists
if condition is not None and condition[0] not in self.cregs:
raise DAGCircuitError("invalid creg in condition for %s" % name)
def _check_bits(self, args, amap, bval):
"""Check the values of a list of (qu)bit arguments.
For each element A of args, check that amap contains A and
self.wire_type[A] equals bval.
args is a list of (regname,idx) tuples
amap is a dictionary keyed on (regname,idx) tuples
bval is boolean
"""
# Check for each wire
for q in args:
if q not in amap:
raise DAGCircuitError("(qu)bit %s not found" % (q,))
if self.wire_type[q] != bval:
raise DAGCircuitError("expected wire type %s for %s"
% (bval, q))
def _bits_in_condition(self, cond):
"""Return a list of bits (regname,idx) in the given condition.
cond is either None or a (regname,int) tuple specifying
a classical if condition.
"""
all_bits = []
if cond is not None:
all_bits.extend([(cond[0], j) for j in range(self.cregs[cond[0]].size)])
return all_bits
def _add_op_node(self, nname, nqargs, ncargs, nparams, ncondition, nop):
"""Add a new operation node to the graph and assign properties.
nname node name
nqargs quantum arguments
ncargs classical arguments
nparams parameters
ncondition classical condition (or None)
nop Instruction instance representing this operation
"""
# Add a new operation node to the graph
self.node_counter += 1
self.multi_graph.add_node(self.node_counter)
# Update that operation node's data
self.multi_graph.node[self.node_counter]["type"] = "op"
self.multi_graph.node[self.node_counter]["name"] = nname
self.multi_graph.node[self.node_counter]["qargs"] = nqargs
self.multi_graph.node[self.node_counter]["cargs"] = ncargs
self.multi_graph.node[self.node_counter]["params"] = nparams
self.multi_graph.node[self.node_counter]["condition"] = ncondition
self.multi_graph.node[self.node_counter]["op"] = nop
def apply_operation_back(self, name, qargs, cargs=None, params=None,
condition=None, op=None):
"""Apply an operation to the output of the circuit.
name is a string
qargs is a list of tuples like ("q",0)
cargs is a list of tuples like ("c",0)
params is a list of symbols that represent numbers
condition is either None or a tuple (string,int) giving (creg,value)
op is an Instruction instance representing this node
"""
cargs = cargs or []
params = params or []
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(name, qargs, cargs, params)
self._check_condition(name, condition)
self._check_bits(qargs, self.output_map, False)
self._check_bits(all_cbits, self.output_map, True)
self._add_op_node(name, qargs, cargs, params, condition, op)
# Add new in-edges from predecessors of the output nodes to the
# operation node while deleting the old in-edges of the output nodes
# and adding new edges from the operation node to each output node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.predecessors(self.output_map[q]))
if len(ie) != 1:
raise QISKitError("output node has multiple in-edges")
self.multi_graph.add_edge(ie[0], self.node_counter, name=q)
self.multi_graph.remove_edge(ie[0], self.output_map[q])
self.multi_graph.add_edge(
self.node_counter, self.output_map[q], name=q)
def apply_operation_front(self, name, qargs, cargs=None, params=None,
condition=None, op=None):
"""Apply an operation to the input of the circuit.
name is a string
qargs is a list of strings like "q[0]"
cargs is a list of strings like "c[0]"
params is a list of strings that represent floats
condition is either None or a tuple (string,int) giving (creg,value)
"""
cargs = cargs or []
params = params or []
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(name, qargs, cargs, params)
self._check_condition(name, condition)
self._check_bits(qargs, self.input_map, False)
self._check_bits(all_cbits, self.input_map, True)
self._add_op_node(name, qargs, cargs, params, condition, op)
# Add new out-edges to successors of the input nodes from the
# operation node while deleting the old out-edges of the input nodes
# and adding new edges to the operation node from each input node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = self.multi_graph.successors(self.input_map[q])
if len(ie) != 1:
raise QISKitError("input node has multiple out-edges")
self.multi_graph.add_edge(self.node_counter, ie[0], name=q)
self.multi_graph.remove_edge(self.input_map[q], ie[0])
self.multi_graph.add_edge(
self.input_map[q], self.node_counter, name=q)
def _make_union_basis(self, input_circuit):
"""Return a new basis map.
The new basis is a copy of self.basis with
new elements of input_circuit.basis added.
input_circuit is a DAGCircuit
"""
union_basis = self.basis.copy()
for g in input_circuit.basis:
if g not in union_basis:
union_basis[g] = input_circuit.basis[g]
if union_basis[g] != input_circuit.basis[g]:
raise DAGCircuitError("incompatible basis")
return union_basis
def _make_union_gates(self, input_circuit):
"""Return a new gates map.
The new gates are a copy of self.gates with
new elements of input_circuit.gates added.
input_circuit is a DAGCircuit
NOTE: gates in input_circuit that are also in self must
be *identical* to the gates in self
"""
union_gates = {}
for k, v in self.gates.items():
union_gates[k] = v
for k, v in input_circuit.gates.items():
if k not in union_gates:
union_gates[k] = v
if union_gates[k]["opaque"] != input_circuit.gates[k]["opaque"] or \
union_gates[k]["n_args"] != input_circuit.gates[k]["n_args"] or \
union_gates[k]["n_bits"] != input_circuit.gates[k]["n_bits"] or \
union_gates[k]["args"] != input_circuit.gates[k]["args"] or \
union_gates[k]["bits"] != input_circuit.gates[k]["bits"]:
raise DAGCircuitError("inequivalent gate definitions for %s"
% k)
return union_gates
def _check_wiremap_registers(self, wire_map, keyregs, valregs,
valreg=True):
"""Check that wiremap neither fragments nor leaves duplicate registers.
1. There are no fragmented registers. A register in keyregs
is fragmented if not all of its (qu)bits are renamed by wire_map.
2. There are no duplicate registers. A register is duplicate if
it appears in both self and keyregs but not in wire_map.
wire_map is a map from (regname,idx) in keyregs to (regname,idx)
in valregs
keyregs is a map from register names to Register objects
valregs is a map from register names to Register objects
valreg is a Bool, if False the method ignores valregs and does not
add regs for bits in the wire_map image that don't appear in valregs
Return the set of regs to add to self
"""
add_regs = set()
reg_frag_chk = {}
for k, v in keyregs.items():
reg_frag_chk[k] = {j: False for j in range(v.size)}
for k in wire_map.keys():
if k[0] in keyregs:
reg_frag_chk[k[0]][k[1]] = True
for k, v in reg_frag_chk.items():
rname = ",".join(map(str, k))
s = set(v.values())
if len(s) == 2:
raise DAGCircuitError("wire_map fragments reg %s" % rname)
elif s == set([False]):
if k in self.qregs or k in self.cregs:
raise DAGCircuitError("unmapped duplicate reg %s" % rname)
else:
# Add registers that appear only in keyregs
add_regs.add(keyregs[k])
else:
if valreg:
# If mapping to a register not in valregs, add it.
# (k,0) exists in wire_map because wire_map doesn't
# fragment k
if not wire_map[(k, 0)][0] in valregs:
size = max(map(lambda x: x[1], filter(lambda x: x[0] == wire_map[(k, 0)][0],
wire_map.values())))
qreg = QuantumRegister(wire_map[(k, 0)][0], size + 1)
add_regs.add(qreg)
return add_regs
def _check_wiremap_validity(self, wire_map, keymap, valmap, input_circuit):
"""Check that the wiremap is consistent.
Check that the wiremap refers to valid wires and that
those wires have consistent types.
wire_map is a map from (regname,idx) in keymap to (regname,idx)
in valmap
keymap is a map whose keys are wire_map keys
valmap is a map whose keys are wire_map values
input_circuit is a DAGCircuit
"""
for k, v in wire_map.items():
kname = ",".join(map(str, k))
vname = ",".join(map(str, v))
if k not in keymap:
raise DAGCircuitError("invalid wire mapping key %s" % kname)
if v not in valmap:
raise DAGCircuitError("invalid wire mapping value %s"
% vname)
if input_circuit.wire_type[k] != self.wire_type[v]:
raise DAGCircuitError("inconsistent wire_map at (%s,%s)"
% (kname, vname))
def _map_condition(self, wire_map, condition):
"""Use the wire_map dict to change the condition tuple's creg name.
wire_map is map from wires to wires
condition is a tuple (reg,int)
Returns the new condition tuple
"""
if condition is None:
n_condition = None
else:
# Map the register name, using fact that registers must not be
# fragmented by the wire_map (this must have been checked
# elsewhere)
bit0 = (condition[0], 0)
n_condition = (wire_map.get(bit0, bit0)[0], condition[1])
return n_condition
def compose_back(self, input_circuit, wire_map=None):
"""Apply the input circuit to the output of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of input qubits of the input circuit are mapped
to a subset of output qubits of this circuit.
wire_map[input_qubit_to_input_circuit] = output_qubit_of_self
"""
wire_map = wire_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map for duplicate values
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_wiremap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.input_map,
self.output_map, input_circuit)
# Compose
self.basis = union_basis
self.gates = union_gates
for node in nx.topological_sort(input_circuit.multi_graph):
nd = input_circuit.multi_graph.node[node]
if nd["type"] == "in":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["name"], nd["name"])
# the mapped wire should already exist
if m_name not in self.output_map:
raise QISKitError("wire (%s,%d) not in self" % (m_name[0], m_name[1]))
if nd["name"] not in input_circuit.wire_type:
raise QISKitError("inconsistent wire_type for (%s,%d) in input_circuit"
% (nd["name"][0], nd["name"][1]))
elif nd["type"] == "out":
# ignore output nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: wire_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x), nd["cargs"]))
self.apply_operation_back(nd["name"], m_qargs, m_cargs,
nd["params"], condition, nd["op"])
else:
raise QISKitError("bad node type %s" % nd["type"])
def compose_front(self, input_circuit, wire_map=None):
"""Apply the input circuit to the input of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of output qubits of the input circuit are mapped
to a subset of input qubits of
this circuit.
"""
wire_map = wire_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_wiremap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.output_map,
self.input_map, input_circuit)
# Compose
self.basis = union_basis
self.gates = union_gates
for n in reversed(list(nx.topological_sort(input_circuit.multi_graph))):
nd = input_circuit.multi_graph.node[n]
if nd["type"] == "out":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["name"], nd["name"])
# the mapped wire should already exist
if m_name not in self.input_map:
raise QISKitError("wire (%s,%d) not in self" % (m_name[0], m_name[1]))
if nd["name"] not in input_circuit.wire_type:
raise QISKitError(
"inconsistent wire_type for (%s,%d) in input_circuit"
% (nd["name"][0], nd["name"][1]))
elif nd["type"] == "in":
# ignore input nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: wire_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x), nd["cargs"]))
self.apply_operation_front(nd["name"], m_qargs, m_cargs,
nd["params"], condition, nd["op"])
else:
raise QISKitError("bad node type %s" % nd["type"])
def size(self):
"""Return the number of operations."""
return self.multi_graph.order() - 2 * len(self.wire_type)
def depth(self):
"""Return the circuit depth."""
if not nx.is_directed_acyclic_graph(self.multi_graph):
raise QISKitError("not a DAG")
return nx.dag_longest_path_length(self.multi_graph) - 1
def width(self):
"""Return the total number of qubits used by the circuit."""
return len(self.wire_type) - self.num_cbits()
def num_cbits(self):
"""Return the total number of bits used by the circuit."""
return list(self.wire_type.values()).count(True)
def num_tensor_factors(self):
"""Compute how many components the circuit can decompose into."""
return nx.number_weakly_connected_components(self.multi_graph)
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.gates[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.gates[name]["n_args"] > 0:
out += "(" + ",".join(self.gates[name]["args"]) + ")"
out += " " + ",".join(self.gates[name]["bits"])
if self.gates[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.gates[name]["body"].qasm() + "}"
return out
def qasm(self, decls_only=False, add_swap=False,
no_decls=False, qeflag=False, aliases=None, eval_symbols=False):
"""Return a string containing QASM for this circuit.
if qeflag is True, add a line to include "qelib1.inc"
and only generate gate code for gates not in qelib1.
if eval_symbols is True, evaluate all symbolic
expressions to their floating point representation.
if no_decls is True, only print the instructions.
if aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
if decls_only is True, only print the declarations.
if add_swap is True, add the definition of swap in terms of
cx if necessary.
"""
# TODO: some of the input flags are not needed anymore
# Rename qregs if necessary
if aliases:
qregdata = OrderedDict()
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
# Write top matter
if no_decls:
out = ""
else:
printed_gates = []
out = "OPENQASM 2.0;\n"
if qeflag:
out += "include \"qelib1.inc\";\n"
for k, v in qregdata.items():
out += "qreg %s[%d];\n" % (k, v.size)
for k, v in self.cregs.items():
out += "creg %s[%d];\n" % (k, v.size)
omit = ["U", "CX", "measure", "reset", "barrier"]
# TODO: dagcircuit shouldn't know about extensions
if qeflag:
qelib = ["u3", "u2", "u1", "cx", "id", "x", "y", "z", "h",
"s", "sdg", "t", "tdg", "cz", "cy", "ccx", "cu1",
"cu3", "swap", "cswap", "u0", "rx", "ry", "rz",
"ch", "crz", "rzz"]
omit.extend(qelib)
printed_gates.extend(qelib)
simulator_instructions = ["snapshot", "save", "load", "noise", "wait"]
omit.extend(simulator_instructions)
for k in self.basis.keys():
if k not in omit:
if not self.gates[k]["opaque"]:
calls = self.gates[k]["body"].calls()
for c in calls:
if c not in printed_gates:
out += self._gate_string(c) + "\n"
printed_gates.append(c)
if k not in printed_gates:
out += self._gate_string(k) + "\n"
printed_gates.append(k)
if add_swap and not qeflag and "cx" not in self.basis:
out += "gate cx a,b { CX a,b; }\n"
if add_swap and "swap" not in self.basis:
out += "gate swap a,b { cx a,b; cx b,a; cx a,b; }\n"
# Write the instructions
if not decls_only:
for n in nx.lexicographical_topological_sort(self.multi_graph):
nd = self.multi_graph.node[n]
if nd["type"] == "op":
if nd["condition"] is not None:
out += "if(%s==%d) " \
% (nd["condition"][0], nd["condition"][1])
if not nd["cargs"]:
nm = nd["name"]
if aliases:
qarglist = map(lambda x: aliases[x], nd["qargs"])
else:
qarglist = nd["qargs"]
qarg = ",".join(map(lambda x: "%s[%d]" % (x[0], x[1]),
qarglist))
if nd["params"]:
if eval_symbols:
param = ",".join(map(lambda x: str(sympy.N(x)),
nd["params"]))
else:
param = ",".join(map(lambda x: x.replace("**", "^"),
map(str, nd["params"])))
out += "%s(%s) %s;\n" % (nm, param, qarg)
else:
out += "%s %s;\n" % (nm, qarg)
else:
if nd["name"] == "measure":
if len(nd["cargs"]) != 1 or len(nd["qargs"]) != 1 \
or nd["params"]:
raise QISKitError("bad node data")
qname = nd["qargs"][0][0]
qindex = nd["qargs"][0][1]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
out += "measure %s[%d] -> %s[%d];\n" \
% (qname,
qindex,
nd["cargs"][0][0],
nd["cargs"][0][1])
else:
raise QISKitError("bad node data")
return out
def _check_wires_list(self, wires, name, input_circuit, condition=None):
"""Check that a list of wires satisfies some conditions.
wires = list of (register_name, index) tuples
name = name of operation
input_circuit = replacement circuit for operation
condition = None or (creg_name, value) if this instance of the
operation is classically controlled
The wires give an order for (qu)bits in the input circuit
that is replacing the named operation.
- no duplicate names
- correct length for named operation
- elements are wires of input_circuit
Raises an exception otherwise.
"""
if len(set(wires)) != len(wires):
raise DAGCircuitError("duplicate wires")
wire_tot = self.basis[name][0] + self.basis[name][1]
if condition is not None:
wire_tot += self.cregs[condition[0]].size
if len(wires) != wire_tot:
raise DAGCircuitError("expected %d wires, got %d"
% (wire_tot, len(wires)))
for w in wires:
if w not in input_circuit.wire_type:
raise DAGCircuitError("wire (%s,%d) not in input circuit"
% (w[0], w[1]))
def _make_pred_succ_maps(self, n):
"""Return predecessor and successor dictionaries.
These map from wire names to predecessor and successor
nodes for the operation node n in self.multi_graph.
"""
pred_map = {e[2]['name']: e[0] for e in
self.multi_graph.in_edges(nbunch=n, data=True)}
succ_map = {e[2]['name']: e[1] for e in
self.multi_graph.out_edges(nbunch=n, data=True)}
return pred_map, succ_map
def _full_pred_succ_maps(self, pred_map, succ_map, input_circuit,
wire_map):
"""Map all wires of the input circuit.
Map all wires of the input circuit to predecessor and
successor nodes in self, keyed on wires in self.
pred_map, succ_map dicts come from _make_pred_succ_maps
input_circuit is the input circuit
wire_map is the wire map from wires of input_circuit to wires of self
returns full_pred_map, full_succ_map
"""
full_pred_map = {}
full_succ_map = {}
for w in input_circuit.input_map:
# If w is wire mapped, find the corresponding predecessor
# of the node
if w in wire_map:
full_pred_map[wire_map[w]] = pred_map[wire_map[w]]
full_succ_map[wire_map[w]] = succ_map[wire_map[w]]
else:
# Otherwise, use the corresponding output nodes of self
# and compute the predecessor.
full_succ_map[w] = self.output_map[w]
full_pred_map[w] = self.multi_graph.predecessors(
self.output_map[w])[0]
if len(list(self.multi_graph.predecessors(self.output_map[w]))) != 1:
raise QISKitError(
"too many predecessors for (%s,%d) output node" % (w[0], w[1])
)
return full_pred_map, full_succ_map
@staticmethod
def _match_dag_nodes(node1, node2):
"""
Check if DAG nodes are considered equivalent, e.g. as a node_match for nx.is_isomorphic.
Args:
node1 (dict): A node to compare.
node2 (dict): The other node to compare.
Returns:
Bool: If node1 == node2
"""
copy_node1 = {k: v for (k, v) in node1.items()}
copy_node2 = {k: v for (k, v) in node2.items()}
return copy_node1 == copy_node2
def __eq__(self, other):
return nx.is_isomorphic(self.multi_graph, other.multi_graph,
node_match=DAGCircuit._match_dag_nodes)
def node_nums_in_topological_order(self):
"""
Returns the nodes (their ids) in topological order.
Returns:
List(int): The list of node numbers in topological order
"""
return nx.topological_sort(self.multi_graph)
def substitute_circuit_all(self, name, input_circuit, wires=None):
"""Replace every occurrence of named operation with input_circuit."""
# TODO: rewrite this method to call substitute_circuit_one
wires = wires or None
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
self._check_wires_list(wires, name, input_circuit)
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: ("", 0) for w in wires}
add_qregs = self._check_wiremap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Iterate through the nodes of self and replace the selected nodes
# by iterating through the input_circuit, constructing and
# checking the validity of the wire_map for each replacement
# NOTE: We do not replace conditioned gates. One way to implement
# this later is to add or update the conditions of each gate
# that we add from the input_circuit.
self.basis = union_basis
self.gates = union_gates
for n in self.node_nums_in_topological_order():
nd = self.multi_graph.node[n]
if nd["type"] == "op" and nd["name"] == name:
if nd["condition"] is None:
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"], nd["cargs"]]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map, input_circuit)
pred_map, succ_map = self._make_pred_succ_maps(n)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(n)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map,
md["condition"])
m_qargs = [wire_map.get(x, x) for x in md["qargs0"]]
m_cargs = [wire_map.get(x, x) for x in md["cargs0"]]
self._add_op_node(md["name"], m_qargs, m_cargs,
md["params"], condition, md["op"])
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter, name=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w], full_succ_map[w],
name=w)
o_pred = list(self.multi_graph.predecessors(
self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise QISKitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise QISKitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(
p[0], self.output_map[w])
def substitute_circuit_one(self, node, input_circuit, wires=None):
"""Replace one node with input_circuit.
node is a reference to a node of self.multi_graph of type "op"
input_circuit is a DAGCircuit
"""
wires = wires or None
nd = self.multi_graph.node[node]
name = nd["name"]
self._check_wires_list(wires, name, input_circuit, nd["condition"])
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: ("", 0) for w in wires}
add_qregs = self._check_wiremap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_wiremap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Replace the node by iterating through the input_circuit.
# Constructing and checking the validity of the wire_map.
# If a gate is conditioned, we expect the replacement subcircuit
# to depend on those control bits as well.
self.basis = union_basis
self.gates = union_gates
if nd["type"] != "op":
raise DAGCircuitError("expected node type \"op\", got %s"
% nd["type"])
condition_bit_list = self._bits_in_condition(nd["condition"])
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"],
nd["cargs"],
condition_bit_list]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map, input_circuit)
pred_map, succ_map = self._make_pred_succ_maps(node)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(node)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map, md["condition"])
m_qargs = list(map(lambda x: wire_map.get(x, x),
md["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x),
md["cargs"]))
self._add_op_node(md["name"], m_qargs, m_cargs,
md["params"], condition, md["op"])
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter,
name=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(
full_pred_map[w], full_succ_map[w], name=w)
o_pred = list(self.multi_graph.predecessors(self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise QISKitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise QISKitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(p[0], self.output_map[w])
def get_named_nodes(self, name):
"""Get the set of "op" node ids with the given name."""
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
# We need to instantiate the full list now because the underlying multi_graph
# may change when users iterate over the named nodes.
return {node_id for node_id, data in self.multi_graph.nodes(data=True)
if data["type"] == "op" and data["name"] == name}
def get_cnot_nodes(self):
"""Get the set of Cnot."""
cx_names = ['cx', 'CX']
cxs_nodes = []
for cx_name in cx_names:
if cx_name in self.basis:
for cx_id in self.get_named_nodes(cx_name):
cxs_nodes.append(self.multi_graph.node[cx_id])
return cxs_nodes
def _remove_op_node(self, n):
"""Remove an operation node n.
Add edges from predecessors to successors.
"""
pred_map, succ_map = self._make_pred_succ_maps(n)
self.multi_graph.remove_node(n)
for w in pred_map.keys():
self.multi_graph.add_edge(pred_map[w], succ_map[w], name=w)
def remove_ancestors_of(self, node):
"""Remove all of the ancestor operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
# TODO: probably better to do all at once using
# multi_graph.remove_nodes_from; same for related functions ...
for n in anc:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_descendants_of(self, node):
"""Remove all of the descendant operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
for n in dec:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nonancestors_of(self, node):
"""Remove all of the non-ancestors operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(anc))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nondescendants_of(self, node):
"""Remove all of the non-descendants operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(dec))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def layers(self):
"""Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit.
A layer is a circuit whose gates act on disjoint qubits, i.e.
a layer has depth 1. The total number of layers equals the
circuit depth d. The layers are indexed from 0 to d-1 with the
earliest layer at index 0. The layers are constructed using a
greedy algorithm. Each returned layer is a dict containing
{"graph": circuit graph, "partition": list of qubit lists}.
TODO: Gates that use the same cbits will end up in different
layers as this is currently implemented. This may not be
the desired behavior.
"""
graph_layers = self.multigraph_layers()
try:
next(graph_layers) # Remove input nodes
except StopIteration:
return
def nodes_data(nodes):
"""Construct full nodes from just node ids."""
return ((node_id, self.multi_graph.nodes[node_id]) for node_id in nodes)
for graph_layer in graph_layers:
# Get the op nodes from the layer, removing any input and output nodes.
op_nodes = [node for node in nodes_data(graph_layer) if node[1]["type"] == "op"]
# Stop yielding once there are no more op_nodes in a layer.
if not op_nodes:
return
# Construct a shallow copy of self
new_layer = copy.copy(self)
new_layer.multi_graph = nx.MultiDiGraph()
new_layer.multi_graph.add_nodes_from(nodes_data(self.input_map.values()))
new_layer.multi_graph.add_nodes_from(nodes_data(self.output_map.values()))
# The quantum registers that have an operation in this layer.
support_list = [
op_node[1]["qargs"]
for op_node in op_nodes
if op_node[1]["name"] not in {"barrier", "snapshot", "save", "load", "noise"}
]
new_layer.multi_graph.add_nodes_from(op_nodes)
# Now add the edges to the multi_graph
# By default we just wire inputs to the outputs.
wires = {self.input_map[register]: self.output_map[register]
for register in self.wire_type}
# Wire inputs to op nodes, and op nodes to outputs.
for op_node in op_nodes:
args = self._bits_in_condition(op_node[1]["condition"]) \
+ op_node[1]["cargs"] + op_node[1]["qargs"]
arg_ids = (self.input_map[arg] for arg in args) # map from ("q",0) to node id.
for arg_id in arg_ids:
wires[arg_id], wires[op_node[0]] = op_node[0], wires[arg_id]
# Add wiring to/from the operations and between unused inputs & outputs.
new_layer.multi_graph.add_edges_from(wires.items())
yield {"graph": new_layer, "partition": support_list}
def serial_layers(self):
"""Yield a layer for all gates of this circuit.
A serial layer is a circuit with one gate. The layers have the
same structure as in layers().
"""
for n in self.node_nums_in_topological_order():
nxt_nd = self.multi_graph.node[n]
if nxt_nd["type"] == "op":
new_layer = DAGCircuit()
for qreg in self.qregs.values():
new_layer.add_qreg(qreg)
for creg in self.cregs.values():
new_layer.add_creg(creg)
new_layer.basis = self.basis.copy()
new_layer.gates = self.gates.copy()
# Save the support of the operation we add to the layer
support_list = []
# Operation data
qa = copy.copy(nxt_nd["qargs"])
ca = copy.copy(nxt_nd["cargs"])
pa = copy.copy(nxt_nd["params"])
co = copy.copy(nxt_nd["condition"])
op = copy.copy(nxt_nd["op"])
_ = self._bits_in_condition(co)
# Add node to new_layer
new_layer.apply_operation_back(nxt_nd["name"],
qa, ca, pa, co, op)
# Add operation to partition
if nxt_nd["name"] not in ["barrier",
"snapshot", "save", "load", "noise"]:
# support_list.append(list(set(qa) | set(ca) | set(cob)))
support_list.append(list(qa))
l_dict = {"graph": new_layer, "partition": support_list}
yield l_dict
def multigraph_layers(self):
"""Yield layers of the multigraph."""
predecessor_count = dict() # Dict[node, predecessors not visited]
cur_layer = [node for node in self.input_map.values()]
yield cur_layer
next_layer = []
while cur_layer:
for node in cur_layer:
# Count multiedges with multiplicity.
for successor in self.multi_graph.successors(node):
multiplicity = self.multi_graph.number_of_edges(node, successor)
if successor in predecessor_count:
predecessor_count[successor] -= multiplicity
else:
predecessor_count[successor] = \
self.multi_graph.in_degree(successor) - multiplicity
if predecessor_count[successor] == 0:
next_layer.append(successor)
del predecessor_count[successor]
yield next_layer
cur_layer = next_layer
next_layer = []
def collect_runs(self, namelist):
"""Return a set of runs of "op" nodes with the given names.
For example, "... h q[0]; cx q[0],q[1]; cx q[0],q[1]; h q[1]; .."
would produce the tuple of cx nodes as an element of the set returned
from a call to collect_runs(["cx"]). If instead the cx nodes were
"cx q[0],q[1]; cx q[1],q[0];", the method would still return the
pair in a tuple. The namelist can contain names that are not
in the circuit's basis.
Nodes must have only one successor to continue the run.
"""
group_list = []
# Iterate through the nodes of self in topological order
# and form tuples containing sequences of gates
# on the same qubit(s).
ts = list(self.node_nums_in_topological_order())
nodes_seen = dict(zip(ts, [False] * len(ts)))
for node in ts:
nd = self.multi_graph.node[node]
if nd["type"] == "op" and nd["name"] in namelist \
and not nodes_seen[node]:
group = [node]
nodes_seen[node] = True
s = list(self.multi_graph.successors(node))
while len(s) == 1 and \
self.multi_graph.node[s[0]]["type"] == "op" and \
self.multi_graph.node[s[0]]["name"] in namelist:
group.append(s[0])
nodes_seen[s[0]] = True
s = list(self.multi_graph.successors(s[0]))
if len(group) > 1:
group_list.append(tuple(group))
return set(group_list)
def count_ops(self):
"""Count the occurrences of operation names.
Returns a dictionary of counts keyed on the operation name.
"""
op_dict = {}
for node in self.node_nums_in_topological_order():
nd = self.multi_graph.node[node]
name = nd["name"]
if nd["type"] == "op":
if name not in op_dict:
op_dict[name] = 1
else:
op_dict[name] += 1
return op_dict
def properties(self):
"""Return a dictionary of circuit properties."""
summary = {"size": self.size(),
"depth": self.depth(),
"width": self.width(),
"bits": self.num_cbits(),
"factors": self.num_tensor_factors(),
"operations": self.count_ops()}
return summary
@staticmethod
def fromQuantumCircuit(circuit, expand_gates=True):
"""Build a ``DAGCircuit`` object from a ``QuantumCircuit``.
Args:
circuit (QuantumCircuit): the input circuit.
expand_gates (bool): if ``False``, none of the gates are expanded,
i.e. the gates that are defined in the circuit are included in
the DAG basis.
Return:
DAGCircuit: the DAG representing the input circuit.
"""
dagcircuit = DAGCircuit()
dagcircuit.name = circuit.name
for register in circuit.qregs:
dagcircuit.add_qreg(register)
for register in circuit.cregs:
dagcircuit.add_creg(register)
# Add user gate definitions
for name, data in circuit.definitions.items():
dagcircuit.add_basis_element(name, data["n_bits"], 0,
data["n_args"])
dagcircuit.add_gate_data(name, data)
# Add instructions
builtins = {
"U": ["U", 1, 0, 3],
"CX": ["CX", 2, 0, 0],
"measure": ["measure", 1, 1, 0],
"reset": ["reset", 1, 0, 0],
"barrier": ["barrier", -1, 0, 0]
}
# Add simulator instructions
simulator_instructions = {
"snapshot": ["snapshot", -1, 0, 1],
"save": ["save", -1, 0, 1],
"load": ["load", -1, 0, 1],
"noise": ["noise", -1, 0, 1]
}
for main_instruction in circuit.data:
# TODO: generate definitions and nodes for CompositeGates,
# for now simply drop their instructions into the DAG
instruction_list = []
is_composite = isinstance(main_instruction,
_compositegate.CompositeGate)
if is_composite and expand_gates:
instruction_list = main_instruction.instruction_list()
else:
instruction_list.append(main_instruction)
for instruction in instruction_list:
# Add OpenQASM built-in gates on demand
if instruction.name in builtins:
dagcircuit.add_basis_element(*builtins[instruction.name])
# Add simulator extension instructions
if instruction.name in simulator_instructions:
dagcircuit.add_basis_element(*simulator_instructions[instruction.name])
# Separate classical arguments to measurements
if instruction.name == "measure":
qargs = [(instruction.qargs[0][0].name, instruction.qargs[0][1])]
cargs = [(instruction.cargs[0][0].name, instruction.cargs[0][1])]
else:
qargs = list(map(lambda x: (x[0].name, x[1]), instruction.qargs))
cargs = []
# Get arguments for classical control (if any)
if instruction.control is None:
control = None
else:
control = (instruction.control[0].name, instruction.control[1])
if is_composite and not expand_gates:
is_inverse = instruction.inverse_flag
name = instruction.name if not is_inverse else instruction.inverse_name
else:
name = instruction.name
dagcircuit.apply_operation_back(name, qargs, cargs,
instruction.param,
control, instruction)
return dagcircuit
<|code_end|>
|
Revise the documentation TOC subsection handling
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
An issue raised during #1254:
> Also Is it possible in the template to show the subsection when that section is viewed.
The new fancy design currently does not show subsections in the left-side TOC pane (except for the autodocs). Ideally it should show the subsections, allowing collapsing with sensible defaults and usability.
|
doc/conf.py
<|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Qiskit documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 25 18:13:28 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
from qiskit import __version__
sys.path.insert(0, os.path.abspath('.'))
# Imported manually, as otherwise it will not be fully imported.
import qiskit.extensions.simulator
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.napoleon',
'sphinx.ext.doctest',
'sphinx.ext.coverage',
'sphinx.ext.mathjax',
'sphinx.ext.viewcode',
'sphinx.ext.githubpages']
# Napoleon settings
napoleon_google_docstring = True
napoleon_numpy_docstring = False
napoleon_include_init_with_doc = True
napoleon_include_private_with_doc = False
napoleon_include_special_with_doc = False
napoleon_use_admonition_for_examples = False
napoleon_use_admonition_for_notes = False
napoleon_use_admonition_for_references = False
napoleon_use_ivar = False
napoleon_use_param = True
napoleon_use_rtype = True
autoclass_content = 'both'
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'Qiskit Terra'
copyright = '2017-2018 IBM'
author = 'IBM'
# Add description
html_context = {
'description': 'Qiskit Terra'
}
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = __version__
# The full version, including alpha/beta/rc tags.
release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store',
'_autodoc/modules.rst', 'de', 'ja']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
# html_theme = 'alabaster'
# html_theme = 'bizstyle'
# html_theme = agogo
html_theme = 'sphinx_materialdesign_theme' # use the theme in subdir 'theme'
html_theme_path = ['./'] # make sphinx search for themes in current dir
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {
# Specify a list of menu in Header.
# Tuples forms:
# ('Name', 'external url or path of pages in the document', boolean, 'icon name')
#
# Third argument:
# True indicates an external link.
# False indicates path of pages in the document.
#
# Fourth argument:
# Specify the icon name.
# For details see link.
# https://material.io/icons/
'header_links' : [
('Home', 'index', False, 'home'),
("ExternalLink", "http://example.com", True, 'launch'),
("NoIconLink", "http://example.com", True, ''),
("GitHub", "https://github.com/myyasuda/sphinx_materialdesign_theme", True, 'link')
],
# Customize css colors.
# For details see link.
# https://getmdl.io/customize/index.html
#
# Values: amber, blue, brown, cyan deep_orange, deep_purple, green, grey, indigo, light_blue,
# light_green, lime, orange, pink, purple, red, teal, yellow(Default: indigo)
'primary_color': 'blue',
# Values: Same as primary_color. (Default: pink)
'accent_color': 'indigo',
# Customize layout.
# For details see link.
# https://getmdl.io/components/index.html#layout-section
'fixed_drawer': True,
'fixed_header': False,
'header_waterfall': True,
'header_scroll': False,
# Render title in header.
# Values: True, False (Default: False)
'show_header_title': False,
# Render title in drawer.
# Values: True, False (Default: True)
'show_drawer_title': True,
# Render footer.
}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['./theme/static/']
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = 'theme/static/qiskit-terra-logo.png'
html_favicon = 'theme/static/favicon.ico'
html_last_updated_fmt = '%Y/%m/%d'
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'Qiskitdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'Qiskit.tex', 'Qiskit Documentation',
'''Jim Challenger, Andrew Cross, Ismael Faro, Jay Gambetta''', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'qiskit', 'Qiskit Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'Qiskit Terra', 'Qiskit Terra Documentation',
author, 'Qiskit', 'One line description of project.',
'Miscellaneous'),
]
# Avoid a warning and treat the docstrings of the QasmLexer tokens as verbatim,
# as PLY uses docstring as a way to define the patterns the token matches.
def remove_module_docstring(app, what, name, obj, options, lines):
if name.startswith('qiskit.qasm._qasmlexer.QasmLexer.t_') and lines:
lines[0] = u'Token matching: ``%s``' % lines[0]
def setup(app):
app.connect('autodoc-process-docstring', remove_module_docstring)
<|code_end|>
|
doc/conf.py
<|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Qiskit documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 25 18:13:28 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
from qiskit import __version__
sys.path.insert(0, os.path.abspath('.'))
# Imported manually, as otherwise it will not be fully imported.
import qiskit.extensions.simulator
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.napoleon',
'sphinx.ext.doctest',
'sphinx.ext.coverage',
'sphinx.ext.mathjax',
'sphinx.ext.viewcode',
'sphinx.ext.githubpages']
# Napoleon settings
napoleon_google_docstring = True
napoleon_numpy_docstring = False
napoleon_include_init_with_doc = True
napoleon_include_private_with_doc = False
napoleon_include_special_with_doc = False
napoleon_use_admonition_for_examples = False
napoleon_use_admonition_for_notes = False
napoleon_use_admonition_for_references = False
napoleon_use_ivar = False
napoleon_use_param = True
napoleon_use_rtype = True
autoclass_content = 'both'
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'Qiskit Terra'
copyright = '2017-2018 IBM'
author = 'IBM'
# Add description
html_context = {
'description': 'Qiskit Terra'
}
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = __version__
# The full version, including alpha/beta/rc tags.
release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store',
'_autodoc/modules.rst', 'de', 'ja']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
# html_theme = 'alabaster'
# html_theme = 'bizstyle'
# html_theme = agogo
html_sidebars = {
'**': ['globaltoc.html']
}
html_theme = 'sphinx_materialdesign_theme' # use the theme in subdir 'theme'
html_theme_path = ['./'] # make sphinx search for themes in current dir
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {
# Specify a list of menu in Header.
# Tuples forms:
# ('Name', 'external url or path of pages in the document', boolean, 'icon name')
#
# Third argument:
# True indicates an external link.
# False indicates path of pages in the document.
#
# Fourth argument:
# Specify the icon name.
# For details see link.
# https://material.io/icons/
'header_links' : [
('Home', 'index', False, 'home'),
("ExternalLink", "http://example.com", True, 'launch'),
("NoIconLink", "http://example.com", True, ''),
("GitHub", "https://github.com/myyasuda/sphinx_materialdesign_theme", True, 'link')
],
# Customize css colors.
# For details see link.
# https://getmdl.io/customize/index.html
#
# Values: amber, blue, brown, cyan deep_orange, deep_purple, green, grey, indigo, light_blue,
# light_green, lime, orange, pink, purple, red, teal, yellow(Default: indigo)
'primary_color': 'blue',
# Values: Same as primary_color. (Default: pink)
'accent_color': 'indigo',
# Customize layout.
# For details see link.
# https://getmdl.io/components/index.html#layout-section
'fixed_drawer': True,
'fixed_header': False,
'header_waterfall': True,
'header_scroll': False,
# Render title in header.
# Values: True, False (Default: False)
'show_header_title': False,
# Render title in drawer.
# Values: True, False (Default: True)
'show_drawer_title': True,
# Render footer.
}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['./theme/static/']
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = 'theme/static/qiskit-terra-logo.png'
html_favicon = 'theme/static/favicon.ico'
html_last_updated_fmt = '%Y/%m/%d'
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'Qiskitdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'Qiskit.tex', 'Qiskit Documentation',
'''Jim Challenger, Andrew Cross, Ismael Faro, Jay Gambetta''', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'qiskit', 'Qiskit Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'Qiskit Terra', 'Qiskit Terra Documentation',
author, 'Qiskit', 'One line description of project.',
'Miscellaneous'),
]
# Avoid a warning and treat the docstrings of the QasmLexer tokens as verbatim,
# as PLY uses docstring as a way to define the patterns the token matches.
def remove_module_docstring(app, what, name, obj, options, lines):
if name.startswith('qiskit.qasm._qasmlexer.QasmLexer.t_') and lines:
lines[0] = u'Token matching: ``%s``' % lines[0]
def setup(app):
app.connect('autodoc-process-docstring', remove_module_docstring)
<|code_end|>
|
Result.get_data()['unitary'] differs from Result.get_unitary()
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: Latest Master (assuming post https://github.com/Qiskit/qiskit-terra/pull/1360 )
- **Python version**: 3.7
- **Operating system**: Linux
### What is the current behavior?
When running a simulation with the unitary_simulator locally the result from Result.get_data()['unitary'] isn't the expected data format.
I have a script which running a GHZ test circuit through the unitary simulator I use for testing some visualizations and this started failing post #1360 when taking the dot product of an 8 entry array with the unitary from `result.get_data()['unitary']` because of a size mismatch so I started investigating.
It looks like the to_dict method at https://github.com/Qiskit/qiskit-terra/blob/master/qiskit/result/result.py#L84 doesn't know how to handle the complex numbers properly and is splitting them up into a list with each component .
### Steps to reproduce the problem
My test script is:
```
import qiskit
n = 3 # number of qubits
q = qiskit.QuantumRegister(n)
c = qiskit.ClassicalRegister(n, 'c')
ghz = qiskit.QuantumCircuit(q, c, name='ghz')
ghz.h(q[0])
ghz.cx(q[0], q[1])
ghz.cx(q[0], q[2])
ghz.s(q[0])
ghz.measure(q[0], c[0])
ghz.measure(q[1], c[1])
ghz.measure(q[2], c[2])
sim = 'unitary_simulator'
backend = qiskit.Aer.get_backend(sim)
result = qiskit.execute(ghz, backend, shots=1000).result()
unitary = result.get_unitary('ghz')
```
But it looks like anyone accessing the unitary from get_data()['unitary'] will hit this issue.
For one sample execution:
`result.get_data('ghz')['unitary']` returns
```
[[[0.7071067811865476, 0.0],
[0.7071067811865475, -8.659560562354932e-17],
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0]],
[[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[4.329780281177466e-17, 0.7071067811865475],
[-1.29893408435324e-16, -0.7071067811865476]],
[[0.0, 0.0],
[0.0, 0.0],
[0.7071067811865476, 0.0],
[0.7071067811865475, -8.659560562354932e-17],
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0]],
[[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[4.329780281177466e-17, 0.7071067811865475],
[-1.29893408435324e-16, -0.7071067811865476],
[0.0, 0.0],
[0.0, 0.0]],
[[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[0.7071067811865476, 0.0],
[0.7071067811865475, -8.659560562354932e-17],
[0.0, 0.0],
[0.0, 0.0]],
[[0.0, 0.0],
[0.0, 0.0],
[4.329780281177466e-17, 0.7071067811865475],
[-1.29893408435324e-16, -0.7071067811865476],
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0]],
[[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[0.7071067811865476, 0.0],
[0.7071067811865475, -8.659560562354932e-17]],
[[4.329780281177466e-17, 0.7071067811865475],
[-1.29893408435324e-16, -0.7071067811865476],
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0]]]
```
and
`unitary`
```
[[(0.7071067811865476+0j),
(0.7071067811865475-8.659560562354932e-17j),
0j,
0j,
0j,
0j,
0j,
0j],
[0j,
0j,
0j,
0j,
0j,
0j,
(4.329780281177466e-17+0.7071067811865475j),
(-1.29893408435324e-16-0.7071067811865476j)],
[0j,
0j,
(0.7071067811865476+0j),
(0.7071067811865475-8.659560562354932e-17j),
0j,
0j,
0j,
0j],
[0j,
0j,
0j,
0j,
(4.329780281177466e-17+0.7071067811865475j),
(-1.29893408435324e-16-0.7071067811865476j),
0j,
0j],
[0j,
0j,
0j,
0j,
(0.7071067811865476+0j),
(0.7071067811865475-8.659560562354932e-17j),
0j,
0j],
[0j,
0j,
(4.329780281177466e-17+0.7071067811865475j),
(-1.29893408435324e-16-0.7071067811865476j),
0j,
0j,
0j,
0j],
[0j,
0j,
0j,
0j,
0j,
0j,
(0.7071067811865476+0j),
(0.7071067811865475-8.659560562354932e-17j)],
[(4.329780281177466e-17+0.7071067811865475j),
(-1.29893408435324e-16-0.7071067811865476j),
0j,
0j,
0j,
0j,
0j,
0j]]
```
### What is the expected behavior?
I would expect result['unitary'] and unitary to have the same data.
### Suggested solutions
Investigate the cause of what's transforming the complex numbers into a list and then adjust it to not do that.
|
qiskit/result/result.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Model for schema-conformant Results."""
import warnings
from qiskit import QISKitError, QuantumCircuit
from qiskit.validation.base import BaseModel, bind_schema
from .models import ResultSchema
@bind_schema(ResultSchema)
class Result(BaseModel):
"""Model for Results.
Please note that this class only describes the required fields. For the
full description of the model, please check ``ResultSchema``.
Attributes:
backend_name (str): backend name.
backend_version (str): backend version, in the form X.Y.Z.
qobj_id (str): user-generated Qobj id.
job_id (str): unique execution id from the backend.
success (bool): True if complete input qobj executed correctly. (Implies
each experiment success)
results (ExperimentResult): corresponding results for array of
experiments of the input qobj
"""
def __init__(self, backend_name, backend_version, qobj_id, job_id, success,
results, **kwargs):
self.backend_name = backend_name
self.backend_version = backend_version
self.qobj_id = qobj_id
self.job_id = job_id
self.success = success
self.results = results
super().__init__(**kwargs)
def data(self, circuit=None):
"""Get the raw data for an experiment.
Note this data will be a single classical and quantum register and in a
format required by the results schema. We recomened that most users use
the get_xxx method and the data will be post processed for the data type.
Args:
circuit (str or QuantumCircuit or int or None): the index of the
experiment. Several types are accepted for convenience::
* str: the name of the experiment.
* QuantumCircuit: the name of the instance will be used.
* int: the position of the experiment.
* None: if there is only one experiment, returns it.
Returns:
dict: A dictionary of results data for an experiment. The data depends on
the backend it ran on.
QASM backend backend returns a dictionary of dictionary with
key 'counts' and with the counts, with the second dictionary keys
containing a string in hex format (``0x123``) and values equal to the
number of times this outcome was measured.
Statevector backend returns a dictionary with key 'statevector' and values being a
list[complex] list of 2^n_qubits complex amplitudes.
Unitary backend returns a dictionary with key 'unitary' and values being a
list[list[complex]] list of 2^n_qubits x 2^n_qubits complex
amplitudes.
The simulator backends also have an optional 'key' snapshot which returns
a dict of snapshots specified by the simulator backend.
Raises:
QISKitError: if data for the experiment could not be retrieved.
"""
try:
return self._get_experiment(circuit).data.to_dict()
except (KeyError, TypeError):
raise QISKitError('No data for circuit "{0}"'.format(circuit))
def get_counts(self, circuit=None):
"""Get the histogram data of an experiment.
Args:
circuit (str or QuantumCircuit or int or None): the index of the
experiment, as specified by ``get_data()``.
Returns:
dict[str:int]: a dictionary with the counts for each qubit, with
the keys containing a string in hex format (``0x123``).
Raises:
QISKitError: if there are no counts for the experiment.
"""
try:
return self._get_experiment(circuit).data.counts.to_dict()
except KeyError:
raise QISKitError('No counts for circuit "{0}"'.format(circuit))
def get_statevector(self, circuit=None):
"""Get the final statevector of an experiment.
Args:
circuit (str or QuantumCircuit or int or None): the index of the
experiment, as specified by ``data()``.
Returns:
list[complex]: list of 2^n_qubits complex amplitudes.
Raises:
QISKitError: if there is no statevector for the experiment.
"""
try:
return self._get_experiment(circuit).data.statevector
except KeyError:
raise QISKitError('No statevector for circuit "{0}"'.format(circuit))
def get_unitary(self, circuit=None):
"""Get the final unitary of an experiment.
Args:
circuit (str or QuantumCircuit or int or None): the index of the
experiment, as specified by ``data()``.
Returns:
list[list[complex]]: list of 2^n_qubits x 2^n_qubits complex
amplitudes.
Raises:
QISKitError: if there is no unitary for the experiment.
"""
try:
return self._get_experiment(circuit).data.unitary
except KeyError:
raise QISKitError('No unitary for circuit "{0}"'.format(circuit))
def get_snapshots(self, circuit=None):
"""Get snapshots recorded during the run of an experiment.
Args:
circuit (str or QuantumCircuit or int or None): the index of the
experiment, as specified by ``data()``.
Returns:
dict[slot: dict[str: array]]: dictionary where the keys are the
requested snapshot slots, and the values are a dictionary of
the snapshots themselves.
Raises:
QISKitError: if there are no snapshots for the experiment.
"""
try:
return self._get_experiment(circuit).data.snapshots.to_dict()
except KeyError:
raise QISKitError('No snapshots for circuit "{0}"'.format(circuit))
def get_snapshot(self, slot=None, circuit=None):
"""Get snapshot at a specific slot of an experiment.
Args:
slot (str): snapshot slot to retrieve. If None and there is only one
slot, return that one.
circuit (str or QuantumCircuit or int or None): the index of the
experiment, as specified by ``data()``.
Returns:
dict[slot: dict[str: array]]: list of 2^n_qubits complex amplitudes.
Raises:
QISKitError: if there is no snapshot at all, or in this slot
"""
try:
snapshots_dict = self.get_snapshots(circuit)
if slot is None:
slots = list(snapshots_dict.keys())
if len(slots) == 1:
slot = slots[0]
else:
raise QISKitError("You have to select a slot when there "
"is more than one available")
snapshot_dict = snapshots_dict[slot]
snapshot_types = list(snapshot_dict.keys())
if len(snapshot_types) == 1:
snapshot_list = snapshot_dict[snapshot_types[0]]
if len(snapshot_list) == 1:
return snapshot_list[0]
return snapshot_list
return snapshot_dict
except KeyError:
raise QISKitError('No snapshot at slot {0} for '
'circuit "{1}"'.format(slot, circuit))
def _get_experiment(self, key=None):
"""Return an experiment from a given key.
Args:
key (str or QuantumCircuit or int or None): the index of the
experiment, as specified by ``get_data()``.
Returns:
ExperimentResult: the results for an experiment.
Raises:
QISKitError: if there is no data for the circuit, or an unhandled
error occurred while fetching the data.
"""
if not self.success:
raise QISKitError(getattr(self, 'status',
'Result was not successful'))
# Automatically return the first result if no key was provided.
if key is None:
if len(self.results) != 1:
raise QISKitError(
'You have to select a circuit when there is more than '
'one available')
else:
key = 0
# Key is an integer: return result by index.
if isinstance(key, int):
return self.results[key]
# Key is a QuantumCircuit or str: retrieve result by name.
if isinstance(key, QuantumCircuit):
key = key.name
try:
# Look into `result[x].header.name` for the names.
return next(result for result in self.results
if getattr(getattr(result, 'header', None),
'name', '') == key)
except StopIteration:
raise QISKitError('Data for experiment "%s" could not be found.' %
key)
# To be deprecated after 0.7
def __iadd__(self, other):
"""Append a Result object to current Result object.
Arg:
other (Result): a Result object to append.
Returns:
Result: The current object with appended results.
Raises:
QISKitError: if the Results cannot be combined.
"""
warnings.warn('Result addition is deprecated and will be removed in '
'version 0.7+.', DeprecationWarning)
this_backend = self.backend_name
other_backend = other.backend_name
if this_backend != other_backend:
raise QISKitError('Result objects from different backends cannot be combined.')
if not self.success or not other.success:
raise QISKitError('Can not combine a failed result with another result.')
self.results.extend(other.results)
return self
def __add__(self, other):
"""Combine Result objects.
Arg:
other (Result): a Result object to combine.
Returns:
Result: A new Result object consisting of combined objects.
"""
warnings.warn('Result addition is deprecated and will be removed in '
'version 0.7+.', DeprecationWarning)
copy_of_self = self.from_dict(self.to_dict())
copy_of_self += other
return copy_of_self
def get_status(self):
"""Return whole result status."""
warnings.warn('get_status() is deprecated and will be removed in '
'version 0.7+. Instead use result.status directly.',
DeprecationWarning)
return getattr(self, 'status', '')
def circuit_statuses(self):
"""Return statuses of all circuits.
Returns:
list(str): List of status result strings.
"""
warnings.warn('circuit_statuses() is deprecated and will be removed in '
'version 0.7+. Instead use result.results[x]status '
'directly.', DeprecationWarning)
return [getattr(experiment_result, 'status', '') for
experiment_result in self.results]
def get_circuit_status(self, icircuit):
"""Return the status of circuit at index icircuit.
Args:
icircuit (int): index of circuit
Returns:
string: the status of the circuit.
"""
warnings.warn('get_circuit_status() is deprecated and will be removed '
'in version 0.7+. Instead use result.results[x]status '
'directly.', DeprecationWarning)
return self[icircuit].status
def get_job_id(self):
"""Return the job id assigned by the api if this is a remote job.
Returns:
string: a string containing the job id.
"""
warnings.warn('get_job_id() is deprecated and will be removed in '
'version 0.7+. Instead use result.job_id directly.',
DeprecationWarning)
return self.job_id
def get_ran_qasm(self, name):
"""Get the ran qasm for the named circuit and backend.
Args:
name (str): the name of the quantum circuit.
Returns:
string: A text version of the qasm file that has been run.
Raises:
QISKitError: if the circuit was not found.
"""
warnings.warn('get_ran_qasm() is deprecated and will be removed in '
'version 0.7+.', DeprecationWarning)
try:
return self.results[name].compiled_circuit_qasm
except KeyError:
raise QISKitError('No qasm for circuit "{0}"'.format(name))
def get_names(self):
"""Get the circuit names of the results.
Returns:
List: A list of circuit names.
"""
warnings.warn('get_names() is deprecated and will be removed in '
'version 0.7+. Instead inspect result.results directly',
DeprecationWarning)
return list(self.results.keys())
<|code_end|>
|
qiskit/result/result.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Model for schema-conformant Results."""
import warnings
from qiskit import QISKitError, QuantumCircuit
from qiskit.validation.base import BaseModel, bind_schema
from .models import ResultSchema
@bind_schema(ResultSchema)
class Result(BaseModel):
"""Model for Results.
Please note that this class only describes the required fields. For the
full description of the model, please check ``ResultSchema``.
Attributes:
backend_name (str): backend name.
backend_version (str): backend version, in the form X.Y.Z.
qobj_id (str): user-generated Qobj id.
job_id (str): unique execution id from the backend.
success (bool): True if complete input qobj executed correctly. (Implies
each experiment success)
results (ExperimentResult): corresponding results for array of
experiments of the input qobj
"""
def __init__(self, backend_name, backend_version, qobj_id, job_id, success,
results, **kwargs):
self.backend_name = backend_name
self.backend_version = backend_version
self.qobj_id = qobj_id
self.job_id = job_id
self.success = success
self.results = results
super().__init__(**kwargs)
def data(self, circuit=None):
"""Get the raw data for an experiment.
Note this data will be a single classical and quantum register and in a
format required by the results schema. We recomened that most users use
the get_xxx method and the data will be post processed for the data type.
Args:
circuit (str or QuantumCircuit or int or None): the index of the
experiment. Several types are accepted for convenience::
* str: the name of the experiment.
* QuantumCircuit: the name of the instance will be used.
* int: the position of the experiment.
* None: if there is only one experiment, returns it.
Returns:
dict: A dictionary of results data for an experiment. The data
depends on the backend it ran on.
QASM backends return a dictionary of dictionary with the key
'counts' and with the counts, with the second dictionary keys
containing a string in hex format (``0x123``) and values equal to
the number of times this outcome was measured.
Statevector backends return a dictionary with key 'statevector' and
values being a list[list[complex components]] list of 2^n_qubits
complex amplitudes. Where each complex number is represented as a 2
entry list for each component. For example, a list of
[0.5+1j, 0-1j] would be represented as [[0.5, 1], [0, -1]].
Unitary backends return a dictionary with key 'unitary' and values
being a list[list[list[complex components]]] list of
2^n_qubits x 2^n_qubits complex amplitudes in a two entry list for
each component. For example if the amplitude is
[[0.5+0j, 0-1j], ...] the value returned will be
[[[0.5, 0], [0, -1]], ...].
The simulator backends also have an optional key 'snapshot' which
returns a dict of snapshots specified by the simulator backend.
The value is of the form dict[slot: dict[str: array]]
where the keys are the requested snapshot slots, and the values are
a dictionary of the snapshots.
Raises:
QISKitError: if data for the experiment could not be retrieved.
"""
try:
return self._get_experiment(circuit).data.to_dict()
except (KeyError, TypeError):
raise QISKitError('No data for circuit "{0}"'.format(circuit))
def get_counts(self, circuit=None):
"""Get the histogram data of an experiment.
Args:
circuit (str or QuantumCircuit or int or None): the index of the
experiment, as specified by ``get_data()``.
Returns:
dict[str:int]: a dictionary with the counts for each qubit, with
the keys containing a string in hex format (``0x123``).
Raises:
QISKitError: if there are no counts for the experiment.
"""
try:
return self._get_experiment(circuit).data.counts.to_dict()
except KeyError:
raise QISKitError('No counts for circuit "{0}"'.format(circuit))
def get_statevector(self, circuit=None):
"""Get the final statevector of an experiment.
Args:
circuit (str or QuantumCircuit or int or None): the index of the
experiment, as specified by ``data()``.
Returns:
list[complex]: list of 2^n_qubits complex amplitudes.
Raises:
QISKitError: if there is no statevector for the experiment.
"""
try:
return self._get_experiment(circuit).data.statevector
except KeyError:
raise QISKitError('No statevector for circuit "{0}"'.format(circuit))
def get_unitary(self, circuit=None):
"""Get the final unitary of an experiment.
Args:
circuit (str or QuantumCircuit or int or None): the index of the
experiment, as specified by ``data()``.
Returns:
list[list[complex]]: list of 2^n_qubits x 2^n_qubits complex
amplitudes.
Raises:
QISKitError: if there is no unitary for the experiment.
"""
try:
return self._get_experiment(circuit).data.unitary
except KeyError:
raise QISKitError('No unitary for circuit "{0}"'.format(circuit))
def get_snapshots(self, circuit=None):
"""Get snapshots recorded during the run of an experiment.
Args:
circuit (str or QuantumCircuit or int or None): the index of the
experiment, as specified by ``data()``.
Returns:
dict[slot: dict[str: array]]: dictionary where the keys are the
requested snapshot slots, and the values are a dictionary of
the snapshots.
Raises:
QISKitError: if there are no snapshots for the experiment.
"""
try:
return self._get_experiment(circuit).data.snapshots.to_dict()
except KeyError:
raise QISKitError('No snapshots for circuit "{0}"'.format(circuit))
def get_snapshot(self, slot=None, circuit=None):
"""Get snapshot at a specific slot of an experiment.
Args:
slot (str): snapshot slot to retrieve. If None and there is only one
slot, return that one.
circuit (str or QuantumCircuit or int or None): the index of the
experiment, as specified by ``data()``.
Returns:
dict[slot: dict[str: array]]: list of 2^n_qubits complex amplitudes.
Raises:
QISKitError: if there is no snapshot at all, or in this slot
"""
try:
snapshots_dict = self.get_snapshots(circuit)
if slot is None:
slots = list(snapshots_dict.keys())
if len(slots) == 1:
slot = slots[0]
else:
raise QISKitError("You have to select a slot when there "
"is more than one available")
snapshot_dict = snapshots_dict[slot]
snapshot_types = list(snapshot_dict.keys())
if len(snapshot_types) == 1:
snapshot_list = snapshot_dict[snapshot_types[0]]
if len(snapshot_list) == 1:
return snapshot_list[0]
return snapshot_list
return snapshot_dict
except KeyError:
raise QISKitError('No snapshot at slot {0} for '
'circuit "{1}"'.format(slot, circuit))
def _get_experiment(self, key=None):
"""Return an experiment from a given key.
Args:
key (str or QuantumCircuit or int or None): the index of the
experiment, as specified by ``get_data()``.
Returns:
ExperimentResult: the results for an experiment.
Raises:
QISKitError: if there is no data for the circuit, or an unhandled
error occurred while fetching the data.
"""
if not self.success:
raise QISKitError(getattr(self, 'status',
'Result was not successful'))
# Automatically return the first result if no key was provided.
if key is None:
if len(self.results) != 1:
raise QISKitError(
'You have to select a circuit when there is more than '
'one available')
else:
key = 0
# Key is an integer: return result by index.
if isinstance(key, int):
return self.results[key]
# Key is a QuantumCircuit or str: retrieve result by name.
if isinstance(key, QuantumCircuit):
key = key.name
try:
# Look into `result[x].header.name` for the names.
return next(result for result in self.results
if getattr(getattr(result, 'header', None),
'name', '') == key)
except StopIteration:
raise QISKitError('Data for experiment "%s" could not be found.' %
key)
# To be deprecated after 0.7
def __iadd__(self, other):
"""Append a Result object to current Result object.
Arg:
other (Result): a Result object to append.
Returns:
Result: The current object with appended results.
Raises:
QISKitError: if the Results cannot be combined.
"""
warnings.warn('Result addition is deprecated and will be removed in '
'version 0.7+.', DeprecationWarning)
this_backend = self.backend_name
other_backend = other.backend_name
if this_backend != other_backend:
raise QISKitError('Result objects from different backends cannot be combined.')
if not self.success or not other.success:
raise QISKitError('Can not combine a failed result with another result.')
self.results.extend(other.results)
return self
def __add__(self, other):
"""Combine Result objects.
Arg:
other (Result): a Result object to combine.
Returns:
Result: A new Result object consisting of combined objects.
"""
warnings.warn('Result addition is deprecated and will be removed in '
'version 0.7+.', DeprecationWarning)
copy_of_self = self.from_dict(self.to_dict())
copy_of_self += other
return copy_of_self
def get_status(self):
"""Return whole result status."""
warnings.warn('get_status() is deprecated and will be removed in '
'version 0.7+. Instead use result.status directly.',
DeprecationWarning)
return getattr(self, 'status', '')
def circuit_statuses(self):
"""Return statuses of all circuits.
Returns:
list(str): List of status result strings.
"""
warnings.warn('circuit_statuses() is deprecated and will be removed in '
'version 0.7+. Instead use result.results[x]status '
'directly.', DeprecationWarning)
return [getattr(experiment_result, 'status', '') for
experiment_result in self.results]
def get_circuit_status(self, icircuit):
"""Return the status of circuit at index icircuit.
Args:
icircuit (int): index of circuit
Returns:
string: the status of the circuit.
"""
warnings.warn('get_circuit_status() is deprecated and will be removed '
'in version 0.7+. Instead use result.results[x]status '
'directly.', DeprecationWarning)
return self[icircuit].status
def get_job_id(self):
"""Return the job id assigned by the api if this is a remote job.
Returns:
string: a string containing the job id.
"""
warnings.warn('get_job_id() is deprecated and will be removed in '
'version 0.7+. Instead use result.job_id directly.',
DeprecationWarning)
return self.job_id
def get_ran_qasm(self, name):
"""Get the ran qasm for the named circuit and backend.
Args:
name (str): the name of the quantum circuit.
Returns:
string: A text version of the qasm file that has been run.
Raises:
QISKitError: if the circuit was not found.
"""
warnings.warn('get_ran_qasm() is deprecated and will be removed in '
'version 0.7+.', DeprecationWarning)
try:
return self.results[name].compiled_circuit_qasm
except KeyError:
raise QISKitError('No qasm for circuit "{0}"'.format(name))
def get_names(self):
"""Get the circuit names of the results.
Returns:
List: A list of circuit names.
"""
warnings.warn('get_names() is deprecated and will be removed in '
'version 0.7+. Instead inspect result.results directly',
DeprecationWarning)
return list(self.results.keys())
<|code_end|>
|
Compile and execute use a progress bar even if a single circuit is passed.
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: master
- **Python version**: 3.7
- **Operating system**: OSX
### What is the current behavior?
The `compile` and `execute` functions make use of a progress bar for a single circuit.
### Steps to reproduce the problem
```
from qiskit import *
from qiskit.tools.jupyter import TextProgressBar
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.cx(q[0], q[1])
qc.measure(q, c)
backend = Aer.get_backend('qasm_simulator')
TextProgressBar()
qobj = compile([qc], backend)
```
### What is the expected behavior?
A progress bar should not be used for a single circuit.
### Suggested solutions
|
qiskit/transpiler/_parallel.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# This file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names
# of its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################
"""
Routines for running Python functions in parallel using process pools
from the multiprocessing library.
"""
import os
import platform
from multiprocessing import Pool
from qiskit._qiskiterror import QISKitError
from qiskit._util import local_hardware_info
from qiskit._pubsub import Publisher
# Number of local physical cpus
CPU_COUNT = local_hardware_info()['cpus']
def parallel_map(task, values, task_args=tuple(), task_kwargs={}, # pylint: disable=W0102
num_processes=CPU_COUNT):
"""
Parallel execution of a mapping of `values` to the function `task`. This
is functionally equivalent to::
result = [task(value, *task_args, **task_kwargs) for value in values]
On Windows this function defaults to a serial implementation to avoid the
overhead from spawning processes in Windows.
Args:
task (func): Function that is to be called for each value in ``task_vec``.
values (array_like): List or array of values for which the ``task``
function is to be evaluated.
task_args (list): Optional additional arguments to the ``task`` function.
task_kwargs (dict): Optional additional keyword argument to the ``task`` function.
num_processes (int): Number of processes to spawn.
Returns:
result: The result list contains the value of
``task(value, *task_args, **task_kwargs)`` for
each value in ``values``.
Raises:
QISKitError: If user interrupts via keyboard.
Events:
terra.transpiler.parallel.start: The collection of parallel tasks are about to start.
terra.transpiler.parallel.update: One of the parallel task has finished.
terra.transpiler.parallel.finish: All the parallel tasks have finished.
"""
Publisher().publish("terra.transpiler.parallel.start", len(values))
if len(values) == 1:
Publisher().publish("terra.transpiler.parallel.finish")
return [task(values[0], *task_args, **task_kwargs)]
nfinished = [0]
def _callback(_):
nfinished[0] += 1
Publisher().publish("terra.transpiler.parallel.done", nfinished[0])
# Run in parallel if not Win and not in parallel already
if platform.system() != 'Windows' and num_processes > 1 \
and os.getenv('QISKIT_IN_PARALLEL') == 'FALSE':
os.environ['QISKIT_IN_PARALLEL'] = 'TRUE'
try:
pool = Pool(processes=num_processes)
async_res = [pool.apply_async(task, (value,) + task_args, task_kwargs,
_callback) for value in values]
while not all([item.ready() for item in async_res]):
for item in async_res:
item.wait(timeout=0.1)
pool.terminate()
pool.join()
except KeyboardInterrupt:
pool.terminate()
pool.join()
Publisher().publish("terra.parallel.parallel.finish")
raise QISKitError('Keyboard interrupt in parallel_map.')
Publisher().publish("terra.transpiler.parallel.finish")
os.environ['QISKIT_IN_PARALLEL'] = 'FALSE'
return [ar.get() for ar in async_res]
# Cannot do parallel on Windows , if another parallel_map is running in parallel,
# or len(values) == 1.
results = []
for _, value in enumerate(values):
result = task(value, *task_args, **task_kwargs)
results.append(result)
_callback(0)
Publisher().publish("terra.transpiler.parallel.finish")
return results
<|code_end|>
|
qiskit/transpiler/_parallel.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# This file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names
# of its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################
"""
Routines for running Python functions in parallel using process pools
from the multiprocessing library.
"""
import os
import platform
from multiprocessing import Pool
from qiskit._qiskiterror import QISKitError
from qiskit._util import local_hardware_info
from qiskit._pubsub import Publisher
# Number of local physical cpus
CPU_COUNT = local_hardware_info()['cpus']
def parallel_map(task, values, task_args=tuple(), task_kwargs={}, # pylint: disable=W0102
num_processes=CPU_COUNT):
"""
Parallel execution of a mapping of `values` to the function `task`. This
is functionally equivalent to::
result = [task(value, *task_args, **task_kwargs) for value in values]
On Windows this function defaults to a serial implementation to avoid the
overhead from spawning processes in Windows.
Args:
task (func): Function that is to be called for each value in ``task_vec``.
values (array_like): List or array of values for which the ``task``
function is to be evaluated.
task_args (list): Optional additional arguments to the ``task`` function.
task_kwargs (dict): Optional additional keyword argument to the ``task`` function.
num_processes (int): Number of processes to spawn.
Returns:
result: The result list contains the value of
``task(value, *task_args, **task_kwargs)`` for
each value in ``values``.
Raises:
QISKitError: If user interrupts via keyboard.
Events:
terra.transpiler.parallel.start: The collection of parallel tasks are about to start.
terra.transpiler.parallel.update: One of the parallel task has finished.
terra.transpiler.parallel.finish: All the parallel tasks have finished.
"""
if len(values) == 1:
return [task(values[0], *task_args, **task_kwargs)]
Publisher().publish("terra.transpiler.parallel.start", len(values))
nfinished = [0]
def _callback(_):
nfinished[0] += 1
Publisher().publish("terra.transpiler.parallel.done", nfinished[0])
# Run in parallel if not Win and not in parallel already
if platform.system() != 'Windows' and num_processes > 1 \
and os.getenv('QISKIT_IN_PARALLEL') == 'FALSE':
os.environ['QISKIT_IN_PARALLEL'] = 'TRUE'
try:
pool = Pool(processes=num_processes)
async_res = [pool.apply_async(task, (value,) + task_args, task_kwargs,
_callback) for value in values]
while not all([item.ready() for item in async_res]):
for item in async_res:
item.wait(timeout=0.1)
pool.terminate()
pool.join()
except KeyboardInterrupt:
pool.terminate()
pool.join()
Publisher().publish("terra.parallel.parallel.finish")
raise QISKitError('Keyboard interrupt in parallel_map.')
Publisher().publish("terra.transpiler.parallel.finish")
os.environ['QISKIT_IN_PARALLEL'] = 'FALSE'
return [ar.get() for ar in async_res]
# Cannot do parallel on Windows , if another parallel_map is running in parallel,
# or len(values) == 1.
results = []
for _, value in enumerate(values):
result = task(value, *task_args, **task_kwargs)
results.append(result)
_callback(0)
Publisher().publish("terra.transpiler.parallel.finish")
return results
<|code_end|>
|
Memory-related spec changes for 0.7
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
After recent discussion, the specs needs further tweaks before 0.7:
* `BackendConfiguration`:
* `BackendConfiguration.memory` (boolean): new **required** field, indicates if the backend supports `memory`
* `BackendConfiguration.max_shots` (int): new **required** field, contains the maximum number of shots supported
* `Qobj`:
* `config.memory` (boolean): new **optional** field, indicates if the job is going to use `memory`
This changes need to be reflected as well in #1047, for tracking purposes.
|
qiskit/backends/models/backendconfiguration.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Model and schema for backend configuration."""
from marshmallow.fields import Boolean, DateTime, Integer, List, Nested, String
from marshmallow.validate import Equal, Length, OneOf, Range, Regexp
from qiskit.validation import BaseModel, BaseSchema, bind_schema
class GateConfigSchema(BaseSchema):
"""Schema for GateConfig."""
# Required properties.
name = String(required=True)
parameters = List(String(), required=True)
qasm_def = String(required=True)
# Optional properties.
coupling_map = List(List(Integer(),
validate=Length(min=1)),
validate=Length(min=1))
latency_map = List(List(Integer(validate=OneOf([0, 1])),
validate=Length(min=1)),
validate=Length(min=1))
conditional = Boolean()
description = String()
class BackendConfigurationSchema(BaseSchema):
"""Schema for BackendConfiguration."""
# Required properties.
backend_name = String(required=True)
backend_version = String(required=True,
validate=Regexp("[0-9]+.[0-9]+.[0-9]+$"))
n_qubits = Integer(required=True, validate=Range(min=1))
basis_gates = List(String(), required=True,
validate=Length(min=1))
gates = Nested(GateConfigSchema, required=True, many=True,
validate=Length(min=1))
local = Boolean(required=True)
simulator = Boolean(required=True)
conditional = Boolean(required=True)
open_pulse = Boolean(required=True, validate=Equal(False))
memory = Boolean(required=True)
max_shots = Integer(required=True, validate=Range(min=1))
# Optional properties.
sample_name = String()
coupling_map = List(List(Integer(),
validate=Length(min=1)),
validate=Length(min=1))
n_registers = Integer(validate=Range(min=1))
register_map = List(List(Integer(validate=OneOf([0, 1])),
validate=Length(min=1)),
validate=Length(min=1))
configurable = Boolean()
credits_required = Boolean()
online_date = DateTime()
display_name = String()
description = String()
tags = List(String())
@bind_schema(GateConfigSchema)
class GateConfig(BaseModel):
"""Model for GateConfig.
Please note that this class only describes the required fields. For the
full description of the model, please check ``GateConfigSchema``.
Attributes:
name (str): the gate name as it will be referred to in QASM.
parameters (list[str]): variable names for the gate parameters (if any).
qasm_def (str): definition of this gate in terms of QASM primitives U
and CX.
"""
def __init__(self, name, parameters, qasm_def, **kwargs):
self.name = name
self.parameters = parameters
self.qasm_def = qasm_def
super().__init__(**kwargs)
@bind_schema(BackendConfigurationSchema)
class BackendConfiguration(BaseModel):
"""Model for BackendConfiguration.
Please note that this class only describes the required fields. For the
full description of the model, please check ``BackendConfigurationSchema``.
Attributes:
backend_name (str): backend name.
backend_version (str): backend version in the form X.Y.Z.
n_qubits (int): number of qubits.
basis_gates (list[str]): list of basis gates names on the backend.
gates (GateConfig): list of basis gates on the backend.
local (bool): backend is local or remote.
simulator (bool): backend is a simulator.
conditional (bool): backend supports conditional operations.
open_pulse (bool): backend supports open pulse.
memory (bool): backend supports memory.
max_shots (int): maximum number of shots supported.
"""
def __init__(self, backend_name, backend_version, n_qubits, basis_gates,
gates, local, simulator, conditional, open_pulse, memory,
max_shots, **kwargs):
self.backend_name = backend_name
self.backend_version = backend_version
self.n_qubits = n_qubits
self.basis_gates = basis_gates
self.gates = gates
self.local = local
self.simulator = simulator
self.conditional = conditional
self.open_pulse = open_pulse
self.memory = memory
self.max_shots = max_shots
super().__init__(**kwargs)
<|code_end|>
|
qiskit/backends/models/backendconfiguration.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Model and schema for backend configuration."""
from marshmallow.fields import Boolean, DateTime, Integer, List, Nested, String
from marshmallow.validate import Equal, Length, OneOf, Range, Regexp
from qiskit.validation import BaseModel, BaseSchema, bind_schema
class GateConfigSchema(BaseSchema):
"""Schema for GateConfig."""
# Required properties.
name = String(required=True)
parameters = List(String(), required=True)
qasm_def = String(required=True)
# Optional properties.
coupling_map = List(List(Integer(),
validate=Length(min=1)),
validate=Length(min=1))
latency_map = List(List(Integer(validate=OneOf([0, 1])),
validate=Length(min=1)),
validate=Length(min=1))
conditional = Boolean()
description = String()
class BackendConfigurationSchema(BaseSchema):
"""Schema for BackendConfiguration."""
# Required properties.
backend_name = String(required=True)
backend_version = String(required=True,
validate=Regexp("[0-9]+.[0-9]+.[0-9]+$"))
n_qubits = Integer(required=True, validate=Range(min=1))
basis_gates = List(String(), required=True,
validate=Length(min=1))
gates = Nested(GateConfigSchema, required=True, many=True,
validate=Length(min=1))
local = Boolean(required=True)
simulator = Boolean(required=True)
conditional = Boolean(required=True)
open_pulse = Boolean(required=True, validate=Equal(False))
memory = Boolean(required=True)
max_shots = Integer(required=True, validate=Range(min=1))
# Optional properties.
max_experiments = Integer(validate=Range(min=1))
sample_name = String()
coupling_map = List(List(Integer(),
validate=Length(min=1)),
validate=Length(min=1))
n_registers = Integer(validate=Range(min=1))
register_map = List(List(Integer(validate=OneOf([0, 1])),
validate=Length(min=1)),
validate=Length(min=1))
configurable = Boolean()
credits_required = Boolean()
online_date = DateTime()
display_name = String()
description = String()
tags = List(String())
@bind_schema(GateConfigSchema)
class GateConfig(BaseModel):
"""Model for GateConfig.
Please note that this class only describes the required fields. For the
full description of the model, please check ``GateConfigSchema``.
Attributes:
name (str): the gate name as it will be referred to in QASM.
parameters (list[str]): variable names for the gate parameters (if any).
qasm_def (str): definition of this gate in terms of QASM primitives U
and CX.
"""
def __init__(self, name, parameters, qasm_def, **kwargs):
self.name = name
self.parameters = parameters
self.qasm_def = qasm_def
super().__init__(**kwargs)
@bind_schema(BackendConfigurationSchema)
class BackendConfiguration(BaseModel):
"""Model for BackendConfiguration.
Please note that this class only describes the required fields. For the
full description of the model, please check ``BackendConfigurationSchema``.
Attributes:
backend_name (str): backend name.
backend_version (str): backend version in the form X.Y.Z.
n_qubits (int): number of qubits.
basis_gates (list[str]): list of basis gates names on the backend.
gates (GateConfig): list of basis gates on the backend.
local (bool): backend is local or remote.
simulator (bool): backend is a simulator.
conditional (bool): backend supports conditional operations.
open_pulse (bool): backend supports open pulse.
memory (bool): backend supports memory.
max_shots (int): maximum number of shots supported.
"""
def __init__(self, backend_name, backend_version, n_qubits, basis_gates,
gates, local, simulator, conditional, open_pulse, memory,
max_shots, **kwargs):
self.backend_name = backend_name
self.backend_version = backend_version
self.n_qubits = n_qubits
self.basis_gates = basis_gates
self.gates = gates
self.local = local
self.simulator = simulator
self.conditional = conditional
self.open_pulse = open_pulse
self.memory = memory
self.max_shots = max_shots
super().__init__(**kwargs)
<|code_end|>
|
the default decimals in get_statevector is too small
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
The original statevector simulator will return decimals as many as possible; however, the new terra clips it to 8-digits by default, which results in many chemistry simulations fails because the returned statevector is not enough.
For example, 8-digits is not accurate enough for me to reach ground state energy of H2 since the optimizer can not build accurate gradient with such precision.
I imagine that some users will result in the same situation and it is not easy to find this issue.
Could we make the default to as many as possible and then if users would like to truncate that they can pass the parameters.
|
qiskit/backends/ibmq/ibmqjob.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""IBMQJob module
This module is used for creating asynchronous job objects for the
IBM Q Experience.
"""
from concurrent import futures
import time
import logging
import pprint
import contextlib
import json
import datetime
import numpy
from qiskit.qobj import qobj_to_dict
from qiskit.transpiler import transpile_dag
from qiskit.backends import BaseJob, JobError, JobTimeoutError
from qiskit.backends.jobstatus import JobStatus, JOB_FINAL_STATES
from qiskit.result import Result
from qiskit.result._utils import result_from_old_style_dict
from qiskit.qobj import validate_qobj_against_schema
from .api import ApiError
logger = logging.getLogger(__name__)
API_FINAL_STATES = (
'COMPLETED',
'CANCELLED',
'ERROR_CREATING_JOB',
'ERROR_VALIDATING_JOB',
'ERROR_RUNNING_JOB'
)
class IBMQJob(BaseJob):
"""Represent the jobs that will be executed on IBM-Q simulators and real
devices. Jobs are intended to be created calling ``run()`` on a particular
backend.
Creating a ``Job`` instance does not imply running it. You need to do it in
separate steps::
job = IBMQJob(...)
job.submit() # It won't block.
An error while submitting a job will cause the next call to ``status()`` to
raise. If submitting the job successes, you can inspect the job's status by
using ``status()``. Status can be one of ``JobStatus`` members::
from qiskit.backends.jobstatus import JobStatus
job = IBMQJob(...)
job.submit()
try:
job_status = job.status() # It won't block. It will query the backend API.
if job_status is JobStatus.RUNNING:
print('The job is still running')
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
A call to ``status()`` can raise if something happens at the API level that
prevents Qiskit from determining the status of the job. An example of this
is a temporary connection lose or a network failure.
The ``submit()`` and ``status()`` methods are examples of non-blocking API.
``Job`` instances also have `id()` and ``result()`` methods which will
block::
job = IBMQJob(...)
job.submit()
try:
job_id = job.id() # It will block until completing submission.
print('The job {} was successfully submitted'.format(job_id))
job_result = job.result() # It will block until finishing.
print('The job finished with result {}'.format(job_result))
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
Both methods can raise if something ath the API level happens that prevent
Qiskit from determining the status of the job.
.. NOTE::
When querying the API for getting the status, two kinds of errors are
possible. The most severe is the one preventing Qiskit from getting a
response from the backend. This can be caused by a network failure or a
temporary system break. In these cases, calling ``status()`` will raise.
If Qiskit successfully retrieves the status of a job, it could be it
finished with errors. In that case, ``status()`` will simply return
``JobStatus.ERROR`` and you can call ``error_message()`` to get more
info.
Attributes:
_executor (futures.Executor): executor to handle asynchronous jobs
"""
_executor = futures.ThreadPoolExecutor()
def __init__(self, backend, job_id, api, is_device, qobj=None,
creation_date=None, api_status=None):
"""IBMQJob init function.
We can instantiate jobs from two sources: A QObj, and an already submitted job returned by
the API servers.
Args:
backend (str): The backend instance used to run this job.
job_id (str): The job ID of an already submitted job. Pass `None`
if you are creating a new one.
api (IBMQConnector): IBMQ connector.
is_device (bool): whether backend is a real device # TODO: remove this after Qobj
qobj (Qobj): The Quantum Object. See notes below
creation_date (str): When the job was run.
api_status (str): `status` field directly from the API response.
Notes:
It is mandatory to pass either ``qobj`` or ``job_id``. Passing a ``qobj``
will ignore ``job_id`` and will create an instance to be submitted to the
API server for job creation. Passing only a `job_id`will create an instance
representing an already-created job retrieved from the API server.
"""
super().__init__(backend, job_id)
self._job_data = None
if qobj is not None:
validate_qobj_against_schema(qobj)
self._qobj_payload = qobj_to_dict(qobj, version='1.0.0')
# TODO: No need for this conversion, just use the new equivalent members above
old_qobj = qobj_to_dict(qobj, version='0.0.1')
self._job_data = {
'circuits': old_qobj['circuits'],
'hpc': old_qobj['config'].get('hpc'),
'seed': old_qobj['circuits'][0]['config']['seed'],
'shots': old_qobj['config']['shots'],
'max_credits': old_qobj['config']['max_credits']
}
else:
self._qobj_payload = {}
self._future_captured_exception = None
self._api = api
self._backend = backend
self._cancelled = False
self._status = JobStatus.INITIALIZING
# In case of not providing a `qobj`, it is assumed the job already
# exists in the API (with `job_id`).
if qobj is None:
# Some API calls (`get_status_jobs`, `get_status_job`) provide
# enough information to recreate the `Job`. If that is the case, try
# to make use of that information during instantiation, as
# `self.status()` involves an extra call to the API.
if api_status == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_status == 'COMPLETED':
self._status = JobStatus.DONE
elif api_status == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
else:
self.status()
self._queue_position = None
self._is_device = is_device
def current_utc_time():
"""Gets the current time in UTC format"""
datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
self._creation_date = creation_date or current_utc_time()
self._future = None
self._api_error_msg = None
# pylint: disable=arguments-differ
def result(self, timeout=None, wait=5):
"""Return the result from the job.
Args:
timeout (int): number of seconds to wait for job
wait (int): time between queries to IBM Q server
Returns:
qiskit.Result: Result object
Raises:
JobError: exception raised during job initialization
"""
job_response = self._wait_for_result(timeout=timeout, wait=wait)
return self._result_from_job_response(job_response)
def _wait_for_result(self, timeout=None, wait=5):
self._wait_for_submission()
try:
job_response = self._wait_for_job(timeout=timeout, wait=wait)
except ApiError as api_err:
raise JobError(str(api_err))
status = self.status()
if status is not JobStatus.DONE:
raise JobError('Invalid job state. The job should be DONE but '
'it is {}'.format(str(status)))
return job_response
def _result_from_job_response(self, job_response):
return Result.from_dict(job_response['qObjectResult'])
def cancel(self):
"""Attempt to cancel a job.
Returns:
bool: True if job can be cancelled, else False. Currently this is
only possible on commercial systems.
Raises:
JobError: if there was some unexpected failure in the server
"""
hub = self._api.config.get('hub', None)
group = self._api.config.get('group', None)
project = self._api.config.get('project', None)
try:
response = self._api.cancel_job(self._job_id, hub, group, project)
self._cancelled = 'error' not in response
return self._cancelled
except ApiError as error:
self._cancelled = False
raise JobError('Error cancelling job: %s' % error.usr_msg)
def status(self):
"""Query the API to update the status.
Returns:
JobStatus: The status of the job, once updated.
Raises:
JobError: if there was an exception in the future being executed
or the server sent an unknown answer.
"""
# Implies self._job_id is None
if self._future_captured_exception is not None:
raise JobError(str(self._future_captured_exception))
if self._job_id is None or self._status in JOB_FINAL_STATES:
return self._status
try:
# TODO: See result values
api_job = self._api.get_status_job(self._job_id)
if 'status' not in api_job:
raise JobError('get_status_job didn\'t return status: %s' %
pprint.pformat(api_job))
# pylint: disable=broad-except
except Exception as err:
raise JobError(str(err))
if api_job['status'] == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_job['status'] == 'RUNNING':
self._status = JobStatus.RUNNING
queued, self._queue_position = _is_job_queued(api_job)
if queued:
self._status = JobStatus.QUEUED
elif api_job['status'] == 'COMPLETED':
self._status = JobStatus.DONE
elif api_job['status'] == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
elif 'ERROR' in api_job['status']:
# Error status are of the form "ERROR_*_JOB"
self._status = JobStatus.ERROR
# TODO: This seems to be an inconsistency in the API package.
self._api_error_msg = api_job.get('error') or api_job.get('Error')
else:
raise JobError('Unrecognized answer from server: \n{}'
.format(pprint.pformat(api_job)))
return self._status
def error_message(self):
"""Return the error message returned from the API server response."""
return self._api_error_msg
def queue_position(self):
"""Return the position in the server queue.
Returns:
Number: Position in the queue.
"""
return self._queue_position
def creation_date(self):
"""
Return creation date.
"""
return self._creation_date
def job_id(self):
"""Return backend determined id.
If the Id is not set because the job is already initializing, this call
will block until we have an Id.
"""
self._wait_for_submission()
return self._job_id
def submit(self):
"""Submit job to IBM-Q.
Raises:
JobError: If we have already submitted the job.
"""
# TODO: Validation against the schema should be done here and not
# during initialization. Once done, we should document that the method
# can raise QobjValidationError.
if self._future is not None or self._job_id is not None:
raise JobError("We have already submitted the job!")
self._future = self._executor.submit(self._submit_callback)
def _submit_callback(self):
"""Submit qobj job to IBM-Q.
Returns:
dict: A dictionary with the response of the submitted job
"""
backend_name = self.backend().name()
try:
submit_info = self._api.run_job(self._qobj_payload, backend=backend_name)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submission success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _wait_for_job(self, timeout=60, wait=5):
"""Wait until all online ran circuits of a qobj are 'COMPLETED'.
Args:
timeout (float or None): seconds to wait for job. If None, wait
indefinitely.
wait (float): seconds between queries
Returns:
dict: A dict with the contents of the API request.
Raises:
JobTimeoutError: if the job does not return results before a specified timeout.
JobError: if something wrong happened in some of the server API calls
"""
start_time = time.time()
while self.status() not in JOB_FINAL_STATES:
elapsed_time = time.time() - start_time
if timeout is not None and elapsed_time >= timeout:
raise JobTimeoutError(
'Timeout while waiting for the job: {}'.format(self._job_id)
)
logger.info('status = %s (%d seconds)', self._status, elapsed_time)
time.sleep(wait)
if self._cancelled:
raise JobError(
'Job result impossible to retrieve. The job was cancelled.')
return self._api.get_job(self._job_id)
def _wait_for_submission(self, timeout=60):
"""Waits for the request to return a job ID"""
if self._job_id is None:
if self._future is None:
raise JobError("You have to submit before asking for status or results!")
try:
submit_info = self._future.result(timeout=timeout)
if self._future_captured_exception is not None:
# pylint can't see if catch of None type
# pylint: disable=raising-bad-type
raise self._future_captured_exception
except TimeoutError as ex:
raise JobTimeoutError(
"Timeout waiting for the job being submitted: {}".format(ex)
)
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
raise JobError(str(submit_info['error']))
class IBMQJobPreQobj(IBMQJob):
"""
Subclass of IBMQJob for handling pre-qobj jobs.
"""
def _submit_callback(self):
"""Submit old style qasms job to IBM-Q. Can remove when all devices
understand Qobj.
Returns:
dict: A dictionary with the response of the submitted job
"""
api_jobs = []
circuits = self._job_data['circuits']
for circuit in circuits:
job = _create_api_job_from_circuit(circuit)
api_jobs.append(job)
hpc_camel_cased = _format_hpc_parameters(self._job_data['hpc'])
seed = self._job_data['seed']
shots = self._job_data['shots']
max_credits = self._job_data['max_credits']
try:
submit_info = self._api.run_job(api_jobs, backend=self.backend().name(),
shots=shots, max_credits=max_credits,
seed=seed, hpc=hpc_camel_cased)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submission success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _result_from_job_response(self, job_response):
if self._is_device:
# TODO: temporarily disabled for #1373, reenable before 0.7.
# _reorder_bits(job_response)
pass
experiment_results = []
for circuit_result in job_response['qasms']:
this_result = {'data': circuit_result['data'],
'compiled_circuit_qasm': circuit_result.get('qasm'),
'status': circuit_result['status'],
'success': circuit_result['status'] == 'DONE',
'shots': job_response['shots']}
if 'metadata' in circuit_result:
this_result['metadata'] = circuit_result['metadata']
if 'header' in circuit_result['metadata'].get('compiled_circuit', {}):
this_result['header'] = \
circuit_result['metadata']['compiled_circuit']['header']
else:
this_result['header'] = {}
experiment_results.append(this_result)
ret = {
'id': self._job_id,
'status': job_response['status'],
'used_credits': job_response.get('usedCredits'),
'result': experiment_results,
'backend_name': self.backend().name(),
'success': job_response['status'] == 'COMPLETED',
}
# Append header: from the response; from the payload; or none.
header = job_response.get('header',
self._qobj_payload.get('header', {}))
if header:
ret['header'] = header
return result_from_old_style_dict(ret)
def _reorder_bits(job_data):
"""Temporary fix for ibmq backends.
For every ran circuit, get reordering information from qobj
and apply reordering on result.
Args:
job_data (dict): dict with the bare contents of the API.get_job request.
Raises:
JobError: raised if the creg sizes don't add up in result header.
"""
for circuit_result in job_data['qasms']:
if 'metadata' in circuit_result:
circ = circuit_result['metadata'].get('compiled_circuit')
else:
logger.warning('result object missing metadata for reordering'
' bits: bits may be out of order')
return
# device_qubit -> device_clbit (how it should have been)
measure_dict = {op['qubits'][0]: op['clbits'][0]
for op in circ['operations']
if op['name'] == 'measure'}
counts_dict_new = {}
for item in circuit_result['data']['counts'].items():
# fix clbit ordering to what it should have been
bits = list(item[0])
bits.reverse() # lsb in 0th position
count = item[1]
reordered_bits = list('x' * len(bits))
for device_clbit, bit in enumerate(bits):
if device_clbit in measure_dict:
correct_device_clbit = measure_dict[device_clbit]
reordered_bits[correct_device_clbit] = bit
reordered_bits.reverse()
# only keep the clbits specified by circuit, not everything on device
num_clbits = circ['header']['number_of_clbits']
compact_key = reordered_bits[-num_clbits:]
compact_key = "".join([b if b != 'x' else '0'
for b in compact_key])
# insert spaces to signify different classical registers
cregs = circ['header']['clbit_labels']
if sum([creg[1] for creg in cregs]) != num_clbits:
raise JobError("creg sizes don't add up in result header.")
creg_begin_pos = []
creg_end_pos = []
acc = 0
for creg in reversed(cregs):
creg_size = creg[1]
creg_begin_pos.append(acc)
creg_end_pos.append(acc + creg_size)
acc += creg_size
compact_key = " ".join([compact_key[creg_begin_pos[i]:creg_end_pos[i]]
for i in range(len(cregs))])
# marginalize over unwanted measured qubits
if compact_key not in counts_dict_new:
counts_dict_new[compact_key] = count
else:
counts_dict_new[compact_key] += count
circuit_result['data']['counts'] = counts_dict_new
def _numpy_type_converter(obj):
ret = obj
if isinstance(obj, numpy.integer):
ret = int(obj)
elif isinstance(obj, numpy.floating): # pylint: disable=no-member
ret = float(obj)
elif isinstance(obj, numpy.ndarray):
ret = obj.tolist()
return ret
def _create_api_job_from_circuit(circuit):
"""Helper function that creates a special job required by the API, from a circuit."""
api_job = {}
if not circuit.get('compiled_circuit_qasm'):
compiled_circuit = transpile_dag(circuit['circuit'])
circuit['compiled_circuit_qasm'] = compiled_circuit.qasm(qeflag=True)
if isinstance(circuit['compiled_circuit_qasm'], bytes):
api_job['qasm'] = circuit['compiled_circuit_qasm'].decode()
else:
api_job['qasm'] = circuit['compiled_circuit_qasm']
if circuit.get('name'):
api_job['name'] = circuit['name']
# convert numpy types for json serialization
compiled_circuit = json.loads(json.dumps(circuit['compiled_circuit'],
default=_numpy_type_converter))
api_job['metadata'] = {'compiled_circuit': compiled_circuit}
return api_job
def _is_job_queued(api_job_response):
"""Checks whether a job has been queued or not."""
is_queued, position = False, 0
if 'infoQueue' in api_job_response:
if 'status' in api_job_response['infoQueue']:
queue_status = api_job_response['infoQueue']['status']
is_queued = queue_status == 'PENDING_IN_QUEUE'
if 'position' in api_job_response['infoQueue']:
position = api_job_response['infoQueue']['position']
return is_queued, position
def _format_hpc_parameters(hpc):
"""Helper function to get HPC parameters with the correct format"""
if hpc is None:
return None
hpc_camel_cased = None
with contextlib.suppress(KeyError, TypeError):
# Use CamelCase when passing the hpc parameters to the API.
hpc_camel_cased = {
'multiShotOptimization': hpc['multi_shot_optimization'],
'ompNumThreads': hpc['omp_num_threads']
}
return hpc_camel_cased
<|code_end|>
qiskit/result/postprocess.py
<|code_start|><|code_end|>
qiskit/result/result.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Model for schema-conformant Results."""
import warnings
import numpy as np
from qiskit import QiskitError, QuantumCircuit
from qiskit.validation.base import BaseModel, bind_schema
from .models import ResultSchema
@bind_schema(ResultSchema)
class Result(BaseModel):
"""Model for Results.
Please note that this class only describes the required fields. For the
full description of the model, please check ``ResultSchema``.
Attributes:
backend_name (str): backend name.
backend_version (str): backend version, in the form X.Y.Z.
qobj_id (str): user-generated Qobj id.
job_id (str): unique execution id from the backend.
success (bool): True if complete input qobj executed correctly. (Implies
each experiment success)
results (ExperimentResult): corresponding results for array of
experiments of the input qobj
"""
def __init__(self, backend_name, backend_version, qobj_id, job_id, success,
results, **kwargs):
self.backend_name = backend_name
self.backend_version = backend_version
self.qobj_id = qobj_id
self.job_id = job_id
self.success = success
self.results = results
super().__init__(**kwargs)
def data(self, circuit=None):
"""Get the raw data for an experiment.
Note this data will be a single classical and quantum register and in a
format required by the results schema. We recomened that most users use
the get_xxx method and the data will be post processed for the data type.
Args:
circuit (str or QuantumCircuit or int or None): the index of the
experiment. Several types are accepted for convenience::
* str: the name of the experiment.
* QuantumCircuit: the name of the instance will be used.
* int: the position of the experiment.
* None: if there is only one experiment, returns it.
Returns:
dict: A dictionary of results data for an experiment. The data
depends on the backend it ran on.
QASM backends return a dictionary of dictionary with the key
'counts' and with the counts, with the second dictionary keys
containing a string in hex format (``0x123``) and values equal to
the number of times this outcome was measured.
Statevector backends return a dictionary with key 'statevector' and
values being a list[list[complex components]] list of 2^n_qubits
complex amplitudes. Where each complex number is represented as a 2
entry list for each component. For example, a list of
[0.5+1j, 0-1j] would be represented as [[0.5, 1], [0, -1]].
Unitary backends return a dictionary with key 'unitary' and values
being a list[list[list[complex components]]] list of
2^n_qubits x 2^n_qubits complex amplitudes in a two entry list for
each component. For example if the amplitude is
[[0.5+0j, 0-1j], ...] the value returned will be
[[[0.5, 0], [0, -1]], ...].
The simulator backends also have an optional key 'snapshots' which
returns a dict of snapshots specified by the simulator backend.
The value is of the form dict[slot: dict[str: array]]
where the keys are the requested snapshot slots, and the values are
a dictionary of the snapshots.
Raises:
QiskitError: if data for the experiment could not be retrieved.
"""
try:
return self._get_experiment(circuit).data.to_dict()
except (KeyError, TypeError):
raise QiskitError('No data for circuit "{0}"'.format(circuit))
def get_counts(self, circuit=None):
"""Get the histogram data of an experiment.
Args:
circuit (str or QuantumCircuit or int or None): the index of the
experiment, as specified by ``get_data()``.
Returns:
dict[str:int]: a dictionary with the counts for each qubit, with
the keys containing a string in hex format (``0x123``).
Raises:
QiskitError: if there are no counts for the experiment.
"""
try:
return self._get_experiment(circuit).data.counts.to_dict()
except KeyError:
raise QiskitError('No counts for circuit "{0}"'.format(circuit))
def get_statevector(self, circuit=None, decimals=8):
"""Get the final statevector of an experiment.
Args:
circuit (str or QuantumCircuit or int or None): the index of the
experiment, as specified by ``data()``.
decimals (int): the number of decimals in the statevector
Returns:
list[complex]: list of 2^n_qubits complex amplitudes.
Raises:
QiskitError: if there is no statevector for the experiment.
"""
try:
return np.around(self._get_experiment(circuit).data.statevector,
decimals=decimals)
except KeyError:
raise QiskitError('No statevector for circuit "{0}"'.format(circuit))
def get_unitary(self, circuit=None, decimals=8):
"""Get the final unitary of an experiment.
Args:
circuit (str or QuantumCircuit or int or None): the index of the
experiment, as specified by ``data()``.
decimals (int): the number of decimals in the unitary
Returns:
list[list[complex]]: list of 2^n_qubits x 2^n_qubits complex
amplitudes.
Raises:
QiskitError: if there is no unitary for the experiment.
"""
try:
return np.around(self._get_experiment(circuit).data.unitary,
decimals=decimals)
except KeyError:
raise QiskitError('No unitary for circuit "{0}"'.format(circuit))
def _get_experiment(self, key=None):
"""Return an experiment from a given key.
Args:
key (str or QuantumCircuit or int or None): the index of the
experiment, as specified by ``get_data()``.
Returns:
ExperimentResult: the results for an experiment.
Raises:
QiskitError: if there is no data for the circuit, or an unhandled
error occurred while fetching the data.
"""
if not self.success:
raise QiskitError(getattr(self, 'status',
'Result was not successful'))
# Automatically return the first result if no key was provided.
if key is None:
if len(self.results) != 1:
raise QiskitError(
'You have to select a circuit when there is more than '
'one available')
else:
key = 0
# Key is an integer: return result by index.
if isinstance(key, int):
return self.results[key]
# Key is a QuantumCircuit or str: retrieve result by name.
if isinstance(key, QuantumCircuit):
key = key.name
try:
# Look into `result[x].header.name` for the names.
return next(result for result in self.results
if getattr(getattr(result, 'header', None),
'name', '') == key)
except StopIteration:
raise QiskitError('Data for experiment "%s" could not be found.' %
key)
# To be deprecated after 0.7
def __iadd__(self, other):
"""Append a Result object to current Result object.
Arg:
other (Result): a Result object to append.
Returns:
Result: The current object with appended results.
Raises:
QiskitError: if the Results cannot be combined.
"""
warnings.warn('Result addition is deprecated and will be removed in '
'version 0.7+.', DeprecationWarning)
this_backend = self.backend_name
other_backend = other.backend_name
if this_backend != other_backend:
raise QiskitError('Result objects from different backends cannot be combined.')
if not self.success or not other.success:
raise QiskitError('Can not combine a failed result with another result.')
self.results.extend(other.results)
return self
def __add__(self, other):
"""Combine Result objects.
Arg:
other (Result): a Result object to combine.
Returns:
Result: A new Result object consisting of combined objects.
"""
warnings.warn('Result addition is deprecated and will be removed in '
'version 0.7+.', DeprecationWarning)
copy_of_self = self.from_dict(self.to_dict())
copy_of_self += other
return copy_of_self
def get_status(self):
"""Return whole result status."""
warnings.warn('get_status() is deprecated and will be removed in '
'version 0.7+. Instead use result.status directly.',
DeprecationWarning)
return getattr(self, 'status', '')
def circuit_statuses(self):
"""Return statuses of all circuits.
Returns:
list(str): List of status result strings.
"""
warnings.warn('circuit_statuses() is deprecated and will be removed in '
'version 0.7+. Instead use result.results[x]status '
'directly.', DeprecationWarning)
return [getattr(experiment_result, 'status', '') for
experiment_result in self.results]
def get_circuit_status(self, icircuit):
"""Return the status of circuit at index icircuit.
Args:
icircuit (int): index of circuit
Returns:
string: the status of the circuit.
"""
warnings.warn('get_circuit_status() is deprecated and will be removed '
'in version 0.7+. Instead use result.results[x]status '
'directly.', DeprecationWarning)
return self[icircuit].status
def get_job_id(self):
"""Return the job id assigned by the api if this is a remote job.
Returns:
string: a string containing the job id.
"""
warnings.warn('get_job_id() is deprecated and will be removed in '
'version 0.7+. Instead use result.job_id directly.',
DeprecationWarning)
return self.job_id
def get_ran_qasm(self, name):
"""Get the ran qasm for the named circuit and backend.
Args:
name (str): the name of the quantum circuit.
Returns:
string: A text version of the qasm file that has been run.
Raises:
QiskitError: if the circuit was not found.
"""
warnings.warn('get_ran_qasm() is deprecated and will be removed in '
'version 0.7+.', DeprecationWarning)
try:
return self.results[name].compiled_circuit_qasm
except KeyError:
raise QiskitError('No qasm for circuit "{0}"'.format(name))
def get_names(self):
"""Get the circuit names of the results.
Returns:
List: A list of circuit names.
"""
warnings.warn('get_names() is deprecated and will be removed in '
'version 0.7+. Instead inspect result.results directly',
DeprecationWarning)
return list(self.results.keys())
<|code_end|>
|
qiskit/backends/ibmq/ibmqjob.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""IBMQJob module
This module is used for creating asynchronous job objects for the
IBM Q Experience.
"""
from concurrent import futures
import time
import logging
import pprint
import contextlib
import json
import datetime
import numpy
from qiskit.qobj import qobj_to_dict
from qiskit.transpiler import transpile_dag
from qiskit.backends import BaseJob, JobError, JobTimeoutError
from qiskit.backends.jobstatus import JobStatus, JOB_FINAL_STATES
from qiskit.result import Result
from qiskit.result._utils import result_from_old_style_dict
from qiskit.qobj import validate_qobj_against_schema
from .api import ApiError
logger = logging.getLogger(__name__)
API_FINAL_STATES = (
'COMPLETED',
'CANCELLED',
'ERROR_CREATING_JOB',
'ERROR_VALIDATING_JOB',
'ERROR_RUNNING_JOB'
)
class IBMQJob(BaseJob):
"""Represent the jobs that will be executed on IBM-Q simulators and real
devices. Jobs are intended to be created calling ``run()`` on a particular
backend.
Creating a ``Job`` instance does not imply running it. You need to do it in
separate steps::
job = IBMQJob(...)
job.submit() # It won't block.
An error while submitting a job will cause the next call to ``status()`` to
raise. If submitting the job successes, you can inspect the job's status by
using ``status()``. Status can be one of ``JobStatus`` members::
from qiskit.backends.jobstatus import JobStatus
job = IBMQJob(...)
job.submit()
try:
job_status = job.status() # It won't block. It will query the backend API.
if job_status is JobStatus.RUNNING:
print('The job is still running')
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
A call to ``status()`` can raise if something happens at the API level that
prevents Qiskit from determining the status of the job. An example of this
is a temporary connection lose or a network failure.
The ``submit()`` and ``status()`` methods are examples of non-blocking API.
``Job`` instances also have `id()` and ``result()`` methods which will
block::
job = IBMQJob(...)
job.submit()
try:
job_id = job.id() # It will block until completing submission.
print('The job {} was successfully submitted'.format(job_id))
job_result = job.result() # It will block until finishing.
print('The job finished with result {}'.format(job_result))
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
Both methods can raise if something ath the API level happens that prevent
Qiskit from determining the status of the job.
.. NOTE::
When querying the API for getting the status, two kinds of errors are
possible. The most severe is the one preventing Qiskit from getting a
response from the backend. This can be caused by a network failure or a
temporary system break. In these cases, calling ``status()`` will raise.
If Qiskit successfully retrieves the status of a job, it could be it
finished with errors. In that case, ``status()`` will simply return
``JobStatus.ERROR`` and you can call ``error_message()`` to get more
info.
Attributes:
_executor (futures.Executor): executor to handle asynchronous jobs
"""
_executor = futures.ThreadPoolExecutor()
def __init__(self, backend, job_id, api, is_device, qobj=None,
creation_date=None, api_status=None):
"""IBMQJob init function.
We can instantiate jobs from two sources: A QObj, and an already submitted job returned by
the API servers.
Args:
backend (str): The backend instance used to run this job.
job_id (str): The job ID of an already submitted job. Pass `None`
if you are creating a new one.
api (IBMQConnector): IBMQ connector.
is_device (bool): whether backend is a real device # TODO: remove this after Qobj
qobj (Qobj): The Quantum Object. See notes below
creation_date (str): When the job was run.
api_status (str): `status` field directly from the API response.
Notes:
It is mandatory to pass either ``qobj`` or ``job_id``. Passing a ``qobj``
will ignore ``job_id`` and will create an instance to be submitted to the
API server for job creation. Passing only a `job_id`will create an instance
representing an already-created job retrieved from the API server.
"""
super().__init__(backend, job_id)
self._job_data = None
if qobj is not None:
validate_qobj_against_schema(qobj)
self._qobj_payload = qobj_to_dict(qobj, version='1.0.0')
# TODO: No need for this conversion, just use the new equivalent members above
old_qobj = qobj_to_dict(qobj, version='0.0.1')
self._job_data = {
'circuits': old_qobj['circuits'],
'hpc': old_qobj['config'].get('hpc'),
'seed': old_qobj['circuits'][0]['config']['seed'],
'shots': old_qobj['config']['shots'],
'max_credits': old_qobj['config']['max_credits']
}
else:
self._qobj_payload = {}
self._future_captured_exception = None
self._api = api
self._backend = backend
self._cancelled = False
self._status = JobStatus.INITIALIZING
# In case of not providing a `qobj`, it is assumed the job already
# exists in the API (with `job_id`).
if qobj is None:
# Some API calls (`get_status_jobs`, `get_status_job`) provide
# enough information to recreate the `Job`. If that is the case, try
# to make use of that information during instantiation, as
# `self.status()` involves an extra call to the API.
if api_status == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_status == 'COMPLETED':
self._status = JobStatus.DONE
elif api_status == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
else:
self.status()
self._queue_position = None
self._is_device = is_device
def current_utc_time():
"""Gets the current time in UTC format"""
datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
self._creation_date = creation_date or current_utc_time()
self._future = None
self._api_error_msg = None
# pylint: disable=arguments-differ
def result(self, timeout=None, wait=5):
"""Return the result from the job.
Args:
timeout (int): number of seconds to wait for job
wait (int): time between queries to IBM Q server
Returns:
qiskit.Result: Result object
Raises:
JobError: exception raised during job initialization
"""
job_response = self._wait_for_result(timeout=timeout, wait=wait)
return self._result_from_job_response(job_response)
def _wait_for_result(self, timeout=None, wait=5):
self._wait_for_submission()
try:
job_response = self._wait_for_job(timeout=timeout, wait=wait)
except ApiError as api_err:
raise JobError(str(api_err))
status = self.status()
if status is not JobStatus.DONE:
raise JobError('Invalid job state. The job should be DONE but '
'it is {}'.format(str(status)))
return job_response
def _result_from_job_response(self, job_response):
return Result.from_dict(job_response['qObjectResult'])
def cancel(self):
"""Attempt to cancel a job.
Returns:
bool: True if job can be cancelled, else False. Currently this is
only possible on commercial systems.
Raises:
JobError: if there was some unexpected failure in the server
"""
hub = self._api.config.get('hub', None)
group = self._api.config.get('group', None)
project = self._api.config.get('project', None)
try:
response = self._api.cancel_job(self._job_id, hub, group, project)
self._cancelled = 'error' not in response
return self._cancelled
except ApiError as error:
self._cancelled = False
raise JobError('Error cancelling job: %s' % error.usr_msg)
def status(self):
"""Query the API to update the status.
Returns:
JobStatus: The status of the job, once updated.
Raises:
JobError: if there was an exception in the future being executed
or the server sent an unknown answer.
"""
# Implies self._job_id is None
if self._future_captured_exception is not None:
raise JobError(str(self._future_captured_exception))
if self._job_id is None or self._status in JOB_FINAL_STATES:
return self._status
try:
# TODO: See result values
api_job = self._api.get_status_job(self._job_id)
if 'status' not in api_job:
raise JobError('get_status_job didn\'t return status: %s' %
pprint.pformat(api_job))
# pylint: disable=broad-except
except Exception as err:
raise JobError(str(err))
if api_job['status'] == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_job['status'] == 'RUNNING':
self._status = JobStatus.RUNNING
queued, self._queue_position = _is_job_queued(api_job)
if queued:
self._status = JobStatus.QUEUED
elif api_job['status'] == 'COMPLETED':
self._status = JobStatus.DONE
elif api_job['status'] == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
elif 'ERROR' in api_job['status']:
# Error status are of the form "ERROR_*_JOB"
self._status = JobStatus.ERROR
# TODO: This seems to be an inconsistency in the API package.
self._api_error_msg = api_job.get('error') or api_job.get('Error')
else:
raise JobError('Unrecognized answer from server: \n{}'
.format(pprint.pformat(api_job)))
return self._status
def error_message(self):
"""Return the error message returned from the API server response."""
return self._api_error_msg
def queue_position(self):
"""Return the position in the server queue.
Returns:
Number: Position in the queue.
"""
return self._queue_position
def creation_date(self):
"""
Return creation date.
"""
return self._creation_date
def job_id(self):
"""Return backend determined id.
If the Id is not set because the job is already initializing, this call
will block until we have an Id.
"""
self._wait_for_submission()
return self._job_id
def submit(self):
"""Submit job to IBM-Q.
Raises:
JobError: If we have already submitted the job.
"""
# TODO: Validation against the schema should be done here and not
# during initialization. Once done, we should document that the method
# can raise QobjValidationError.
if self._future is not None or self._job_id is not None:
raise JobError("We have already submitted the job!")
self._future = self._executor.submit(self._submit_callback)
def _submit_callback(self):
"""Submit qobj job to IBM-Q.
Returns:
dict: A dictionary with the response of the submitted job
"""
backend_name = self.backend().name()
try:
submit_info = self._api.run_job(self._qobj_payload, backend=backend_name)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submission success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _wait_for_job(self, timeout=60, wait=5):
"""Wait until all online ran circuits of a qobj are 'COMPLETED'.
Args:
timeout (float or None): seconds to wait for job. If None, wait
indefinitely.
wait (float): seconds between queries
Returns:
dict: A dict with the contents of the API request.
Raises:
JobTimeoutError: if the job does not return results before a specified timeout.
JobError: if something wrong happened in some of the server API calls
"""
start_time = time.time()
while self.status() not in JOB_FINAL_STATES:
elapsed_time = time.time() - start_time
if timeout is not None and elapsed_time >= timeout:
raise JobTimeoutError(
'Timeout while waiting for the job: {}'.format(self._job_id)
)
logger.info('status = %s (%d seconds)', self._status, elapsed_time)
time.sleep(wait)
if self._cancelled:
raise JobError(
'Job result impossible to retrieve. The job was cancelled.')
return self._api.get_job(self._job_id)
def _wait_for_submission(self, timeout=60):
"""Waits for the request to return a job ID"""
if self._job_id is None:
if self._future is None:
raise JobError("You have to submit before asking for status or results!")
try:
submit_info = self._future.result(timeout=timeout)
if self._future_captured_exception is not None:
# pylint can't see if catch of None type
# pylint: disable=raising-bad-type
raise self._future_captured_exception
except TimeoutError as ex:
raise JobTimeoutError(
"Timeout waiting for the job being submitted: {}".format(ex)
)
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
raise JobError(str(submit_info['error']))
class IBMQJobPreQobj(IBMQJob):
"""
Subclass of IBMQJob for handling pre-qobj jobs.
"""
def _submit_callback(self):
"""Submit old style qasms job to IBM-Q. Can remove when all devices
understand Qobj.
Returns:
dict: A dictionary with the response of the submitted job
"""
api_jobs = []
circuits = self._job_data['circuits']
for circuit in circuits:
job = _create_api_job_from_circuit(circuit)
api_jobs.append(job)
hpc_camel_cased = _format_hpc_parameters(self._job_data['hpc'])
seed = self._job_data['seed']
shots = self._job_data['shots']
max_credits = self._job_data['max_credits']
try:
submit_info = self._api.run_job(api_jobs, backend=self.backend().name(),
shots=shots, max_credits=max_credits,
seed=seed, hpc=hpc_camel_cased)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submission success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _result_from_job_response(self, job_response):
if self._is_device:
_reorder_bits(job_response)
experiment_results = []
for circuit_result in job_response['qasms']:
this_result = {'data': circuit_result['data'],
'compiled_circuit_qasm': circuit_result.get('qasm'),
'status': circuit_result['status'],
'success': circuit_result['status'] == 'DONE',
'shots': job_response['shots']}
if 'metadata' in circuit_result:
this_result['metadata'] = circuit_result['metadata']
if 'header' in circuit_result['metadata'].get('compiled_circuit', {}):
this_result['header'] = \
circuit_result['metadata']['compiled_circuit']['header']
else:
this_result['header'] = {}
experiment_results.append(this_result)
ret = {
'id': self._job_id,
'status': job_response['status'],
'used_credits': job_response.get('usedCredits'),
'result': experiment_results,
'backend_name': self.backend().name(),
'success': job_response['status'] == 'COMPLETED',
}
# Append header: from the response; from the payload; or none.
header = job_response.get('header',
self._qobj_payload.get('header', {}))
if header:
ret['header'] = header
return result_from_old_style_dict(ret)
def _reorder_bits(job_data):
"""Temporary fix for ibmq backends.
For every ran circuit, get reordering information from qobj
and apply reordering on result.
Args:
job_data (dict): dict with the bare contents of the API.get_job request.
Raises:
JobError: raised if the creg sizes don't add up in result header.
"""
for circuit_result in job_data['qasms']:
if 'metadata' in circuit_result:
circ = circuit_result['metadata'].get('compiled_circuit')
else:
logger.warning('result object missing metadata for reordering'
' bits: bits may be out of order')
return
# device_qubit -> device_clbit (how it should have been)
measure_dict = {op['qubits'][0]: op['memory'][0]
for op in circ['operations']
if op['name'] == 'measure'}
counts_dict_new = {}
for item in circuit_result['data']['counts'].items():
# fix clbit ordering to what it should have been
bits = list(item[0])
bits.reverse() # lsb in 0th position
count = item[1]
reordered_bits = list('x' * len(bits))
for device_clbit, bit in enumerate(bits):
if device_clbit in measure_dict:
correct_device_clbit = measure_dict[device_clbit]
reordered_bits[correct_device_clbit] = bit
reordered_bits.reverse()
# only keep the clbits specified by circuit, not everything on device
num_clbits = circ['header']['memory_slots']
compact_key = reordered_bits[-num_clbits:]
compact_key = "".join([b if b != 'x' else '0'
for b in compact_key])
# insert spaces to signify different classical registers
cregs = circ['header']['creg_sizes']
if sum([creg[1] for creg in cregs]) != num_clbits:
raise JobError("creg sizes don't add up in result header.")
creg_begin_pos = []
creg_end_pos = []
acc = 0
for creg in reversed(cregs):
creg_size = creg[1]
creg_begin_pos.append(acc)
creg_end_pos.append(acc + creg_size)
acc += creg_size
compact_key = " ".join([compact_key[creg_begin_pos[i]:creg_end_pos[i]]
for i in range(len(cregs))])
# marginalize over unwanted measured qubits
if compact_key not in counts_dict_new:
counts_dict_new[compact_key] = count
else:
counts_dict_new[compact_key] += count
circuit_result['data']['counts'] = counts_dict_new
def _numpy_type_converter(obj):
ret = obj
if isinstance(obj, numpy.integer):
ret = int(obj)
elif isinstance(obj, numpy.floating): # pylint: disable=no-member
ret = float(obj)
elif isinstance(obj, numpy.ndarray):
ret = obj.tolist()
return ret
def _create_api_job_from_circuit(circuit):
"""Helper function that creates a special job required by the API, from a circuit."""
api_job = {}
if not circuit.get('compiled_circuit_qasm'):
compiled_circuit = transpile_dag(circuit['circuit'])
circuit['compiled_circuit_qasm'] = compiled_circuit.qasm(qeflag=True)
if isinstance(circuit['compiled_circuit_qasm'], bytes):
api_job['qasm'] = circuit['compiled_circuit_qasm'].decode()
else:
api_job['qasm'] = circuit['compiled_circuit_qasm']
if circuit.get('name'):
api_job['name'] = circuit['name']
# convert numpy types for json serialization
compiled_circuit = json.loads(json.dumps(circuit['compiled_circuit'],
default=_numpy_type_converter))
api_job['metadata'] = {'compiled_circuit': compiled_circuit}
return api_job
def _is_job_queued(api_job_response):
"""Checks whether a job has been queued or not."""
is_queued, position = False, 0
if 'infoQueue' in api_job_response:
if 'status' in api_job_response['infoQueue']:
queue_status = api_job_response['infoQueue']['status']
is_queued = queue_status == 'PENDING_IN_QUEUE'
if 'position' in api_job_response['infoQueue']:
position = api_job_response['infoQueue']['position']
return is_queued, position
def _format_hpc_parameters(hpc):
"""Helper function to get HPC parameters with the correct format"""
if hpc is None:
return None
hpc_camel_cased = None
with contextlib.suppress(KeyError, TypeError):
# Use CamelCase when passing the hpc parameters to the API.
hpc_camel_cased = {
'multiShotOptimization': hpc['multi_shot_optimization'],
'ompNumThreads': hpc['omp_num_threads']
}
return hpc_camel_cased
<|code_end|>
qiskit/result/postprocess.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Post-processing of raw result."""
import numpy as np
def _hex_to_bin(hexstring):
"""Convert hexadecimal readouts (memory) to binary readouts."""
return str(bin(int(hexstring, 16)))[2:]
def _pad_zeros(bitstring, memory_slots):
"""If the bitstring is truncated, pad extra zeros to make its
length equal to memory_slots"""
return format(int(bitstring, 2), '0{}b'.format(memory_slots))
def _separate_bitstring(bitstring, creg_sizes):
"""Separate a bitstring according to the registers defined in the result header."""
substrings = []
running_index = 0
for _, size in reversed(creg_sizes):
substrings.append(bitstring[running_index: running_index + size])
running_index += size
return ' '.join(substrings)
def format_memory(memory, header):
"""
Format a single bitstring (memory) from a single shot experiment.
- The hexadecimals are expanded to bitstrings
- Spaces are inserted at register divisions.
Args:
memory (str): result of a single experiment.
header (dict): the experiment header dictionary containing
useful information for postprocessing.
Returns:
dict: a formatted memory
"""
creg_sizes = header.get('creg_sizes')
memory_slots = header.get('memory_slots')
if memory.startswith('0x'):
memory = _hex_to_bin(memory)
if memory_slots:
memory = _pad_zeros(memory, memory_slots)
if creg_sizes:
memory = _separate_bitstring(memory, creg_sizes)
return memory
def format_counts(counts, header):
"""Format a single experiment result coming from backend to present
to the Qiskit user.
Args:
counts (dict): counts histogram of multiple shots
header (dict): the experiment header dictionary containing
useful information for postprocessing.
Returns:
dict: a formatted counts
"""
counts_dict = {}
for key, val in counts.items():
key = format_memory(key, header)
counts_dict[key] = val
return counts_dict
def format_statevector(vec, decimals=None):
"""Format statevector coming from the backend to present to the Qiskit user.
Args:
vec (list): a list of [re, im] complex numbers.
decimals (int): the number of decimals in the statevector.
If None, no rounding is done.
Returns:
list[complex]: a list of python complex numbers.
"""
num_basis = len(vec)
vec_complex = np.zeros(num_basis, dtype=complex)
for i in range(num_basis):
vec_complex[i] = vec[i][0] + 1j * vec[i][1]
if decimals:
vec_complex = np.around(vec_complex, decimals=decimals)
return vec_complex
def format_unitary(mat, decimals=None):
"""Format unitary coming from the backend to present to the Qiskit user.
Args:
mat (list[list]): a list of list of [re, im] complex numbers
decimals (int): the number of decimals in the statevector.
If None, no rounding is done.
Returns:
list[list[complex]]: a matrix of complex numbers
"""
num_basis = len(mat)
mat_complex = np.zeros((num_basis, num_basis), dtype=complex)
for i, vec in enumerate(mat):
mat_complex[i] = format_statevector(vec, decimals)
return mat_complex
<|code_end|>
qiskit/result/result.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Model for schema-conformant Results."""
import warnings
from qiskit import QiskitError, QuantumCircuit
from qiskit.validation.base import BaseModel, bind_schema
from .postprocess import format_counts, format_statevector, format_unitary
from .models import ResultSchema
@bind_schema(ResultSchema)
class Result(BaseModel):
"""Model for Results.
Please note that this class only describes the required fields. For the
full description of the model, please check ``ResultSchema``.
Attributes:
backend_name (str): backend name.
backend_version (str): backend version, in the form X.Y.Z.
qobj_id (str): user-generated Qobj id.
job_id (str): unique execution id from the backend.
success (bool): True if complete input qobj executed correctly. (Implies
each experiment success)
results (ExperimentResult): corresponding results for array of
experiments of the input qobj
"""
def __init__(self, backend_name, backend_version, qobj_id, job_id, success,
results, **kwargs):
self.backend_name = backend_name
self.backend_version = backend_version
self.qobj_id = qobj_id
self.job_id = job_id
self.success = success
self.results = results
super().__init__(**kwargs)
def data(self, circuit=None):
"""Get the raw data for an experiment.
Note this data will be a single classical and quantum register and in a
format required by the results schema. We recomened that most users use
the get_xxx method, and the data will be post-processed for the data type.
Args:
circuit (str or QuantumCircuit or int or None): the index of the
experiment. Several types are accepted for convenience::
* str: the name of the experiment.
* QuantumCircuit: the name of the instance will be used.
* int: the position of the experiment.
* None: if there is only one experiment, returns it.
Returns:
dict: A dictionary of results data for an experiment. The data
depends on the backend it ran on.
QASM backends return a dictionary of dictionary with the key
'counts' and with the counts, with the second dictionary keys
containing a string in hex format (``0x123``) and values equal to
the number of times this outcome was measured.
Statevector backends return a dictionary with key 'statevector' and
values being a list[list[complex components]] list of 2^n_qubits
complex amplitudes. Where each complex number is represented as a 2
entry list for each component. For example, a list of
[0.5+1j, 0-1j] would be represented as [[0.5, 1], [0, -1]].
Unitary backends return a dictionary with key 'unitary' and values
being a list[list[list[complex components]]] list of
2^n_qubits x 2^n_qubits complex amplitudes in a two entry list for
each component. For example if the amplitude is
[[0.5+0j, 0-1j], ...] the value returned will be
[[[0.5, 0], [0, -1]], ...].
The simulator backends also have an optional key 'snapshots' which
returns a dict of snapshots specified by the simulator backend.
The value is of the form dict[slot: dict[str: array]]
where the keys are the requested snapshot slots, and the values are
a dictionary of the snapshots.
Raises:
QiskitError: if data for the experiment could not be retrieved.
"""
try:
return self._get_experiment(circuit).data.to_dict()
except (KeyError, TypeError):
raise QiskitError('No data for circuit "{0}"'.format(circuit))
def get_counts(self, circuit=None):
"""Get the histogram data of an experiment.
Args:
circuit (str or QuantumCircuit or int or None): the index of the
experiment, as specified by ``get_data()``.
Returns:
dict[str:int]: a dictionary with the counts for each qubit, with
the keys containing a string in binary format and separated
according to the registers in circuit (e.g. ``0100 1110``).
The string is little-endian (cr[0] on the right hand side).
Raises:
QiskitError: if there are no counts for the experiment.
"""
try:
return format_counts(self.data(circuit)['counts'],
self._get_experiment(circuit).header.to_dict())
except KeyError:
raise QiskitError('No counts for circuit "{0}"'.format(circuit))
def get_statevector(self, circuit=None, decimals=None):
"""Get the final statevector of an experiment.
Args:
circuit (str or QuantumCircuit or int or None): the index of the
experiment, as specified by ``data()``.
decimals (int): the number of decimals in the statevector.
If None, does not round.
Returns:
list[complex]: list of 2^n_qubits complex amplitudes.
Raises:
QiskitError: if there is no statevector for the experiment.
"""
try:
return format_statevector(self.data(circuit)['statevector'],
decimals=decimals)
except KeyError:
raise QiskitError('No statevector for circuit "{0}"'.format(circuit))
def get_unitary(self, circuit=None, decimals=None):
"""Get the final unitary of an experiment.
Args:
circuit (str or QuantumCircuit or int or None): the index of the
experiment, as specified by ``data()``.
decimals (int): the number of decimals in the unitary.
If None, does not round.
Returns:
list[list[complex]]: list of 2^n_qubits x 2^n_qubits complex
amplitudes.
Raises:
QiskitError: if there is no unitary for the experiment.
"""
try:
return format_unitary(self.data(circuit)['unitary'],
decimals=decimals)
except KeyError:
raise QiskitError('No unitary for circuit "{0}"'.format(circuit))
def _get_experiment(self, key=None):
"""Return a single experiment result from a given key.
Args:
key (str or QuantumCircuit or int or None): the index of the
experiment, as specified by ``get_data()``.
Returns:
ExperimentResult: the results for an experiment.
Raises:
QiskitError: if there is no data for the circuit, or an unhandled
error occurred while fetching the data.
"""
if not self.success:
raise QiskitError(getattr(self, 'status',
'Result was not successful'))
# Automatically return the first result if no key was provided.
if key is None:
if len(self.results) != 1:
raise QiskitError(
'You have to select a circuit when there is more than '
'one available')
else:
key = 0
# Key is an integer: return result by index.
if isinstance(key, int):
return self.results[key]
# Key is a QuantumCircuit or str: retrieve result by name.
if isinstance(key, QuantumCircuit):
key = key.name
try:
# Look into `result[x].header.name` for the names.
return next(result for result in self.results
if getattr(getattr(result, 'header', None),
'name', '') == key)
except StopIteration:
raise QiskitError('Data for experiment "%s" could not be found.' %
key)
# To be deprecated after 0.7
def __iadd__(self, other):
"""Append a Result object to current Result object.
Arg:
other (Result): a Result object to append.
Returns:
Result: The current object with appended results.
Raises:
QiskitError: if the Results cannot be combined.
"""
warnings.warn('Result addition is deprecated and will be removed in '
'version 0.7+.', DeprecationWarning)
this_backend = self.backend_name
other_backend = other.backend_name
if this_backend != other_backend:
raise QiskitError('Result objects from different backends cannot be combined.')
if not self.success or not other.success:
raise QiskitError('Can not combine a failed result with another result.')
self.results.extend(other.results)
return self
def __add__(self, other):
"""Combine Result objects.
Arg:
other (Result): a Result object to combine.
Returns:
Result: A new Result object consisting of combined objects.
"""
warnings.warn('Result addition is deprecated and will be removed in '
'version 0.7+.', DeprecationWarning)
copy_of_self = self.from_dict(self.to_dict())
copy_of_self += other
return copy_of_self
def get_status(self):
"""Return whole result status."""
warnings.warn('get_status() is deprecated and will be removed in '
'version 0.7+. Instead use result.status directly.',
DeprecationWarning)
return getattr(self, 'status', '')
def circuit_statuses(self):
"""Return statuses of all circuits.
Returns:
list(str): List of status result strings.
"""
warnings.warn('circuit_statuses() is deprecated and will be removed in '
'version 0.7+. Instead use result.results[x]status '
'directly.', DeprecationWarning)
return [getattr(experiment_result, 'status', '') for
experiment_result in self.results]
def get_circuit_status(self, icircuit):
"""Return the status of circuit at index icircuit.
Args:
icircuit (int): index of circuit
Returns:
string: the status of the circuit.
"""
warnings.warn('get_circuit_status() is deprecated and will be removed '
'in version 0.7+. Instead use result.results[x]status '
'directly.', DeprecationWarning)
return self[icircuit].status
def get_job_id(self):
"""Return the job id assigned by the api if this is a remote job.
Returns:
string: a string containing the job id.
"""
warnings.warn('get_job_id() is deprecated and will be removed in '
'version 0.7+. Instead use result.job_id directly.',
DeprecationWarning)
return self.job_id
def get_ran_qasm(self, name):
"""Get the ran qasm for the named circuit and backend.
Args:
name (str): the name of the quantum circuit.
Returns:
string: A text version of the qasm file that has been run.
Raises:
QiskitError: if the circuit was not found.
"""
warnings.warn('get_ran_qasm() is deprecated and will be removed in '
'version 0.7+.', DeprecationWarning)
try:
return self.results[name].compiled_circuit_qasm
except KeyError:
raise QiskitError('No qasm for circuit "{0}"'.format(name))
def get_names(self):
"""Get the circuit names of the results.
Returns:
List: A list of circuit names.
"""
warnings.warn('get_names() is deprecated and will be removed in '
'version 0.7+. Instead inspect result.results directly',
DeprecationWarning)
return list(self.results.keys())
<|code_end|>
|
clean up transpile to make faster (parallel)
This is a follow-on to #1134 and #1144 and #1032 should be made on this after we have done the other two issues.
|
qiskit/transpiler/_transpiler.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Tools for compiling a batch of quantum circuits."""
import logging
import warnings
import numpy as np
import scipy.sparse as sp
import scipy.sparse.csgraph as cs
from qiskit.transpiler._transpilererror import TranspilerError
from qiskit._qiskiterror import QiskitError
from qiskit._quantumcircuit import QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit import _quantumcircuit, _quantumregister
from qiskit.unrollers import _dagunroller
from qiskit.unrollers import _dagbackend
from qiskit.mapper import (Coupling, optimize_1q_gates, swap_mapper,
cx_cancellation, direction_mapper,
remove_last_measurements, return_last_measurements)
from qiskit._pubsub import Publisher, Subscriber
from ._parallel import parallel_map
logger = logging.getLogger(__name__)
def transpile(circuits, backend, basis_gates=None, coupling_map=None, initial_layout=None,
seed_mapper=None, hpc=None, pass_manager=None):
"""transpile a list of circuits.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend): a backend to compile for
basis_gates (str): comma-separated basis gate set to compile to
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
seed_mapper (int): random seed for the swap_mapper
hpc (dict): HPC simulator parameters
pass_manager (PassManager): a pass_manager for the transpiler stage
Returns:
QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s).
Raises:
TranspilerError: in case of bad compile options, e.g. the hpc options.
"""
return_form_is_single = False
if isinstance(circuits, _quantumcircuit.QuantumCircuit):
circuits = [circuits]
return_form_is_single = True
# FIXME: THIS NEEDS TO BE CLEANED UP -- some things to decide for list of circuits:
# 1. do all circuits have same coupling map?
# 2. do all circuit have the same basis set?
# 3. do they all have same registers etc?
# Check for valid parameters for the experiments.
if hpc is not None and \
not all(key in hpc for key in ('multi_shot_optimization', 'omp_num_threads')):
raise TranspilerError('Unknown HPC parameter format!')
basis_gates = basis_gates or ','.join(backend.configuration().basis_gates)
coupling_map = coupling_map or getattr(backend.configuration(),
'coupling_map', None)
# step 1: Making the list of dag circuits
dags = _circuits_2_dags(circuits)
# step 2: Transpile all the dags
# FIXME: Work-around for transpiling multiple circuits with different qreg names.
# Make compile take a list of initial_layouts.
_initial_layout = initial_layout
# Pick a good initial layout if coupling_map is not already satisfied
# otherwise keep it as q[i]->q[i].
# TODO: move this inside mapper pass.
initial_layouts = []
for dag in dags:
if (initial_layout is None and not backend.configuration().simulator
and not _matches_coupling_map(dag, coupling_map)):
_initial_layout = _pick_best_layout(dag, backend)
initial_layouts.append(_initial_layout)
dags = _dags_2_dags(dags, basis_gates=basis_gates, coupling_map=coupling_map,
initial_layouts=initial_layouts, seed_mapper=seed_mapper,
pass_manager=pass_manager)
# step 3: Converting the dags back to circuits
circuits = _dags_2_circuits(dags)
if return_form_is_single:
return circuits[0]
return circuits
def _circuits_2_dags(circuits):
"""Convert a list of circuits into a list of dags.
Args:
circuits (list[QuantumCircuit]): circuits to convert
Returns:
list[DAGCircuit]: the dag representation of the circuits
"""
dags = parallel_map(DAGCircuit.fromQuantumCircuit, circuits)
return dags
def _dags_2_circuits(dags):
"""Convert a list of dags into a list of circuits.
Args:
dags (list[DAGCircuit]): dags to convert
Returns:
list[QuantumCircuit]: the circuit representation of the dags
"""
circuits = parallel_map(QuantumCircuit.fromDAGCircuit, dags)
return circuits
def _dags_2_dags(dags, basis_gates='u1,u2,u3,cx,id', coupling_map=None,
initial_layouts=None, seed_mapper=None, pass_manager=None):
"""Transform multiple dags through a sequence of passes.
Args:
dags (list[DAGCircuit]): dag circuits to transform
basis_gates (str): a comma separated string for the target basis gates
coupling_map (list): A graph of coupling
initial_layouts (list[dict]): A mapping of qubit to qubit for each dag
seed_mapper (int): random seed_mapper for the swap mapper
pass_manager (PassManager): pass manager instance for the transpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
list[DAGCircuit]: the dag circuits after going through transpilation
Events:
terra.transpiler.transpile_dag.start: When the transpilation of the dags is about to start
terra.transpiler.transpile_dag.done: When one of the dags has finished it's transpilation
terra.transpiler.transpile_dag.finish: When all the dags have finished transpiling
"""
def _emit_start(num_dags):
""" Emit a dag transpilation start event
Arg:
num_dags: Number of dags to be transpiled"""
Publisher().publish("terra.transpiler.transpile_dag.start", num_dags)
Subscriber().subscribe("terra.transpiler.parallel.start", _emit_start)
def _emit_done(progress):
""" Emit a dag transpilation done event
Arg:
progress: The dag number that just has finshed transpile"""
Publisher().publish("terra.transpiler.transpile_dag.done", progress)
Subscriber().subscribe("terra.transpiler.parallel.done", _emit_done)
def _emit_finish():
""" Emit a dag transpilation finish event
Arg:
progress: The dag number that just has finshed transpile"""
Publisher().publish("terra.transpiler.transpile_dag.finish")
Subscriber().subscribe("terra.transpiler.parallel.finish", _emit_finish)
dags_layouts = list(zip(dags, initial_layouts))
final_dags = parallel_map(_transpile_dags_parallel, dags_layouts,
task_kwargs={'basis_gates': basis_gates,
'coupling_map': coupling_map,
'seed_mapper': seed_mapper,
'pass_manager': pass_manager})
return final_dags
def _transpile_dags_parallel(dag_layout_tuple, basis_gates='u1,u2,u3,cx,id',
coupling_map=None, seed_mapper=None, pass_manager=None):
"""Helper function for transpiling in parallel (if available).
Args:
dag_layout_tuple (tuple): Tuples of dags and their initial_layouts
basis_gates (str): a comma separated string for the target basis gates
coupling_map (list): A graph of coupling
seed_mapper (int): random seed_mapper for the swap mapper
pass_manager (PassManager): pass manager instance for the transpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
DAGCircuit: DAG circuit after going through transpilation.
"""
final_dag, final_layout = transpile_dag(
dag_layout_tuple[0],
basis_gates=basis_gates,
coupling_map=coupling_map,
initial_layout=dag_layout_tuple[1],
get_layout=True,
seed_mapper=seed_mapper,
pass_manager=pass_manager)
final_dag.layout = [[k, v]
for k, v in final_layout.items()] if final_layout else None
return final_dag
# pylint: disable=redefined-builtin
def transpile_dag(dag, basis_gates='u1,u2,u3,cx,id', coupling_map=None,
initial_layout=None, get_layout=False,
format='dag', seed_mapper=None, pass_manager=None):
"""Transform a dag circuit into another dag circuit (transpile), through
consecutive passes on the dag.
Args:
dag (DAGCircuit): dag circuit to transform via transpilation
basis_gates (str): a comma separated string for the target basis gates
coupling_map (list): A graph of coupling::
[
[control0(int), target0(int)],
[control1(int), target1(int)],
]
eg. [[0, 2], [1, 2], [1, 3], [3, 4]}
initial_layout (dict): A mapping of qubit to qubit::
{
("q", start(int)): ("q", final(int)),
...
}
eg.
{
("q", 0): ("q", 0),
("q", 1): ("q", 1),
("q", 2): ("q", 2),
("q", 3): ("q", 3)
}
get_layout (bool): flag for returning the final layout after mapping
format (str): DEPRECATED The target format of the compilation: {'dag', 'json', 'qasm'}
seed_mapper (int): random seed_mapper for the swap mapper
pass_manager (PassManager): pass manager instance for the transpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
DAGCircuit: transformed dag
DAGCircuit, dict: transformed dag along with the final layout on backend qubits
Raises:
TranspilerError: if the format is not valid.
"""
# TODO: `basis_gates` will be removed after we have the unroller pass.
# TODO: `coupling_map`, `initial_layout`, `get_layout`, `seed_mapper` removed after mapper pass.
# TODO: move this to the mapper pass
num_qubits = sum([qreg.size for qreg in dag.qregs.values()])
if num_qubits == 1 or coupling_map == "all-to-all":
coupling_map = None
final_layout = None
if pass_manager:
# run the passes specified by the pass manager
# TODO return the property set too. See #1086
dag = pass_manager.run_passes(dag)
else:
# default set of passes
# TODO: move each step here to a pass, and use a default passmanager below
basis = basis_gates.split(',') if basis_gates else []
dag_unroller = _dagunroller.DagUnroller(
dag, _dagbackend.DAGBackend(basis))
dag = dag_unroller.expand_gates()
# if a coupling map is given compile to the map
if coupling_map:
logger.info("pre-mapping properties: %s",
dag.properties())
# Insert swap gates
coupling = Coupling(Coupling.coupling_list2dict(coupling_map))
removed_meas = remove_last_measurements(dag)
logger.info("measurements moved: %s", removed_meas)
logger.info("initial layout: %s", initial_layout)
dag, final_layout, last_layout = swap_mapper(
dag, coupling, initial_layout, trials=20, seed=seed_mapper)
logger.info("final layout: %s", final_layout)
# Expand swaps
dag_unroller = _dagunroller.DagUnroller(
dag, _dagbackend.DAGBackend(basis))
dag = dag_unroller.expand_gates()
# Change cx directions
dag = direction_mapper(dag, coupling)
# Simplify cx gates
cx_cancellation(dag)
# Simplify single qubit gates
dag = optimize_1q_gates(dag)
return_last_measurements(dag, removed_meas,
last_layout)
logger.info("post-mapping properties: %s",
dag.properties())
if format != 'dag':
warnings.warn("transpiler no longer supports different formats. "
"only dag to dag transformations are supported.",
DeprecationWarning)
if get_layout:
return dag, final_layout
return dag
def _best_subset(backend, n_qubits):
"""Computes the qubit mapping with the best
connectivity.
Parameters:
backend (BaseBackend): A Qiskit backend instance.
n_qubits (int): Number of subset qubits to consider.
Returns:
ndarray: Array of qubits to use for best
connectivity mapping.
Raises:
QiskitError: Wrong number of qubits given.
"""
if n_qubits == 1:
return np.array([0])
elif n_qubits <= 0:
raise QiskitError('Number of qubits <= 0.')
device_qubits = backend.configuration().n_qubits
if n_qubits > device_qubits:
raise QiskitError('Number of qubits greater than device.')
cmap = np.asarray(getattr(backend.configuration(), 'coupling_map', None))
data = np.ones_like(cmap[:, 0])
sp_cmap = sp.coo_matrix((data, (cmap[:, 0], cmap[:, 1])),
shape=(device_qubits, device_qubits)).tocsr()
best = 0
best_map = None
# do bfs with each node as starting point
for k in range(sp_cmap.shape[0]):
bfs = cs.breadth_first_order(sp_cmap, i_start=k, directed=False,
return_predecessors=False)
connection_count = 0
for i in range(n_qubits):
node_idx = bfs[i]
for j in range(sp_cmap.indptr[node_idx],
sp_cmap.indptr[node_idx + 1]):
node = sp_cmap.indices[j]
for counter in range(n_qubits):
if node == bfs[counter]:
connection_count += 1
break
if connection_count > best:
best = connection_count
best_map = bfs[0:n_qubits]
return best_map
def _matches_coupling_map(dag, coupling_map):
"""Iterate over circuit gates to check if all multi-qubit couplings
match the qubit coupling graph in the backend.
Parameters:
dag (DAGCircuit): DAG representation of circuit.
coupling_map (list): Backend coupling map, represented as an adjacency list.
Returns:
bool: True if all gates readily fit the backend coupling graph.
False if there's at least one gate that uses multiple qubits
which does not match the backend couplings.
"""
match = True
for _, data in dag.multi_graph.nodes(data=True):
if data['type'] == 'op':
gate_map = [qr[1] for qr in data['qargs']]
if len(gate_map) > 1:
if gate_map not in coupling_map:
match = False
break
return match
def _pick_best_layout(dag, backend):
"""Pick a convenient layout depending on the best matching qubit connectivity
Parameters:
dag (DAGCircuit): DAG representation of circuit.
backend (BaseBackend) : The backend with the coupling_map for searching
Returns:
dict: A special ordered initial_layout
"""
num_qubits = sum([qreg.size for qreg in dag.qregs.values()])
best_sub = _best_subset(backend, num_qubits)
layout = {}
map_iter = 0
device_qubits = backend.configuration().n_qubits
q = _quantumregister.QuantumRegister(device_qubits, 'q')
for qreg in dag.qregs.values():
for i in range(qreg.size):
layout[(qreg.name, i)] = (q, int(best_sub[map_iter]))
map_iter += 1
return layout
<|code_end|>
|
qiskit/transpiler/_transpiler.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Tools for compiling a batch of quantum circuits."""
import logging
import warnings
import numpy as np
import scipy.sparse as sp
import scipy.sparse.csgraph as cs
from qiskit.transpiler._transpilererror import TranspilerError
from qiskit._qiskiterror import QiskitError
from qiskit._quantumcircuit import QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit import _quantumcircuit, _quantumregister
from qiskit.unrollers import _dagunroller
from qiskit.unrollers import _dagbackend
from qiskit.mapper import (Coupling, optimize_1q_gates, swap_mapper,
cx_cancellation, direction_mapper,
remove_last_measurements, return_last_measurements)
from ._parallel import parallel_map
logger = logging.getLogger(__name__)
def transpile(circuits, backend, basis_gates=None, coupling_map=None, initial_layout=None,
seed_mapper=None, hpc=None, pass_manager=None):
"""transpile one or more circuits.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend): a backend to compile for
basis_gates (str): comma-separated basis gate set to compile to
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
seed_mapper (int): random seed for the swap_mapper
hpc (dict): HPC simulator parameters
pass_manager (PassManager): a pass_manager for the transpiler stage
Returns:
QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s).
Raises:
TranspilerError: in case of bad compile options, e.g. the hpc options.
"""
return_form_is_single = False
if isinstance(circuits, _quantumcircuit.QuantumCircuit):
circuits = [circuits]
return_form_is_single = True
# FIXME: THIS NEEDS TO BE CLEANED UP -- some things to decide for list of circuits:
# 1. do all circuits have same coupling map?
# 2. do all circuit have the same basis set?
# 3. do they all have same registers etc?
# Check for valid parameters for the experiments.
if hpc is not None and \
not all(key in hpc for key in ('multi_shot_optimization', 'omp_num_threads')):
raise TranspilerError('Unknown HPC parameter format!')
basis_gates = basis_gates or ','.join(backend.configuration().basis_gates)
coupling_map = coupling_map or getattr(backend.configuration(),
'coupling_map', None)
circuits = parallel_map(_transpilation, circuits,
task_args=(backend,),
task_kwargs={'basis_gates': basis_gates,
'coupling_map': coupling_map,
'initial_layout': initial_layout,
'seed_mapper': seed_mapper,
'pass_manager': pass_manager})
if return_form_is_single:
return circuits[0]
return circuits
def _transpilation(circuit, backend, basis_gates=None, coupling_map=None,
initial_layout=None, seed_mapper=None,
pass_manager=None):
"""Perform transpilation of a single circuit.
Args:
circuit (QuantumCircuit): A circuit to transpile.
backend (BaseBackend): a backend to compile for
basis_gates (str): comma-separated basis gate set to compile to
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
seed_mapper (int): random seed for the swap_mapper
pass_manager (PassManager): a pass_manager for the transpiler stage
Returns:
QuantumCircuit: A transpiled circuit.
"""
dag = DAGCircuit.fromQuantumCircuit(circuit)
if (initial_layout is None and not backend.configuration().simulator
and not _matches_coupling_map(dag, coupling_map)):
initial_layout = _pick_best_layout(dag, backend)
final_dag, final_layout = transpile_dag(dag, basis_gates=basis_gates,
coupling_map=coupling_map,
initial_layout=initial_layout,
get_layout=True, format='dag',
seed_mapper=seed_mapper,
pass_manager=pass_manager)
final_dag.layout = [[k, v]
for k, v in final_layout.items()] if final_layout else None
out_circuit = QuantumCircuit.fromDAGCircuit(final_dag)
return out_circuit
# pylint: disable=redefined-builtin
def transpile_dag(dag, basis_gates='u1,u2,u3,cx,id', coupling_map=None,
initial_layout=None, get_layout=False,
format='dag', seed_mapper=None, pass_manager=None):
"""Transform a dag circuit into another dag circuit (transpile), through
consecutive passes on the dag.
Args:
dag (DAGCircuit): dag circuit to transform via transpilation
basis_gates (str): a comma separated string for the target basis gates
coupling_map (list): A graph of coupling::
[
[control0(int), target0(int)],
[control1(int), target1(int)],
]
eg. [[0, 2], [1, 2], [1, 3], [3, 4]}
initial_layout (dict): A mapping of qubit to qubit::
{
("q", start(int)): ("q", final(int)),
...
}
eg.
{
("q", 0): ("q", 0),
("q", 1): ("q", 1),
("q", 2): ("q", 2),
("q", 3): ("q", 3)
}
get_layout (bool): flag for returning the final layout after mapping
format (str): DEPRECATED The target format of the compilation: {'dag', 'json', 'qasm'}
seed_mapper (int): random seed_mapper for the swap mapper
pass_manager (PassManager): pass manager instance for the transpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
DAGCircuit: transformed dag
DAGCircuit, dict: transformed dag along with the final layout on backend qubits
Raises:
TranspilerError: if the format is not valid.
"""
# TODO: `basis_gates` will be removed after we have the unroller pass.
# TODO: `coupling_map`, `initial_layout`, `get_layout`, `seed_mapper` removed after mapper pass.
# TODO: move this to the mapper pass
num_qubits = sum([qreg.size for qreg in dag.qregs.values()])
if num_qubits == 1 or coupling_map == "all-to-all":
coupling_map = None
final_layout = None
if pass_manager:
# run the passes specified by the pass manager
# TODO return the property set too. See #1086
dag = pass_manager.run_passes(dag)
else:
# default set of passes
# TODO: move each step here to a pass, and use a default passmanager below
basis = basis_gates.split(',') if basis_gates else []
dag_unroller = _dagunroller.DagUnroller(
dag, _dagbackend.DAGBackend(basis))
dag = dag_unroller.expand_gates()
# if a coupling map is given compile to the map
if coupling_map:
logger.info("pre-mapping properties: %s",
dag.properties())
# Insert swap gates
coupling = Coupling(Coupling.coupling_list2dict(coupling_map))
removed_meas = remove_last_measurements(dag)
logger.info("measurements moved: %s", removed_meas)
logger.info("initial layout: %s", initial_layout)
dag, final_layout, last_layout = swap_mapper(
dag, coupling, initial_layout, trials=20, seed=seed_mapper)
logger.info("final layout: %s", final_layout)
# Expand swaps
dag_unroller = _dagunroller.DagUnroller(
dag, _dagbackend.DAGBackend(basis))
dag = dag_unroller.expand_gates()
# Change cx directions
dag = direction_mapper(dag, coupling)
# Simplify cx gates
cx_cancellation(dag)
# Simplify single qubit gates
dag = optimize_1q_gates(dag)
return_last_measurements(dag, removed_meas,
last_layout)
logger.info("post-mapping properties: %s",
dag.properties())
if format != 'dag':
warnings.warn("transpiler no longer supports different formats. "
"only dag to dag transformations are supported.",
DeprecationWarning)
if get_layout:
return dag, final_layout
return dag
def _best_subset(backend, n_qubits):
"""Computes the qubit mapping with the best
connectivity.
Parameters:
backend (BaseBackend): A Qiskit backend instance.
n_qubits (int): Number of subset qubits to consider.
Returns:
ndarray: Array of qubits to use for best
connectivity mapping.
Raises:
QiskitError: Wrong number of qubits given.
"""
if n_qubits == 1:
return np.array([0])
elif n_qubits <= 0:
raise QiskitError('Number of qubits <= 0.')
device_qubits = backend.configuration().n_qubits
if n_qubits > device_qubits:
raise QiskitError('Number of qubits greater than device.')
cmap = np.asarray(getattr(backend.configuration(), 'coupling_map', None))
data = np.ones_like(cmap[:, 0])
sp_cmap = sp.coo_matrix((data, (cmap[:, 0], cmap[:, 1])),
shape=(device_qubits, device_qubits)).tocsr()
best = 0
best_map = None
# do bfs with each node as starting point
for k in range(sp_cmap.shape[0]):
bfs = cs.breadth_first_order(sp_cmap, i_start=k, directed=False,
return_predecessors=False)
connection_count = 0
for i in range(n_qubits):
node_idx = bfs[i]
for j in range(sp_cmap.indptr[node_idx],
sp_cmap.indptr[node_idx + 1]):
node = sp_cmap.indices[j]
for counter in range(n_qubits):
if node == bfs[counter]:
connection_count += 1
break
if connection_count > best:
best = connection_count
best_map = bfs[0:n_qubits]
return best_map
def _matches_coupling_map(dag, coupling_map):
"""Iterate over circuit gates to check if all multi-qubit couplings
match the qubit coupling graph in the backend.
Parameters:
dag (DAGCircuit): DAG representation of circuit.
coupling_map (list): Backend coupling map, represented as an adjacency list.
Returns:
bool: True if all gates readily fit the backend coupling graph.
False if there's at least one gate that uses multiple qubits
which does not match the backend couplings.
"""
match = True
for _, data in dag.multi_graph.nodes(data=True):
if data['type'] == 'op':
gate_map = [qr[1] for qr in data['qargs']]
if len(gate_map) > 1:
if gate_map not in coupling_map:
match = False
break
return match
def _pick_best_layout(dag, backend):
"""Pick a convenient layout depending on the best matching qubit connectivity
Parameters:
dag (DAGCircuit): DAG representation of circuit.
backend (BaseBackend) : The backend with the coupling_map for searching
Returns:
dict: A special ordered initial_layout
"""
num_qubits = sum([qreg.size for qreg in dag.qregs.values()])
best_sub = _best_subset(backend, num_qubits)
layout = {}
map_iter = 0
device_qubits = backend.configuration().n_qubits
q = _quantumregister.QuantumRegister(device_qubits, 'q')
for qreg in dag.qregs.values():
for i in range(qreg.size):
layout[(qreg.name, i)] = (q, int(best_sub[map_iter]))
map_iter += 1
return layout
<|code_end|>
|
qobj_to_circuits not using the compiled qasm in the qobj header
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**:
- **Python version**:
- **Operating system**:
### What is the current behavior?
### Steps to reproduce the problem
### What is the expected behavior?
### Suggested solutions
|
qiskit/converters/qobj_to_circuits.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Helper function for converting qobj to a list of circuits"""
from qiskit.circuit import QuantumCircuit
def qobj_to_circuits(qobj):
"""Return a list of QuantumCircuit object(s) from a qobj
Args:
qobj (Qobj): The Qobj object to convert to QuantumCircuits
Returns:
list: A list of QuantumCircuit objects from the qobj
"""
if qobj.experiments:
circuits = []
for x in qobj.experiments:
if hasattr(x.header, 'compiled_circuit_qasm'):
circuits.append(
QuantumCircuit.from_qasm_str(x.header.compiled_circuit_qasm))
return circuits
# TODO(mtreinish): add support for converting a qobj if the qasm isn't
# embedded in the header
return None
<|code_end|>
|
qiskit/converters/qobj_to_circuits.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Helper function for converting qobj to a list of circuits"""
from qiskit.circuit import classicalregister as cr
from qiskit.circuit import quantumcircuit as qc
from qiskit.circuit import quantumregister as qr
def qobj_to_circuits(qobj):
"""Return a list of QuantumCircuit object(s) from a qobj
Args:
qobj (Qobj): The Qobj object to convert to QuantumCircuits
Returns:
list: A list of QuantumCircuit objects from the qobj
"""
if qobj.experiments:
circuits = []
for x in qobj.experiments:
quantum_registers = [
qr.QuantumRegister(
i[1], name=i[0]) for i in x.header.qreg_sizes]
classical_registers = [
cr.ClassicalRegister(
i[1], name=i[0]) for i in x.header.creg_sizes]
circuit = qc.QuantumCircuit(*quantum_registers,
*classical_registers,
name=x.header.name)
qreg_dict = {}
creg_dict = {}
for reg in quantum_registers:
qreg_dict[reg.name] = reg
for reg in classical_registers:
creg_dict[reg.name] = reg
for i in x.instructions:
instr_method = getattr(circuit, i.name)
qubits = []
for qubit in i.qubits:
qubit_label = x.header.qubit_labels[qubit]
qubits.append(
qreg_dict[qubit_label[0]][qubit_label[1]])
clbits = []
for clbit in i.memory:
clbit_label = x.header.clbit_labels[clbit]
clbits.append(
creg_dict[clbit_label[0]][clbit_label[1]])
instr_method(*i.params, *qubits, *clbits)
circuits.append(circuit)
return circuits
return None
<|code_end|>
|
crash when set initial_state with complex vector for simulator
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: the master branch (Dec. 4th)
- **Python version**: 3.7.1
- **Operating system**: macOS 10.13
### What is the current behavior?
Encounter JSON encoding error
### Steps to reproduce the problem
running with the following qasm and setting
```
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
u1(3.14159265358979) q[0];
{'shots': 1, 'config': {'initial_state': array([0.93130364-0.02274014j, 0.2641254 +0.2497883j ])}}
```
error message:
```
Traceback (most recent call last):
File "/Users/rchen/Developer/Quantum/temp/aqua/test/test_operator.py", line 136, in test_create_from_matrix
non_matrix_mode = op.eval('paulis', circuit, backend, run_config=run_config)[0]
File "/Users/rchen/Developer/Quantum/temp/aqua/qiskit_aqua/operator.py", line 779, in eval
has_shared_circuits=has_shared_circuits)
File "/Users/rchen/Developer/Quantum/temp/aqua/qiskit_aqua/utils/run_circuits.py", line 151, in compile_and_run_circuits
return _reuse_shared_circuits(circuits, backend, backend_config, compile_config, run_config, qjob_config)
File "/Users/rchen/Developer/Quantum/temp/aqua/qiskit_aqua/utils/run_circuits.py", line 110, in _reuse_shared_circuits
show_circuit_summary=show_circuit_summary)
File "/Users/rchen/Developer/Quantum/temp/aqua/qiskit_aqua/utils/run_circuits.py", line 239, in compile_and_run_circuits
results.append(job.result(**qjob_config))
File "/Users/rchen/Developer/Quantum/qiskit-terra-chenrich/qiskit/backends/aer/aerjob.py", line 37, in _wrapper
return func(self, *args, **kwargs)
File "/Users/rchen/Developer/Quantum/qiskit-terra-chenrich/qiskit/backends/aer/aerjob.py", line 92, in result
return self._future.result(timeout=timeout)
File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/concurrent/futures/_base.py", line 432, in result
return self.__get_result()
File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/concurrent/futures/_base.py", line 384, in __get_result
raise self._exception
File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "/Users/rchen/Developer/Quantum/qiskit-terra-chenrich/qiskit/backends/aer/statevector_simulator.py", line 71, in _run_job
result = super()._run_job(job_id, qobj)
File "/Users/rchen/Developer/Quantum/qiskit-terra-chenrich/qiskit/backends/aer/qasm_simulator.py", line 97, in _run_job
result = run(qobj_dict, self._configuration.exe)
File "/Users/rchen/Developer/Quantum/qiskit-terra-chenrich/qiskit/backends/aer/qasm_simulator.py", line 195, in run
cin = json.dumps(qobj).encode()
File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type complex is not JSON serializable
```
### What is the expected behavior?
Without crash.
### Suggested solutions
Terra should parse the complex vector to [ [real, imag] [real, imag]].
(I tried with above format, it will work)
|
qiskit/qobj/_qobj.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Models for Qobj and its related components."""
from types import SimpleNamespace
import numpy
import sympy
from ._validation import QobjValidationError
from ._utils import QobjType
# Current version of the Qobj schema.
QOBJ_VERSION = '1.0.0'
# Qobj schema versions:
# * 1.0.0: Qiskit 0.6
# * 0.0.1: Qiskit 0.5.x format (pre-schemas).
class QobjItem(SimpleNamespace):
"""Generic Qobj structure.
Single item of a Qobj structure, acting as a superclass of the rest of the
more specific elements.
"""
REQUIRED_ARGS = ()
def as_dict(self):
"""
Return a dictionary representation of the QobjItem, recursively
converting its public attributes.
Returns:
dict: a dictionary.
"""
return {key: self._expand_item(value) for key, value
in self.__dict__.items() if not key.startswith('_')}
@classmethod
def _expand_item(cls, obj):
# pylint: disable=too-many-return-statements
"""
Return a valid representation of `obj` depending on its type.
"""
if isinstance(obj, (list, tuple)):
return [cls._expand_item(item) for item in obj]
if isinstance(obj, dict):
return {key: cls._expand_item(value) for key, value in obj.items()}
if isinstance(obj, QobjItem):
return obj.as_dict()
if isinstance(obj, numpy.integer):
return int(obj)
if isinstance(obj, numpy.float):
return float(obj)
if isinstance(obj, sympy.Symbol):
return str(obj)
if isinstance(obj, sympy.Basic):
return float(obj.evalf())
if isinstance(obj, numpy.ndarray):
return obj.tolist()
if isinstance(obj, complex):
return [obj.real, obj.imag]
return obj
@classmethod
def from_dict(cls, obj):
"""
Return a QobjItem from a dictionary recursively, checking for the
required attributes.
Returns:
QobjItem: a new QobjItem.
Raises:
QobjValidationError: if the dictionary does not contain the
required attributes for that class.
"""
if not all(key in obj.keys() for key in cls.REQUIRED_ARGS):
raise QobjValidationError(
'The dict does not contain all required keys: missing "%s"' %
[key for key in cls.REQUIRED_ARGS if key not in obj.keys()])
return cls(**{key: cls._qobjectify_item(value)
for key, value in obj.items()})
@classmethod
def _qobjectify_item(cls, obj):
"""
Return a valid value for a QobjItem from a object.
"""
if isinstance(obj, dict):
# TODO: should use the subclasses for finer control over the
# required arguments.
return QobjItem.from_dict(obj)
elif isinstance(obj, list):
return [cls._qobjectify_item(item) for item in obj]
return obj
def __reduce__(self):
"""
Customize the reduction in order to allow serialization, as the Qobjs
are automatically serialized due to the use of futures.
"""
init_args = tuple(getattr(self, key) for key in self.REQUIRED_ARGS)
extra_args = {key: value for key, value in self.__dict__.items()
if key not in self.REQUIRED_ARGS}
return self.__class__, init_args, extra_args
class Qobj(QobjItem):
"""Representation of a Qobj.
Attributes:
qobj_id (str): Qobj identifier.
config (QobjConfig): config settings for the Qobj.
experiments (list[QobjExperiment]): list of experiments.
header (QobjHeader): headers.
type (str): experiment type (QASM/PULSE).
schema_version (str): Qobj version.
"""
REQUIRED_ARGS = ['qobj_id', 'config', 'experiments', 'header']
def __init__(self, qobj_id, config, experiments, header, **kwargs):
# pylint: disable=redefined-builtin,invalid-name
self.qobj_id = qobj_id
self.config = config
self.experiments = experiments
self.header = header
self.type = QobjType.QASM.value
self.schema_version = QOBJ_VERSION
super().__init__(**kwargs)
class QobjConfig(QobjItem):
"""Configuration for a Qobj.
Attributes:
shots (int): number of shots.
memory_slots (int): number of measurements slots in the classical
memory on the backend.
Attributes defined in the schema but not required:
max_credits (int): number of credits.
seed (int): random seed.
"""
REQUIRED_ARGS = ['shots', 'memory_slots']
def __init__(self, shots, memory_slots, **kwargs):
self.shots = shots
self.memory_slots = memory_slots
super().__init__(**kwargs)
class QobjHeader(QobjItem):
"""Header for a Qobj.
Attributes defined in the schema but not required:
backend_name (str): name of the backend
backend_version (str): the backend version this set of experiments was generated for.
qubit_labels (list): map physical qubits to qregs (for QASM).
clbit_labels (list): map classical clbits to memory_slots (for QASM).
"""
pass
class QobjExperiment(QobjItem):
"""Quantum experiment represented inside a Qobj.
instructions (list[QobjInstruction)): list of instructions.
Attributes defined in the schema but not required:
header (QobjExperimentHeader): header.
config (QobjItem): config settings for the Experiment.
"""
REQUIRED_ARGS = ['instructions']
def __init__(self, instructions, **kwargs):
self.instructions = instructions
super().__init__(**kwargs)
class QobjExperimentHeader(QobjItem):
"""Header for a Qobj.
Attributes defined in the schema but not required:
name (str): experiment name.
"""
pass
class QobjInstruction(QobjItem):
"""Quantum Instruction.
Attributes:
name(str): name of the gate.
qubits(list): list of qubits to apply to the gate.
"""
REQUIRED_ARGS = ['name']
def __init__(self, name, **kwargs):
self.name = name
super().__init__(**kwargs)
<|code_end|>
|
qiskit/qobj/_qobj.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Models for Qobj and its related components."""
from types import SimpleNamespace
import numpy
import sympy
from ._validation import QobjValidationError
from ._utils import QobjType
# Current version of the Qobj schema.
QOBJ_VERSION = '1.0.0'
# Qobj schema versions:
# * 1.0.0: Qiskit 0.6
# * 0.0.1: Qiskit 0.5.x format (pre-schemas).
class QobjItem(SimpleNamespace):
"""Generic Qobj structure.
Single item of a Qobj structure, acting as a superclass of the rest of the
more specific elements.
"""
REQUIRED_ARGS = ()
def as_dict(self):
"""
Return a dictionary representation of the QobjItem, recursively
converting its public attributes.
Returns:
dict: a dictionary.
"""
return {key: self._expand_item(value) for key, value
in self.__dict__.items() if not key.startswith('_')}
@classmethod
def _expand_item(cls, obj):
# pylint: disable=too-many-return-statements
"""
Return a valid representation of `obj` depending on its type.
"""
if isinstance(obj, (list, tuple)):
return [cls._expand_item(item) for item in obj]
if isinstance(obj, dict):
return {key: cls._expand_item(value) for key, value in obj.items()}
if isinstance(obj, numpy.integer):
return int(obj)
if isinstance(obj, numpy.float):
return float(obj)
if isinstance(obj, sympy.Symbol):
return str(obj)
if isinstance(obj, sympy.Basic):
return float(obj.evalf())
if isinstance(obj, numpy.ndarray):
return cls._expand_item(obj.tolist())
if isinstance(obj, complex):
return [obj.real, obj.imag]
if hasattr(obj, 'as_dict'):
return obj.as_dict()
return obj
@classmethod
def from_dict(cls, obj):
"""
Return a QobjItem from a dictionary recursively, checking for the
required attributes.
Returns:
QobjItem: a new QobjItem.
Raises:
QobjValidationError: if the dictionary does not contain the
required attributes for that class.
"""
if not all(key in obj.keys() for key in cls.REQUIRED_ARGS):
raise QobjValidationError(
'The dict does not contain all required keys: missing "%s"' %
[key for key in cls.REQUIRED_ARGS if key not in obj.keys()])
return cls(**{key: cls._qobjectify_item(value)
for key, value in obj.items()})
@classmethod
def _qobjectify_item(cls, obj):
"""
Return a valid value for a QobjItem from a object.
"""
if isinstance(obj, dict):
# TODO: should use the subclasses for finer control over the
# required arguments.
return QobjItem.from_dict(obj)
elif isinstance(obj, list):
return [cls._qobjectify_item(item) for item in obj]
return obj
def __reduce__(self):
"""
Customize the reduction in order to allow serialization, as the Qobjs
are automatically serialized due to the use of futures.
"""
init_args = tuple(getattr(self, key) for key in self.REQUIRED_ARGS)
extra_args = {key: value for key, value in self.__dict__.items()
if key not in self.REQUIRED_ARGS}
return self.__class__, init_args, extra_args
class Qobj(QobjItem):
"""Representation of a Qobj.
Attributes:
qobj_id (str): Qobj identifier.
config (QobjConfig): config settings for the Qobj.
experiments (list[QobjExperiment]): list of experiments.
header (QobjHeader): headers.
type (str): experiment type (QASM/PULSE).
schema_version (str): Qobj version.
"""
REQUIRED_ARGS = ['qobj_id', 'config', 'experiments', 'header']
def __init__(self, qobj_id, config, experiments, header, **kwargs):
# pylint: disable=redefined-builtin,invalid-name
self.qobj_id = qobj_id
self.config = config
self.experiments = experiments
self.header = header
self.type = QobjType.QASM.value
self.schema_version = QOBJ_VERSION
super().__init__(**kwargs)
class QobjConfig(QobjItem):
"""Configuration for a Qobj.
Attributes:
shots (int): number of shots.
memory_slots (int): number of measurements slots in the classical
memory on the backend.
Attributes defined in the schema but not required:
max_credits (int): number of credits.
seed (int): random seed.
"""
REQUIRED_ARGS = ['shots', 'memory_slots']
def __init__(self, shots, memory_slots, **kwargs):
self.shots = shots
self.memory_slots = memory_slots
super().__init__(**kwargs)
class QobjHeader(QobjItem):
"""Header for a Qobj.
Attributes defined in the schema but not required:
backend_name (str): name of the backend
backend_version (str): the backend version this set of experiments was generated for.
qubit_labels (list): map physical qubits to qregs (for QASM).
clbit_labels (list): map classical clbits to memory_slots (for QASM).
"""
pass
class QobjExperiment(QobjItem):
"""Quantum experiment represented inside a Qobj.
instructions (list[QobjInstruction)): list of instructions.
Attributes defined in the schema but not required:
header (QobjExperimentHeader): header.
config (QobjItem): config settings for the Experiment.
"""
REQUIRED_ARGS = ['instructions']
def __init__(self, instructions, **kwargs):
self.instructions = instructions
super().__init__(**kwargs)
class QobjExperimentHeader(QobjItem):
"""Header for a Qobj.
Attributes defined in the schema but not required:
name (str): experiment name.
"""
pass
class QobjInstruction(QobjItem):
"""Quantum Instruction.
Attributes:
name(str): name of the gate.
qubits(list): list of qubits to apply to the gate.
"""
REQUIRED_ARGS = ['name']
def __init__(self, name, **kwargs):
self.name = name
super().__init__(**kwargs)
<|code_end|>
|
generated circuits had the same name if circuits are created by multiprocess
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: the master branch
- **Python version**: 3.7.1
- **Operating system**: macOS 10.13
### What is the current behavior?
The generated circuits have the same name and it results in users cannot retrieve the result correctly since terra uses the circuit name to retrieve the result.
### Steps to reproduce the problem
here is the example script
```python
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
import qiskit as qk
import numpy as np
import concurrent.futures
np.random.seed(0)
# from qiskit_aqua.utils import run_circuits
def generate_circuits(num_qubits, parameters, depth=10):
q = QuantumRegister(num_qubits, name='q')
c = ClassicalRegister(num_qubits, name='c')
circuit = QuantumCircuit(q, c)
param_idx = 0
for qubit in range(num_qubits):
circuit.u3(parameters[param_idx], 0.0, 0.0, q[qubit])
circuit.u1(parameters[param_idx+1], q[qubit])
param_idx += 2
return circuit
num_circuits = 10
num_qubits = 2
depth = 1
num_parameters = num_qubits * (depth + 1) * 2
circuits = []
with concurrent.futures.ProcessPoolExecutor(max_workers=num_circuits) as executor:
futures = [executor.submit(generate_circuits, num_qubits, np.random.rand(num_parameters), depth) for _ in range(num_circuits)]
for future in concurrent.futures.as_completed(futures):
qc = future.result()
print(qc.name)
circuits.append(qc)
my_backend = qk.Aer.get_backend('statevector_simulator')
qobj = qk.compile(circuits=circuits, backend=my_backend, seed=0)
qjob = my_backend.run(qobj)
result = qjob.result()
for circuit in circuits:
print(result.get_statevector(circuit))
```
### What is the expected behavior?
The circuit name should be unique even though they are created via multiprocess
### Suggested solutions
I do not know. The workaround I had now is assigning the name by myself.
|
qiskit/circuit/quantumcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=cyclic-import,invalid-name
"""
Quantum circuit object.
"""
from collections import OrderedDict
from copy import deepcopy
import itertools
import warnings
from qiskit.qasm import _qasm
from qiskit._qiskiterror import QiskitError
from .quantumregister import QuantumRegister
from .classicalregister import ClassicalRegister
class QuantumCircuit(object):
"""Quantum circuit."""
instances = 0
prefix = 'circuit'
# Class variable OPENQASM header
header = "OPENQASM 2.0;"
# Class variable with gate definitions
# This is a dict whose values are dicts with the
# following keys:
# "print" = True or False
# "opaque" = True or False
# "n_args" = number of real parameters
# "n_bits" = number of qubits
# "args" = list of parameter names
# "bits" = list of qubit names
# "body" = GateBody AST node
definitions = OrderedDict()
def __init__(self, *regs, name=None):
"""Create a new circuit.
A circuit is a list of instructions bound to some registers.
Args:
*regs (Registers): registers to include in the circuit.
name (str or None): the name of the quantum circuit. If
None, an automatically generated string will be assigned.
Raises:
QiskitError: if the circuit name, if given, is not valid.
"""
if name is None:
name = self.cls_prefix() + str(self.cls_instances())
self._increment_instances()
if not isinstance(name, str):
raise QiskitError("The circuit name should be a string "
"(or None to auto-generate a name).")
self.name = name
# Data contains a list of instructions in the order they were applied.
self.data = []
# This is a map of registers bound to this circuit, by name.
self.qregs = []
self.cregs = []
self.add_register(*regs)
def __str__(self):
return str(self.draw(output='text'))
def __eq__(self, other):
# TODO: removed the DAG from this function
from qiskit.converters import circuit_to_dag
return circuit_to_dag(self) == circuit_to_dag(other)
@classmethod
def _increment_instances(cls):
cls.instances += 1
@classmethod
def cls_instances(cls):
"""Return the current number of instances of this class,
useful for auto naming."""
return cls.instances
@classmethod
def cls_prefix(cls):
"""Return the prefix to use for auto naming."""
return cls.prefix
def has_register(self, register):
"""
Test if this circuit has the register r.
Args:
register (Register): a quantum or classical register.
Returns:
bool: True if the register is contained in this circuit.
"""
has_reg = False
if (isinstance(register, QuantumRegister) and
register in self.qregs):
has_reg = True
elif (isinstance(register, ClassicalRegister) and
register in self.cregs):
has_reg = True
return has_reg
def combine(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Return self + rhs as a new object.
"""
# Check registers in LHS are compatible with RHS
self._check_compatible_regs(rhs)
# Make new circuit with combined registers
combined_qregs = deepcopy(self.qregs)
combined_cregs = deepcopy(self.cregs)
for element in rhs.qregs:
if element not in self.qregs:
combined_qregs.append(element)
for element in rhs.cregs:
if element not in self.cregs:
combined_cregs.append(element)
circuit = QuantumCircuit(*combined_qregs, *combined_cregs)
for gate in itertools.chain(self.data, rhs.data):
gate.reapply(circuit)
return circuit
def extend(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Modify and return self.
"""
# Check registers in LHS are compatible with RHS
self._check_compatible_regs(rhs)
# Add new registers
for element in rhs.qregs:
if element not in self.qregs:
self.qregs.append(element)
for element in rhs.cregs:
if element not in self.cregs:
self.cregs.append(element)
# Add new gates
for gate in rhs.data:
gate.reapply(self)
return self
def __add__(self, rhs):
"""Overload + to implement self.concatenate."""
return self.combine(rhs)
def __iadd__(self, rhs):
"""Overload += to implement self.extend."""
return self.extend(rhs)
def __len__(self):
"""Return number of operations in circuit."""
return len(self.data)
def __getitem__(self, item):
"""Return indexed operation."""
return self.data[item]
def _attach(self, instruction):
"""Attach an instruction."""
self.data.append(instruction)
return instruction
def add_register(self, *regs):
"""Add registers."""
for register in regs:
if register in self.qregs or register in self.cregs:
raise QiskitError("register name \"%s\" already exists"
% register.name)
if isinstance(register, QuantumRegister):
self.qregs.append(register)
elif isinstance(register, ClassicalRegister):
self.cregs.append(register)
else:
raise QiskitError("expected a register")
def add(self, *regs):
"""Add registers."""
warnings.warn('The add() function is deprecated and will be '
'removed in a future release. Instead use '
'QuantumCircuit.add_register().', DeprecationWarning)
self.add_register(*regs)
def _check_qreg(self, register):
"""Raise exception if r is not in this circuit or not qreg."""
if not isinstance(register, QuantumRegister):
raise QiskitError("expected quantum register")
if not self.has_register(register):
raise QiskitError(
"register '%s' not in this circuit" %
register.name)
def _check_qubit(self, qubit):
"""Raise exception if qubit is not in this circuit or bad format."""
if not isinstance(qubit, tuple):
raise QiskitError("%s is not a tuple."
"A qubit should be formated as a tuple." % str(qubit))
if not len(qubit) == 2:
raise QiskitError("%s is not a tuple with two elements, but %i instead" % len(qubit))
if not isinstance(qubit[1], int):
raise QiskitError("The second element of a tuple defining a qubit should be an int:"
"%s was found instead" % type(qubit[1]).__name__)
self._check_qreg(qubit[0])
qubit[0].check_range(qubit[1])
def _check_creg(self, register):
"""Raise exception if r is not in this circuit or not creg."""
if not isinstance(register, ClassicalRegister):
raise QiskitError("Expected ClassicalRegister, but %s given" % type(register))
if not self.has_register(register):
raise QiskitError(
"register '%s' not in this circuit" %
register.name)
def _check_dups(self, qubits):
"""Raise exception if list of qubits contains duplicates."""
squbits = set(qubits)
if len(squbits) != len(qubits):
raise QiskitError("duplicate qubit arguments")
def _check_compatible_regs(self, rhs):
"""Raise exception if the circuits are defined on incompatible registers"""
list1 = self.qregs + self.cregs
list2 = rhs.qregs + rhs.cregs
for element1 in list1:
for element2 in list2:
if element2.name == element1.name:
if element1 != element2:
raise QiskitError("circuits are not compatible")
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.definitions[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.definitions[name]["n_args"] > 0:
out += "(" + ",".join(self.definitions[name]["args"]) + ")"
out += " " + ",".join(self.definitions[name]["bits"])
if self.definitions[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.definitions[name]["body"].qasm() + "}\n"
return out
def qasm(self):
"""Return OPENQASM string."""
string_temp = self.header + "\n"
for gate_name in self.definitions:
if self.definitions[gate_name]["print"]:
string_temp += self._gate_string(gate_name)
for register in self.qregs:
string_temp += register.qasm() + "\n"
for register in self.cregs:
string_temp += register.qasm() + "\n"
for instruction in self.data:
string_temp += instruction.qasm() + "\n"
return string_temp
def draw(self, scale=0.7, filename=None, style=None, output='text',
interactive=False, line_length=None, plot_barriers=True,
reverse_bits=False):
"""Draw the quantum circuit
Using the output parameter you can specify the format. The choices are:
0. text: ASCII art string
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style
file. You can refer to the
:ref:`Style Dict Doc <style-dict-doc>` for
more information on the contents.
output (str): Select the output method to use for drawing the
circuit. Valid choices are `text`, `latex`, `latex_source`,
`mpl`.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the
latex_source output type this has no effect
line_length (int): sets the length of the lines generated by `text`
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: (output `latex`) an in-memory representation of the
image of the circuit diagram.
matplotlib.figure: (output `mpl`) a matplotlib figure object for
the circuit diagram.
String: (output `latex_source`). The LaTeX source code.
TextDrawing: (output `text`). A drawing that can be printed as
ascii art
Raises:
VisualizationError: when an invalid output method is selected
"""
from qiskit.tools import visualization
return visualization.circuit_drawer(self, scale=scale,
filename=filename, style=style,
output=output,
interactive=interactive,
line_length=line_length,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
def size(self):
"""Return total number of operations in circuit."""
# TODO: removed the DAG from this function
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.size()
def depth(self):
"""Return circuit depth (i.e. length of critical path)."""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.depth()
def width(self):
"""Return number of qubits in circuit."""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.width()
def count_ops(self):
"""Count each operation kind in the circuit.
Returns:
dict: a breakdown of how many operations of each kind.
"""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.count_ops()
def num_tensor_factors(self):
"""How many non-entangled subcircuits can the circuit be factored to."""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.num_tensor_factors()
@staticmethod
def from_qasm_file(path):
"""Take in a QASM file and generate a QuantumCircuit object.
Args:
path (str): Path to the file for a QASM program
Return:
QuantumCircuit: The QuantumCircuit object for the input QASM
"""
qasm = _qasm.Qasm(filename=path)
return _circuit_from_qasm(qasm)
@staticmethod
def from_qasm_str(qasm_str):
"""Take in a QASM string and generate a QuantumCircuit object.
Args:
qasm_str (str): A QASM program string
Return:
QuantumCircuit: The QuantumCircuit object for the input QASM
"""
qasm = _qasm.Qasm(data=qasm_str)
return _circuit_from_qasm(qasm)
def _circuit_from_qasm(qasm):
from qiskit.unroll import Unroller
from qiskit.unroll import DAGBackend
from qiskit.converters import dag_to_circuit
ast = qasm.parse()
dag = Unroller(ast, DAGBackend()).execute()
return dag_to_circuit(dag)
<|code_end|>
|
qiskit/circuit/quantumcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=cyclic-import,invalid-name
"""
Quantum circuit object.
"""
from collections import OrderedDict
from copy import deepcopy
import itertools
import warnings
import sys
import multiprocessing as mp
from qiskit.qasm import _qasm
from qiskit._qiskiterror import QiskitError
from .quantumregister import QuantumRegister
from .classicalregister import ClassicalRegister
class QuantumCircuit(object):
"""Quantum circuit."""
instances = 0
prefix = 'circuit'
# Class variable OPENQASM header
header = "OPENQASM 2.0;"
# Class variable with gate definitions
# This is a dict whose values are dicts with the
# following keys:
# "print" = True or False
# "opaque" = True or False
# "n_args" = number of real parameters
# "n_bits" = number of qubits
# "args" = list of parameter names
# "bits" = list of qubit names
# "body" = GateBody AST node
definitions = OrderedDict()
def __init__(self, *regs, name=None):
"""Create a new circuit.
A circuit is a list of instructions bound to some registers.
Args:
*regs (Registers): registers to include in the circuit.
name (str or None): the name of the quantum circuit. If
None, an automatically generated string will be assigned.
Raises:
QiskitError: if the circuit name, if given, is not valid.
"""
if name is None:
name = self.cls_prefix() + str(self.cls_instances())
# pylint: disable=not-callable
# (known pylint bug: https://github.com/PyCQA/pylint/issues/1699)
if sys.platform != "win32" and \
isinstance(mp.current_process(), mp.context.ForkProcess):
name += '-{}'.format(mp.current_process().pid)
self._increment_instances()
if not isinstance(name, str):
raise QiskitError("The circuit name should be a string "
"(or None to auto-generate a name).")
self.name = name
# Data contains a list of instructions in the order they were applied.
self.data = []
# This is a map of registers bound to this circuit, by name.
self.qregs = []
self.cregs = []
self.add_register(*regs)
def __str__(self):
return str(self.draw(output='text'))
def __eq__(self, other):
# TODO: removed the DAG from this function
from qiskit.converters import circuit_to_dag
return circuit_to_dag(self) == circuit_to_dag(other)
@classmethod
def _increment_instances(cls):
cls.instances += 1
@classmethod
def cls_instances(cls):
"""Return the current number of instances of this class,
useful for auto naming."""
return cls.instances
@classmethod
def cls_prefix(cls):
"""Return the prefix to use for auto naming."""
return cls.prefix
def has_register(self, register):
"""
Test if this circuit has the register r.
Args:
register (Register): a quantum or classical register.
Returns:
bool: True if the register is contained in this circuit.
"""
has_reg = False
if (isinstance(register, QuantumRegister) and
register in self.qregs):
has_reg = True
elif (isinstance(register, ClassicalRegister) and
register in self.cregs):
has_reg = True
return has_reg
def combine(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Return self + rhs as a new object.
"""
# Check registers in LHS are compatible with RHS
self._check_compatible_regs(rhs)
# Make new circuit with combined registers
combined_qregs = deepcopy(self.qregs)
combined_cregs = deepcopy(self.cregs)
for element in rhs.qregs:
if element not in self.qregs:
combined_qregs.append(element)
for element in rhs.cregs:
if element not in self.cregs:
combined_cregs.append(element)
circuit = QuantumCircuit(*combined_qregs, *combined_cregs)
for gate in itertools.chain(self.data, rhs.data):
gate.reapply(circuit)
return circuit
def extend(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Modify and return self.
"""
# Check registers in LHS are compatible with RHS
self._check_compatible_regs(rhs)
# Add new registers
for element in rhs.qregs:
if element not in self.qregs:
self.qregs.append(element)
for element in rhs.cregs:
if element not in self.cregs:
self.cregs.append(element)
# Add new gates
for gate in rhs.data:
gate.reapply(self)
return self
def __add__(self, rhs):
"""Overload + to implement self.concatenate."""
return self.combine(rhs)
def __iadd__(self, rhs):
"""Overload += to implement self.extend."""
return self.extend(rhs)
def __len__(self):
"""Return number of operations in circuit."""
return len(self.data)
def __getitem__(self, item):
"""Return indexed operation."""
return self.data[item]
def _attach(self, instruction):
"""Attach an instruction."""
self.data.append(instruction)
return instruction
def add_register(self, *regs):
"""Add registers."""
for register in regs:
if register in self.qregs or register in self.cregs:
raise QiskitError("register name \"%s\" already exists"
% register.name)
if isinstance(register, QuantumRegister):
self.qregs.append(register)
elif isinstance(register, ClassicalRegister):
self.cregs.append(register)
else:
raise QiskitError("expected a register")
def add(self, *regs):
"""Add registers."""
warnings.warn('The add() function is deprecated and will be '
'removed in a future release. Instead use '
'QuantumCircuit.add_register().', DeprecationWarning)
self.add_register(*regs)
def _check_qreg(self, register):
"""Raise exception if r is not in this circuit or not qreg."""
if not isinstance(register, QuantumRegister):
raise QiskitError("expected quantum register")
if not self.has_register(register):
raise QiskitError(
"register '%s' not in this circuit" %
register.name)
def _check_qubit(self, qubit):
"""Raise exception if qubit is not in this circuit or bad format."""
if not isinstance(qubit, tuple):
raise QiskitError("%s is not a tuple."
"A qubit should be formated as a tuple." % str(qubit))
if not len(qubit) == 2:
raise QiskitError("%s is not a tuple with two elements, but %i instead" % len(qubit))
if not isinstance(qubit[1], int):
raise QiskitError("The second element of a tuple defining a qubit should be an int:"
"%s was found instead" % type(qubit[1]).__name__)
self._check_qreg(qubit[0])
qubit[0].check_range(qubit[1])
def _check_creg(self, register):
"""Raise exception if r is not in this circuit or not creg."""
if not isinstance(register, ClassicalRegister):
raise QiskitError("Expected ClassicalRegister, but %s given" % type(register))
if not self.has_register(register):
raise QiskitError(
"register '%s' not in this circuit" %
register.name)
def _check_dups(self, qubits):
"""Raise exception if list of qubits contains duplicates."""
squbits = set(qubits)
if len(squbits) != len(qubits):
raise QiskitError("duplicate qubit arguments")
def _check_compatible_regs(self, rhs):
"""Raise exception if the circuits are defined on incompatible registers"""
list1 = self.qregs + self.cregs
list2 = rhs.qregs + rhs.cregs
for element1 in list1:
for element2 in list2:
if element2.name == element1.name:
if element1 != element2:
raise QiskitError("circuits are not compatible")
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.definitions[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.definitions[name]["n_args"] > 0:
out += "(" + ",".join(self.definitions[name]["args"]) + ")"
out += " " + ",".join(self.definitions[name]["bits"])
if self.definitions[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.definitions[name]["body"].qasm() + "}\n"
return out
def qasm(self):
"""Return OPENQASM string."""
string_temp = self.header + "\n"
for gate_name in self.definitions:
if self.definitions[gate_name]["print"]:
string_temp += self._gate_string(gate_name)
for register in self.qregs:
string_temp += register.qasm() + "\n"
for register in self.cregs:
string_temp += register.qasm() + "\n"
for instruction in self.data:
string_temp += instruction.qasm() + "\n"
return string_temp
def draw(self, scale=0.7, filename=None, style=None, output='text',
interactive=False, line_length=None, plot_barriers=True,
reverse_bits=False):
"""Draw the quantum circuit
Using the output parameter you can specify the format. The choices are:
0. text: ASCII art string
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style
file. You can refer to the
:ref:`Style Dict Doc <style-dict-doc>` for
more information on the contents.
output (str): Select the output method to use for drawing the
circuit. Valid choices are `text`, `latex`, `latex_source`,
`mpl`.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the
latex_source output type this has no effect
line_length (int): sets the length of the lines generated by `text`
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: (output `latex`) an in-memory representation of the
image of the circuit diagram.
matplotlib.figure: (output `mpl`) a matplotlib figure object for
the circuit diagram.
String: (output `latex_source`). The LaTeX source code.
TextDrawing: (output `text`). A drawing that can be printed as
ascii art
Raises:
VisualizationError: when an invalid output method is selected
"""
from qiskit.tools import visualization
return visualization.circuit_drawer(self, scale=scale,
filename=filename, style=style,
output=output,
interactive=interactive,
line_length=line_length,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
def size(self):
"""Return total number of operations in circuit."""
# TODO: removed the DAG from this function
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.size()
def depth(self):
"""Return circuit depth (i.e. length of critical path)."""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.depth()
def width(self):
"""Return number of qubits in circuit."""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.width()
def count_ops(self):
"""Count each operation kind in the circuit.
Returns:
dict: a breakdown of how many operations of each kind.
"""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.count_ops()
def num_tensor_factors(self):
"""How many non-entangled subcircuits can the circuit be factored to."""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.num_tensor_factors()
@staticmethod
def from_qasm_file(path):
"""Take in a QASM file and generate a QuantumCircuit object.
Args:
path (str): Path to the file for a QASM program
Return:
QuantumCircuit: The QuantumCircuit object for the input QASM
"""
qasm = _qasm.Qasm(filename=path)
return _circuit_from_qasm(qasm)
@staticmethod
def from_qasm_str(qasm_str):
"""Take in a QASM string and generate a QuantumCircuit object.
Args:
qasm_str (str): A QASM program string
Return:
QuantumCircuit: The QuantumCircuit object for the input QASM
"""
qasm = _qasm.Qasm(data=qasm_str)
return _circuit_from_qasm(qasm)
def _circuit_from_qasm(qasm):
from qiskit.unroll import Unroller
from qiskit.unroll import DAGBackend
from qiskit.converters import dag_to_circuit
ast = qasm.parse()
dag = Unroller(ast, DAGBackend()).execute()
return dag_to_circuit(dag)
<|code_end|>
|
circuit.draw(output='mpl) does not draw qubit labels correctly.
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: master
- **Python version**: 3.7
- **Operating system**: osx
### What is the current behavior?
Using Latex:
<img width="603" alt="screen shot 2018-12-07 at 11 49 43 am" src="https://user-images.githubusercontent.com/1249193/49661112-39c16400-fa16-11e8-8610-70a1d89474e6.png">
Using MPL:
<img width="496" alt="screen shot 2018-12-07 at 11 50 21 am" src="https://user-images.githubusercontent.com/1249193/49661148-4fcf2480-fa16-11e8-8f52-ad065c35d815.png">
### Steps to reproduce the problem
### What is the expected behavior?
### Suggested solutions
|
qiskit/tools/visualization/_matplotlib.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""mpl circuit visualization backend."""
import collections
import fractions
import itertools
import json
import logging
import math
import numpy as np
try:
from matplotlib import patches
from matplotlib import pyplot as plt
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _qcstyle
from qiskit.tools.visualization import _utils
logger = logging.getLogger(__name__)
Register = collections.namedtuple('Register', 'name index')
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
scale=1.0, style=None, plot_barriers=True,
reverse_bits=False):
if not HAS_MATPLOTLIB:
raise ImportError('The class MatplotlibDrawer needs matplotlib. '
'Run "pip install matplotlib" before.')
self._ast = None
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = collections.OrderedDict()
self._creg_dict = collections.OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = _qcstyle.QCStyle()
self.plot_barriers = plot_barriers
self.reverse_bits = reverse_bits
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False,
labelleft=False, labelright=False)
def parse_circuit(self, circuit):
qregs, cregs, ops = _utils._get_instructions(
circuit, reversebits=self.reverse_bits)
self._registers(cregs, qregs)
self._ops = ops
def _registers(self, creg, qreg):
# NOTE: formats of clbit and qubit are different!
self._creg = []
for e in creg:
self._creg.append(Register(name=e[0], index=e[1]))
self._qreg = []
for e in qreg:
self._qreg.append(Register(name=e[0], index=e[1]))
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(
xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center',
va='center', fontsize=self._style.fs,
color=self._style.gt, clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.sc, clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7,
height=HIG * 0.7, theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID],
[qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy + 0.35 * WID], lc=self._style.cc,
ls=self._style.cline)
arrowhead = patches.Polygon(((cx - 0.20 * WID, cy + 0.35 * WID),
(cx + 0.20 * WID, cy + 0.35 * WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'],
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
plt.close(self.figure)
return self.figure
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
else:
label = '${}$'.format(reg.name)
pos = -ii
self._qreg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(itertools.zip_longest(
self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name, reg.index)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
self._cond['n_lines'] += 1
idx += 1
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left',
va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc,
ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(
itertools.zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qargs' in op.keys():
q_idxs = []
for qarg in op['qargs']:
for index, reg in self._qreg_dict.items():
if (reg['group'] == qarg[0] and
reg['index'] == qarg[1]):
q_idxs.append(index)
break
else:
q_idxs = []
# get creg index
if 'cargs' in op.keys():
c_idxs = []
for carg in op['cargs']:
for index, reg in self._creg_dict.items():
if (reg['group'] == carg[0] and
reg['index'] == carg[1]):
c_idxs.append(index)
break
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or (
'condition' in op.keys() and op['condition']) or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied),
max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(
this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] in [
'barrier', 'snapshot', 'load', 'save',
'noise'] and not self.plot_barriers:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg coordinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'op' in op.keys() and hasattr(op['op'], 'param'):
param = self.param_parse(op['op'].param, self._style.pimode)
else:
param = None
# conditional gate
if 'condition' in op.keys() and op['condition']:
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for
ii in self._creg_dict]
mask = 0
for index, cbit in enumerate(self._creg):
if cbit.name == op['condition'][0]:
mask |= (1 << index)
val = op['condition'][1]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, hex(val))
self._line(qreg_t, creg_b, lc=self._style.cc,
ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] in ['barrier', 'snapshot', 'load', 'save',
'noise']:
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self.plot_barriers:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise _error.VisualizationError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (
self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.tc, clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if math.isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if math.isclose(math.fmod(abs_val, 1.0),
0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
if 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if math.isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return fractions.Fraction(i, j)
return None
<|code_end|>
|
qiskit/tools/visualization/_matplotlib.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""mpl circuit visualization backend."""
import collections
import fractions
import itertools
import json
import logging
import math
import numpy as np
try:
from matplotlib import patches
from matplotlib import pyplot as plt
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _qcstyle
from qiskit.tools.visualization import _utils
logger = logging.getLogger(__name__)
Register = collections.namedtuple('Register', 'name index')
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
scale=1.0, style=None, plot_barriers=True,
reverse_bits=False):
if not HAS_MATPLOTLIB:
raise ImportError('The class MatplotlibDrawer needs matplotlib. '
'Run "pip install matplotlib" before.')
self._ast = None
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = collections.OrderedDict()
self._creg_dict = collections.OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = _qcstyle.QCStyle()
self.plot_barriers = plot_barriers
self.reverse_bits = reverse_bits
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False,
labelleft=False, labelright=False)
def parse_circuit(self, circuit):
qregs, cregs, ops = _utils._get_instructions(
circuit, reversebits=self.reverse_bits)
self._registers(cregs, qregs)
self._ops = ops
def _registers(self, creg, qreg):
# NOTE: formats of clbit and qubit are different!
self._creg = []
for e in creg:
self._creg.append(Register(name=e[0], index=e[1]))
self._qreg = []
for e in qreg:
self._qreg.append(Register(name=e[0], index=e[1]))
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(
xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center',
va='center', fontsize=self._style.fs,
color=self._style.gt, clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.sc, clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7,
height=HIG * 0.7, theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID],
[qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy + 0.35 * WID], lc=self._style.cc,
ls=self._style.cline)
arrowhead = patches.Polygon(((cx - 0.20 * WID, cy + 0.35 * WID),
(cx + 0.20 * WID, cy + 0.35 * WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'],
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
plt.close(self.figure)
return self.figure
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name.name, reg.index)
else:
label = '${}$'.format(reg.name.name)
pos = -ii
self._qreg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(itertools.zip_longest(
self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name.name)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name.name, reg.index)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
self._cond['n_lines'] += 1
idx += 1
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left',
va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc,
ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(
itertools.zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qargs' in op.keys():
q_idxs = []
for qarg in op['qargs']:
for index, reg in self._qreg_dict.items():
if (reg['group'] == qarg[0] and
reg['index'] == qarg[1]):
q_idxs.append(index)
break
else:
q_idxs = []
# get creg index
if 'cargs' in op.keys():
c_idxs = []
for carg in op['cargs']:
for index, reg in self._creg_dict.items():
if (reg['group'] == carg[0] and
reg['index'] == carg[1]):
c_idxs.append(index)
break
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or (
'condition' in op.keys() and op['condition']) or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied),
max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(
this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] in [
'barrier', 'snapshot', 'load', 'save',
'noise'] and not self.plot_barriers:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg coordinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'op' in op.keys() and hasattr(op['op'], 'param'):
param = self.param_parse(op['op'].param, self._style.pimode)
else:
param = None
# conditional gate
if 'condition' in op.keys() and op['condition']:
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for
ii in self._creg_dict]
mask = 0
for index, cbit in enumerate(self._creg):
if cbit.name == op['condition'][0]:
mask |= (1 << index)
val = op['condition'][1]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, hex(val))
self._line(qreg_t, creg_b, lc=self._style.cc,
ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] in ['barrier', 'snapshot', 'load', 'save',
'noise']:
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self.plot_barriers:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise _error.VisualizationError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (
self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.tc, clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if math.isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if math.isclose(math.fmod(abs_val, 1.0),
0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
if 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if math.isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return fractions.Fraction(i, j)
return None
<|code_end|>
|
Process Tomography
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: 0.6.1
- **Python version**: 3.7
- **Operating system**: OsX
### What is the current behavior?
The process tomography for a teleported state seems providing awkward results. Conversely, state tomography for the same circuit works just fine
Specifically, this is the ideal Chi matrix for a X Gate.

And this is the Chi matrix as output of process tomography

### Steps to reproduce the problem
```
import numpy as np
import time
# importing Qiskit
from qiskit import Aer, IBMQ
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import register, execute
# import backend utilities
from qiskit.backends import JobStatus
# import tomography library
import qiskit.tools.qcvv.tomography as tomo
# useful additional packages
from qiskit.tools.visualization import plot_state
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.qi.qi import *
from qiskit.wrapper.jupyter import *
#from qiskit.backends.ibmq import least_busy
# Load saved IBMQ accounts
IBMQ.load_accounts()
#U_id = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]])
#U_id = np.array([[1,1],[1,-1]])
U_id = np.array([[0,1],[1,0]])
# compute Choi-matrix from unitary
id_choi = outer(vectorize(U_id))
#plot_state(id_choi)
# Creating circuit for tomography
q = QuantumRegister(3)
c = ClassicalRegister(3)
qc = QuantumCircuit(q, c, name='teleportation')
# inizializing qubit ⓪ to be teleported
#qc.u1(0.5, q[0])
qc.x(q[0])
#qc.h(q[0])
qc.barrier()
# creating entangled pair between qubit ① and qubit ②
qc.h(q[1])
qc.cx(q[1], q[2])
qc.barrier(q)
# teleportation
qc.cx(q[0], q[1])
qc.barrier(q)
# Measure qubit ⓪ in the + - basis
qc.h(q[0])
qc.cz(q[0],q[2])
#qc.measure(q[0], c[0])
#if c[0] == 1:
# qc.z(q[2])
qc.barrier(q)
# Measure qubit ① in the computational basis
qc.cx(q[1],q[2])
#qc.measure(q[1], c[1])
#if c[1] == 1:
# qc.x(q[2])
qc.barrier(q)
# measuring for executing the circuit.. to be removed for tomography
#qc.measure(q[0], c[0])
#qc.measure(q[1], c[1])
#qc.measure(q[2], c[2])
# Construct state tomography set for measurement of qubits [0, 1] in the Pauli basis
tomo_set = tomo.process_tomography_set([2])
# Add the state tomography measurement circuits to the Quantum Program
tomo_circuits = tomo.create_tomography_circuits(qc, q, c, tomo_set)
backend = Aer.get_backend('qasm_simulator')
shots = 1000
job_exp = execute(qc, backend=backend, shots=shots)
result_exp = job_exp.result()
counts_exp = result_exp.get_counts(qc)
plot_histogram(counts_exp)
tomo_job = execute(tomo_circuits, backend=backend, shots=shots)
tomo_results = tomo_job.result()
process_data = tomo.tomography_data(tomo_results, qc.name, tomo_set)
choi_fit = tomo.fit_tomography_data(process_data, options={'trace':2})
plot_state(id_choi)
plot_state(choi_fit)
print('Process Fidelity = ', state_fidelity(vectorize(U_id)/2, choi_fit))
```
[code.txt](https://github.com/Qiskit/qiskit-terra/files/2650016/code.txt)
### What is the expected behavior?
returning a Chi matrix equal or close to id_choi
### Suggested solutions
|
qiskit/tools/qcvv/tomography.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""
Quantum Tomography Module
Description:
This module contains functions for performing quantum state and quantum
process tomography. This includes:
- Functions for generating a set of circuits to
extract tomographically complete sets of measurement data.
- Functions for generating a tomography data set from the
results after the circuits have been executed on a backend.
- Functions for reconstructing a quantum state, or quantum process
(Choi-matrix) from tomography data sets.
Reconstruction Methods:
Currently implemented reconstruction methods are
- Linear inversion by weighted least-squares fitting.
- Fast maximum likelihood reconstruction using ref [1].
References:
[1] J Smolin, JM Gambetta, G Smith, Phys. Rev. Lett. 108, 070502 (2012).
Open access: arXiv:1106.5458 [quant-ph].
Workflow:
The basic functions for performing state and tomography experiments are:
- `tomography_set`, `state_tomography_set`, and `process_tomography_set`
all generates data structures for tomography experiments.
- `create_tomography_circuits` generates the quantum circuits specified
in a `tomography_set` for performing state tomography of the output
- `tomography_data` extracts the results after executing the tomography
circuits and returns it in a data structure used by fitters for state
reconstruction.
- `fit_tomography_data` reconstructs a density matrix or Choi-matrix from
the a set of tomography data.
"""
import logging
from functools import reduce
from itertools import product
from re import match
import numpy as np
from qiskit import QuantumCircuit
from qiskit import QiskitError
from qiskit.tools.qi.qi import vectorize, devectorize, outer
logger = logging.getLogger(__name__)
###############################################################################
# Tomography Bases
###############################################################################
class TomographyBasis(dict):
"""
Dictionary subsclass that includes methods for adding gates to circuits.
A TomographyBasis is a dictionary where the keys index a measurement
and the values are a list of projectors associated to that measurement.
It also includes two optional methods `prep_gate` and `meas_gate`:
- `prep_gate` adds gates to a circuit to prepare the corresponding
basis projector from an initial ground state.
- `meas_gate` adds gates to a circuit to transform the default
Z-measurement into a measurement in the basis.
With the exception of built in bases, these functions do nothing unless
they are specified by the user. They may be set by the data members
`prep_fun` and `meas_fun`. We illustrate this with an example.
Example:
A measurement in the Pauli-X basis has two outcomes corresponding to
the projectors:
`Xp = [[0.5, 0.5], [0.5, 0.5]]`
`Xm = [[0.5, -0.5], [-0.5, 0.5]]`
We can express this as a basis by
`BX = TomographyBasis( {'X': [Xp, Xm]} )`
To specifiy the gates to prepare and measure in this basis we :
```
def BX_prep_fun(circuit, qreg, op):
bas, proj = op
if bas == "X":
if proj == 0:
circuit.u2(0., np.pi, qreg) # apply H
else: # proj == 1
circuit.u2(np.pi, np.pi, qreg) # apply H.X
def BX_prep_fun(circuit, qreg, op):
if op == "X":
circuit.u2(0., np.pi, qreg) # apply H
```
We can then attach these functions to the basis using:
`BX.prep_fun = BX_prep_fun`
`BX.meas_fun = BX_meas_fun`.
Generating function:
A generating function `tomography_basis` exists to create bases in a
single step. Using the above example this can be done by:
```
BX = tomography_basis({'X': [Xp, Xm]},
prep_fun=BX_prep_fun,
meas_fun=BX_meas_fun)
```
"""
prep_fun = None
meas_fun = None
def prep_gate(self, circuit, qreg, op):
"""
Add state preparation gates to a circuit.
Args:
circuit (QuantumCircuit): circuit to add a preparation to.
qreg (tuple(QuantumRegister,int)): quantum register to apply
preparation to.
op (tuple(str, int)): the basis label and index for the
preparation op.
"""
if self.prep_fun is None:
pass
else:
self.prep_fun(circuit, qreg, op)
def meas_gate(self, circuit, qreg, op):
"""
Add measurement gates to a circuit.
Args:
circuit (QuantumCircuit): circuit to add measurement to.
qreg (tuple(QuantumRegister,int)): quantum register being measured.
op (str): the basis label for the measurement.
"""
if self.meas_fun is None:
pass
else:
self.meas_fun(circuit, qreg, op)
def tomography_basis(basis, prep_fun=None, meas_fun=None):
"""
Generate a TomographyBasis object.
See TomographyBasis for further details.abs
Args:
prep_fun (callable) optional: the function which adds preparation
gates to a circuit.
meas_fun (callable) optional: the function which adds measurement
gates to a circuit.
Returns:
TomographyBasis: A tomography basis.
"""
ret = TomographyBasis(basis)
ret.prep_fun = prep_fun
ret.meas_fun = meas_fun
return ret
# PAULI BASIS
# This corresponds to measurements in the X, Y, Z basis where
# Outcomes 0,1 are the +1,-1 eigenstates respectively.
# State preparation is also done in the +1 and -1 eigenstates.
def __pauli_prep_gates(circuit, qreg, op):
"""
Add state preparation gates to a circuit.
"""
bas, proj = op
if bas not in ['X', 'Y', 'Z']:
raise QiskitError("There's no X, Y or Z basis for this Pauli "
"preparation")
if bas == "X":
if proj == 1:
circuit.u2(np.pi, np.pi, qreg) # H.X
else:
circuit.u2(0., np.pi, qreg) # H
elif bas == "Y":
if proj == 1:
circuit.u2(-0.5 * np.pi, np.pi, qreg) # S.H.X
else:
circuit.u2(0.5 * np.pi, np.pi, qreg) # S.H
elif bas == "Z" and proj == 1:
circuit.u3(np.pi, 0., np.pi, qreg) # X
def __pauli_meas_gates(circuit, qreg, op):
"""
Add state measurement gates to a circuit.
"""
if op not in ['X', 'Y', 'Z']:
raise QiskitError("There's no X, Y or Z basis for this Pauli "
"measurement")
if op == "X":
circuit.u2(0., np.pi, qreg) # H
elif op == "Y":
circuit.u2(0., 0.5 * np.pi, qreg) # H.S^*
__PAULI_BASIS_OPS = {
'X':
[np.array([[0.5, 0.5], [0.5, 0.5]]),
np.array([[0.5, -0.5], [-0.5, 0.5]])],
'Y': [
np.array([[0.5, -0.5j], [0.5j, 0.5]]),
np.array([[0.5, 0.5j], [-0.5j, 0.5]])
],
'Z': [np.array([[1, 0], [0, 0]]),
np.array([[0, 0], [0, 1]])]
}
# Create the actual basis
PAULI_BASIS = tomography_basis(
__PAULI_BASIS_OPS,
prep_fun=__pauli_prep_gates,
meas_fun=__pauli_meas_gates)
# SIC-POVM BASIS
def __sic_prep_gates(circuit, qreg, op):
"""
Add state preparation gates to a circuit.
"""
bas, proj = op
if bas != 'S':
raise QiskitError('Not in SIC basis!')
theta = -2 * np.arctan(np.sqrt(2))
if proj == 1:
circuit.u3(theta, np.pi, 0.0, qreg)
elif proj == 2:
circuit.u3(theta, np.pi / 3, 0.0, qreg)
elif proj == 3:
circuit.u3(theta, -np.pi / 3, 0.0, qreg)
__SIC_BASIS_OPS = {
'S': [
np.array([[1, 0], [0, 0]]),
np.array([[1, np.sqrt(2)], [np.sqrt(2), 2]]) / 3,
np.array([[1, np.exp(np.pi * 2j / 3) * np.sqrt(2)],
[np.exp(-np.pi * 2j / 3) * np.sqrt(2), 2]]) / 3,
np.array([[1, np.exp(-np.pi * 2j / 3) * np.sqrt(2)],
[np.exp(np.pi * 2j / 3) * np.sqrt(2), 2]]) / 3
]
}
SIC_BASIS = tomography_basis(__SIC_BASIS_OPS, prep_fun=__sic_prep_gates)
###############################################################################
# Tomography Set and labels
###############################################################################
def tomography_set(qubits,
meas_basis='Pauli',
prep_basis=None):
"""
Generate a dictionary of tomography experiment configurations.
This returns a data structure that is used by other tomography functions
to generate state and process tomography circuits, and extract tomography
data from results after execution on a backend.
Quantum State Tomography:
Be default it will return a set for performing Quantum State
Tomography where individual qubits are measured in the Pauli basis.
A custom measurement basis may also be used by defining a user
`tomography_basis` and passing this in for the `meas_basis` argument.
Quantum Process Tomography:
A quantum process tomography set is created by specifying a preparation
basis along with a measurement basis. The preparation basis may be a
user defined `tomography_basis`, or one of the two built in basis 'SIC'
or 'Pauli'.
- SIC: Is a minimal symmetric informationally complete preparation
basis for 4 states for each qubit (4 ^ number of qubits total
preparation states). These correspond to the |0> state and the 3
other vertices of a tetrahedron on the Bloch-sphere.
- Pauli: Is a tomographically overcomplete preparation basis of the six
eigenstates of the 3 Pauli operators (6 ^ number of qubits
total preparation states).
Args:
qubits (list): The qubits being measured.
meas_basis (tomography_basis or str): The qubit measurement basis.
The default value is 'Pauli'.
prep_basis (tomography_basis or None): The optional qubit preparation
basis. If no basis is specified state tomography will be performed
instead of process tomography. A built in basis may be specified by
'SIC' or 'Pauli' (SIC basis recommended for > 2 qubits).
Returns:
dict: A dict of tomography configurations that can be parsed by
`create_tomography_circuits` and `tomography_data` functions
for implementing quantum tomography experiments. This output contains
fields "qubits", "meas_basis", "circuits". It may also optionally
contain a field "prep_basis" for process tomography experiments.
```
{
'qubits': qubits (list[ints]),
'meas_basis': meas_basis (tomography_basis),
'circuit_labels': (list[string]),
'circuits': (list[dict]) # prep and meas configurations
# optionally for process tomography experiments:
'prep_basis': prep_basis (tomography_basis)
}
```
Raises:
QiskitError: if the Qubits argument is not a list.
"""
if not isinstance(qubits, list):
raise QiskitError('Qubits argument must be a list')
num_of_qubits = len(qubits)
if isinstance(meas_basis, str):
if meas_basis.lower() == 'pauli':
meas_basis = PAULI_BASIS
if isinstance(prep_basis, str):
if prep_basis.lower() == 'pauli':
prep_basis = PAULI_BASIS
elif prep_basis.lower() == 'sic':
prep_basis = SIC_BASIS
circuits = []
circuit_labels = []
# add meas basis configs
if prep_basis is None:
# State Tomography
for meas_product in product(meas_basis.keys(), repeat=num_of_qubits):
meas = dict(zip(qubits, meas_product))
circuits.append({'meas': meas})
# Make label
label = '_meas_'
for qubit, op in meas.items():
label += '%s(%d)' % (op[0], qubit)
circuit_labels.append(label)
return {'qubits': qubits,
'circuits': circuits,
'circuit_labels': circuit_labels,
'meas_basis': meas_basis}
# Process Tomography
num_of_s = len(list(prep_basis.values())[0])
plst_single = [(b, s)
for b in prep_basis.keys()
for s in range(num_of_s)]
for plst_product in product(plst_single, repeat=num_of_qubits):
for meas_product in product(meas_basis.keys(),
repeat=num_of_qubits):
prep = dict(zip(qubits, plst_product))
meas = dict(zip(qubits, meas_product))
circuits.append({'prep': prep, 'meas': meas})
# Make label
label = '_prep_'
for qubit, op in prep.items():
label += '%s%d(%d)' % (op[0], op[1], qubit)
label += '_meas_'
for qubit, op in meas.items():
label += '%s(%d)' % (op[0], qubit)
circuit_labels.append(label)
return {'qubits': qubits,
'circuits': circuits,
'circuit_labels': circuit_labels,
'prep_basis': prep_basis,
'meas_basis': meas_basis}
def state_tomography_set(qubits, meas_basis='Pauli'):
"""
Generate a dictionary of state tomography experiment configurations.
This returns a data structure that is used by other tomography functions
to generate state and process tomography circuits, and extract tomography
data from results after execution on a backend.
Quantum State Tomography:
Be default it will return a set for performing Quantum State
Tomography where individual qubits are measured in the Pauli basis.
A custom measurement basis may also be used by defining a user
`tomography_basis` and passing this in for the `meas_basis` argument.
Quantum Process Tomography:
A quantum process tomography set is created by specifying a preparation
basis along with a measurement basis. The preparation basis may be a
user defined `tomography_basis`, or one of the two built in basis 'SIC'
or 'Pauli'.
- SIC: Is a minimal symmetric informationally complete preparation
basis for 4 states for each qubit (4 ^ number of qubits total
preparation states). These correspond to the |0> state and the 3
other vertices of a tetrahedron on the Bloch-sphere.
- Pauli: Is a tomographically overcomplete preparation basis of the six
eigenstates of the 3 Pauli operators (6 ^ number of qubits
total preparation states).
Args:
qubits (list): The qubits being measured.
meas_basis (tomography_basis or str): The qubit measurement basis.
The default value is 'Pauli'.
Returns:
dict: A dict of tomography configurations that can be parsed by
`create_tomography_circuits` and `tomography_data` functions
for implementing quantum tomography experiments. This output contains
fields "qubits", "meas_basis", "circuits".
```
{
'qubits': qubits (list[ints]),
'meas_basis': meas_basis (tomography_basis),
'circuit_labels': (list[string]),
'circuits': (list[dict]) # prep and meas configurations
}
```
"""
return tomography_set(qubits, meas_basis=meas_basis)
def process_tomography_set(qubits, meas_basis='Pauli', prep_basis='SIC'):
"""
Generate a dictionary of process tomography experiment configurations.
This returns a data structure that is used by other tomography functions
to generate state and process tomography circuits, and extract tomography
data from results after execution on a backend.
A quantum process tomography set is created by specifying a preparation
basis along with a measurement basis. The preparation basis may be a
user defined `tomography_basis`, or one of the two built in basis 'SIC'
or 'Pauli'.
- SIC: Is a minimal symmetric informationally complete preparation
basis for 4 states for each qubit (4 ^ number of qubits total
preparation states). These correspond to the |0> state and the 3
other vertices of a tetrahedron on the Bloch-sphere.
- Pauli: Is a tomographically overcomplete preparation basis of the six
eigenstates of the 3 Pauli operators (6 ^ number of qubits
total preparation states).
Args:
qubits (list): The qubits being measured.
meas_basis (tomography_basis or str): The qubit measurement basis.
The default value is 'Pauli'.
prep_basis (tomography_basis or str): The qubit preparation basis.
The default value is 'SIC'.
Returns:
dict: A dict of tomography configurations that can be parsed by
`create_tomography_circuits` and `tomography_data` functions
for implementing quantum tomography experiments. This output contains
fields "qubits", "meas_basis", "prep_basus", circuits".
```
{
'qubits': qubits (list[ints]),
'meas_basis': meas_basis (tomography_basis),
'prep_basis': prep_basis (tomography_basis),
'circuit_labels': (list[string]),
'circuits': (list[dict]) # prep and meas configurations
}
```
"""
return tomography_set(qubits, meas_basis=meas_basis, prep_basis=prep_basis)
def tomography_circuit_names(tomo_set, name=''):
"""
Return a list of tomography circuit names.
The returned list is the same as the one returned by
`create_tomography_circuits` and can be used by a QuantumProgram
to execute tomography circuits and extract measurement results.
Args:
tomo_set (tomography_set): a tomography set generated by
`tomography_set`.
name (str): the name of the base QuantumCircuit used by the
tomography experiment.
Returns:
list: A list of circuit names.
"""
return [name + l for l in tomo_set['circuit_labels']]
###############################################################################
# Tomography circuit generation
###############################################################################
def create_tomography_circuits(circuit, qreg, creg, tomoset):
"""
Add tomography measurement circuits to a QuantumProgram.
The quantum program must contain a circuit 'name', which is treated as a
state preparation circuit for state tomography, or as teh circuit being
measured for process tomography. This function then appends the circuit
with a set of measurements specified by the input `tomography_set`,
optionally it also prepends the circuit with state preparation circuits if
they are specified in the `tomography_set`.
For n-qubit tomography with a tomographically complete set of preparations
and measurements this results in $4^n 3^n$ circuits being added to the
quantum program.
Args:
circuit (QuantumCircuit): The circuit to be appended with tomography
state preparation and/or measurements.
qreg (QuantumRegister): the quantum register containing qubits to be
measured.
creg (ClassicalRegister): the classical register containing bits to
store measurement outcomes.
tomoset (tomography_set): the dict of tomography configurations.
Returns:
list: A list of quantum tomography circuits for the input circuit.
Raises:
QiskitError: if circuit is not a valid QuantumCircuit
Example:
For a tomography set specifying state tomography of qubit-0 prepared
by a circuit 'circ' this would return:
```
['circ_meas_X(0)', 'circ_meas_Y(0)', 'circ_meas_Z(0)']
```
For process tomography of the same circuit with preparation in the
SIC-POVM basis it would return:
```
[
'circ_prep_S0(0)_meas_X(0)', 'circ_prep_S0(0)_meas_Y(0)',
'circ_prep_S0(0)_meas_Z(0)', 'circ_prep_S1(0)_meas_X(0)',
'circ_prep_S1(0)_meas_Y(0)', 'circ_prep_S1(0)_meas_Z(0)',
'circ_prep_S2(0)_meas_X(0)', 'circ_prep_S2(0)_meas_Y(0)',
'circ_prep_S2(0)_meas_Z(0)', 'circ_prep_S3(0)_meas_X(0)',
'circ_prep_S3(0)_meas_Y(0)', 'circ_prep_S3(0)_meas_Z(0)'
]
```
"""
if not isinstance(circuit, QuantumCircuit):
raise QiskitError('Input circuit must be a QuantumCircuit object')
dics = tomoset['circuits']
labels = tomography_circuit_names(tomoset, circuit.name)
tomography_circuits = []
for label, conf in zip(labels, dics):
tmp = circuit
# Add prep circuits
if 'prep' in conf:
prep = QuantumCircuit(qreg, creg, name='tmp_prep')
for qubit, op in conf['prep'].items():
tomoset['prep_basis'].prep_gate(prep, qreg[qubit], op)
prep.barrier(qreg[qubit]) # pylint: disable=no-member
tmp = prep + tmp
# Add measurement circuits
meas = QuantumCircuit(qreg, creg, name='tmp_meas')
for qubit, op in conf['meas'].items():
meas.barrier(qreg[qubit]) # pylint: disable=no-member
tomoset['meas_basis'].meas_gate(meas, qreg[qubit], op)
meas.measure(qreg[qubit], creg[qubit])
tmp = tmp + meas
# Add label to the circuit
tmp.name = label
tomography_circuits.append(tmp)
logger.info('>> created tomography circuits for "%s"', circuit.name)
return tomography_circuits
###############################################################################
# Get results data
###############################################################################
def tomography_data(results, name, tomoset):
"""
Return a results dict for a state or process tomography experiment.
Args:
results (Result): Results from execution of a process tomography
circuits on a backend.
name (string): The name of the circuit being reconstructed.
tomoset (tomography_set): the dict of tomography configurations.
Returns:
list: A list of dicts for the outcome of each process tomography
measurement circuit.
"""
labels = tomography_circuit_names(tomoset, name)
circuits = tomoset['circuits']
data = []
prep = None
for j, _ in enumerate(labels):
counts = marginal_counts(results.get_counts(labels[j]),
tomoset['qubits'])
shots = sum(counts.values())
meas = circuits[j]['meas']
prep = circuits[j].get('prep', None)
meas_qubits = sorted(meas.keys())
if prep:
prep_qubits = sorted(prep.keys())
circuit = {}
for c in counts.keys():
circuit[c] = {}
circuit[c]['meas'] = [(meas[meas_qubits[k]], int(c[-1 - k]))
for k in range(len(meas_qubits))]
if prep:
circuit[c]['prep'] = [prep[prep_qubits[k]]
for k in range(len(prep_qubits))]
data.append({'counts': counts, 'shots': shots, 'circuit': circuit})
ret = {'data': data, 'meas_basis': tomoset['meas_basis']}
if prep:
ret['prep_basis'] = tomoset['prep_basis']
return ret
def marginal_counts(counts, meas_qubits):
"""
Compute the marginal counts for a subset of measured qubits.
Args:
counts (dict): the counts returned from a backend ({str: int}).
meas_qubits (list[int]): the qubits to return the marginal
counts distribution for.
Returns:
dict: A counts dict for the meas_qubits.abs
Example: if `counts = {'00': 10, '01': 5}`
`marginal_counts(counts, [0])` returns `{'0': 15, '1': 0}`.
`marginal_counts(counts, [0])` returns `{'0': 10, '1': 5}`.
"""
# pylint: disable=cell-var-from-loop
# Extract total number of qubits from count keys
num_of_qubits = len(list(counts.keys())[0])
# keys for measured qubits only
qs = sorted(meas_qubits, reverse=True)
meas_keys = count_keys(len(qs))
# get regex match strings for summing outcomes of other qubits
rgx = [
reduce(lambda x, y: (key[qs.index(y)] if y in qs else '\\d') + x,
range(num_of_qubits), '') for key in meas_keys
]
# build the return list
meas_counts = []
for m in rgx:
c = 0
for key, val in counts.items():
if match(m, key):
c += val
meas_counts.append(c)
# return as counts dict on measured qubits only
return dict(zip(meas_keys, meas_counts))
def count_keys(n):
"""Generate outcome bitstrings for n-qubits.
Args:
n (int): the number of qubits.
Returns:
list: A list of bitstrings ordered as follows:
Example: n=2 returns ['00', '01', '10', '11'].
"""
return [bin(j)[2:].zfill(n) for j in range(2**n)]
###############################################################################
# Tomographic Reconstruction functions.
###############################################################################
def fit_tomography_data(tomo_data, method='wizard', options=None):
"""
Reconstruct a density matrix or process-matrix from tomography data.
If the input data is state_tomography_data the returned operator will
be a density matrix. If the input data is process_tomography_data the
returned operator will be a Choi-matrix in the column-vectorization
convention.
Args:
tomo_data (dict): process tomography measurement data.
method (str): the fitting method to use.
Available methods:
- 'wizard' (default)
- 'leastsq'
options (dict or None): additional options for fitting method.
Returns:
numpy.array: The fitted operator.
Available methods:
- 'wizard' (Default): The returned operator will be constrained to be
positive-semidefinite.
Options:
- 'trace': the trace of the returned operator.
The default value is 1.
- 'beta': hedging parameter for computing frequencies from
zero-count data. The default value is 0.50922.
- 'epsilon: threshold for truncating small eigenvalues to zero.
The default value is 0
- 'leastsq': Fitting without positive-semidefinite constraint.
Options:
- 'trace': Same as for 'wizard' method.
- 'beta': Same as for 'wizard' method.
Raises:
Exception: if the `method` parameter is not valid.
"""
if isinstance(method, str) and method.lower() in ['wizard', 'leastsq']:
# get options
trace = __get_option('trace', options)
beta = __get_option('beta', options)
# fit state
rho = __leastsq_fit(tomo_data, trace=trace, beta=beta)
if method == 'wizard':
# Use wizard method to constrain positivity
epsilon = __get_option('epsilon', options)
rho = __wizard(rho, epsilon=epsilon)
return rho
else:
raise Exception('Invalid reconstruction method "%s"' % method)
def __get_option(opt, options):
"""
Return an optional value or None if not found.
"""
if options is not None:
if opt in options:
return options[opt]
return None
###############################################################################
# Fit Method: Linear Inversion
###############################################################################
def __leastsq_fit(tomo_data, weights=None, trace=None, beta=None):
"""
Reconstruct a state from unconstrained least-squares fitting.
Args:
tomo_data (list[dict]): state or process tomography data.
weights (list or array or None): weights to use for least squares
fitting. The default is standard deviation from a binomial
distribution.
trace (float or None): trace of returned operator. The default is 1.
beta (float or None): hedge parameter (>=0) for computing frequencies
from zero-count data. The default value is 0.50922.
Returns:
numpy.array: A numpy array of the reconstructed operator.
"""
if trace is None:
trace = 1. # default to unit trace
data = tomo_data['data']
keys = data[0]['circuit'].keys()
# Get counts and shots
counts = []
shots = []
ops = []
for dat in data:
for key in keys:
counts.append(dat['counts'][key])
shots.append(dat['shots'])
projectors = dat['circuit'][key]
op = __projector(projectors['meas'], tomo_data['meas_basis'])
if 'prep' in projectors:
op_prep = __projector(projectors['prep'],
tomo_data['prep_basis'])
op = np.kron(op_prep.conj(), op)
ops.append(op)
# Convert counts to frequencies
counts = np.array(counts)
shots = np.array(shots)
freqs = counts / shots
# Use hedged frequencies to calculate least squares fitting weights
if weights is None:
if beta is None:
beta = 0.50922
K = len(keys)
freqs_hedged = (counts + beta) / (shots + K * beta)
weights = np.sqrt(shots / (freqs_hedged * (1 - freqs_hedged)))
return __tomo_linear_inv(freqs, ops, weights, trace=trace)
def __projector(op_list, basis):
"""Returns a projectors.
"""
ret = 1
# list is from qubit 0 to 1
for op in op_list:
label, eigenstate = op
ret = np.kron(basis[label][eigenstate], ret)
return ret
def __tomo_linear_inv(freqs, ops, weights=None, trace=None):
"""
Reconstruct a matrix through linear inversion.
Args:
freqs (list[float]): list of observed frequences.
ops (list[np.array]): list of corresponding projectors.
weights (list[float] or array_like):
weights to be used for weighted fitting.
trace (float or None): trace of returned operator.
Returns:
numpy.array: A numpy array of the reconstructed operator.
"""
# get weights matrix
if weights is not None:
W = np.array(weights)
if W.ndim == 1:
W = np.diag(W)
# Get basis S matrix
S = np.array([vectorize(m).conj()
for m in ops]).reshape(len(ops), ops[0].size)
if weights is not None:
S = np.dot(W, S) # W.S
# get frequencies vec
v = np.array(freqs) # |f>
if weights is not None:
v = np.dot(W, freqs) # W.|f>
Sdg = S.T.conj() # S^*.W^*
inv = np.linalg.pinv(np.dot(Sdg, S)) # (S^*.W^*.W.S)^-1
# linear inversion of freqs
ret = devectorize(np.dot(inv, np.dot(Sdg, v)))
# renormalize to input trace value
if trace is not None:
ret = trace * ret / np.trace(ret)
return ret
###############################################################################
# Fit Method: Wizard
###############################################################################
def __wizard(rho, epsilon=None):
"""
Returns the nearest positive semidefinite operator to an operator.
This method is based on reference [1]. It constrains positivity
by setting negative eigenvalues to zero and rescaling the positive
eigenvalues.
Args:
rho (array_like): the input operator.
epsilon(float or None): threshold (>=0) for truncating small
eigenvalues values to zero.
Returns:
numpy.array: A positive semidefinite numpy array.
"""
if epsilon is None:
epsilon = 0. # default value
dim = len(rho)
rho_wizard = np.zeros([dim, dim])
v, w = np.linalg.eigh(rho) # v eigenvecrors v[0] < v[1] <...
for j in range(dim):
if v[j] < epsilon:
tmp = v[j]
v[j] = 0.
# redistribute loop
x = 0.
for k in range(j + 1, dim):
x += tmp / (dim - (j + 1))
v[k] = v[k] + tmp / (dim - (j + 1))
for j in range(dim):
rho_wizard = rho_wizard + v[j] * outer(w[:, j])
return rho_wizard
###############################################################
# Wigner function tomography
###############################################################
def build_wigner_circuits(circuit, phis, thetas, qubits,
qreg, creg):
"""Create the circuits to rotate to points in phase space
Args:
circuit (QuantumCircuit): The circuit to be appended with tomography
state preparation and/or measurements.
phis (np.matrix[[complex]]): phis
thetas (np.matrix[[complex]]): thetas
qubits (list[int]): a list of the qubit indexes of qreg to be measured.
qreg (QuantumRegister): the quantum register containing qubits to be
measured.
creg (ClassicalRegister): the classical register containing bits to
store measurement outcomes.
Returns:
list: A list of names of the added wigner function circuits.
Raises:
QiskitError: if circuit is not a valid QuantumCircuit.
"""
if not isinstance(circuit, QuantumCircuit):
raise QiskitError('Input circuit must be a QuantumCircuit object')
tomography_circuits = []
points = len(phis[0])
for point in range(points):
label = '_wigner_phase_point'
label += str(point)
tmp_circ = QuantumCircuit(qreg, creg, name=label)
for qubit, _ in enumerate(qubits):
tmp_circ.u3(thetas[qubit][point], 0, # pylint: disable=no-member
phis[qubit][point], qreg[qubits[qubit]])
tmp_circ.measure(qreg[qubits[qubit]], creg[qubits[qubit]])
# Add to original circuit
tmp_circ = circuit + tmp_circ
tmp_circ.name = circuit.name + label
tomography_circuits.append(tmp_circ)
logger.info('>> Created Wigner function circuits for "%s"', circuit.name)
return tomography_circuits
def wigner_data(q_result, meas_qubits, labels, shots=None):
"""Get the value of the Wigner function from measurement results.
Args:
q_result (Result): Results from execution of a state tomography
circuits on a backend.
meas_qubits (list[int]): a list of the qubit indexes measured.
labels (list[str]): a list of names of the circuits
shots (int): number of shots
Returns:
list: The values of the Wigner function at measured points in
phase space
"""
num = len(meas_qubits)
dim = 2**num
p = [0.5 + 0.5 * np.sqrt(3), 0.5 - 0.5 * np.sqrt(3)]
parity = 1
for i in range(num):
parity = np.kron(parity, p)
w = [0] * len(labels)
wpt = 0
counts = [marginal_counts(q_result.get_counts(circ), meas_qubits)
for circ in labels]
for entry in counts:
x = [0] * dim
for i in range(dim):
if bin(i)[2:].zfill(num) in entry:
x[i] = float(entry[bin(i)[2:].zfill(num)])
if shots is None:
shots = np.sum(x)
for i in range(dim):
w[wpt] = w[wpt] + (x[i] / shots) * parity[i]
wpt += 1
return w
<|code_end|>
|
qiskit/tools/qcvv/tomography.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""
Quantum Tomography Module
Description:
This module contains functions for performing quantum state and quantum
process tomography. This includes:
- Functions for generating a set of circuits to
extract tomographically complete sets of measurement data.
- Functions for generating a tomography data set from the
results after the circuits have been executed on a backend.
- Functions for reconstructing a quantum state, or quantum process
(Choi-matrix) from tomography data sets.
Reconstruction Methods:
Currently implemented reconstruction methods are
- Linear inversion by weighted least-squares fitting.
- Fast maximum likelihood reconstruction using ref [1].
References:
[1] J Smolin, JM Gambetta, G Smith, Phys. Rev. Lett. 108, 070502 (2012).
Open access: arXiv:1106.5458 [quant-ph].
Workflow:
The basic functions for performing state and tomography experiments are:
- `tomography_set`, `state_tomography_set`, and `process_tomography_set`
all generates data structures for tomography experiments.
- `create_tomography_circuits` generates the quantum circuits specified
in a `tomography_set` for performing state tomography of the output
- `tomography_data` extracts the results after executing the tomography
circuits and returns it in a data structure used by fitters for state
reconstruction.
- `fit_tomography_data` reconstructs a density matrix or Choi-matrix from
the a set of tomography data.
"""
import logging
from functools import reduce
from itertools import product
from re import match
import numpy as np
from qiskit import QuantumCircuit
from qiskit import QiskitError
from qiskit.tools.qi.qi import vectorize, devectorize, outer
logger = logging.getLogger(__name__)
###############################################################################
# Tomography Bases
###############################################################################
class TomographyBasis(dict):
"""
Dictionary subsclass that includes methods for adding gates to circuits.
A TomographyBasis is a dictionary where the keys index a measurement
and the values are a list of projectors associated to that measurement.
It also includes two optional methods `prep_gate` and `meas_gate`:
- `prep_gate` adds gates to a circuit to prepare the corresponding
basis projector from an initial ground state.
- `meas_gate` adds gates to a circuit to transform the default
Z-measurement into a measurement in the basis.
With the exception of built in bases, these functions do nothing unless
they are specified by the user. They may be set by the data members
`prep_fun` and `meas_fun`. We illustrate this with an example.
Example:
A measurement in the Pauli-X basis has two outcomes corresponding to
the projectors:
`Xp = [[0.5, 0.5], [0.5, 0.5]]`
`Xm = [[0.5, -0.5], [-0.5, 0.5]]`
We can express this as a basis by
`BX = TomographyBasis( {'X': [Xp, Xm]} )`
To specifiy the gates to prepare and measure in this basis we :
```
def BX_prep_fun(circuit, qreg, op):
bas, proj = op
if bas == "X":
if proj == 0:
circuit.u2(0., np.pi, qreg) # apply H
else: # proj == 1
circuit.u2(np.pi, np.pi, qreg) # apply H.X
def BX_prep_fun(circuit, qreg, op):
if op == "X":
circuit.u2(0., np.pi, qreg) # apply H
```
We can then attach these functions to the basis using:
`BX.prep_fun = BX_prep_fun`
`BX.meas_fun = BX_meas_fun`.
Generating function:
A generating function `tomography_basis` exists to create bases in a
single step. Using the above example this can be done by:
```
BX = tomography_basis({'X': [Xp, Xm]},
prep_fun=BX_prep_fun,
meas_fun=BX_meas_fun)
```
"""
prep_fun = None
meas_fun = None
def prep_gate(self, circuit, qreg, op):
"""
Add state preparation gates to a circuit.
Args:
circuit (QuantumCircuit): circuit to add a preparation to.
qreg (tuple(QuantumRegister,int)): quantum register to apply
preparation to.
op (tuple(str, int)): the basis label and index for the
preparation op.
"""
if self.prep_fun is None:
pass
else:
self.prep_fun(circuit, qreg, op)
def meas_gate(self, circuit, qreg, op):
"""
Add measurement gates to a circuit.
Args:
circuit (QuantumCircuit): circuit to add measurement to.
qreg (tuple(QuantumRegister,int)): quantum register being measured.
op (str): the basis label for the measurement.
"""
if self.meas_fun is None:
pass
else:
self.meas_fun(circuit, qreg, op)
def tomography_basis(basis, prep_fun=None, meas_fun=None):
"""
Generate a TomographyBasis object.
See TomographyBasis for further details.abs
Args:
prep_fun (callable) optional: the function which adds preparation
gates to a circuit.
meas_fun (callable) optional: the function which adds measurement
gates to a circuit.
Returns:
TomographyBasis: A tomography basis.
"""
ret = TomographyBasis(basis)
ret.prep_fun = prep_fun
ret.meas_fun = meas_fun
return ret
# PAULI BASIS
# This corresponds to measurements in the X, Y, Z basis where
# Outcomes 0,1 are the +1,-1 eigenstates respectively.
# State preparation is also done in the +1 and -1 eigenstates.
def __pauli_prep_gates(circuit, qreg, op):
"""
Add state preparation gates to a circuit.
"""
bas, proj = op
if bas not in ['X', 'Y', 'Z']:
raise QiskitError("There's no X, Y or Z basis for this Pauli "
"preparation")
if bas == "X":
if proj == 1:
circuit.u2(np.pi, np.pi, qreg) # H.X
else:
circuit.u2(0., np.pi, qreg) # H
elif bas == "Y":
if proj == 1:
circuit.u2(-0.5 * np.pi, np.pi, qreg) # S.H.X
else:
circuit.u2(0.5 * np.pi, np.pi, qreg) # S.H
elif bas == "Z" and proj == 1:
circuit.u3(np.pi, 0., np.pi, qreg) # X
def __pauli_meas_gates(circuit, qreg, op):
"""
Add state measurement gates to a circuit.
"""
if op not in ['X', 'Y', 'Z']:
raise QiskitError("There's no X, Y or Z basis for this Pauli "
"measurement")
if op == "X":
circuit.u2(0., np.pi, qreg) # H
elif op == "Y":
circuit.u2(0., 0.5 * np.pi, qreg) # H.S^*
__PAULI_BASIS_OPS = {
'X':
[np.array([[0.5, 0.5], [0.5, 0.5]]),
np.array([[0.5, -0.5], [-0.5, 0.5]])],
'Y': [
np.array([[0.5, -0.5j], [0.5j, 0.5]]),
np.array([[0.5, 0.5j], [-0.5j, 0.5]])
],
'Z': [np.array([[1, 0], [0, 0]]),
np.array([[0, 0], [0, 1]])]
}
# Create the actual basis
PAULI_BASIS = tomography_basis(
__PAULI_BASIS_OPS,
prep_fun=__pauli_prep_gates,
meas_fun=__pauli_meas_gates)
# SIC-POVM BASIS
def __sic_prep_gates(circuit, qreg, op):
"""
Add state preparation gates to a circuit.
"""
bas, proj = op
if bas != 'S':
raise QiskitError('Not in SIC basis!')
theta = -2 * np.arctan(np.sqrt(2))
if proj == 1:
circuit.u3(theta, np.pi, 0.0, qreg)
elif proj == 2:
circuit.u3(theta, np.pi / 3, 0.0, qreg)
elif proj == 3:
circuit.u3(theta, -np.pi / 3, 0.0, qreg)
__SIC_BASIS_OPS = {
'S': [
np.array([[1, 0], [0, 0]]),
np.array([[1, np.sqrt(2)], [np.sqrt(2), 2]]) / 3,
np.array([[1, np.exp(np.pi * 2j / 3) * np.sqrt(2)],
[np.exp(-np.pi * 2j / 3) * np.sqrt(2), 2]]) / 3,
np.array([[1, np.exp(-np.pi * 2j / 3) * np.sqrt(2)],
[np.exp(np.pi * 2j / 3) * np.sqrt(2), 2]]) / 3
]
}
SIC_BASIS = tomography_basis(__SIC_BASIS_OPS, prep_fun=__sic_prep_gates)
###############################################################################
# Tomography Set and labels
###############################################################################
def tomography_set(meas_qubits,
meas_basis='Pauli',
prep_qubits=None,
prep_basis=None):
"""
Generate a dictionary of tomography experiment configurations.
This returns a data structure that is used by other tomography functions
to generate state and process tomography circuits, and extract tomography
data from results after execution on a backend.
Quantum State Tomography:
Be default it will return a set for performing Quantum State
Tomography where individual qubits are measured in the Pauli basis.
A custom measurement basis may also be used by defining a user
`tomography_basis` and passing this in for the `meas_basis` argument.
Quantum Process Tomography:
A quantum process tomography set is created by specifying a preparation
basis along with a measurement basis. The preparation basis may be a
user defined `tomography_basis`, or one of the two built in basis 'SIC'
or 'Pauli'.
- SIC: Is a minimal symmetric informationally complete preparation
basis for 4 states for each qubit (4 ^ number of qubits total
preparation states). These correspond to the |0> state and the 3
other vertices of a tetrahedron on the Bloch-sphere.
- Pauli: Is a tomographically overcomplete preparation basis of the six
eigenstates of the 3 Pauli operators (6 ^ number of qubits
total preparation states).
Args:
meas_qubits (list): The qubits being measured.
meas_basis (tomography_basis or str): The qubit measurement basis.
The default value is 'Pauli'.
prep_qubits (list or None): The qubits being prepared. If None then
meas_qubits will be used for process tomography experiments.
prep_basis (tomography_basis or None): The optional qubit preparation
basis. If no basis is specified state tomography will be performed
instead of process tomography. A built in basis may be specified by
'SIC' or 'Pauli' (SIC basis recommended for > 2 qubits).
Returns:
dict: A dict of tomography configurations that can be parsed by
`create_tomography_circuits` and `tomography_data` functions
for implementing quantum tomography experiments. This output contains
fields "qubits", "meas_basis", "circuits". It may also optionally
contain a field "prep_basis" for process tomography experiments.
```
{
'qubits': qubits (list[ints]),
'meas_basis': meas_basis (tomography_basis),
'circuit_labels': (list[string]),
'circuits': (list[dict]) # prep and meas configurations
# optionally for process tomography experiments:
'prep_basis': prep_basis (tomography_basis)
}
```
Raises:
QiskitError: if the Qubits argument is not a list.
"""
if not isinstance(meas_qubits, list):
raise QiskitError('Qubits argument must be a list')
num_of_qubits = len(meas_qubits)
if prep_qubits is None:
prep_qubits = meas_qubits
if not isinstance(prep_qubits, list):
raise QiskitError('prep_qubits argument must be a list')
if len(prep_qubits) != len(meas_qubits):
raise QiskitError('meas_qubits and prep_qubitsare different length')
if isinstance(meas_basis, str):
if meas_basis.lower() == 'pauli':
meas_basis = PAULI_BASIS
if isinstance(prep_basis, str):
if prep_basis.lower() == 'pauli':
prep_basis = PAULI_BASIS
elif prep_basis.lower() == 'sic':
prep_basis = SIC_BASIS
circuits = []
circuit_labels = []
# add meas basis configs
if prep_basis is None:
# State Tomography
for meas_product in product(meas_basis.keys(), repeat=num_of_qubits):
meas = dict(zip(meas_qubits, meas_product))
circuits.append({'meas': meas})
# Make label
label = '_meas_'
for qubit, op in meas.items():
label += '%s(%d)' % (op[0], qubit)
circuit_labels.append(label)
return {'qubits': meas_qubits,
'circuits': circuits,
'circuit_labels': circuit_labels,
'meas_basis': meas_basis}
# Process Tomography
num_of_s = len(list(prep_basis.values())[0])
plst_single = [(b, s)
for b in prep_basis.keys()
for s in range(num_of_s)]
for plst_product in product(plst_single, repeat=num_of_qubits):
for meas_product in product(meas_basis.keys(),
repeat=num_of_qubits):
prep = dict(zip(prep_qubits, plst_product))
meas = dict(zip(meas_qubits, meas_product))
circuits.append({'prep': prep, 'meas': meas})
# Make label
label = '_prep_'
for qubit, op in prep.items():
label += '%s%d(%d)' % (op[0], op[1], qubit)
label += '_meas_'
for qubit, op in meas.items():
label += '%s(%d)' % (op[0], qubit)
circuit_labels.append(label)
return {'qubits': meas_qubits,
'circuits': circuits,
'circuit_labels': circuit_labels,
'prep_basis': prep_basis,
'meas_basis': meas_basis}
def state_tomography_set(qubits, meas_basis='Pauli'):
"""
Generate a dictionary of state tomography experiment configurations.
This returns a data structure that is used by other tomography functions
to generate state and process tomography circuits, and extract tomography
data from results after execution on a backend.
Quantum State Tomography:
Be default it will return a set for performing Quantum State
Tomography where individual qubits are measured in the Pauli basis.
A custom measurement basis may also be used by defining a user
`tomography_basis` and passing this in for the `meas_basis` argument.
Quantum Process Tomography:
A quantum process tomography set is created by specifying a preparation
basis along with a measurement basis. The preparation basis may be a
user defined `tomography_basis`, or one of the two built in basis 'SIC'
or 'Pauli'.
- SIC: Is a minimal symmetric informationally complete preparation
basis for 4 states for each qubit (4 ^ number of qubits total
preparation states). These correspond to the |0> state and the 3
other vertices of a tetrahedron on the Bloch-sphere.
- Pauli: Is a tomographically overcomplete preparation basis of the six
eigenstates of the 3 Pauli operators (6 ^ number of qubits
total preparation states).
Args:
qubits (list): The qubits being measured.
meas_basis (tomography_basis or str): The qubit measurement basis.
The default value is 'Pauli'.
Returns:
dict: A dict of tomography configurations that can be parsed by
`create_tomography_circuits` and `tomography_data` functions
for implementing quantum tomography experiments. This output contains
fields "qubits", "meas_basis", "circuits".
```
{
'qubits': qubits (list[ints]),
'meas_basis': meas_basis (tomography_basis),
'circuit_labels': (list[string]),
'circuits': (list[dict]) # prep and meas configurations
}
```
"""
return tomography_set(qubits, meas_basis=meas_basis)
def process_tomography_set(meas_qubits, meas_basis='Pauli',
prep_qubits=None, prep_basis='SIC'):
"""
Generate a dictionary of process tomography experiment configurations.
This returns a data structure that is used by other tomography functions
to generate state and process tomography circuits, and extract tomography
data from results after execution on a backend.
A quantum process tomography set is created by specifying a preparation
basis along with a measurement basis. The preparation basis may be a
user defined `tomography_basis`, or one of the two built in basis 'SIC'
or 'Pauli'.
- SIC: Is a minimal symmetric informationally complete preparation
basis for 4 states for each qubit (4 ^ number of qubits total
preparation states). These correspond to the |0> state and the 3
other vertices of a tetrahedron on the Bloch-sphere.
- Pauli: Is a tomographically overcomplete preparation basis of the six
eigenstates of the 3 Pauli operators (6 ^ number of qubits
total preparation states).
Args:
meas_qubits (list): The qubits being measured.
meas_basis (tomography_basis or str): The qubit measurement basis.
The default value is 'Pauli'.
prep_qubits (list or None): The qubits being prepared. If None then
meas_qubits will be used for process tomography experiments.
prep_basis (tomography_basis or str): The qubit preparation basis.
The default value is 'SIC'.
Returns:
dict: A dict of tomography configurations that can be parsed by
`create_tomography_circuits` and `tomography_data` functions
for implementing quantum tomography experiments. This output contains
fields "qubits", "meas_basis", "prep_basus", circuits".
```
{
'qubits': qubits (list[ints]),
'meas_basis': meas_basis (tomography_basis),
'prep_basis': prep_basis (tomography_basis),
'circuit_labels': (list[string]),
'circuits': (list[dict]) # prep and meas configurations
}
```
"""
return tomography_set(meas_qubits, meas_basis=meas_basis,
prep_qubits=prep_qubits, prep_basis=prep_basis)
def tomography_circuit_names(tomo_set, name=''):
"""
Return a list of tomography circuit names.
The returned list is the same as the one returned by
`create_tomography_circuits` and can be used by a QuantumProgram
to execute tomography circuits and extract measurement results.
Args:
tomo_set (tomography_set): a tomography set generated by
`tomography_set`.
name (str): the name of the base QuantumCircuit used by the
tomography experiment.
Returns:
list: A list of circuit names.
"""
return [name + l for l in tomo_set['circuit_labels']]
###############################################################################
# Tomography circuit generation
###############################################################################
def create_tomography_circuits(circuit, qreg, creg, tomoset):
"""
Add tomography measurement circuits to a QuantumProgram.
The quantum program must contain a circuit 'name', which is treated as a
state preparation circuit for state tomography, or as teh circuit being
measured for process tomography. This function then appends the circuit
with a set of measurements specified by the input `tomography_set`,
optionally it also prepends the circuit with state preparation circuits if
they are specified in the `tomography_set`.
For n-qubit tomography with a tomographically complete set of preparations
and measurements this results in $4^n 3^n$ circuits being added to the
quantum program.
Args:
circuit (QuantumCircuit): The circuit to be appended with tomography
state preparation and/or measurements.
qreg (QuantumRegister): the quantum register containing qubits to be
measured.
creg (ClassicalRegister): the classical register containing bits to
store measurement outcomes.
tomoset (tomography_set): the dict of tomography configurations.
Returns:
list: A list of quantum tomography circuits for the input circuit.
Raises:
QiskitError: if circuit is not a valid QuantumCircuit
Example:
For a tomography set specifying state tomography of qubit-0 prepared
by a circuit 'circ' this would return:
```
['circ_meas_X(0)', 'circ_meas_Y(0)', 'circ_meas_Z(0)']
```
For process tomography of the same circuit with preparation in the
SIC-POVM basis it would return:
```
[
'circ_prep_S0(0)_meas_X(0)', 'circ_prep_S0(0)_meas_Y(0)',
'circ_prep_S0(0)_meas_Z(0)', 'circ_prep_S1(0)_meas_X(0)',
'circ_prep_S1(0)_meas_Y(0)', 'circ_prep_S1(0)_meas_Z(0)',
'circ_prep_S2(0)_meas_X(0)', 'circ_prep_S2(0)_meas_Y(0)',
'circ_prep_S2(0)_meas_Z(0)', 'circ_prep_S3(0)_meas_X(0)',
'circ_prep_S3(0)_meas_Y(0)', 'circ_prep_S3(0)_meas_Z(0)'
]
```
"""
if not isinstance(circuit, QuantumCircuit):
raise QiskitError('Input circuit must be a QuantumCircuit object')
dics = tomoset['circuits']
labels = tomography_circuit_names(tomoset, circuit.name)
tomography_circuits = []
for label, conf in zip(labels, dics):
tmp = circuit
# Add prep circuits
if 'prep' in conf:
prep = QuantumCircuit(qreg, creg, name='tmp_prep')
for qubit, op in conf['prep'].items():
tomoset['prep_basis'].prep_gate(prep, qreg[qubit], op)
prep.barrier(qreg[qubit]) # pylint: disable=no-member
tmp = prep + tmp
# Add measurement circuits
meas = QuantumCircuit(qreg, creg, name='tmp_meas')
for qubit, op in conf['meas'].items():
meas.barrier(qreg[qubit]) # pylint: disable=no-member
tomoset['meas_basis'].meas_gate(meas, qreg[qubit], op)
meas.measure(qreg[qubit], creg[qubit])
tmp = tmp + meas
# Add label to the circuit
tmp.name = label
tomography_circuits.append(tmp)
logger.info('>> created tomography circuits for "%s"', circuit.name)
return tomography_circuits
###############################################################################
# Get results data
###############################################################################
def tomography_data(results, name, tomoset):
"""
Return a results dict for a state or process tomography experiment.
Args:
results (Result): Results from execution of a process tomography
circuits on a backend.
name (string): The name of the circuit being reconstructed.
tomoset (tomography_set): the dict of tomography configurations.
Returns:
list: A list of dicts for the outcome of each process tomography
measurement circuit.
"""
labels = tomography_circuit_names(tomoset, name)
circuits = tomoset['circuits']
data = []
prep = None
for j, _ in enumerate(labels):
counts = marginal_counts(results.get_counts(labels[j]),
tomoset['qubits'])
shots = sum(counts.values())
meas = circuits[j]['meas']
prep = circuits[j].get('prep', None)
meas_qubits = sorted(meas.keys())
if prep:
prep_qubits = sorted(prep.keys())
circuit = {}
for c in counts.keys():
circuit[c] = {}
circuit[c]['meas'] = [(meas[meas_qubits[k]], int(c[-1 - k]))
for k in range(len(meas_qubits))]
if prep:
circuit[c]['prep'] = [prep[prep_qubits[k]]
for k in range(len(prep_qubits))]
data.append({'counts': counts, 'shots': shots, 'circuit': circuit})
ret = {'data': data, 'meas_basis': tomoset['meas_basis']}
if prep:
ret['prep_basis'] = tomoset['prep_basis']
return ret
def marginal_counts(counts, meas_qubits):
"""
Compute the marginal counts for a subset of measured qubits.
Args:
counts (dict): the counts returned from a backend ({str: int}).
meas_qubits (list[int]): the qubits to return the marginal
counts distribution for.
Returns:
dict: A counts dict for the meas_qubits.abs
Example: if `counts = {'00': 10, '01': 5}`
`marginal_counts(counts, [0])` returns `{'0': 15, '1': 0}`.
`marginal_counts(counts, [0])` returns `{'0': 10, '1': 5}`.
"""
# pylint: disable=cell-var-from-loop
# Extract total number of qubits from count keys
num_of_qubits = len(list(counts.keys())[0])
# keys for measured qubits only
qs = sorted(meas_qubits, reverse=True)
meas_keys = count_keys(len(qs))
# get regex match strings for summing outcomes of other qubits
rgx = [
reduce(lambda x, y: (key[qs.index(y)] if y in qs else '\\d') + x,
range(num_of_qubits), '') for key in meas_keys
]
# build the return list
meas_counts = []
for m in rgx:
c = 0
for key, val in counts.items():
if match(m, key):
c += val
meas_counts.append(c)
# return as counts dict on measured qubits only
return dict(zip(meas_keys, meas_counts))
def count_keys(n):
"""Generate outcome bitstrings for n-qubits.
Args:
n (int): the number of qubits.
Returns:
list: A list of bitstrings ordered as follows:
Example: n=2 returns ['00', '01', '10', '11'].
"""
return [bin(j)[2:].zfill(n) for j in range(2**n)]
###############################################################################
# Tomographic Reconstruction functions.
###############################################################################
def fit_tomography_data(tomo_data, method='wizard', options=None):
"""
Reconstruct a density matrix or process-matrix from tomography data.
If the input data is state_tomography_data the returned operator will
be a density matrix. If the input data is process_tomography_data the
returned operator will be a Choi-matrix in the column-vectorization
convention.
Args:
tomo_data (dict): process tomography measurement data.
method (str): the fitting method to use.
Available methods:
- 'wizard' (default)
- 'leastsq'
options (dict or None): additional options for fitting method.
Returns:
numpy.array: The fitted operator.
Available methods:
- 'wizard' (Default): The returned operator will be constrained to be
positive-semidefinite.
Options:
- 'trace': the trace of the returned operator.
The default value is 1.
- 'beta': hedging parameter for computing frequencies from
zero-count data. The default value is 0.50922.
- 'epsilon: threshold for truncating small eigenvalues to zero.
The default value is 0
- 'leastsq': Fitting without positive-semidefinite constraint.
Options:
- 'trace': Same as for 'wizard' method.
- 'beta': Same as for 'wizard' method.
Raises:
Exception: if the `method` parameter is not valid.
"""
if isinstance(method, str) and method.lower() in ['wizard', 'leastsq']:
# get options
trace = __get_option('trace', options)
beta = __get_option('beta', options)
# fit state
rho = __leastsq_fit(tomo_data, trace=trace, beta=beta)
if method == 'wizard':
# Use wizard method to constrain positivity
epsilon = __get_option('epsilon', options)
rho = __wizard(rho, epsilon=epsilon)
return rho
else:
raise Exception('Invalid reconstruction method "%s"' % method)
def __get_option(opt, options):
"""
Return an optional value or None if not found.
"""
if options is not None:
if opt in options:
return options[opt]
return None
###############################################################################
# Fit Method: Linear Inversion
###############################################################################
def __leastsq_fit(tomo_data, weights=None, trace=None, beta=None):
"""
Reconstruct a state from unconstrained least-squares fitting.
Args:
tomo_data (list[dict]): state or process tomography data.
weights (list or array or None): weights to use for least squares
fitting. The default is standard deviation from a binomial
distribution.
trace (float or None): trace of returned operator. The default is 1.
beta (float or None): hedge parameter (>=0) for computing frequencies
from zero-count data. The default value is 0.50922.
Returns:
numpy.array: A numpy array of the reconstructed operator.
"""
if trace is None:
trace = 1. # default to unit trace
data = tomo_data['data']
keys = data[0]['circuit'].keys()
# Get counts and shots
counts = []
shots = []
ops = []
for dat in data:
for key in keys:
counts.append(dat['counts'][key])
shots.append(dat['shots'])
projectors = dat['circuit'][key]
op = __projector(projectors['meas'], tomo_data['meas_basis'])
if 'prep' in projectors:
op_prep = __projector(projectors['prep'],
tomo_data['prep_basis'])
op = np.kron(op_prep.conj(), op)
ops.append(op)
# Convert counts to frequencies
counts = np.array(counts)
shots = np.array(shots)
freqs = counts / shots
# Use hedged frequencies to calculate least squares fitting weights
if weights is None:
if beta is None:
beta = 0.50922
K = len(keys)
freqs_hedged = (counts + beta) / (shots + K * beta)
weights = np.sqrt(shots / (freqs_hedged * (1 - freqs_hedged)))
return __tomo_linear_inv(freqs, ops, weights, trace=trace)
def __projector(op_list, basis):
"""Returns a projectors.
"""
ret = 1
# list is from qubit 0 to 1
for op in op_list:
label, eigenstate = op
ret = np.kron(basis[label][eigenstate], ret)
return ret
def __tomo_linear_inv(freqs, ops, weights=None, trace=None):
"""
Reconstruct a matrix through linear inversion.
Args:
freqs (list[float]): list of observed frequences.
ops (list[np.array]): list of corresponding projectors.
weights (list[float] or array_like):
weights to be used for weighted fitting.
trace (float or None): trace of returned operator.
Returns:
numpy.array: A numpy array of the reconstructed operator.
"""
# get weights matrix
if weights is not None:
W = np.array(weights)
if W.ndim == 1:
W = np.diag(W)
# Get basis S matrix
S = np.array([vectorize(m).conj()
for m in ops]).reshape(len(ops), ops[0].size)
if weights is not None:
S = np.dot(W, S) # W.S
# get frequencies vec
v = np.array(freqs) # |f>
if weights is not None:
v = np.dot(W, freqs) # W.|f>
Sdg = S.T.conj() # S^*.W^*
inv = np.linalg.pinv(np.dot(Sdg, S)) # (S^*.W^*.W.S)^-1
# linear inversion of freqs
ret = devectorize(np.dot(inv, np.dot(Sdg, v)))
# renormalize to input trace value
if trace is not None:
ret = trace * ret / np.trace(ret)
return ret
###############################################################################
# Fit Method: Wizard
###############################################################################
def __wizard(rho, epsilon=None):
"""
Returns the nearest positive semidefinite operator to an operator.
This method is based on reference [1]. It constrains positivity
by setting negative eigenvalues to zero and rescaling the positive
eigenvalues.
Args:
rho (array_like): the input operator.
epsilon(float or None): threshold (>=0) for truncating small
eigenvalues values to zero.
Returns:
numpy.array: A positive semidefinite numpy array.
"""
if epsilon is None:
epsilon = 0. # default value
dim = len(rho)
rho_wizard = np.zeros([dim, dim])
v, w = np.linalg.eigh(rho) # v eigenvecrors v[0] < v[1] <...
for j in range(dim):
if v[j] < epsilon:
tmp = v[j]
v[j] = 0.
# redistribute loop
x = 0.
for k in range(j + 1, dim):
x += tmp / (dim - (j + 1))
v[k] = v[k] + tmp / (dim - (j + 1))
for j in range(dim):
rho_wizard = rho_wizard + v[j] * outer(w[:, j])
return rho_wizard
###############################################################
# Wigner function tomography
###############################################################
def build_wigner_circuits(circuit, phis, thetas, qubits,
qreg, creg):
"""Create the circuits to rotate to points in phase space
Args:
circuit (QuantumCircuit): The circuit to be appended with tomography
state preparation and/or measurements.
phis (np.matrix[[complex]]): phis
thetas (np.matrix[[complex]]): thetas
qubits (list[int]): a list of the qubit indexes of qreg to be measured.
qreg (QuantumRegister): the quantum register containing qubits to be
measured.
creg (ClassicalRegister): the classical register containing bits to
store measurement outcomes.
Returns:
list: A list of names of the added wigner function circuits.
Raises:
QiskitError: if circuit is not a valid QuantumCircuit.
"""
if not isinstance(circuit, QuantumCircuit):
raise QiskitError('Input circuit must be a QuantumCircuit object')
tomography_circuits = []
points = len(phis[0])
for point in range(points):
label = '_wigner_phase_point'
label += str(point)
tmp_circ = QuantumCircuit(qreg, creg, name=label)
for qubit, _ in enumerate(qubits):
tmp_circ.u3(thetas[qubit][point], 0, # pylint: disable=no-member
phis[qubit][point], qreg[qubits[qubit]])
tmp_circ.measure(qreg[qubits[qubit]], creg[qubits[qubit]])
# Add to original circuit
tmp_circ = circuit + tmp_circ
tmp_circ.name = circuit.name + label
tomography_circuits.append(tmp_circ)
logger.info('>> Created Wigner function circuits for "%s"', circuit.name)
return tomography_circuits
def wigner_data(q_result, meas_qubits, labels, shots=None):
"""Get the value of the Wigner function from measurement results.
Args:
q_result (Result): Results from execution of a state tomography
circuits on a backend.
meas_qubits (list[int]): a list of the qubit indexes measured.
labels (list[str]): a list of names of the circuits
shots (int): number of shots
Returns:
list: The values of the Wigner function at measured points in
phase space
"""
num = len(meas_qubits)
dim = 2**num
p = [0.5 + 0.5 * np.sqrt(3), 0.5 - 0.5 * np.sqrt(3)]
parity = 1
for i in range(num):
parity = np.kron(parity, p)
w = [0] * len(labels)
wpt = 0
counts = [marginal_counts(q_result.get_counts(circ), meas_qubits)
for circ in labels]
for entry in counts:
x = [0] * dim
for i in range(dim):
if bin(i)[2:].zfill(num) in entry:
x[i] = float(entry[bin(i)[2:].zfill(num)])
if shots is None:
shots = np.sum(x)
for i in range(dim):
w[wpt] = w[wpt] + (x[i] / shots) * parity[i]
wpt += 1
return w
<|code_end|>
|
Handling old-format jobs (test_get_jobs_filter_job_status)
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Information
We are experiencing some intermitent failures at `test.python.ibmq.test_ibmqjob.TestIBMQJob.test_get_jobs_filter_job_status` (specifically, seems to happen at premium):
https://travis-ci.org/Qiskit/qiskit-terra/jobs/461104008
```
1: b'Traceback (most recent call last):'
1: b' File "/home/travis/build/Qiskit/qiskit-terra/test/python/ibmq/test_ibmqjob.py", line 283, in test_get_jobs_filter_job_status'
1: b" self.log.info('match #%d: %s', i, job.result().status)"
1: b' File "/home/travis/build/Qiskit/qiskit-terra/qiskit/backends/ibmq/ibmqjob.py", line 210, in result'
1: b' return self._result_from_job_response(job_response)'
1: b' File "/home/travis/build/Qiskit/qiskit-terra/qiskit/backends/ibmq/ibmqjob.py", line 506, in _result_from_job_response'
1: b' _reorder_bits(job_response)'
1: b' File "/home/travis/build/Qiskit/qiskit-terra/qiskit/backends/ibmq/ibmqjob.py", line 546, in _reorder_bits'
1: b" for circuit_result in job_data['qasms']:"
1: b"KeyError: 'qasms'"
1: b''
```
This seems to be because of the co-existence of different formats currently, and sort of accounted for - by 0.7, all jobs created and stored should have the same format. However, we should provide a cleaner way of dealing with pre-0.7 style jobs, revising the functions that retrieve them from the API (and emitting a warning if an old-style job cannot be parsed or similar).
### What is the expected behavior?
### Suggested solutions
|
qiskit/backends/ibmq/ibmqbackend.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""IbmQ module
This module is used for connecting to the Quantum Experience.
"""
import logging
from marshmallow import ValidationError
from qiskit import QiskitError
from qiskit.backends import BaseBackend, JobStatus
from qiskit.backends.models import BackendStatus, BackendProperties
from .api import ApiError
from .ibmqjob import IBMQJob, IBMQJobPreQobj
logger = logging.getLogger(__name__)
class IBMQBackend(BaseBackend):
"""Backend class interfacing with the Quantum Experience remotely.
"""
def __init__(self, configuration, provider, credentials, api):
"""Initialize remote backend for IBM Quantum Experience.
Args:
configuration (BackendConfiguration): configuration of backend.
provider (IBMQProvider): provider.
credentials (Credentials): credentials.
api (IBMQConnector):
api for communicating with the Quantum Experience.
"""
super().__init__(provider=provider, configuration=configuration)
self._api = api
self._credentials = credentials
self.hub = credentials.hub
self.group = credentials.group
self.project = credentials.project
def run(self, qobj):
"""Run qobj asynchronously.
Args:
qobj (dict): description of job
Returns:
IBMQJob: an instance derived from BaseJob
"""
job_class = _job_class_from_backend_support(self)
job = job_class(self, None, self._api,
not self.configuration().simulator, qobj=qobj)
job.submit()
return job
def properties(self):
"""Return the online backend properties.
The return is via QX API call.
Returns:
BackendProperties: The properties of the backend. If the backend
is a simulator, it returns ``None``.
"""
if self.configuration().simulator:
return None
api_properties = self._api.backend_properties(self.name())
return BackendProperties.from_dict(api_properties)
def status(self):
"""Return the online backend status.
Returns:
BackendStatus: The status of the backend.
Raises:
LookupError: If status for the backend can't be found.
IBMQBackendError: If the status can't be formatted properly.
"""
api_status = self._api.backend_status(self.name())
try:
return BackendStatus.from_dict(api_status)
except ValidationError as ex:
raise LookupError(
"Couldn't get backend status: {0}".format(ex))
def jobs(self, limit=50, skip=0, status=None, db_filter=None):
"""Attempt to get the jobs submitted to the backend.
Args:
limit (int): number of jobs to retrieve
skip (int): starting index of retrieval
status (None or JobStatus or str): only get jobs with this status,
where status is e.g. `JobStatus.RUNNING` or `'RUNNING'`
db_filter (dict): `loopback-based filter
<https://loopback.io/doc/en/lb2/Querying-data.html>`_.
This is an interface to a database ``where`` filter. Some
examples of its usage are:
Filter last five jobs with errors::
job_list = backend.jobs(limit=5, status=JobStatus.ERROR)
Filter last five jobs with counts=1024, and counts for
states ``00`` and ``11`` each exceeding 400::
cnts_filter = {'shots': 1024,
'qasms.result.data.counts.00': {'gt': 400},
'qasms.result.data.counts.11': {'gt': 400}}
job_list = backend.jobs(limit=5, db_filter=cnts_filter)
Filter last five jobs from 30 days ago::
past_date = datetime.datetime.now() - datetime.timedelta(days=30)
date_filter = {'creationDate': {'lt': past_date.isoformat()}}
job_list = backend.jobs(limit=5, db_filter=date_filter)
Returns:
list(IBMQJob): list of IBMQJob instances
Raises:
IBMQBackendValueError: status keyword value unrecognized
"""
backend_name = self.name()
api_filter = {'backend.name': backend_name}
if status:
if isinstance(status, str):
status = JobStatus[status]
if status == JobStatus.RUNNING:
this_filter = {'status': 'RUNNING',
'infoQueue': {'exists': False}}
elif status == JobStatus.QUEUED:
this_filter = {'status': 'RUNNING',
'infoQueue.status': 'PENDING_IN_QUEUE'}
elif status == JobStatus.CANCELLED:
this_filter = {'status': 'CANCELLED'}
elif status == JobStatus.DONE:
this_filter = {'status': 'COMPLETED'}
elif status == JobStatus.ERROR:
this_filter = {'status': {'regexp': '^ERROR'}}
else:
raise IBMQBackendValueError('unrecognized value for "status" keyword '
'in job filter')
api_filter.update(this_filter)
if db_filter:
# status takes precedence over db_filter for same keys
api_filter = {**db_filter, **api_filter}
job_info_list = self._api.get_status_jobs(limit=limit, skip=skip,
filter=api_filter)
job_list = []
for job_info in job_info_list:
job_class = _job_class_from_job_response(job_info)
is_device = not bool(self.configuration().simulator)
job = job_class(self, job_info.get('id'), self._api, is_device,
creation_date=job_info.get('creationDate'),
api_status=job_info.get('status'))
job_list.append(job)
return job_list
def retrieve_job(self, job_id):
"""Attempt to get the specified job by job_id
Args:
job_id (str): the job id of the job to retrieve
Returns:
IBMQJob: class instance
Raises:
IBMQBackendError: if retrieval failed
"""
try:
job_info = self._api.get_status_job(job_id)
if 'error' in job_info:
raise IBMQBackendError('Failed to get job "{}": {}'
.format(job_id, job_info['error']))
except ApiError as ex:
raise IBMQBackendError('Failed to get job "{}":{}'
.format(job_id, str(ex)))
job_class = _job_class_from_job_response(job_info)
is_device = not bool(self.configuration().simulator)
job = job_class(self, job_info.get('id'), self._api, is_device,
creation_date=job_info.get('creationDate'),
api_status=job_info.get('status'))
return job
def __repr__(self):
credentials_info = ''
if self.hub:
credentials_info = '{}, {}, {}'.format(self.hub, self.group,
self.project)
return "<{}('{}') from IBMQ({})>".format(
self.__class__.__name__, self.name(), credentials_info)
class IBMQBackendError(QiskitError):
"""IBM Q Backend Errors"""
pass
class IBMQBackendValueError(IBMQBackendError, ValueError):
""" Value errors thrown within IBMQBackend """
pass
def _job_class_from_job_response(job_response):
is_qobj = job_response.get('kind', None) == 'q-object'
return IBMQJob if is_qobj else IBMQJobPreQobj
def _job_class_from_backend_support(backend):
support_qobj = getattr(backend.configuration(), 'allow_q_object', False)
return IBMQJob if support_qobj else IBMQJobPreQobj
<|code_end|>
|
qiskit/backends/ibmq/ibmqbackend.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""IbmQ module
This module is used for connecting to the Quantum Experience.
"""
import logging
import warnings
from marshmallow import ValidationError
from qiskit import QiskitError
from qiskit.backends import BaseBackend, JobStatus, JobError
from qiskit.backends.models import BackendStatus, BackendProperties
from .api import ApiError
from .ibmqjob import IBMQJob, IBMQJobPreQobj
logger = logging.getLogger(__name__)
class IBMQBackend(BaseBackend):
"""Backend class interfacing with the Quantum Experience remotely.
"""
def __init__(self, configuration, provider, credentials, api):
"""Initialize remote backend for IBM Quantum Experience.
Args:
configuration (BackendConfiguration): configuration of backend.
provider (IBMQProvider): provider.
credentials (Credentials): credentials.
api (IBMQConnector):
api for communicating with the Quantum Experience.
"""
super().__init__(provider=provider, configuration=configuration)
self._api = api
self._credentials = credentials
self.hub = credentials.hub
self.group = credentials.group
self.project = credentials.project
def run(self, qobj):
"""Run qobj asynchronously.
Args:
qobj (dict): description of job
Returns:
IBMQJob: an instance derived from BaseJob
"""
job_class = _job_class_from_backend_support(self)
job = job_class(self, None, self._api,
not self.configuration().simulator, qobj=qobj)
job.submit()
return job
def properties(self):
"""Return the online backend properties.
The return is via QX API call.
Returns:
BackendProperties: The properties of the backend. If the backend
is a simulator, it returns ``None``.
"""
if self.configuration().simulator:
return None
api_properties = self._api.backend_properties(self.name())
return BackendProperties.from_dict(api_properties)
def status(self):
"""Return the online backend status.
Returns:
BackendStatus: The status of the backend.
Raises:
LookupError: If status for the backend can't be found.
IBMQBackendError: If the status can't be formatted properly.
"""
api_status = self._api.backend_status(self.name())
try:
return BackendStatus.from_dict(api_status)
except ValidationError as ex:
raise LookupError(
"Couldn't get backend status: {0}".format(ex))
def jobs(self, limit=50, skip=0, status=None, db_filter=None):
"""Attempt to get the jobs submitted to the backend.
Args:
limit (int): number of jobs to retrieve
skip (int): starting index of retrieval
status (None or JobStatus or str): only get jobs with this status,
where status is e.g. `JobStatus.RUNNING` or `'RUNNING'`
db_filter (dict): `loopback-based filter
<https://loopback.io/doc/en/lb2/Querying-data.html>`_.
This is an interface to a database ``where`` filter. Some
examples of its usage are:
Filter last five jobs with errors::
job_list = backend.jobs(limit=5, status=JobStatus.ERROR)
Filter last five jobs with counts=1024, and counts for
states ``00`` and ``11`` each exceeding 400::
cnts_filter = {'shots': 1024,
'qasms.result.data.counts.00': {'gt': 400},
'qasms.result.data.counts.11': {'gt': 400}}
job_list = backend.jobs(limit=5, db_filter=cnts_filter)
Filter last five jobs from 30 days ago::
past_date = datetime.datetime.now() - datetime.timedelta(days=30)
date_filter = {'creationDate': {'lt': past_date.isoformat()}}
job_list = backend.jobs(limit=5, db_filter=date_filter)
Returns:
list(IBMQJob): list of IBMQJob instances
Raises:
IBMQBackendValueError: status keyword value unrecognized
"""
backend_name = self.name()
api_filter = {'backend.name': backend_name}
if status:
if isinstance(status, str):
status = JobStatus[status]
if status == JobStatus.RUNNING:
this_filter = {'status': 'RUNNING',
'infoQueue': {'exists': False}}
elif status == JobStatus.QUEUED:
this_filter = {'status': 'RUNNING',
'infoQueue.status': 'PENDING_IN_QUEUE'}
elif status == JobStatus.CANCELLED:
this_filter = {'status': 'CANCELLED'}
elif status == JobStatus.DONE:
this_filter = {'status': 'COMPLETED'}
elif status == JobStatus.ERROR:
this_filter = {'status': {'regexp': '^ERROR'}}
else:
raise IBMQBackendValueError('unrecognized value for "status" keyword '
'in job filter')
api_filter.update(this_filter)
if db_filter:
# status takes precedence over db_filter for same keys
api_filter = {**db_filter, **api_filter}
job_info_list = self._api.get_status_jobs(limit=limit, skip=skip,
filter=api_filter)
job_list = []
for job_info in job_info_list:
job_class = _job_class_from_job_response(job_info)
if job_class is IBMQJobPreQobj:
warnings.warn('The result of job {} is in an old and no longer supported format, '
'please resend the job with Qiskit 0.7'.format(job_info.get('id')),
DeprecationWarning)
continue
is_device = not bool(self.configuration().simulator)
job = job_class(self, job_info.get('id'), self._api, is_device,
creation_date=job_info.get('creationDate'),
api_status=job_info.get('status'))
job_list.append(job)
return job_list
def retrieve_job(self, job_id):
"""Attempt to get the specified job by job_id
Args:
job_id (str): the job id of the job to retrieve
Returns:
IBMQJob: class instance
Raises:
IBMQBackendError: if retrieval failed
DeprecatedFormatJobError: if the job retrieved has a format pre 0.7
"""
try:
job_info = self._api.get_status_job(job_id)
if 'error' in job_info:
raise IBMQBackendError('Failed to get job "{}": {}'
.format(job_id, job_info['error']))
except ApiError as ex:
raise IBMQBackendError('Failed to get job "{}":{}'
.format(job_id, str(ex)))
job_class = _job_class_from_job_response(job_info)
if job_class is IBMQJobPreQobj:
raise DeprecatedFormatJobError('The result of job {} is in an old and no '
'longer supported format, please resend the '
'job with Qiskit 0.7'.format(job_id))
is_device = not bool(self.configuration().simulator)
job = job_class(self, job_info.get('id'), self._api, is_device,
creation_date=job_info.get('creationDate'),
api_status=job_info.get('status'))
return job
def __repr__(self):
credentials_info = ''
if self.hub:
credentials_info = '{}, {}, {}'.format(self.hub, self.group,
self.project)
return "<{}('{}') from IBMQ({})>".format(
self.__class__.__name__, self.name(), credentials_info)
class IBMQBackendError(QiskitError):
"""IBM Q Backend Errors"""
pass
class IBMQBackendValueError(IBMQBackendError, ValueError):
"""Value errors thrown within IBMQBackend """
pass
class DeprecatedFormatJobError(JobError):
"""Retrieving responses pre-qobj is no longer supported."""
pass
def _job_class_from_job_response(job_response):
is_qobj = job_response.get('kind', None) == 'q-object'
return IBMQJob if is_qobj else IBMQJobPreQobj
def _job_class_from_backend_support(backend):
support_qobj = getattr(backend.configuration(), 'allow_q_object', False)
return IBMQJob if support_qobj else IBMQJobPreQobj
<|code_end|>
|
BasicMapper error with measurements
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**:
- **Python version**:
- **Operating system**:
### What is the current behavior?
```python
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import Aer
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import BasicMapper
from qiskit.transpiler import transpile
from qiskit.mapper import Coupling
coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
qr = QuantumRegister(7, 'q')
cr = ClassicalRegister(7, 'c')
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[3])
circuit.cx(qr[0], qr[6])
circuit.cx(qr[6], qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[3], qr[1])
circuit.cx(qr[3], qr[0])
circuit.measure(qr, cr)
simulator = Aer.get_backend('qasm_simulator')
coupling_map = Coupling(couplinglist=coupling)
pass_manager = PassManager()
pass_manager.add_passes([BasicMapper(coupling_map=coupling_map)])
basic_circ = transpile(circuit, simulator, pass_manager=pass_manager)
```
|
qiskit/dagcircuit/_dagcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Object to represent a quantum circuit as a directed acyclic graph.
The nodes in the graph are either input/output nodes or operation nodes.
The operation nodes are elements of a basis that is part of the circuit.
The QASM definitions of the basis elements are carried with the circuit.
The edges correspond to qubits or bits in the circuit. A directed edge
from node A to node B means that the (qu)bit passes from the output of A
to the input of B. The object's methods allow circuits to be constructed,
composed, and modified. Some natural properties like depth can be computed
directly from the graph.
"""
import re
from collections import OrderedDict
import copy
import itertools
import networkx as nx
from qiskit import QuantumRegister, ClassicalRegister
from qiskit.circuit import Gate
from ._dagcircuiterror import DAGCircuitError
class DAGCircuit:
"""
Quantum circuit as a directed acyclic graph.
There are 3 types of nodes in the graph: inputs, outputs, and operations.
The nodes are connected by directed edges that correspond to qubits and
bits.
"""
# pylint: disable=invalid-name
def __init__(self):
"""Create an empty circuit."""
# Circuit name. Generally, this corresponds to the name
# of the QuantumCircuit from which the DAG was generated.
self.name = None
# Set of wires (Register,idx) in the dag
self.wires = []
# Map from wire (Register,idx) to input nodes of the graph
self.input_map = OrderedDict()
# Map from wire (Register,idx) to output nodes of the graph
self.output_map = OrderedDict()
# Running count of the total number of nodes
self.node_counter = 0
# Map of user defined gates to ast nodes defining them
self.gates = OrderedDict()
# Map of named operations in this circuit and their signatures.
# The signature is an integer tuple (nq,nc,np) specifying the
# number of input qubits, input bits, and real parameters.
# The definition is external to the circuit object.
self.basis = OrderedDict()
self.add_basis_element(name="U", number_qubits=1,
number_classical=0, number_parameters=3)
self.add_basis_element("CX", 2, 0, 0)
self.add_basis_element("measure", 1, 1, 0)
self.add_basis_element("reset", 1, 0, 0)
self.add_basis_element("barrier", -1)
# Directed multigraph whose nodes are inputs, outputs, or operations.
# Operation nodes have equal in- and out-degrees and carry
# additional data about the operation, including the argument order
# and parameter values.
# Input nodes have out-degree 1 and output nodes have in-degree 1.
# Edges carry wire labels (reg,idx) and each operation has
# corresponding in- and out-edges with the same wire labels.
self.multi_graph = nx.MultiDiGraph()
# Map of qreg name to QuantumRegister object
self.qregs = OrderedDict()
# Map of creg name to ClassicalRegister object
self.cregs = OrderedDict()
# layout of dag quantum registers on the chip
# TODO: rethink this. doesn't seem related to concept of DAG,
# but if we want to be able to generate qobj
# directly from a dag, we need it.
self.layout = []
def get_qubits(self):
"""Return a list of qubits as (QuantumRegister, index) pairs."""
return [(v, i) for k, v in self.qregs.items() for i in range(v.size)]
# TODO: unused function. is it needed?
def rename_register(self, regname, newname):
"""Rename a classical or quantum register throughout the circuit.
regname = existing register name string
newname = replacement register name string
"""
if regname == newname:
return
if newname in self.qregs or newname in self.cregs:
raise DAGCircuitError("duplicate register name %s" % newname)
if regname not in self.qregs and regname not in self.cregs:
raise DAGCircuitError("no register named %s" % regname)
if regname in self.qregs:
reg = self.qregs[regname]
reg.name = newname
self.qregs[newname] = reg
self.qregs.pop(regname, None)
if regname in self.cregs:
reg = self.cregs[regname]
reg.name = newname
self.qregs[newname] = reg
self.qregs.pop(regname, None)
# n node d = data
for _, d in self.multi_graph.nodes(data=True):
if d["type"] == "in" or d["type"] == "out":
if regname in d["name"]:
d["name"] = re.sub(regname, newname, d["name"])
elif d["type"] == "op":
qa = []
for a in d["qargs"]:
if a[0] == regname:
a = (newname, a[1])
qa.append(a)
d["qargs"] = qa
ca = []
for a in d["cargs"]:
if a[0] == regname:
a = (newname, a[1])
ca.append(a)
d["cargs"] = ca
if d["condition"] is not None:
if d["condition"][0] == regname:
d["condition"] = (newname, d["condition"][1])
# eX = edge, d= data
for _, _, d in self.multi_graph.edges(data=True):
if regname in d["name"]:
d["name"] = re.sub(regname, newname, d["name"])
def remove_all_ops_named(self, opname):
"""Remove all operation nodes with the given name."""
for n in self.get_named_nodes(opname):
self._remove_op_node(n)
def add_qreg(self, qreg):
"""Add all wires in a quantum register."""
if not isinstance(qreg, QuantumRegister):
raise DAGCircuitError("not a QuantumRegister instance.")
if qreg.name in self.qregs:
raise DAGCircuitError("duplicate register %s" % qreg.name)
self.qregs[qreg.name] = qreg
for j in range(qreg.size):
self._add_wire((qreg, j))
def add_creg(self, creg):
"""Add all wires in a classical register."""
if not isinstance(creg, ClassicalRegister):
raise DAGCircuitError("not a ClassicalRegister instance.")
if creg.name in self.cregs:
raise DAGCircuitError("duplicate register %s" % creg.name)
self.cregs[creg.name] = creg
for j in range(creg.size):
self._add_wire((creg, j))
def _add_wire(self, wire):
"""Add a qubit or bit to the circuit.
Args:
wire (tuple): (Register,int) containing a register instance and index
This adds a pair of in and out nodes connected by an edge.
Raises:
DAGCircuitError: if trying to add duplicate wire
"""
if wire not in self.wires:
self.wires.append(wire)
self.node_counter += 1
self.input_map[wire] = self.node_counter
self.node_counter += 1
self.output_map[wire] = self.node_counter
in_node = self.input_map[wire]
out_node = self.output_map[wire]
self.multi_graph.add_edge(in_node, out_node)
self.multi_graph.node[in_node]["type"] = "in"
self.multi_graph.node[out_node]["type"] = "out"
self.multi_graph.node[in_node]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.node[out_node]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.node[in_node]["wire"] = wire
self.multi_graph.node[out_node]["wire"] = wire
self.multi_graph.adj[in_node][out_node][0]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.adj[in_node][out_node][0]["wire"] = wire
else:
raise DAGCircuitError("duplicate wire %s" % (wire,))
def add_basis_element(self, name, number_qubits,
number_classical=0, number_parameters=0):
"""Add an operation to the basis.
name is string label for operation
number_qubits is number of qubit arguments
number_classical is number of bit arguments
number_parameters is number of real parameters
The parameters (nq,nc,np) are ignored for the special case
when name = "barrier". The barrier instruction has a variable
number of qubit arguments.
"""
if name not in self.basis:
self.basis[name] = (
number_qubits,
number_classical,
number_parameters)
if name in self.gates:
if self.gates[name]["n_args"] != number_parameters or \
self.gates[name]["n_bits"] != number_qubits or number_classical != 0:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def add_gate_data(self, name, gatedata):
"""Add the definition of a gate.
gatedata is dict with fields:
"print" = True or False
"opaque" = True or False
"n_args" = number of real parameters
"n_bits" = number of qubits
"args" = list of parameter names
"bits" = list of qubit names
"body" = GateBody AST node
"""
if name not in self.gates:
self.gates[name] = gatedata
if name in self.basis:
if self.basis[name][0] != self.gates[name]["n_bits"] or \
self.basis[name][1] != 0 or \
self.basis[name][2] != self.gates[name]["n_args"]:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def _check_basis_data(self, op, qargs, cargs):
"""Check the arguments against the data for this operation.
Args:
op (Instruction): a quantum operation
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple]): cbits that op will be applied to
Raises:
DAGCircuitError: If the check fails.
"""
# Check that we have this operation
if op.name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations" % op.name)
# Check the number of arguments matches the signature
if op.name in ["barrier"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s" % op.name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s" % op.name)
elif op.name in ["snapshot", "noise", "save", "load"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s" % op.name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s" % op.name)
else:
if len(qargs) != self.basis[op.name][0]:
raise DAGCircuitError("incorrect number of qubits for %s" % op.name)
if len(cargs) != self.basis[op.name][1]:
raise DAGCircuitError("incorrect number of bits for %s" % op.name)
def _check_condition(self, name, condition):
"""Verify that the condition is valid.
Args:
name (string): used for error reporting
condition (tuple or None): a condition tuple (ClassicalRegister,int)
Raises:
DAGCircuitError: if conditioning on an invalid register
"""
# Verify creg exists
if condition is not None and condition[0].name not in self.cregs:
raise DAGCircuitError("invalid creg in condition for %s" % name)
def _check_bits(self, args, amap):
"""Check the values of a list of (qu)bit arguments.
For each element of args, check that amap contains it.
Args:
args (list): (register,idx) tuples
amap (dict): a dictionary keyed on (register,idx) tuples
Raises:
DAGCircuitError: if a qubit is not contained in amap
"""
# Check for each wire
for wire in args:
if wire not in amap:
raise DAGCircuitError("(qu)bit %s not found" % (wire,))
def _bits_in_condition(self, cond):
"""Return a list of bits in the given condition.
Args:
cond (tuple or None): optional condition (ClassicalRegister, int)
Returns:
list[(ClassicalRegister, idx)]: list of bits
"""
all_bits = []
if cond is not None:
all_bits.extend([(cond[0], j) for j in range(self.cregs[cond[0].name].size)])
return all_bits
def _add_op_node(self, op, qargs, cargs, condition=None):
"""Add a new operation node to the graph and assign properties.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list): list of quantum wires to attach to.
cargs (list): list of classical wires to attach to.
condition (tuple or None): optional condition (ClassicalRegister, int)
"""
# Add a new operation node to the graph
self.node_counter += 1
self.multi_graph.add_node(self.node_counter)
# Update the operation itself. TODO: remove after qargs not connected to op
op.qargs = qargs
op.cargs = cargs
# Update that operation node's data
self.multi_graph.node[self.node_counter]["type"] = "op"
self.multi_graph.node[self.node_counter]["op"] = op
self.multi_graph.node[self.node_counter]["name"] = op.name
self.multi_graph.node[self.node_counter]["qargs"] = qargs
self.multi_graph.node[self.node_counter]["cargs"] = cargs
self.multi_graph.node[self.node_counter]["condition"] = condition
def apply_operation_back(self, op, qargs=None, cargs=None, condition=None):
"""Apply an operation to the output of the circuit.
TODO: make `qargs` and `cargs` mandatory, when they are dropped from op.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple]): cbits that op will be applied to
condition (tuple or None): optional condition (ClassicalRegister, int)
Raises:
DAGCircuitError: if a leaf node is connected to multiple outputs
"""
qargs = qargs or op.qargs
cargs = cargs or op.cargs
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(op, qargs, cargs)
self._check_condition(op.name, condition)
self._check_bits(qargs, self.output_map)
self._check_bits(all_cbits, self.output_map)
self._add_op_node(op, qargs, cargs, condition)
# Add new in-edges from predecessors of the output nodes to the
# operation node while deleting the old in-edges of the output nodes
# and adding new edges from the operation node to each output node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.predecessors(self.output_map[q]))
if len(ie) != 1:
raise DAGCircuitError("output node has multiple in-edges")
self.multi_graph.add_edge(ie[0], self.node_counter,
name="%s[%s]" % (q[0].name, q[1]), wire=q)
self.multi_graph.remove_edge(ie[0], self.output_map[q])
self.multi_graph.add_edge(self.node_counter, self.output_map[q],
name="%s[%s]" % (q[0].name, q[1]), wire=q)
def apply_operation_front(self, op, qargs=None, cargs=None, condition=None):
"""Apply an operation to the input of the circuit.
TODO: make `qargs` and `cargs` mandatory, when they are dropped from op.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple]): cbits that op will be applied to
condition (tuple or None): optional condition (ClassicalRegister, value)
Raises:
DAGCircuitError: if initial nodes connected to multiple out edges
"""
qargs = qargs or op.qargs
cargs = cargs or op.cargs
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(op, qargs, cargs)
self._check_condition(op.name, condition)
self._check_bits(qargs, self.input_map)
self._check_bits(all_cbits, self.input_map)
self._add_op_node(op, qargs, cargs, condition)
# Add new out-edges to successors of the input nodes from the
# operation node while deleting the old out-edges of the input nodes
# and adding new edges to the operation node from each input node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.successors(self.input_map[q]))
if len(ie) != 1:
raise DAGCircuitError("input node has multiple out-edges")
self.multi_graph.add_edge(self.node_counter, ie[0],
name="%s[%s]" % (q[0].name, q[1]), wire=q)
self.multi_graph.remove_edge(self.input_map[q], ie[0])
self.multi_graph.add_edge(self.input_map[q], self.node_counter,
name="%s[%s]" % (q[0].name, q[1]), wire=q)
def _make_union_basis(self, input_circuit):
"""Return a new basis map.
The new basis is a copy of self.basis with
new elements of input_circuit.basis added.
input_circuit is a DAGCircuit
"""
union_basis = self.basis.copy()
for g in input_circuit.basis:
if g not in union_basis:
union_basis[g] = input_circuit.basis[g]
if union_basis[g] != input_circuit.basis[g]:
raise DAGCircuitError("incompatible basis")
return union_basis
def _make_union_gates(self, input_circuit):
"""Return a new gates map.
The new gates are a copy of self.gates with
new elements of input_circuit.gates added.
input_circuit is a DAGCircuit
NOTE: gates in input_circuit that are also in self must
be *identical* to the gates in self
"""
union_gates = {}
for k, v in self.gates.items():
union_gates[k] = v
for k, v in input_circuit.gates.items():
if k not in union_gates:
union_gates[k] = v
if union_gates[k]["opaque"] != input_circuit.gates[k]["opaque"] or \
union_gates[k]["n_args"] != input_circuit.gates[k]["n_args"] or \
union_gates[k]["n_bits"] != input_circuit.gates[k]["n_bits"] or \
union_gates[k]["args"] != input_circuit.gates[k]["args"] or \
union_gates[k]["bits"] != input_circuit.gates[k]["bits"]:
raise DAGCircuitError("inequivalent gate definitions for %s"
% k)
return union_gates
def _check_edgemap_registers(self, edge_map, keyregs, valregs, valreg=True):
"""Check that wiremap neither fragments nor leaves duplicate registers.
1. There are no fragmented registers. A register in keyregs
is fragmented if not all of its (qu)bits are renamed by edge_map.
2. There are no duplicate registers. A register is duplicate if
it appears in both self and keyregs but not in edge_map.
Args:
edge_map (dict): map from (reg,idx) in keyregs to (reg,idx) in valregs
keyregs (dict): a map from register names to Register objects
valregs (dict): a map from register names to Register objects
valreg (bool): if False the method ignores valregs and does not
add regs for bits in the edge_map image that don't appear in valregs
Returns:
set(Register): the set of regs to add to self
Raises:
DAGCircuitError: if the wiremap fragments, or duplicates exist
"""
# FIXME: some mixing of objects and strings here are awkward (due to
# self.qregs/self.cregs still keying on string.
add_regs = set()
reg_frag_chk = {}
for v in keyregs.values():
reg_frag_chk[v] = {j: False for j in range(len(v))}
for k in edge_map.keys():
if k[0].name in keyregs:
reg_frag_chk[k[0]][k[1]] = True
for k, v in reg_frag_chk.items():
s = set(v.values())
if len(s) == 2:
raise DAGCircuitError("edge_map fragments reg %s" % k)
elif s == set([False]):
if k in self.qregs.values() or k in self.cregs.values():
raise DAGCircuitError("unmapped duplicate reg %s" % k)
else:
# Add registers that appear only in keyregs
add_regs.add(k)
else:
if valreg:
# If mapping to a register not in valregs, add it.
# (k,0) exists in edge_map because edge_map doesn't
# fragment k
if not edge_map[(k, 0)][0].name in valregs:
size = max(map(lambda x: x[1],
filter(lambda x: x[0] == edge_map[(k, 0)][0],
edge_map.values())))
qreg = QuantumRegister(size + 1, edge_map[(k, 0)][0].name)
add_regs.add(qreg)
return add_regs
def _check_wiremap_validity(self, wire_map, keymap, valmap):
"""Check that the wiremap is consistent.
Check that the wiremap refers to valid wires and that
those wires have consistent types.
Args:
wire_map (dict): map from (register,idx) in keymap to
(register,idx) in valmap
keymap (dict): a map whose keys are wire_map keys
valmap (dict): a map whose keys are wire_map values
Raises:
DAGCircuitError: if wire_map not valid
"""
for k, v in wire_map.items():
kname = "%s[%d]" % (k[0].name, k[1])
vname = "%s[%d]" % (v[0].name, v[1])
if k not in keymap:
raise DAGCircuitError("invalid wire mapping key %s" % kname)
if v not in valmap:
raise DAGCircuitError("invalid wire mapping value %s" % vname)
if type(k) is not type(v):
raise DAGCircuitError("inconsistent wire_map at (%s,%s)" %
(kname, vname))
def _map_condition(self, wire_map, condition):
"""Use the wire_map dict to change the condition tuple's creg name.
Args:
wire_map (dict): a map from wires to wires
condition (tuple): (ClassicalRegister,int)
Returns:
tuple(ClassicalRegister,int): new condition
"""
if condition is None:
new_condition = None
else:
# Map the register name, using fact that registers must not be
# fragmented by the wire_map (this must have been checked
# elsewhere)
bit0 = (condition[0], 0)
new_condition = (wire_map.get(bit0, bit0)[0], condition[1])
return new_condition
def extend_back(self, dag, edge_map=None):
"""Add `dag` at the end of `self`, using `edge_map`.
"""
for qreg in dag.qregs.values():
if qreg.name not in self.qregs:
self.add_qreg(QuantumRegister(qreg.size, qreg.name))
for creg in dag.cregs.values():
if creg.name not in self.cregs:
self.add_creg(ClassicalRegister(creg.size, creg.name))
self.compose_back(dag, edge_map)
def compose_back(self, input_circuit, edge_map=None):
"""Apply the input circuit to the output of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of input qubits of the input circuit are mapped
to a subset of output qubits of this circuit.
Args:
input_circuit (DAGCircuit): circuit to append
edge_map (dict): map {(Register, int): (Register, int)}
from the output wires of input_circuit to input wires
of self.
Raises:
DAGCircuitError: if missing, duplicate or incosistent wire
"""
edge_map = edge_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map for duplicate values
if len(set(edge_map.values())) != len(edge_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_edgemap_registers(edge_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(edge_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(edge_map, input_circuit.input_map,
self.output_map)
# Compose
self.basis = union_basis
self.gates = union_gates
for node in nx.topological_sort(input_circuit.multi_graph):
nd = input_circuit.multi_graph.node[node]
if nd["type"] == "in":
# if in wire_map, get new name, else use existing name
m_wire = edge_map.get(nd["wire"], nd["wire"])
# the mapped wire should already exist
if m_wire not in self.output_map:
raise DAGCircuitError("wire (%s,%d) not in self" % (m_wire[0].name, m_wire[1]))
if nd["wire"] not in input_circuit.wires:
raise DAGCircuitError("inconsistent wire type for (%s,%d) in input_circuit"
% (nd["wire"][0].name, nd["wire"][1]))
elif nd["type"] == "out":
# ignore output nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(edge_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: edge_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: edge_map.get(x, x), nd["cargs"]))
self.apply_operation_back(nd["op"], m_qargs, m_cargs, condition)
else:
raise DAGCircuitError("bad node type %s" % nd["type"])
# FIXME: this does not work as expected. it is also not used anywhere
def compose_front(self, input_circuit, wire_map=None):
"""Apply the input circuit to the input of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of output qubits of the input circuit are mapped
to a subset of input qubits of this circuit.
Args:
input_circuit (DAGCircuit): circuit to append
wire_map (dict): map {(Register, int): (Register, int)}
from the output wires of input_circuit to input wires
of self.
Raises:
DAGCircuitError: missing, duplicate or inconsistent wire
"""
wire_map = wire_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_edgemap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.output_map,
self.input_map)
# Compose
self.basis = union_basis
self.gates = union_gates
for n in reversed(list(nx.topological_sort(input_circuit.multi_graph))):
nd = input_circuit.multi_graph.node[n]
if nd["type"] == "out":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["wire"], nd["wire"])
# the mapped wire should already exist
if m_name not in self.input_map:
raise DAGCircuitError("wire (%s,%d) not in self" % (m_name[0].name, m_name[1]))
if nd["wire"] not in input_circuit.wires:
raise DAGCircuitError(
"inconsistent wire for (%s,%d) in input_circuit"
% (nd["wire"][0].name, nd["wire"][1]))
elif nd["type"] == "in":
# ignore input nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
self.apply_operation_front(nd["op"], condition)
else:
raise DAGCircuitError("bad node type %s" % nd["type"])
def size(self):
"""Return the number of operations."""
return self.multi_graph.order() - 2 * len(self.wires)
def depth(self):
"""Return the circuit depth.
Returns:
int: the circuit depth
Raises:
DAGCircuitError: if not a directed acyclic graph
"""
if not nx.is_directed_acyclic_graph(self.multi_graph):
raise DAGCircuitError("not a DAG")
return nx.dag_longest_path_length(self.multi_graph) - 1
def width(self):
"""Return the total number of qubits used by the circuit."""
return len(self.wires) - self.num_cbits()
def num_cbits(self):
"""Return the total number of bits used by the circuit."""
return sum(creg.size for creg in self.cregs.values())
def num_tensor_factors(self):
"""Compute how many components the circuit can decompose into."""
return nx.number_weakly_connected_components(self.multi_graph)
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.gates[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.gates[name]["n_args"] > 0:
out += "(" + ",".join(self.gates[name]["args"]) + ")"
out += " " + ",".join(self.gates[name]["bits"])
if self.gates[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.gates[name]["body"].qasm() + "}"
return out
def qasm(self, no_decls=False, qeflag=False, aliases=None, eval_symbols=False):
"""Return a string containing QASM for this circuit.
Args:
qeflag (bool): if True, add a line to include "qelib1.inc"
and only generate gate code for gates not in qelib1.
eval_symbols (bool): if True, evaluate all symbolic
expressions to their floating point representation.
no_decls (bool): if True, only print the instructions.
aliases (dict): if not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
Returns:
str: OpenQASM representation of the DAG
Raises:
DAGCircuitError: if dag nodes not in expected format
"""
# TODO: some of the input flags are not needed anymore
# Rename qregs if necessary
if aliases:
qregdata = OrderedDict()
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
# Write top matter
if no_decls:
out = ""
else:
printed_gates = []
out = "OPENQASM 2.0;\n"
if qeflag:
out += "include \"qelib1.inc\";\n"
for k, v in qregdata.items():
out += "qreg %s[%d];\n" % (k, v.size)
for k, v in self.cregs.items():
out += "creg %s[%d];\n" % (k, v.size)
omit = ["U", "CX", "measure", "reset", "barrier"]
# TODO: dagcircuit shouldn't know about extensions
if qeflag:
qelib = ["u3", "u2", "u1", "cx", "id", "x", "y", "z", "h",
"s", "sdg", "t", "tdg", "cz", "cy", "ccx", "cu1",
"cu3", "swap", "cswap", "u0", "rx", "ry", "rz",
"ch", "crz", "rzz"]
omit.extend(qelib)
printed_gates.extend(qelib)
simulator_instructions = ["snapshot", "save", "load", "noise", "wait"]
omit.extend(simulator_instructions)
for k in self.basis.keys():
if k not in omit:
if not self.gates[k]["opaque"]:
calls = self.gates[k]["body"].calls()
for c in calls:
if c not in printed_gates:
out += self._gate_string(c) + "\n"
printed_gates.append(c)
if k not in printed_gates:
out += self._gate_string(k) + "\n"
printed_gates.append(k)
# Write the instructions
for n in nx.lexicographical_topological_sort(
self.multi_graph, key=lambda x: (self.multi_graph.nodes[x]["type"],
self.multi_graph.nodes[x]["name"])):
nd = self.multi_graph.node[n]
if nd["type"] == "op":
if nd["condition"] is not None:
out += "if(%s==%d) " \
% (nd["condition"][0], nd["condition"][1])
if not nd["cargs"]:
nm = nd["op"].name
if aliases:
qarglist = map(lambda x: aliases[x], nd["qargs"])
else:
qarglist = nd["qargs"]
qarg = ",".join(map(lambda x: "%s[%d]" % (x[0].name, x[1]),
qarglist))
if nd["op"].param:
if eval_symbols:
param = ",".join(map(lambda x: str(x.evalf()),
nd["op"].param))
else:
param = ",".join(map(lambda x: x.replace("**", "^"),
map(str, nd["op"].param)))
out += "%s(%s) %s;\n" % (nm, param, qarg)
else:
out += "%s %s;\n" % (nm, qarg)
else:
if nd["op"].name == "measure":
if len(nd["cargs"]) != 1 or len(nd["qargs"]) != 1 \
or nd["op"].param:
raise DAGCircuitError("bad node data")
qname = nd["qargs"][0][0].name
qindex = nd["qargs"][0][1]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
out += "measure %s[%d] -> %s[%d];\n" \
% (qname,
qindex,
nd["cargs"][0][0].name,
nd["cargs"][0][1])
else:
raise DAGCircuitError("bad node data")
return out
def _check_wires_list(self, wires, op, input_circuit, condition=None):
"""Check that a list of wires satisfies some conditions.
- no duplicate names
- correct length for operation
- elements are wires of input_circuit
Raise an exception otherwise.
Args:
wires (list[register, index]): gives an order for (qu)bits
in the input_circuit that is replacing the operation.
op (Instruction): operation
input_circuit (DAGCircuit): replacement circuit for operation
condition (tuple or None): if this instance of the
operation is classically controlled by a (ClassicalRegister, int)
Raises:
DAGCircuitError: if check doesn't pass.
"""
if len(set(wires)) != len(wires):
raise DAGCircuitError("duplicate wires")
wire_tot = len(op.qargs) + len(op.cargs)
if condition is not None:
wire_tot += condition[0].size
if len(wires) != wire_tot:
raise DAGCircuitError("expected %d wires, got %d"
% (wire_tot, len(wires)))
for w in wires:
if w not in input_circuit.wires:
raise DAGCircuitError("wire (%s,%d) not in input circuit"
% (w[0], w[1]))
def _make_pred_succ_maps(self, n):
"""Return predecessor and successor dictionaries.
Args:
n (int): reference to self.multi_graph node id
Returns:
set(dict): set({predecessor_map, successor_map})
These map from wire (Register, int) to predecessor (successor)
nodes of n.
"""
pred_map = {e[2]['wire']: e[0] for e in
self.multi_graph.in_edges(nbunch=n, data=True)}
succ_map = {e[2]['wire']: e[1] for e in
self.multi_graph.out_edges(nbunch=n, data=True)}
return pred_map, succ_map
def _full_pred_succ_maps(self, pred_map, succ_map, input_circuit,
wire_map):
"""Map all wires of the input circuit.
Map all wires of the input circuit to predecessor and
successor nodes in self, keyed on wires in self.
Args:
pred_map (dict): comes from _make_pred_succ_maps
succ_map (dict): comes from _make_pred_succ_maps
input_circuit (DAGCircuit): the input circuit
wire_map (dict): the map from wires of input_circuit to wires of self
Returns:
tuple: full_pred_map, full_succ_map (dict, dict)
Raises:
DAGCircuitError: if more than one predecessor for output nodes
"""
full_pred_map = {}
full_succ_map = {}
for w in input_circuit.input_map:
# If w is wire mapped, find the corresponding predecessor
# of the node
if w in wire_map:
full_pred_map[wire_map[w]] = pred_map[wire_map[w]]
full_succ_map[wire_map[w]] = succ_map[wire_map[w]]
else:
# Otherwise, use the corresponding output nodes of self
# and compute the predecessor.
full_succ_map[w] = self.output_map[w]
full_pred_map[w] = self.multi_graph.predecessors(
self.output_map[w])[0]
if len(list(self.multi_graph.predecessors(self.output_map[w]))) != 1:
raise DAGCircuitError(
"too many predecessors for (%s,%d) output node" % (w[0], w[1])
)
return full_pred_map, full_succ_map
@staticmethod
def _match_dag_nodes(node1, node2):
"""
Check if DAG nodes are considered equivalent, e.g. as a node_match for nx.is_isomorphic.
Args:
node1 (dict): A node to compare.
node2 (dict): The other node to compare.
Returns:
Bool: If node1 == node2
"""
copy_node1 = {k: v for (k, v) in node1.items()}
copy_node2 = {k: v for (k, v) in node2.items()}
return copy_node1 == copy_node2
def __eq__(self, other):
return nx.is_isomorphic(self.multi_graph, other.multi_graph,
node_match=DAGCircuit._match_dag_nodes)
def node_nums_in_topological_order(self):
"""
Returns the nodes (their ids) in topological order.
Returns:
list: The list of node numbers in topological order
"""
return nx.topological_sort(self.multi_graph)
def substitute_circuit_all(self, op, input_circuit, wires=None):
"""Replace every occurrence of operation op with input_circuit.
Args:
op (Instruction): operation type to substitute across the dag.
input_circuit (DAGCircuit): what to replace with
wires (list[register, index]): gives an order for (qu)bits
in the input_circuit that is replacing the operation.
Raises:
DAGCircuitError: if met with unexpected predecessor/successors
"""
# TODO: rewrite this method to call substitute_circuit_one
wires = wires or []
if op.name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% op.name)
self._check_wires_list(wires, op, input_circuit)
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: (QuantumRegister(1, 'proxy'), 0) for w in wires}
add_qregs = self._check_edgemap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Iterate through the nodes of self and replace the selected nodes
# by iterating through the input_circuit, constructing and
# checking the validity of the wire_map for each replacement
# NOTE: We do not replace conditioned gates. One way to implement
# this later is to add or update the conditions of each gate
# that we add from the input_circuit.
self.basis = union_basis
self.gates = union_gates
for n in self.node_nums_in_topological_order():
nd = self.multi_graph.node[n]
if nd["type"] == "op" and nd["op"] == op:
if nd["condition"] is None:
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"], nd["cargs"]]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map)
pred_map, succ_map = self._make_pred_succ_maps(n)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(n)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map,
md["condition"])
m_qargs = [wire_map.get(x, x) for x in md["qargs0"]]
m_cargs = [wire_map.get(x, x) for x in md["cargs0"]]
self._add_op_node(md["op"], m_qargs, m_cargs, condition)
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter,
name="%s[%s]" % (q[0].name, q[1]),
wire=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w],
full_succ_map[w],
name="%s[%s]" % (w[0].name, w[1]),
wire=w)
o_pred = list(self.multi_graph.predecessors(
self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise DAGCircuitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise DAGCircuitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(
p[0], self.output_map[w])
def substitute_circuit_one(self, node, input_circuit, wires=None):
"""Replace one node with input_circuit.
Args:
node (int): node of self.multi_graph (of type "op") to substitute
input_circuit (DAGCircuit): circuit that will substitute the node
wires (list[(Register, index)]): gives an order for (qu)bits
in the input circuit. This order gets matched to the node wires
by qargs first, then cargs, then conditions.
Raises:
DAGCircuitError: if met with unexpected predecessor/successors
"""
wires = wires or []
nd = self.multi_graph.node[node]
self._check_wires_list(wires, nd["op"], input_circuit, nd["condition"])
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: QuantumRegister(1, 'proxy') for w in wires}
add_qregs = self._check_edgemap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Replace the node by iterating through the input_circuit.
# Constructing and checking the validity of the wire_map.
# If a gate is conditioned, we expect the replacement subcircuit
# to depend on those control bits as well.
self.basis = union_basis
self.gates = union_gates
if nd["type"] != "op":
raise DAGCircuitError("expected node type \"op\", got %s"
% nd["type"])
condition_bit_list = self._bits_in_condition(nd["condition"])
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"],
nd["cargs"],
condition_bit_list]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map)
pred_map, succ_map = self._make_pred_succ_maps(node)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(node)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map, md["condition"])
m_qargs = list(map(lambda x: wire_map.get(x, x),
md["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x),
md["cargs"]))
self._add_op_node(md["op"], m_qargs, m_cargs, condition)
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter,
name="%s[%s]" % (q[0].name, q[1]),
wire=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w],
full_succ_map[w],
name="%s[%s]" % (w[0].name, w[1]),
wire=w)
o_pred = list(self.multi_graph.predecessors(self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise DAGCircuitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise DAGCircuitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(p[0], self.output_map[w])
def get_op_nodes(self, op=None, data=False):
"""Get the list of "op" nodes in the dag.
Note: this method returns all nodes of a given op type (e.g. HGate),
and does not look at the gate operands. Because in the future, the
operands won't even be part of the gate.
Args:
op (Instruction or None): op nodes to return. if op=None, return
all op nodes.
data (bool): Default: False. If True, return a list of tuple
(node_id, node_data). If False, return a list of int (node_id)
Returns:
list: the list of node ids containing the given op.
"""
nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data["type"] == "op":
if op is None:
nodes.append((node_id, node_data))
elif type(node_data["op"]) is type(op):
nodes.append((node_id, node_data))
if not data:
nodes = [n[0] for n in nodes]
return nodes
def get_gate_nodes(self, data=False):
"""Get the list of gate nodes in the dag.
Args:
data (bool): Default: False. If True, return a list of tuple
(node_id, node_data). If False, return a list of int (node_id)
Returns:
list: the list of node ids that represent gates.
"""
nodes = []
for node_id, node_data in self.get_op_nodes(data=True):
if isinstance(node_data['op'], Gate):
nodes.append((node_id, node_data))
if not data:
nodes = [n[0] for n in nodes]
return nodes
def get_named_nodes(self, name):
"""Get the set of "op" node ids with the given name."""
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
# We need to instantiate the full list now because the underlying multi_graph
# may change when users iterate over the named nodes.
return {node_id for node_id, data in self.multi_graph.nodes(data=True)
if data["type"] == "op" and data["op"].name == name}
def get_cnot_nodes(self):
"""Get the set of Cnot."""
cx_names = ['cx', 'CX']
cxs_nodes = []
for cx_name in cx_names:
if cx_name in self.basis:
for cx_id in self.get_named_nodes(cx_name):
cxs_nodes.append(self.multi_graph.node[cx_id])
return cxs_nodes
def _remove_op_node(self, n):
"""Remove an operation node n.
Add edges from predecessors to successors.
"""
pred_map, succ_map = self._make_pred_succ_maps(n)
self.multi_graph.remove_node(n)
for w in pred_map.keys():
self.multi_graph.add_edge(pred_map[w], succ_map[w],
name="%s[%s]" % (w[0].name, w[1]), wire=w)
def remove_ancestors_of(self, node):
"""Remove all of the ancestor operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
# TODO: probably better to do all at once using
# multi_graph.remove_nodes_from; same for related functions ...
for n in anc:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_descendants_of(self, node):
"""Remove all of the descendant operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
for n in dec:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nonancestors_of(self, node):
"""Remove all of the non-ancestors operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(anc))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nondescendants_of(self, node):
"""Remove all of the non-descendants operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(dec))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def layers(self):
"""Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit.
A layer is a circuit whose gates act on disjoint qubits, i.e.
a layer has depth 1. The total number of layers equals the
circuit depth d. The layers are indexed from 0 to d-1 with the
earliest layer at index 0. The layers are constructed using a
greedy algorithm. Each returned layer is a dict containing
{"graph": circuit graph, "partition": list of qubit lists}.
TODO: Gates that use the same cbits will end up in different
layers as this is currently implemented. This may not be
the desired behavior.
"""
graph_layers = self.multigraph_layers()
try:
next(graph_layers) # Remove input nodes
except StopIteration:
return
def nodes_data(nodes):
"""Construct full nodes from just node ids."""
return ((node_id, self.multi_graph.nodes[node_id]) for node_id in nodes)
for graph_layer in graph_layers:
# Get the op nodes from the layer, removing any input and output nodes.
op_nodes = [node for node in nodes_data(graph_layer) if node[1]["type"] == "op"]
# Stop yielding once there are no more op_nodes in a layer.
if not op_nodes:
return
# Construct a shallow copy of self
new_layer = copy.copy(self)
new_layer.multi_graph = nx.MultiDiGraph()
new_layer.multi_graph.add_nodes_from(nodes_data(self.input_map.values()))
new_layer.multi_graph.add_nodes_from(nodes_data(self.output_map.values()))
# The quantum registers that have an operation in this layer.
support_list = [
op_node[1]["qargs"]
for op_node in op_nodes
if op_node[1]["op"].name not in {"barrier", "snapshot", "save", "load", "noise"}
]
new_layer.multi_graph.add_nodes_from(op_nodes)
# Now add the edges to the multi_graph
# By default we just wire inputs to the outputs.
wires = {self.input_map[wire]: self.output_map[wire]
for wire in self.wires}
# Wire inputs to op nodes, and op nodes to outputs.
for op_node in op_nodes:
args = self._bits_in_condition(op_node[1]["condition"]) \
+ op_node[1]["cargs"] + op_node[1]["qargs"]
arg_ids = (self.input_map[(arg[0], arg[1])] for arg in args)
for arg_id in arg_ids:
wires[arg_id], wires[op_node[0]] = op_node[0], wires[arg_id]
# Add wiring to/from the operations and between unused inputs & outputs.
new_layer.multi_graph.add_edges_from(wires.items())
yield {"graph": new_layer, "partition": support_list}
def serial_layers(self):
"""Yield a layer for all gates of this circuit.
A serial layer is a circuit with one gate. The layers have the
same structure as in layers().
"""
for n in self.node_nums_in_topological_order():
nxt_nd = self.multi_graph.node[n]
if nxt_nd["type"] == "op":
new_layer = DAGCircuit()
for qreg in self.qregs.values():
new_layer.add_qreg(qreg)
for creg in self.cregs.values():
new_layer.add_creg(creg)
new_layer.basis = self.basis.copy()
new_layer.gates = self.gates.copy()
# Save the support of the operation we add to the layer
support_list = []
# Operation data
op = copy.copy(nxt_nd["op"])
qa = copy.copy(nxt_nd["qargs"])
ca = copy.copy(nxt_nd["cargs"])
co = copy.copy(nxt_nd["condition"])
_ = self._bits_in_condition(co)
# Add node to new_layer
new_layer.apply_operation_back(op, qa, ca, co)
# Add operation to partition
if nxt_nd["name"] not in ["barrier",
"snapshot", "save", "load", "noise"]:
support_list.append(list(qa))
l_dict = {"graph": new_layer, "partition": support_list}
yield l_dict
def multigraph_layers(self):
"""Yield layers of the multigraph."""
predecessor_count = dict() # Dict[node, predecessors not visited]
cur_layer = [node for node in self.input_map.values()]
yield cur_layer
next_layer = []
while cur_layer:
for node in cur_layer:
# Count multiedges with multiplicity.
for successor in self.multi_graph.successors(node):
multiplicity = self.multi_graph.number_of_edges(node, successor)
if successor in predecessor_count:
predecessor_count[successor] -= multiplicity
else:
predecessor_count[successor] = \
self.multi_graph.in_degree(successor) - multiplicity
if predecessor_count[successor] == 0:
next_layer.append(successor)
del predecessor_count[successor]
yield next_layer
cur_layer = next_layer
next_layer = []
def collect_runs(self, namelist):
"""Return a set of runs of "op" nodes with the given names.
For example, "... h q[0]; cx q[0],q[1]; cx q[0],q[1]; h q[1]; .."
would produce the tuple of cx nodes as an element of the set returned
from a call to collect_runs(["cx"]). If instead the cx nodes were
"cx q[0],q[1]; cx q[1],q[0];", the method would still return the
pair in a tuple. The namelist can contain names that are not
in the circuit's basis.
Nodes must have only one successor to continue the run.
"""
group_list = []
# Iterate through the nodes of self in topological order
# and form tuples containing sequences of gates
# on the same qubit(s).
ts = list(self.node_nums_in_topological_order())
nodes_seen = dict(zip(ts, [False] * len(ts)))
for node in ts:
nd = self.multi_graph.node[node]
if nd["type"] == "op" and nd["name"] in namelist \
and not nodes_seen[node]:
group = [node]
nodes_seen[node] = True
s = list(self.multi_graph.successors(node))
while len(s) == 1 and \
self.multi_graph.node[s[0]]["type"] == "op" and \
self.multi_graph.node[s[0]]["name"] in namelist:
group.append(s[0])
nodes_seen[s[0]] = True
s = list(self.multi_graph.successors(s[0]))
if len(group) > 1:
group_list.append(tuple(group))
return set(group_list)
def count_ops(self):
"""Count the occurrences of operation names.
Returns a dictionary of counts keyed on the operation name.
"""
op_dict = {}
for node in self.node_nums_in_topological_order():
nd = self.multi_graph.node[node]
name = nd["name"]
if nd["type"] == "op":
if name not in op_dict:
op_dict[name] = 1
else:
op_dict[name] += 1
return op_dict
def properties(self):
"""Return a dictionary of circuit properties."""
summary = {"size": self.size(),
"depth": self.depth(),
"width": self.width(),
"bits": self.num_cbits(),
"factors": self.num_tensor_factors(),
"operations": self.count_ops()}
return summary
<|code_end|>
qiskit/transpiler/passes/mapping/direction_mapper.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A direction mapper rearrenges the direction of the cx nodes to make the circuit
compatible to the directed coupling map.
"""
from copy import copy
from qiskit.transpiler._basepasses import TransformationPass
from qiskit.transpiler import MapperError
from qiskit.dagcircuit import DAGCircuit
from qiskit.mapper import Layout
from qiskit.extensions.standard import HGate
class DirectionMapper(TransformationPass):
"""
Rearranges the direction of the cx nodes to make the circuit
compatible with the directed coupling map.
It uses this equivalence:
---(+)--- --[H]---.---[H]--
| = |
----.---- --[H]--(+)--[H]--
"""
def __init__(self, coupling_map, initial_layout=None):
"""
Args:
coupling_map (Coupling): Directed graph represented a coupling map.
initial_layout (Layout): The initial layout of the DAG.
"""
super().__init__()
self.coupling_map = coupling_map
self.initial_layout = initial_layout
def run(self, dag):
"""
Flips the cx nodes to match the directed coupling map.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: The rearranged dag for the coupling map
Raises:
MapperError: If the circuit cannot be mapped just by flipping the
cx nodes.
"""
new_dag = DAGCircuit()
if self.initial_layout is None:
# create a one-to-one layout
self.initial_layout = Layout()
wire_no = 0
for qreg in dag.qregs.values():
for index in range(qreg.size):
self.initial_layout[(qreg, index)] = wire_no
wire_no += 1
current_layout = copy(self.initial_layout)
for layer in dag.serial_layers():
subdag = layer['graph']
for cnot in subdag.get_cnot_nodes():
control = cnot['op'].qargs[0]
target = cnot['op'].qargs[1]
physical_q0 = current_layout[control]
physical_q1 = current_layout[target]
if self.coupling_map.distance(physical_q0, physical_q1) != 1:
raise MapperError('The circuit requires a connectiontion between the phsycial '
'qubits %s and %s' % (physical_q0, physical_q1))
if (physical_q0, physical_q1) not in self.coupling_map.get_edges():
# A flip needs to be done
# Create the involved registers
if control[0] not in subdag.qregs.values():
subdag.add_qreg(control[0])
if target[0] not in subdag.qregs.values():
subdag.add_qreg(target[0])
# Add H gates around
subdag.add_basis_element('h', 1, 0, 0)
subdag.apply_operation_back(HGate(target))
subdag.apply_operation_back(HGate(control))
subdag.apply_operation_front(HGate(target))
subdag.apply_operation_front(HGate(control))
# Flips the CX
cnot['op'].qargs[0], cnot['op'].qargs[1] = target, control
edge_map = current_layout.combine_into_edge_map(self.initial_layout)
new_dag.compose_back(subdag, edge_map)
return new_dag
<|code_end|>
|
qiskit/dagcircuit/_dagcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Object to represent a quantum circuit as a directed acyclic graph.
The nodes in the graph are either input/output nodes or operation nodes.
The operation nodes are elements of a basis that is part of the circuit.
The QASM definitions of the basis elements are carried with the circuit.
The edges correspond to qubits or bits in the circuit. A directed edge
from node A to node B means that the (qu)bit passes from the output of A
to the input of B. The object's methods allow circuits to be constructed,
composed, and modified. Some natural properties like depth can be computed
directly from the graph.
"""
import re
from collections import OrderedDict
import copy
import itertools
import networkx as nx
from qiskit import QuantumRegister, ClassicalRegister
from qiskit.circuit import Gate
from ._dagcircuiterror import DAGCircuitError
class DAGCircuit:
"""
Quantum circuit as a directed acyclic graph.
There are 3 types of nodes in the graph: inputs, outputs, and operations.
The nodes are connected by directed edges that correspond to qubits and
bits.
"""
# pylint: disable=invalid-name
def __init__(self):
"""Create an empty circuit."""
# Circuit name. Generally, this corresponds to the name
# of the QuantumCircuit from which the DAG was generated.
self.name = None
# Set of wires (Register,idx) in the dag
self.wires = []
# Map from wire (Register,idx) to input nodes of the graph
self.input_map = OrderedDict()
# Map from wire (Register,idx) to output nodes of the graph
self.output_map = OrderedDict()
# Running count of the total number of nodes
self.node_counter = 0
# Map of user defined gates to ast nodes defining them
self.gates = OrderedDict()
# Map of named operations in this circuit and their signatures.
# The signature is an integer tuple (nq,nc,np) specifying the
# number of input qubits, input bits, and real parameters.
# The definition is external to the circuit object.
self.basis = OrderedDict()
self.add_basis_element(name="U", number_qubits=1,
number_classical=0, number_parameters=3)
self.add_basis_element("CX", 2, 0, 0)
self.add_basis_element("measure", 1, 1, 0)
self.add_basis_element("reset", 1, 0, 0)
self.add_basis_element("barrier", -1)
# Directed multigraph whose nodes are inputs, outputs, or operations.
# Operation nodes have equal in- and out-degrees and carry
# additional data about the operation, including the argument order
# and parameter values.
# Input nodes have out-degree 1 and output nodes have in-degree 1.
# Edges carry wire labels (reg,idx) and each operation has
# corresponding in- and out-edges with the same wire labels.
self.multi_graph = nx.MultiDiGraph()
# Map of qreg name to QuantumRegister object
self.qregs = OrderedDict()
# Map of creg name to ClassicalRegister object
self.cregs = OrderedDict()
# layout of dag quantum registers on the chip
# TODO: rethink this. doesn't seem related to concept of DAG,
# but if we want to be able to generate qobj
# directly from a dag, we need it.
self.layout = []
def get_qubits(self):
"""Return a list of qubits as (QuantumRegister, index) pairs."""
return [(v, i) for k, v in self.qregs.items() for i in range(v.size)]
# TODO: unused function. is it needed?
def rename_register(self, regname, newname):
"""Rename a classical or quantum register throughout the circuit.
regname = existing register name string
newname = replacement register name string
"""
if regname == newname:
return
if newname in self.qregs or newname in self.cregs:
raise DAGCircuitError("duplicate register name %s" % newname)
if regname not in self.qregs and regname not in self.cregs:
raise DAGCircuitError("no register named %s" % regname)
if regname in self.qregs:
reg = self.qregs[regname]
reg.name = newname
self.qregs[newname] = reg
self.qregs.pop(regname, None)
if regname in self.cregs:
reg = self.cregs[regname]
reg.name = newname
self.qregs[newname] = reg
self.qregs.pop(regname, None)
# n node d = data
for _, d in self.multi_graph.nodes(data=True):
if d["type"] == "in" or d["type"] == "out":
if regname in d["name"]:
d["name"] = re.sub(regname, newname, d["name"])
elif d["type"] == "op":
qa = []
for a in d["qargs"]:
if a[0] == regname:
a = (newname, a[1])
qa.append(a)
d["qargs"] = qa
ca = []
for a in d["cargs"]:
if a[0] == regname:
a = (newname, a[1])
ca.append(a)
d["cargs"] = ca
if d["condition"] is not None:
if d["condition"][0] == regname:
d["condition"] = (newname, d["condition"][1])
# eX = edge, d= data
for _, _, d in self.multi_graph.edges(data=True):
if regname in d["name"]:
d["name"] = re.sub(regname, newname, d["name"])
def remove_all_ops_named(self, opname):
"""Remove all operation nodes with the given name."""
for n in self.get_named_nodes(opname):
self._remove_op_node(n)
def add_qreg(self, qreg):
"""Add all wires in a quantum register."""
if not isinstance(qreg, QuantumRegister):
raise DAGCircuitError("not a QuantumRegister instance.")
if qreg.name in self.qregs:
raise DAGCircuitError("duplicate register %s" % qreg.name)
self.qregs[qreg.name] = qreg
for j in range(qreg.size):
self._add_wire((qreg, j))
def add_creg(self, creg):
"""Add all wires in a classical register."""
if not isinstance(creg, ClassicalRegister):
raise DAGCircuitError("not a ClassicalRegister instance.")
if creg.name in self.cregs:
raise DAGCircuitError("duplicate register %s" % creg.name)
self.cregs[creg.name] = creg
for j in range(creg.size):
self._add_wire((creg, j))
def _add_wire(self, wire):
"""Add a qubit or bit to the circuit.
Args:
wire (tuple): (Register,int) containing a register instance and index
This adds a pair of in and out nodes connected by an edge.
Raises:
DAGCircuitError: if trying to add duplicate wire
"""
if wire not in self.wires:
self.wires.append(wire)
self.node_counter += 1
self.input_map[wire] = self.node_counter
self.node_counter += 1
self.output_map[wire] = self.node_counter
in_node = self.input_map[wire]
out_node = self.output_map[wire]
self.multi_graph.add_edge(in_node, out_node)
self.multi_graph.node[in_node]["type"] = "in"
self.multi_graph.node[out_node]["type"] = "out"
self.multi_graph.node[in_node]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.node[out_node]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.node[in_node]["wire"] = wire
self.multi_graph.node[out_node]["wire"] = wire
self.multi_graph.adj[in_node][out_node][0]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.adj[in_node][out_node][0]["wire"] = wire
else:
raise DAGCircuitError("duplicate wire %s" % (wire,))
def add_basis_element(self, name, number_qubits,
number_classical=0, number_parameters=0):
"""Add an operation to the basis.
name is string label for operation
number_qubits is number of qubit arguments
number_classical is number of bit arguments
number_parameters is number of real parameters
The parameters (nq,nc,np) are ignored for the special case
when name = "barrier". The barrier instruction has a variable
number of qubit arguments.
"""
if name not in self.basis:
self.basis[name] = (
number_qubits,
number_classical,
number_parameters)
if name in self.gates:
if self.gates[name]["n_args"] != number_parameters or \
self.gates[name]["n_bits"] != number_qubits or number_classical != 0:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def add_gate_data(self, name, gatedata):
"""Add the definition of a gate.
gatedata is dict with fields:
"print" = True or False
"opaque" = True or False
"n_args" = number of real parameters
"n_bits" = number of qubits
"args" = list of parameter names
"bits" = list of qubit names
"body" = GateBody AST node
"""
if name not in self.gates:
self.gates[name] = gatedata
if name in self.basis:
if self.basis[name][0] != self.gates[name]["n_bits"] or \
self.basis[name][1] != 0 or \
self.basis[name][2] != self.gates[name]["n_args"]:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def _check_basis_data(self, op, qargs, cargs):
"""Check the arguments against the data for this operation.
Args:
op (Instruction): a quantum operation
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple]): cbits that op will be applied to
Raises:
DAGCircuitError: If the check fails.
"""
# Check that we have this operation
if op.name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations" % op.name)
# Check the number of arguments matches the signature
if op.name in ["barrier"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s" % op.name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s" % op.name)
elif op.name in ["snapshot", "noise", "save", "load"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s" % op.name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s" % op.name)
else:
if len(qargs) != self.basis[op.name][0]:
raise DAGCircuitError("incorrect number of qubits for %s" % op.name)
if len(cargs) != self.basis[op.name][1]:
raise DAGCircuitError("incorrect number of bits for %s" % op.name)
def _check_condition(self, name, condition):
"""Verify that the condition is valid.
Args:
name (string): used for error reporting
condition (tuple or None): a condition tuple (ClassicalRegister,int)
Raises:
DAGCircuitError: if conditioning on an invalid register
"""
# Verify creg exists
if condition is not None and condition[0].name not in self.cregs:
raise DAGCircuitError("invalid creg in condition for %s" % name)
def _check_bits(self, args, amap):
"""Check the values of a list of (qu)bit arguments.
For each element of args, check that amap contains it.
Args:
args (list): (register,idx) tuples
amap (dict): a dictionary keyed on (register,idx) tuples
Raises:
DAGCircuitError: if a qubit is not contained in amap
"""
# Check for each wire
for wire in args:
if wire not in amap:
raise DAGCircuitError("(qu)bit %s not found" % (wire,))
def _bits_in_condition(self, cond):
"""Return a list of bits in the given condition.
Args:
cond (tuple or None): optional condition (ClassicalRegister, int)
Returns:
list[(ClassicalRegister, idx)]: list of bits
"""
all_bits = []
if cond is not None:
all_bits.extend([(cond[0], j) for j in range(self.cregs[cond[0].name].size)])
return all_bits
def _add_op_node(self, op, qargs, cargs, condition=None):
"""Add a new operation node to the graph and assign properties.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list): list of quantum wires to attach to.
cargs (list): list of classical wires to attach to.
condition (tuple or None): optional condition (ClassicalRegister, int)
"""
# Add a new operation node to the graph
self.node_counter += 1
self.multi_graph.add_node(self.node_counter)
# Update the operation itself. TODO: remove after qargs not connected to op
op.qargs = qargs
op.cargs = cargs
# Update that operation node's data
self.multi_graph.node[self.node_counter]["type"] = "op"
self.multi_graph.node[self.node_counter]["op"] = op
self.multi_graph.node[self.node_counter]["name"] = op.name
self.multi_graph.node[self.node_counter]["qargs"] = qargs
self.multi_graph.node[self.node_counter]["cargs"] = cargs
self.multi_graph.node[self.node_counter]["condition"] = condition
def apply_operation_back(self, op, qargs=None, cargs=None, condition=None):
"""Apply an operation to the output of the circuit.
TODO: make `qargs` and `cargs` mandatory, when they are dropped from op.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple]): cbits that op will be applied to
condition (tuple or None): optional condition (ClassicalRegister, int)
Raises:
DAGCircuitError: if a leaf node is connected to multiple outputs
"""
qargs = qargs or op.qargs
cargs = cargs or op.cargs
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(op, qargs, cargs)
self._check_condition(op.name, condition)
self._check_bits(qargs, self.output_map)
self._check_bits(all_cbits, self.output_map)
self._add_op_node(op, qargs, cargs, condition)
# Add new in-edges from predecessors of the output nodes to the
# operation node while deleting the old in-edges of the output nodes
# and adding new edges from the operation node to each output node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.predecessors(self.output_map[q]))
if len(ie) != 1:
raise DAGCircuitError("output node has multiple in-edges")
self.multi_graph.add_edge(ie[0], self.node_counter,
name="%s[%s]" % (q[0].name, q[1]), wire=q)
self.multi_graph.remove_edge(ie[0], self.output_map[q])
self.multi_graph.add_edge(self.node_counter, self.output_map[q],
name="%s[%s]" % (q[0].name, q[1]), wire=q)
def apply_operation_front(self, op, qargs=None, cargs=None, condition=None):
"""Apply an operation to the input of the circuit.
TODO: make `qargs` and `cargs` mandatory, when they are dropped from op.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple]): cbits that op will be applied to
condition (tuple or None): optional condition (ClassicalRegister, value)
Raises:
DAGCircuitError: if initial nodes connected to multiple out edges
"""
qargs = qargs or op.qargs
cargs = cargs or op.cargs
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(op, qargs, cargs)
self._check_condition(op.name, condition)
self._check_bits(qargs, self.input_map)
self._check_bits(all_cbits, self.input_map)
self._add_op_node(op, qargs, cargs, condition)
# Add new out-edges to successors of the input nodes from the
# operation node while deleting the old out-edges of the input nodes
# and adding new edges to the operation node from each input node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.successors(self.input_map[q]))
if len(ie) != 1:
raise DAGCircuitError("input node has multiple out-edges")
self.multi_graph.add_edge(self.node_counter, ie[0],
name="%s[%s]" % (q[0].name, q[1]), wire=q)
self.multi_graph.remove_edge(self.input_map[q], ie[0])
self.multi_graph.add_edge(self.input_map[q], self.node_counter,
name="%s[%s]" % (q[0].name, q[1]), wire=q)
def _make_union_basis(self, input_circuit):
"""Return a new basis map.
The new basis is a copy of self.basis with
new elements of input_circuit.basis added.
input_circuit is a DAGCircuit
"""
union_basis = self.basis.copy()
for g in input_circuit.basis:
if g not in union_basis:
union_basis[g] = input_circuit.basis[g]
if union_basis[g] != input_circuit.basis[g]:
raise DAGCircuitError("incompatible basis")
return union_basis
def _make_union_gates(self, input_circuit):
"""Return a new gates map.
The new gates are a copy of self.gates with
new elements of input_circuit.gates added.
input_circuit is a DAGCircuit
NOTE: gates in input_circuit that are also in self must
be *identical* to the gates in self
"""
union_gates = {}
for k, v in self.gates.items():
union_gates[k] = v
for k, v in input_circuit.gates.items():
if k not in union_gates:
union_gates[k] = v
if union_gates[k]["opaque"] != input_circuit.gates[k]["opaque"] or \
union_gates[k]["n_args"] != input_circuit.gates[k]["n_args"] or \
union_gates[k]["n_bits"] != input_circuit.gates[k]["n_bits"] or \
union_gates[k]["args"] != input_circuit.gates[k]["args"] or \
union_gates[k]["bits"] != input_circuit.gates[k]["bits"]:
raise DAGCircuitError("inequivalent gate definitions for %s"
% k)
return union_gates
def _check_edgemap_registers(self, edge_map, keyregs, valregs, valreg=True):
"""Check that wiremap neither fragments nor leaves duplicate registers.
1. There are no fragmented registers. A register in keyregs
is fragmented if not all of its (qu)bits are renamed by edge_map.
2. There are no duplicate registers. A register is duplicate if
it appears in both self and keyregs but not in edge_map.
Args:
edge_map (dict): map from (reg,idx) in keyregs to (reg,idx) in valregs
keyregs (dict): a map from register names to Register objects
valregs (dict): a map from register names to Register objects
valreg (bool): if False the method ignores valregs and does not
add regs for bits in the edge_map image that don't appear in valregs
Returns:
set(Register): the set of regs to add to self
Raises:
DAGCircuitError: if the wiremap fragments, or duplicates exist
"""
# FIXME: some mixing of objects and strings here are awkward (due to
# self.qregs/self.cregs still keying on string.
add_regs = set()
reg_frag_chk = {}
for v in keyregs.values():
reg_frag_chk[v] = {j: False for j in range(len(v))}
for k in edge_map.keys():
if k[0].name in keyregs:
reg_frag_chk[k[0]][k[1]] = True
for k, v in reg_frag_chk.items():
s = set(v.values())
if len(s) == 2:
raise DAGCircuitError("edge_map fragments reg %s" % k)
elif s == set([False]):
if k in self.qregs.values() or k in self.cregs.values():
raise DAGCircuitError("unmapped duplicate reg %s" % k)
else:
# Add registers that appear only in keyregs
add_regs.add(k)
else:
if valreg:
# If mapping to a register not in valregs, add it.
# (k,0) exists in edge_map because edge_map doesn't
# fragment k
if not edge_map[(k, 0)][0].name in valregs:
size = max(map(lambda x: x[1],
filter(lambda x: x[0] == edge_map[(k, 0)][0],
edge_map.values())))
qreg = QuantumRegister(size + 1, edge_map[(k, 0)][0].name)
add_regs.add(qreg)
return add_regs
def _check_wiremap_validity(self, wire_map, keymap, valmap):
"""Check that the wiremap is consistent.
Check that the wiremap refers to valid wires and that
those wires have consistent types.
Args:
wire_map (dict): map from (register,idx) in keymap to
(register,idx) in valmap
keymap (dict): a map whose keys are wire_map keys
valmap (dict): a map whose keys are wire_map values
Raises:
DAGCircuitError: if wire_map not valid
"""
for k, v in wire_map.items():
kname = "%s[%d]" % (k[0].name, k[1])
vname = "%s[%d]" % (v[0].name, v[1])
if k not in keymap:
raise DAGCircuitError("invalid wire mapping key %s" % kname)
if v not in valmap:
raise DAGCircuitError("invalid wire mapping value %s" % vname)
if type(k) is not type(v):
raise DAGCircuitError("inconsistent wire_map at (%s,%s)" %
(kname, vname))
def _map_condition(self, wire_map, condition):
"""Use the wire_map dict to change the condition tuple's creg name.
Args:
wire_map (dict): a map from wires to wires
condition (tuple): (ClassicalRegister,int)
Returns:
tuple(ClassicalRegister,int): new condition
"""
if condition is None:
new_condition = None
else:
# Map the register name, using fact that registers must not be
# fragmented by the wire_map (this must have been checked
# elsewhere)
bit0 = (condition[0], 0)
new_condition = (wire_map.get(bit0, bit0)[0], condition[1])
return new_condition
def extend_back(self, dag, edge_map=None):
"""Add `dag` at the end of `self`, using `edge_map`.
"""
edge_map = edge_map or {}
for qreg in dag.qregs.values():
if qreg.name not in self.qregs:
self.add_qreg(QuantumRegister(qreg.size, qreg.name))
edge_map.update([(qbit, qbit) for qbit in qreg if qbit not in edge_map])
for creg in dag.cregs.values():
if creg.name not in self.cregs:
self.add_creg(ClassicalRegister(creg.size, creg.name))
edge_map.update([(cbit, cbit) for cbit in creg if cbit not in edge_map])
self.compose_back(dag, edge_map)
def compose_back(self, input_circuit, edge_map=None):
"""Apply the input circuit to the output of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of input qubits of the input circuit are mapped
to a subset of output qubits of this circuit.
Args:
input_circuit (DAGCircuit): circuit to append
edge_map (dict): map {(Register, int): (Register, int)}
from the output wires of input_circuit to input wires
of self.
Raises:
DAGCircuitError: if missing, duplicate or incosistent wire
"""
edge_map = edge_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map for duplicate values
if len(set(edge_map.values())) != len(edge_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_edgemap_registers(edge_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(edge_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(edge_map, input_circuit.input_map,
self.output_map)
# Compose
self.basis = union_basis
self.gates = union_gates
for node in nx.topological_sort(input_circuit.multi_graph):
nd = input_circuit.multi_graph.node[node]
if nd["type"] == "in":
# if in wire_map, get new name, else use existing name
m_wire = edge_map.get(nd["wire"], nd["wire"])
# the mapped wire should already exist
if m_wire not in self.output_map:
raise DAGCircuitError("wire (%s,%d) not in self" % (m_wire[0].name, m_wire[1]))
if nd["wire"] not in input_circuit.wires:
raise DAGCircuitError("inconsistent wire type for (%s,%d) in input_circuit"
% (nd["wire"][0].name, nd["wire"][1]))
elif nd["type"] == "out":
# ignore output nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(edge_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: edge_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: edge_map.get(x, x), nd["cargs"]))
self.apply_operation_back(nd["op"], m_qargs, m_cargs, condition)
else:
raise DAGCircuitError("bad node type %s" % nd["type"])
# FIXME: this does not work as expected. it is also not used anywhere
def compose_front(self, input_circuit, wire_map=None):
"""Apply the input circuit to the input of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of output qubits of the input circuit are mapped
to a subset of input qubits of this circuit.
Args:
input_circuit (DAGCircuit): circuit to append
wire_map (dict): map {(Register, int): (Register, int)}
from the output wires of input_circuit to input wires
of self.
Raises:
DAGCircuitError: missing, duplicate or inconsistent wire
"""
wire_map = wire_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_edgemap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.output_map,
self.input_map)
# Compose
self.basis = union_basis
self.gates = union_gates
for n in reversed(list(nx.topological_sort(input_circuit.multi_graph))):
nd = input_circuit.multi_graph.node[n]
if nd["type"] == "out":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["wire"], nd["wire"])
# the mapped wire should already exist
if m_name not in self.input_map:
raise DAGCircuitError("wire (%s,%d) not in self" % (m_name[0].name, m_name[1]))
if nd["wire"] not in input_circuit.wires:
raise DAGCircuitError(
"inconsistent wire for (%s,%d) in input_circuit"
% (nd["wire"][0].name, nd["wire"][1]))
elif nd["type"] == "in":
# ignore input nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
self.apply_operation_front(nd["op"], condition)
else:
raise DAGCircuitError("bad node type %s" % nd["type"])
def size(self):
"""Return the number of operations."""
return self.multi_graph.order() - 2 * len(self.wires)
def depth(self):
"""Return the circuit depth.
Returns:
int: the circuit depth
Raises:
DAGCircuitError: if not a directed acyclic graph
"""
if not nx.is_directed_acyclic_graph(self.multi_graph):
raise DAGCircuitError("not a DAG")
return nx.dag_longest_path_length(self.multi_graph) - 1
def width(self):
"""Return the total number of qubits used by the circuit."""
return len(self.wires) - self.num_cbits()
def num_cbits(self):
"""Return the total number of bits used by the circuit."""
return sum(creg.size for creg in self.cregs.values())
def num_tensor_factors(self):
"""Compute how many components the circuit can decompose into."""
return nx.number_weakly_connected_components(self.multi_graph)
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.gates[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.gates[name]["n_args"] > 0:
out += "(" + ",".join(self.gates[name]["args"]) + ")"
out += " " + ",".join(self.gates[name]["bits"])
if self.gates[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.gates[name]["body"].qasm() + "}"
return out
def qasm(self, no_decls=False, qeflag=False, aliases=None, eval_symbols=False):
"""Return a string containing QASM for this circuit.
Args:
qeflag (bool): if True, add a line to include "qelib1.inc"
and only generate gate code for gates not in qelib1.
eval_symbols (bool): if True, evaluate all symbolic
expressions to their floating point representation.
no_decls (bool): if True, only print the instructions.
aliases (dict): if not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
Returns:
str: OpenQASM representation of the DAG
Raises:
DAGCircuitError: if dag nodes not in expected format
"""
# TODO: some of the input flags are not needed anymore
# Rename qregs if necessary
if aliases:
qregdata = OrderedDict()
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
# Write top matter
if no_decls:
out = ""
else:
printed_gates = []
out = "OPENQASM 2.0;\n"
if qeflag:
out += "include \"qelib1.inc\";\n"
for k, v in qregdata.items():
out += "qreg %s[%d];\n" % (k, v.size)
for k, v in self.cregs.items():
out += "creg %s[%d];\n" % (k, v.size)
omit = ["U", "CX", "measure", "reset", "barrier"]
# TODO: dagcircuit shouldn't know about extensions
if qeflag:
qelib = ["u3", "u2", "u1", "cx", "id", "x", "y", "z", "h",
"s", "sdg", "t", "tdg", "cz", "cy", "ccx", "cu1",
"cu3", "swap", "cswap", "u0", "rx", "ry", "rz",
"ch", "crz", "rzz"]
omit.extend(qelib)
printed_gates.extend(qelib)
simulator_instructions = ["snapshot", "save", "load", "noise", "wait"]
omit.extend(simulator_instructions)
for k in self.basis.keys():
if k not in omit:
if not self.gates[k]["opaque"]:
calls = self.gates[k]["body"].calls()
for c in calls:
if c not in printed_gates:
out += self._gate_string(c) + "\n"
printed_gates.append(c)
if k not in printed_gates:
out += self._gate_string(k) + "\n"
printed_gates.append(k)
# Write the instructions
for n in nx.lexicographical_topological_sort(
self.multi_graph, key=lambda x: (self.multi_graph.nodes[x]["type"],
self.multi_graph.nodes[x]["name"])):
nd = self.multi_graph.node[n]
if nd["type"] == "op":
if nd["condition"] is not None:
out += "if(%s==%d) " \
% (nd["condition"][0], nd["condition"][1])
if not nd["cargs"]:
nm = nd["op"].name
if aliases:
qarglist = map(lambda x: aliases[x], nd["qargs"])
else:
qarglist = nd["qargs"]
qarg = ",".join(map(lambda x: "%s[%d]" % (x[0].name, x[1]),
qarglist))
if nd["op"].param:
if eval_symbols:
param = ",".join(map(lambda x: str(x.evalf()),
nd["op"].param))
else:
param = ",".join(map(lambda x: x.replace("**", "^"),
map(str, nd["op"].param)))
out += "%s(%s) %s;\n" % (nm, param, qarg)
else:
out += "%s %s;\n" % (nm, qarg)
else:
if nd["op"].name == "measure":
if len(nd["cargs"]) != 1 or len(nd["qargs"]) != 1 \
or nd["op"].param:
raise DAGCircuitError("bad node data")
qname = nd["qargs"][0][0].name
qindex = nd["qargs"][0][1]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
out += "measure %s[%d] -> %s[%d];\n" \
% (qname,
qindex,
nd["cargs"][0][0].name,
nd["cargs"][0][1])
else:
raise DAGCircuitError("bad node data")
return out
def _check_wires_list(self, wires, op, input_circuit, condition=None):
"""Check that a list of wires satisfies some conditions.
- no duplicate names
- correct length for operation
- elements are wires of input_circuit
Raise an exception otherwise.
Args:
wires (list[register, index]): gives an order for (qu)bits
in the input_circuit that is replacing the operation.
op (Instruction): operation
input_circuit (DAGCircuit): replacement circuit for operation
condition (tuple or None): if this instance of the
operation is classically controlled by a (ClassicalRegister, int)
Raises:
DAGCircuitError: if check doesn't pass.
"""
if len(set(wires)) != len(wires):
raise DAGCircuitError("duplicate wires")
wire_tot = len(op.qargs) + len(op.cargs)
if condition is not None:
wire_tot += condition[0].size
if len(wires) != wire_tot:
raise DAGCircuitError("expected %d wires, got %d"
% (wire_tot, len(wires)))
for w in wires:
if w not in input_circuit.wires:
raise DAGCircuitError("wire (%s,%d) not in input circuit"
% (w[0], w[1]))
def _make_pred_succ_maps(self, n):
"""Return predecessor and successor dictionaries.
Args:
n (int): reference to self.multi_graph node id
Returns:
set(dict): set({predecessor_map, successor_map})
These map from wire (Register, int) to predecessor (successor)
nodes of n.
"""
pred_map = {e[2]['wire']: e[0] for e in
self.multi_graph.in_edges(nbunch=n, data=True)}
succ_map = {e[2]['wire']: e[1] for e in
self.multi_graph.out_edges(nbunch=n, data=True)}
return pred_map, succ_map
def _full_pred_succ_maps(self, pred_map, succ_map, input_circuit,
wire_map):
"""Map all wires of the input circuit.
Map all wires of the input circuit to predecessor and
successor nodes in self, keyed on wires in self.
Args:
pred_map (dict): comes from _make_pred_succ_maps
succ_map (dict): comes from _make_pred_succ_maps
input_circuit (DAGCircuit): the input circuit
wire_map (dict): the map from wires of input_circuit to wires of self
Returns:
tuple: full_pred_map, full_succ_map (dict, dict)
Raises:
DAGCircuitError: if more than one predecessor for output nodes
"""
full_pred_map = {}
full_succ_map = {}
for w in input_circuit.input_map:
# If w is wire mapped, find the corresponding predecessor
# of the node
if w in wire_map:
full_pred_map[wire_map[w]] = pred_map[wire_map[w]]
full_succ_map[wire_map[w]] = succ_map[wire_map[w]]
else:
# Otherwise, use the corresponding output nodes of self
# and compute the predecessor.
full_succ_map[w] = self.output_map[w]
full_pred_map[w] = self.multi_graph.predecessors(
self.output_map[w])[0]
if len(list(self.multi_graph.predecessors(self.output_map[w]))) != 1:
raise DAGCircuitError(
"too many predecessors for (%s,%d) output node" % (w[0], w[1])
)
return full_pred_map, full_succ_map
@staticmethod
def _match_dag_nodes(node1, node2):
"""
Check if DAG nodes are considered equivalent, e.g. as a node_match for nx.is_isomorphic.
Args:
node1 (dict): A node to compare.
node2 (dict): The other node to compare.
Returns:
Bool: If node1 == node2
"""
copy_node1 = {k: v for (k, v) in node1.items()}
copy_node2 = {k: v for (k, v) in node2.items()}
return copy_node1 == copy_node2
def __eq__(self, other):
return nx.is_isomorphic(self.multi_graph, other.multi_graph,
node_match=DAGCircuit._match_dag_nodes)
def node_nums_in_topological_order(self):
"""
Returns the nodes (their ids) in topological order.
Returns:
list: The list of node numbers in topological order
"""
return nx.topological_sort(self.multi_graph)
def substitute_circuit_all(self, op, input_circuit, wires=None):
"""Replace every occurrence of operation op with input_circuit.
Args:
op (Instruction): operation type to substitute across the dag.
input_circuit (DAGCircuit): what to replace with
wires (list[register, index]): gives an order for (qu)bits
in the input_circuit that is replacing the operation.
Raises:
DAGCircuitError: if met with unexpected predecessor/successors
"""
# TODO: rewrite this method to call substitute_circuit_one
wires = wires or []
if op.name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% op.name)
self._check_wires_list(wires, op, input_circuit)
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: (QuantumRegister(1, 'proxy'), 0) for w in wires}
add_qregs = self._check_edgemap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Iterate through the nodes of self and replace the selected nodes
# by iterating through the input_circuit, constructing and
# checking the validity of the wire_map for each replacement
# NOTE: We do not replace conditioned gates. One way to implement
# this later is to add or update the conditions of each gate
# that we add from the input_circuit.
self.basis = union_basis
self.gates = union_gates
for n in self.node_nums_in_topological_order():
nd = self.multi_graph.node[n]
if nd["type"] == "op" and nd["op"] == op:
if nd["condition"] is None:
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"], nd["cargs"]]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map)
pred_map, succ_map = self._make_pred_succ_maps(n)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(n)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map,
md["condition"])
m_qargs = [wire_map.get(x, x) for x in md["qargs0"]]
m_cargs = [wire_map.get(x, x) for x in md["cargs0"]]
self._add_op_node(md["op"], m_qargs, m_cargs, condition)
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter,
name="%s[%s]" % (q[0].name, q[1]),
wire=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w],
full_succ_map[w],
name="%s[%s]" % (w[0].name, w[1]),
wire=w)
o_pred = list(self.multi_graph.predecessors(
self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise DAGCircuitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise DAGCircuitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(
p[0], self.output_map[w])
def substitute_circuit_one(self, node, input_circuit, wires=None):
"""Replace one node with input_circuit.
Args:
node (int): node of self.multi_graph (of type "op") to substitute
input_circuit (DAGCircuit): circuit that will substitute the node
wires (list[(Register, index)]): gives an order for (qu)bits
in the input circuit. This order gets matched to the node wires
by qargs first, then cargs, then conditions.
Raises:
DAGCircuitError: if met with unexpected predecessor/successors
"""
wires = wires or []
nd = self.multi_graph.node[node]
self._check_wires_list(wires, nd["op"], input_circuit, nd["condition"])
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: QuantumRegister(1, 'proxy') for w in wires}
add_qregs = self._check_edgemap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Replace the node by iterating through the input_circuit.
# Constructing and checking the validity of the wire_map.
# If a gate is conditioned, we expect the replacement subcircuit
# to depend on those control bits as well.
self.basis = union_basis
self.gates = union_gates
if nd["type"] != "op":
raise DAGCircuitError("expected node type \"op\", got %s"
% nd["type"])
condition_bit_list = self._bits_in_condition(nd["condition"])
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"],
nd["cargs"],
condition_bit_list]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map)
pred_map, succ_map = self._make_pred_succ_maps(node)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(node)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map, md["condition"])
m_qargs = list(map(lambda x: wire_map.get(x, x),
md["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x),
md["cargs"]))
self._add_op_node(md["op"], m_qargs, m_cargs, condition)
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter,
name="%s[%s]" % (q[0].name, q[1]),
wire=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w],
full_succ_map[w],
name="%s[%s]" % (w[0].name, w[1]),
wire=w)
o_pred = list(self.multi_graph.predecessors(self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise DAGCircuitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise DAGCircuitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(p[0], self.output_map[w])
def get_op_nodes(self, op=None, data=False):
"""Get the list of "op" nodes in the dag.
Note: this method returns all nodes of a given op type (e.g. HGate),
and does not look at the gate operands. Because in the future, the
operands won't even be part of the gate.
Args:
op (Instruction or None): op nodes to return. if op=None, return
all op nodes.
data (bool): Default: False. If True, return a list of tuple
(node_id, node_data). If False, return a list of int (node_id)
Returns:
list: the list of node ids containing the given op.
"""
nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data["type"] == "op":
if op is None:
nodes.append((node_id, node_data))
elif type(node_data["op"]) is type(op):
nodes.append((node_id, node_data))
if not data:
nodes = [n[0] for n in nodes]
return nodes
def get_gate_nodes(self, data=False):
"""Get the list of gate nodes in the dag.
Args:
data (bool): Default: False. If True, return a list of tuple
(node_id, node_data). If False, return a list of int (node_id)
Returns:
list: the list of node ids that represent gates.
"""
nodes = []
for node_id, node_data in self.get_op_nodes(data=True):
if isinstance(node_data['op'], Gate):
nodes.append((node_id, node_data))
if not data:
nodes = [n[0] for n in nodes]
return nodes
def get_named_nodes(self, name):
"""Get the set of "op" node ids with the given name."""
if name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% name)
# We need to instantiate the full list now because the underlying multi_graph
# may change when users iterate over the named nodes.
return {node_id for node_id, data in self.multi_graph.nodes(data=True)
if data["type"] == "op" and data["op"].name == name}
def get_cnot_nodes(self):
"""Get the set of Cnot."""
cx_names = ['cx', 'CX']
cxs_nodes = []
for cx_name in cx_names:
if cx_name in self.basis:
for cx_id in self.get_named_nodes(cx_name):
cxs_nodes.append(self.multi_graph.node[cx_id])
return cxs_nodes
def _remove_op_node(self, n):
"""Remove an operation node n.
Add edges from predecessors to successors.
"""
pred_map, succ_map = self._make_pred_succ_maps(n)
self.multi_graph.remove_node(n)
for w in pred_map.keys():
self.multi_graph.add_edge(pred_map[w], succ_map[w],
name="%s[%s]" % (w[0].name, w[1]), wire=w)
def remove_ancestors_of(self, node):
"""Remove all of the ancestor operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
# TODO: probably better to do all at once using
# multi_graph.remove_nodes_from; same for related functions ...
for n in anc:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_descendants_of(self, node):
"""Remove all of the descendant operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
for n in dec:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nonancestors_of(self, node):
"""Remove all of the non-ancestors operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(anc))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nondescendants_of(self, node):
"""Remove all of the non-descendants operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(dec))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def layers(self):
"""Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit.
A layer is a circuit whose gates act on disjoint qubits, i.e.
a layer has depth 1. The total number of layers equals the
circuit depth d. The layers are indexed from 0 to d-1 with the
earliest layer at index 0. The layers are constructed using a
greedy algorithm. Each returned layer is a dict containing
{"graph": circuit graph, "partition": list of qubit lists}.
TODO: Gates that use the same cbits will end up in different
layers as this is currently implemented. This may not be
the desired behavior.
"""
graph_layers = self.multigraph_layers()
try:
next(graph_layers) # Remove input nodes
except StopIteration:
return
def nodes_data(nodes):
"""Construct full nodes from just node ids."""
return ((node_id, self.multi_graph.nodes[node_id]) for node_id in nodes)
for graph_layer in graph_layers:
# Get the op nodes from the layer, removing any input and output nodes.
op_nodes = [node for node in nodes_data(graph_layer) if node[1]["type"] == "op"]
# Stop yielding once there are no more op_nodes in a layer.
if not op_nodes:
return
# Construct a shallow copy of self
new_layer = copy.copy(self)
new_layer.multi_graph = nx.MultiDiGraph()
new_layer.multi_graph.add_nodes_from(nodes_data(self.input_map.values()))
new_layer.multi_graph.add_nodes_from(nodes_data(self.output_map.values()))
# The quantum registers that have an operation in this layer.
support_list = [
op_node[1]["qargs"]
for op_node in op_nodes
if op_node[1]["op"].name not in {"barrier", "snapshot", "save", "load", "noise"}
]
new_layer.multi_graph.add_nodes_from(op_nodes)
# Now add the edges to the multi_graph
# By default we just wire inputs to the outputs.
wires = {self.input_map[wire]: self.output_map[wire]
for wire in self.wires}
# Wire inputs to op nodes, and op nodes to outputs.
for op_node in op_nodes:
args = self._bits_in_condition(op_node[1]["condition"]) \
+ op_node[1]["cargs"] + op_node[1]["qargs"]
arg_ids = (self.input_map[(arg[0], arg[1])] for arg in args)
for arg_id in arg_ids:
wires[arg_id], wires[op_node[0]] = op_node[0], wires[arg_id]
# Add wiring to/from the operations and between unused inputs & outputs.
new_layer.multi_graph.add_edges_from(wires.items())
yield {"graph": new_layer, "partition": support_list}
def serial_layers(self):
"""Yield a layer for all gates of this circuit.
A serial layer is a circuit with one gate. The layers have the
same structure as in layers().
"""
for n in self.node_nums_in_topological_order():
nxt_nd = self.multi_graph.node[n]
if nxt_nd["type"] == "op":
new_layer = DAGCircuit()
for qreg in self.qregs.values():
new_layer.add_qreg(qreg)
for creg in self.cregs.values():
new_layer.add_creg(creg)
new_layer.basis = self.basis.copy()
new_layer.gates = self.gates.copy()
# Save the support of the operation we add to the layer
support_list = []
# Operation data
op = copy.copy(nxt_nd["op"])
qa = copy.copy(nxt_nd["qargs"])
ca = copy.copy(nxt_nd["cargs"])
co = copy.copy(nxt_nd["condition"])
_ = self._bits_in_condition(co)
# Add node to new_layer
new_layer.apply_operation_back(op, qa, ca, co)
# Add operation to partition
if nxt_nd["name"] not in ["barrier",
"snapshot", "save", "load", "noise"]:
support_list.append(list(qa))
l_dict = {"graph": new_layer, "partition": support_list}
yield l_dict
def multigraph_layers(self):
"""Yield layers of the multigraph."""
predecessor_count = dict() # Dict[node, predecessors not visited]
cur_layer = [node for node in self.input_map.values()]
yield cur_layer
next_layer = []
while cur_layer:
for node in cur_layer:
# Count multiedges with multiplicity.
for successor in self.multi_graph.successors(node):
multiplicity = self.multi_graph.number_of_edges(node, successor)
if successor in predecessor_count:
predecessor_count[successor] -= multiplicity
else:
predecessor_count[successor] = \
self.multi_graph.in_degree(successor) - multiplicity
if predecessor_count[successor] == 0:
next_layer.append(successor)
del predecessor_count[successor]
yield next_layer
cur_layer = next_layer
next_layer = []
def collect_runs(self, namelist):
"""Return a set of runs of "op" nodes with the given names.
For example, "... h q[0]; cx q[0],q[1]; cx q[0],q[1]; h q[1]; .."
would produce the tuple of cx nodes as an element of the set returned
from a call to collect_runs(["cx"]). If instead the cx nodes were
"cx q[0],q[1]; cx q[1],q[0];", the method would still return the
pair in a tuple. The namelist can contain names that are not
in the circuit's basis.
Nodes must have only one successor to continue the run.
"""
group_list = []
# Iterate through the nodes of self in topological order
# and form tuples containing sequences of gates
# on the same qubit(s).
ts = list(self.node_nums_in_topological_order())
nodes_seen = dict(zip(ts, [False] * len(ts)))
for node in ts:
nd = self.multi_graph.node[node]
if nd["type"] == "op" and nd["name"] in namelist \
and not nodes_seen[node]:
group = [node]
nodes_seen[node] = True
s = list(self.multi_graph.successors(node))
while len(s) == 1 and \
self.multi_graph.node[s[0]]["type"] == "op" and \
self.multi_graph.node[s[0]]["name"] in namelist:
group.append(s[0])
nodes_seen[s[0]] = True
s = list(self.multi_graph.successors(s[0]))
if len(group) > 1:
group_list.append(tuple(group))
return set(group_list)
def count_ops(self):
"""Count the occurrences of operation names.
Returns a dictionary of counts keyed on the operation name.
"""
op_dict = {}
for node in self.node_nums_in_topological_order():
nd = self.multi_graph.node[node]
name = nd["name"]
if nd["type"] == "op":
if name not in op_dict:
op_dict[name] = 1
else:
op_dict[name] += 1
return op_dict
def properties(self):
"""Return a dictionary of circuit properties."""
summary = {"size": self.size(),
"depth": self.depth(),
"width": self.width(),
"bits": self.num_cbits(),
"factors": self.num_tensor_factors(),
"operations": self.count_ops()}
return summary
<|code_end|>
qiskit/transpiler/passes/mapping/direction_mapper.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A direction mapper rearrenges the direction of the cx nodes to make the circuit
compatible to the directed coupling map.
"""
from qiskit.transpiler._basepasses import TransformationPass
from qiskit.transpiler import MapperError
from qiskit.dagcircuit import DAGCircuit
from qiskit.mapper import Layout
from qiskit.extensions.standard import HGate
class DirectionMapper(TransformationPass):
"""
Rearranges the direction of the cx nodes to make the circuit
compatible with the directed coupling map.
It uses this equivalence:
---(+)--- --[H]---.---[H]--
| = |
----.---- --[H]--(+)--[H]--
"""
def __init__(self, coupling_map, initial_layout=None):
"""
Args:
coupling_map (Coupling): Directed graph represented a coupling map.
initial_layout (Layout): The initial layout of the DAG.
"""
super().__init__()
self.coupling_map = coupling_map
self.layout = initial_layout
def run(self, dag):
"""
Flips the cx nodes to match the directed coupling map.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: The rearranged dag for the coupling map
Raises:
MapperError: If the circuit cannot be mapped just by flipping the
cx nodes.
"""
new_dag = DAGCircuit()
if self.layout is None:
# create a one-to-one layout
self.layout = Layout()
wire_no = 0
for qreg in dag.qregs.values():
for index in range(qreg.size):
self.layout[(qreg, index)] = wire_no
wire_no += 1
for layer in dag.serial_layers():
subdag = layer['graph']
for cnot in subdag.get_cnot_nodes():
control = cnot['op'].qargs[0]
target = cnot['op'].qargs[1]
physical_q0 = self.layout[control]
physical_q1 = self.layout[target]
if self.coupling_map.distance(physical_q0, physical_q1) != 1:
raise MapperError('The circuit requires a connectiontion between the phsycial '
'qubits %s and %s' % (physical_q0, physical_q1))
if (physical_q0, physical_q1) not in self.coupling_map.get_edges():
# A flip needs to be done
# Create the involved registers
if control[0] not in subdag.qregs.values():
subdag.add_qreg(control[0])
if target[0] not in subdag.qregs.values():
subdag.add_qreg(target[0])
# Add H gates around
subdag.add_basis_element('h', 1, 0, 0)
subdag.apply_operation_back(HGate(target))
subdag.apply_operation_back(HGate(control))
subdag.apply_operation_front(HGate(target))
subdag.apply_operation_front(HGate(control))
# Flips the CX
cnot['op'].qargs[0], cnot['op'].qargs[1] = target, control
new_dag.extend_back(subdag)
return new_dag
<|code_end|>
|
Handling old-format jobs (test_get_jobs_filter_job_status)
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Information
We are experiencing some intermitent failures at `test.python.ibmq.test_ibmqjob.TestIBMQJob.test_get_jobs_filter_job_status` (specifically, seems to happen at premium):
https://travis-ci.org/Qiskit/qiskit-terra/jobs/461104008
```
1: b'Traceback (most recent call last):'
1: b' File "/home/travis/build/Qiskit/qiskit-terra/test/python/ibmq/test_ibmqjob.py", line 283, in test_get_jobs_filter_job_status'
1: b" self.log.info('match #%d: %s', i, job.result().status)"
1: b' File "/home/travis/build/Qiskit/qiskit-terra/qiskit/backends/ibmq/ibmqjob.py", line 210, in result'
1: b' return self._result_from_job_response(job_response)'
1: b' File "/home/travis/build/Qiskit/qiskit-terra/qiskit/backends/ibmq/ibmqjob.py", line 506, in _result_from_job_response'
1: b' _reorder_bits(job_response)'
1: b' File "/home/travis/build/Qiskit/qiskit-terra/qiskit/backends/ibmq/ibmqjob.py", line 546, in _reorder_bits'
1: b" for circuit_result in job_data['qasms']:"
1: b"KeyError: 'qasms'"
1: b''
```
This seems to be because of the co-existence of different formats currently, and sort of accounted for - by 0.7, all jobs created and stored should have the same format. However, we should provide a cleaner way of dealing with pre-0.7 style jobs, revising the functions that retrieve them from the API (and emitting a warning if an old-style job cannot be parsed or similar).
### What is the expected behavior?
### Suggested solutions
|
qiskit/backends/ibmq/ibmqbackend.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""IbmQ module
This module is used for connecting to the Quantum Experience.
"""
import logging
import warnings
from marshmallow import ValidationError
from qiskit import QiskitError
from qiskit.backends import BaseBackend, JobStatus, JobError
from qiskit.backends.models import BackendStatus, BackendProperties
from .api import ApiError
from .ibmqjob import IBMQJob, IBMQJobPreQobj
logger = logging.getLogger(__name__)
class IBMQBackend(BaseBackend):
"""Backend class interfacing with the Quantum Experience remotely.
"""
def __init__(self, configuration, provider, credentials, api):
"""Initialize remote backend for IBM Quantum Experience.
Args:
configuration (BackendConfiguration): configuration of backend.
provider (IBMQProvider): provider.
credentials (Credentials): credentials.
api (IBMQConnector):
api for communicating with the Quantum Experience.
"""
super().__init__(provider=provider, configuration=configuration)
self._api = api
self._credentials = credentials
self.hub = credentials.hub
self.group = credentials.group
self.project = credentials.project
def run(self, qobj):
"""Run qobj asynchronously.
Args:
qobj (dict): description of job
Returns:
IBMQJob: an instance derived from BaseJob
"""
job_class = _job_class_from_backend_support(self)
job = job_class(self, None, self._api,
not self.configuration().simulator, qobj=qobj)
job.submit()
return job
def properties(self):
"""Return the online backend properties.
The return is via QX API call.
Returns:
BackendProperties: The properties of the backend. If the backend
is a simulator, it returns ``None``.
"""
if self.configuration().simulator:
return None
api_properties = self._api.backend_properties(self.name())
return BackendProperties.from_dict(api_properties)
def status(self):
"""Return the online backend status.
Returns:
BackendStatus: The status of the backend.
Raises:
LookupError: If status for the backend can't be found.
IBMQBackendError: If the status can't be formatted properly.
"""
api_status = self._api.backend_status(self.name())
try:
return BackendStatus.from_dict(api_status)
except ValidationError as ex:
raise LookupError(
"Couldn't get backend status: {0}".format(ex))
def jobs(self, limit=50, skip=0, status=None, db_filter=None):
"""Attempt to get the jobs submitted to the backend.
Args:
limit (int): number of jobs to retrieve
skip (int): starting index of retrieval
status (None or JobStatus or str): only get jobs with this status,
where status is e.g. `JobStatus.RUNNING` or `'RUNNING'`
db_filter (dict): `loopback-based filter
<https://loopback.io/doc/en/lb2/Querying-data.html>`_.
This is an interface to a database ``where`` filter. Some
examples of its usage are:
Filter last five jobs with errors::
job_list = backend.jobs(limit=5, status=JobStatus.ERROR)
Filter last five jobs with counts=1024, and counts for
states ``00`` and ``11`` each exceeding 400::
cnts_filter = {'shots': 1024,
'qasms.result.data.counts.00': {'gt': 400},
'qasms.result.data.counts.11': {'gt': 400}}
job_list = backend.jobs(limit=5, db_filter=cnts_filter)
Filter last five jobs from 30 days ago::
past_date = datetime.datetime.now() - datetime.timedelta(days=30)
date_filter = {'creationDate': {'lt': past_date.isoformat()}}
job_list = backend.jobs(limit=5, db_filter=date_filter)
Returns:
list(IBMQJob): list of IBMQJob instances
Raises:
IBMQBackendValueError: status keyword value unrecognized
"""
backend_name = self.name()
api_filter = {'backend.name': backend_name}
if status:
if isinstance(status, str):
status = JobStatus[status]
if status == JobStatus.RUNNING:
this_filter = {'status': 'RUNNING',
'infoQueue': {'exists': False}}
elif status == JobStatus.QUEUED:
this_filter = {'status': 'RUNNING',
'infoQueue.status': 'PENDING_IN_QUEUE'}
elif status == JobStatus.CANCELLED:
this_filter = {'status': 'CANCELLED'}
elif status == JobStatus.DONE:
this_filter = {'status': 'COMPLETED'}
elif status == JobStatus.ERROR:
this_filter = {'status': {'regexp': '^ERROR'}}
else:
raise IBMQBackendValueError('unrecognized value for "status" keyword '
'in job filter')
api_filter.update(this_filter)
if db_filter:
# status takes precedence over db_filter for same keys
api_filter = {**db_filter, **api_filter}
job_info_list = self._api.get_status_jobs(limit=limit, skip=skip,
filter=api_filter)
job_list = []
for job_info in job_info_list:
job_class = _job_class_from_job_response(job_info)
if job_class is IBMQJobPreQobj:
warnings.warn('The result of job {} is in an old and no longer supported format, '
'please resend the job with Qiskit 0.7'.format(job_info.get('id')),
DeprecationWarning)
continue
is_device = not bool(self.configuration().simulator)
job = job_class(self, job_info.get('id'), self._api, is_device,
creation_date=job_info.get('creationDate'),
api_status=job_info.get('status'))
job_list.append(job)
return job_list
def retrieve_job(self, job_id):
"""Attempt to get the specified job by job_id
Args:
job_id (str): the job id of the job to retrieve
Returns:
IBMQJob: class instance
Raises:
IBMQBackendError: if retrieval failed
DeprecatedFormatJobError: if the job retrieved has a format pre 0.7
"""
try:
job_info = self._api.get_status_job(job_id)
if 'error' in job_info:
raise IBMQBackendError('Failed to get job "{}": {}'
.format(job_id, job_info['error']))
except ApiError as ex:
raise IBMQBackendError('Failed to get job "{}":{}'
.format(job_id, str(ex)))
job_class = _job_class_from_job_response(job_info)
if job_class is IBMQJobPreQobj:
raise DeprecatedFormatJobError('The result of job {} is in an old and no '
'longer supported format, please resend the '
'job with Qiskit 0.7'.format(job_id))
is_device = not bool(self.configuration().simulator)
job = job_class(self, job_info.get('id'), self._api, is_device,
creation_date=job_info.get('creationDate'),
api_status=job_info.get('status'))
return job
def __repr__(self):
credentials_info = ''
if self.hub:
credentials_info = '{}, {}, {}'.format(self.hub, self.group,
self.project)
return "<{}('{}') from IBMQ({})>".format(
self.__class__.__name__, self.name(), credentials_info)
class IBMQBackendError(QiskitError):
"""IBM Q Backend Errors"""
pass
class IBMQBackendValueError(IBMQBackendError, ValueError):
"""Value errors thrown within IBMQBackend """
pass
class DeprecatedFormatJobError(JobError):
"""Retrieving responses pre-qobj is no longer supported."""
pass
def _job_class_from_job_response(job_response):
is_qobj = job_response.get('kind', None) == 'q-object'
return IBMQJob if is_qobj else IBMQJobPreQobj
def _job_class_from_backend_support(backend):
support_qobj = getattr(backend.configuration(), 'allow_q_object', False)
return IBMQJob if support_qobj else IBMQJobPreQobj
<|code_end|>
qiskit/backends/ibmq/ibmqjob.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""IBMQJob module
This module is used for creating asynchronous job objects for the
IBM Q Experience.
"""
from concurrent import futures
import time
import logging
import pprint
import contextlib
import json
import datetime
import numpy
from qiskit.qobj import qobj_to_dict
from qiskit.transpiler import transpile_dag
from qiskit.backends import BaseJob, JobError, JobTimeoutError
from qiskit.backends.jobstatus import JobStatus, JOB_FINAL_STATES
from qiskit.result import Result
from qiskit.result._utils import result_from_old_style_dict
from qiskit.qobj import validate_qobj_against_schema
from .api import ApiError
logger = logging.getLogger(__name__)
API_FINAL_STATES = (
'COMPLETED',
'CANCELLED',
'ERROR_CREATING_JOB',
'ERROR_VALIDATING_JOB',
'ERROR_RUNNING_JOB'
)
class IBMQJob(BaseJob):
"""Represent the jobs that will be executed on IBM-Q simulators and real
devices. Jobs are intended to be created calling ``run()`` on a particular
backend.
Creating a ``Job`` instance does not imply running it. You need to do it in
separate steps::
job = IBMQJob(...)
job.submit() # It won't block.
An error while submitting a job will cause the next call to ``status()`` to
raise. If submitting the job successes, you can inspect the job's status by
using ``status()``. Status can be one of ``JobStatus`` members::
from qiskit.backends.jobstatus import JobStatus
job = IBMQJob(...)
job.submit()
try:
job_status = job.status() # It won't block. It will query the backend API.
if job_status is JobStatus.RUNNING:
print('The job is still running')
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
A call to ``status()`` can raise if something happens at the API level that
prevents Qiskit from determining the status of the job. An example of this
is a temporary connection lose or a network failure.
The ``submit()`` and ``status()`` methods are examples of non-blocking API.
``Job`` instances also have `id()` and ``result()`` methods which will
block::
job = IBMQJob(...)
job.submit()
try:
job_id = job.id() # It will block until completing submission.
print('The job {} was successfully submitted'.format(job_id))
job_result = job.result() # It will block until finishing.
print('The job finished with result {}'.format(job_result))
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
Both methods can raise if something ath the API level happens that prevent
Qiskit from determining the status of the job.
.. NOTE::
When querying the API for getting the status, two kinds of errors are
possible. The most severe is the one preventing Qiskit from getting a
response from the backend. This can be caused by a network failure or a
temporary system break. In these cases, calling ``status()`` will raise.
If Qiskit successfully retrieves the status of a job, it could be it
finished with errors. In that case, ``status()`` will simply return
``JobStatus.ERROR`` and you can call ``error_message()`` to get more
info.
Attributes:
_executor (futures.Executor): executor to handle asynchronous jobs
"""
_executor = futures.ThreadPoolExecutor()
def __init__(self, backend, job_id, api, is_device, qobj=None,
creation_date=None, api_status=None):
"""IBMQJob init function.
We can instantiate jobs from two sources: A QObj, and an already submitted job returned by
the API servers.
Args:
backend (str): The backend instance used to run this job.
job_id (str): The job ID of an already submitted job. Pass `None`
if you are creating a new one.
api (IBMQConnector): IBMQ connector.
is_device (bool): whether backend is a real device # TODO: remove this after Qobj
qobj (Qobj): The Quantum Object. See notes below
creation_date (str): When the job was run.
api_status (str): `status` field directly from the API response.
Notes:
It is mandatory to pass either ``qobj`` or ``job_id``. Passing a ``qobj``
will ignore ``job_id`` and will create an instance to be submitted to the
API server for job creation. Passing only a `job_id`will create an instance
representing an already-created job retrieved from the API server.
"""
super().__init__(backend, job_id)
self._job_data = None
if qobj is not None:
validate_qobj_against_schema(qobj)
self._qobj_payload = qobj_to_dict(qobj, version='1.0.0')
# TODO: No need for this conversion, just use the new equivalent members above
old_qobj = qobj_to_dict(qobj, version='0.0.1')
self._job_data = {
'circuits': old_qobj['circuits'],
'hpc': old_qobj['config'].get('hpc'),
'seed': old_qobj['circuits'][0]['config']['seed'],
'shots': old_qobj['config']['shots'],
'max_credits': old_qobj['config']['max_credits']
}
else:
self._qobj_payload = {}
self._future_captured_exception = None
self._api = api
self._backend = backend
self._cancelled = False
self._status = JobStatus.INITIALIZING
# In case of not providing a `qobj`, it is assumed the job already
# exists in the API (with `job_id`).
if qobj is None:
# Some API calls (`get_status_jobs`, `get_status_job`) provide
# enough information to recreate the `Job`. If that is the case, try
# to make use of that information during instantiation, as
# `self.status()` involves an extra call to the API.
if api_status == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_status == 'COMPLETED':
self._status = JobStatus.DONE
elif api_status == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
else:
self.status()
self._queue_position = None
self._is_device = is_device
def current_utc_time():
"""Gets the current time in UTC format"""
datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
self._creation_date = creation_date or current_utc_time()
self._future = None
self._api_error_msg = None
# pylint: disable=arguments-differ
def result(self, timeout=None, wait=5):
"""Return the result from the job.
Args:
timeout (int): number of seconds to wait for job
wait (int): time between queries to IBM Q server
Returns:
qiskit.Result: Result object
Raises:
JobError: exception raised during job initialization
"""
job_response = self._wait_for_result(timeout=timeout, wait=wait)
return self._result_from_job_response(job_response)
def _wait_for_result(self, timeout=None, wait=5):
self._wait_for_submission()
try:
job_response = self._wait_for_job(timeout=timeout, wait=wait)
except ApiError as api_err:
raise JobError(str(api_err))
status = self.status()
if status is not JobStatus.DONE:
raise JobError('Invalid job state. The job should be DONE but '
'it is {}'.format(str(status)))
return job_response
def _result_from_job_response(self, job_response):
return Result.from_dict(job_response['qObjectResult'])
def cancel(self):
"""Attempt to cancel a job.
Returns:
bool: True if job can be cancelled, else False. Currently this is
only possible on commercial systems.
Raises:
JobError: if there was some unexpected failure in the server
"""
hub = self._api.config.get('hub', None)
group = self._api.config.get('group', None)
project = self._api.config.get('project', None)
try:
response = self._api.cancel_job(self._job_id, hub, group, project)
self._cancelled = 'error' not in response
return self._cancelled
except ApiError as error:
self._cancelled = False
raise JobError('Error cancelling job: %s' % error.usr_msg)
def status(self):
"""Query the API to update the status.
Returns:
JobStatus: The status of the job, once updated.
Raises:
JobError: if there was an exception in the future being executed
or the server sent an unknown answer.
"""
# Implies self._job_id is None
if self._future_captured_exception is not None:
raise JobError(str(self._future_captured_exception))
if self._job_id is None or self._status in JOB_FINAL_STATES:
return self._status
try:
# TODO: See result values
api_job = self._api.get_status_job(self._job_id)
if 'status' not in api_job:
raise JobError('get_status_job didn\'t return status: %s' %
pprint.pformat(api_job))
# pylint: disable=broad-except
except Exception as err:
raise JobError(str(err))
if api_job['status'] == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_job['status'] == 'RUNNING':
self._status = JobStatus.RUNNING
queued, self._queue_position = _is_job_queued(api_job)
if queued:
self._status = JobStatus.QUEUED
elif api_job['status'] == 'COMPLETED':
self._status = JobStatus.DONE
elif api_job['status'] == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
elif 'ERROR' in api_job['status']:
# Error status are of the form "ERROR_*_JOB"
self._status = JobStatus.ERROR
# TODO: This seems to be an inconsistency in the API package.
self._api_error_msg = api_job.get('error') or api_job.get('Error')
else:
raise JobError('Unrecognized answer from server: \n{}'
.format(pprint.pformat(api_job)))
return self._status
def error_message(self):
"""Return the error message returned from the API server response."""
return self._api_error_msg
def queue_position(self):
"""Return the position in the server queue.
Returns:
Number: Position in the queue.
"""
return self._queue_position
def creation_date(self):
"""
Return creation date.
"""
return self._creation_date
def job_id(self):
"""Return backend determined id.
If the Id is not set because the job is already initializing, this call
will block until we have an Id.
"""
self._wait_for_submission()
return self._job_id
def submit(self):
"""Submit job to IBM-Q.
Raises:
JobError: If we have already submitted the job.
"""
# TODO: Validation against the schema should be done here and not
# during initialization. Once done, we should document that the method
# can raise QobjValidationError.
if self._future is not None or self._job_id is not None:
raise JobError("We have already submitted the job!")
self._future = self._executor.submit(self._submit_callback)
def _submit_callback(self):
"""Submit qobj job to IBM-Q.
Returns:
dict: A dictionary with the response of the submitted job
"""
backend_name = self.backend().name()
try:
submit_info = self._api.run_job(self._qobj_payload, backend=backend_name)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submission success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _wait_for_job(self, timeout=60, wait=5):
"""Wait until all online ran circuits of a qobj are 'COMPLETED'.
Args:
timeout (float or None): seconds to wait for job. If None, wait
indefinitely.
wait (float): seconds between queries
Returns:
dict: A dict with the contents of the API request.
Raises:
JobTimeoutError: if the job does not return results before a specified timeout.
JobError: if something wrong happened in some of the server API calls
"""
start_time = time.time()
while self.status() not in JOB_FINAL_STATES:
elapsed_time = time.time() - start_time
if timeout is not None and elapsed_time >= timeout:
raise JobTimeoutError(
'Timeout while waiting for the job: {}'.format(self._job_id)
)
logger.info('status = %s (%d seconds)', self._status, elapsed_time)
time.sleep(wait)
if self._cancelled:
raise JobError(
'Job result impossible to retrieve. The job was cancelled.')
return self._api.get_job(self._job_id)
def _wait_for_submission(self, timeout=60):
"""Waits for the request to return a job ID"""
if self._job_id is None:
if self._future is None:
raise JobError("You have to submit before asking for status or results!")
try:
submit_info = self._future.result(timeout=timeout)
if self._future_captured_exception is not None:
# pylint can't see if catch of None type
# pylint: disable=raising-bad-type
raise self._future_captured_exception
except TimeoutError as ex:
raise JobTimeoutError(
"Timeout waiting for the job being submitted: {}".format(ex)
)
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
raise JobError(str(submit_info['error']))
class IBMQJobPreQobj(IBMQJob):
"""
Subclass of IBMQJob for handling pre-qobj jobs.
"""
def _submit_callback(self):
"""Submit old style qasms job to IBM-Q. Can remove when all devices
understand Qobj.
Returns:
dict: A dictionary with the response of the submitted job
"""
api_jobs = []
circuits = self._job_data['circuits']
for circuit in circuits:
job = _create_api_job_from_circuit(circuit)
api_jobs.append(job)
hpc_camel_cased = _format_hpc_parameters(self._job_data['hpc'])
seed = self._job_data['seed']
shots = self._job_data['shots']
max_credits = self._job_data['max_credits']
try:
submit_info = self._api.run_job(api_jobs, backend=self.backend().name(),
shots=shots, max_credits=max_credits,
seed=seed, hpc=hpc_camel_cased)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submission success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _result_from_job_response(self, job_response):
if self._is_device:
_reorder_bits(job_response)
experiment_results = []
for circuit_result in job_response['qasms']:
this_result = {'data': circuit_result['data'],
'compiled_circuit_qasm': circuit_result.get('qasm'),
'status': circuit_result['status'],
'success': circuit_result['status'] == 'DONE',
'shots': job_response['shots']}
if 'metadata' in circuit_result:
this_result['metadata'] = circuit_result['metadata']
if 'header' in circuit_result['metadata'].get('compiled_circuit', {}):
this_result['header'] = \
circuit_result['metadata']['compiled_circuit']['header']
else:
this_result['header'] = {}
experiment_results.append(this_result)
ret = {
'id': self._job_id,
'status': job_response['status'],
'used_credits': job_response.get('usedCredits'),
'result': experiment_results,
'backend_name': self.backend().name(),
'success': job_response['status'] == 'COMPLETED',
}
# Append header: from the response; from the payload; or none.
header = job_response.get('header',
self._qobj_payload.get('header', {}))
if header:
ret['header'] = header
return result_from_old_style_dict(ret)
def _reorder_bits(job_data):
"""Temporary fix for ibmq backends.
For every ran circuit, get reordering information from qobj
and apply reordering on result.
Args:
job_data (dict): dict with the bare contents of the API.get_job request.
Raises:
JobError: raised if the creg sizes don't add up in result header.
"""
for circuit_result in job_data['qasms']:
if 'metadata' in circuit_result:
circ = circuit_result['metadata'].get('compiled_circuit')
else:
logger.warning('result object missing metadata for reordering'
' bits: bits may be out of order')
return
# device_qubit -> device_clbit (how it should have been)
measure_dict = {op['qubits'][0]: op['memory'][0]
for op in circ['operations']
if op['name'] == 'measure'}
counts_dict_new = {}
for item in circuit_result['data']['counts'].items():
# fix clbit ordering to what it should have been
bits = list(item[0])
bits.reverse() # lsb in 0th position
count = item[1]
reordered_bits = list('x' * len(bits))
for device_clbit, bit in enumerate(bits):
if device_clbit in measure_dict:
correct_device_clbit = measure_dict[device_clbit]
reordered_bits[correct_device_clbit] = bit
reordered_bits.reverse()
# only keep the clbits specified by circuit, not everything on device
num_clbits = circ['header']['memory_slots']
compact_key = reordered_bits[-num_clbits:]
compact_key = "".join([b if b != 'x' else '0'
for b in compact_key])
# insert spaces to signify different classical registers
cregs = circ['header']['creg_sizes']
if sum([creg[1] for creg in cregs]) != num_clbits:
raise JobError("creg sizes don't add up in result header.")
creg_begin_pos = []
creg_end_pos = []
acc = 0
for creg in reversed(cregs):
creg_size = creg[1]
creg_begin_pos.append(acc)
creg_end_pos.append(acc + creg_size)
acc += creg_size
compact_key = " ".join([compact_key[creg_begin_pos[i]:creg_end_pos[i]]
for i in range(len(cregs))])
# marginalize over unwanted measured qubits
if compact_key not in counts_dict_new:
counts_dict_new[compact_key] = count
else:
counts_dict_new[compact_key] += count
circuit_result['data']['counts'] = counts_dict_new
def _numpy_type_converter(obj):
ret = obj
if isinstance(obj, numpy.integer):
ret = int(obj)
elif isinstance(obj, numpy.floating): # pylint: disable=no-member
ret = float(obj)
elif isinstance(obj, numpy.ndarray):
ret = obj.tolist()
return ret
def _create_api_job_from_circuit(circuit):
"""Helper function that creates a special job required by the API, from a circuit."""
api_job = {}
if not circuit.get('compiled_circuit_qasm'):
compiled_circuit = transpile_dag(circuit['circuit'])
circuit['compiled_circuit_qasm'] = compiled_circuit.qasm(qeflag=True)
if isinstance(circuit['compiled_circuit_qasm'], bytes):
api_job['qasm'] = circuit['compiled_circuit_qasm'].decode()
else:
api_job['qasm'] = circuit['compiled_circuit_qasm']
if circuit.get('name'):
api_job['name'] = circuit['name']
# convert numpy types for json serialization
compiled_circuit = json.loads(json.dumps(circuit['compiled_circuit'],
default=_numpy_type_converter))
api_job['metadata'] = {'compiled_circuit': compiled_circuit}
return api_job
def _is_job_queued(api_job_response):
"""Checks whether a job has been queued or not."""
is_queued, position = False, 0
if 'infoQueue' in api_job_response:
if 'status' in api_job_response['infoQueue']:
queue_status = api_job_response['infoQueue']['status']
is_queued = queue_status == 'PENDING_IN_QUEUE'
if 'position' in api_job_response['infoQueue']:
position = api_job_response['infoQueue']['position']
return is_queued, position
def _format_hpc_parameters(hpc):
"""Helper function to get HPC parameters with the correct format"""
if hpc is None:
return None
hpc_camel_cased = None
with contextlib.suppress(KeyError, TypeError):
# Use CamelCase when passing the hpc parameters to the API.
hpc_camel_cased = {
'multiShotOptimization': hpc['multi_shot_optimization'],
'ompNumThreads': hpc['omp_num_threads']
}
return hpc_camel_cased
<|code_end|>
|
qiskit/backends/ibmq/ibmqbackend.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""IbmQ module
This module is used for connecting to the Quantum Experience.
"""
import logging
import warnings
from marshmallow import ValidationError
from qiskit import QiskitError
from qiskit.backends import BaseBackend, JobStatus
from qiskit.backends.models import BackendStatus, BackendProperties
from .api import ApiError
from .ibmqjob import IBMQJob, IBMQJobPreQobj
logger = logging.getLogger(__name__)
class IBMQBackend(BaseBackend):
"""Backend class interfacing with the Quantum Experience remotely.
"""
def __init__(self, configuration, provider, credentials, api):
"""Initialize remote backend for IBM Quantum Experience.
Args:
configuration (BackendConfiguration): configuration of backend.
provider (IBMQProvider): provider.
credentials (Credentials): credentials.
api (IBMQConnector):
api for communicating with the Quantum Experience.
"""
super().__init__(provider=provider, configuration=configuration)
self._api = api
self._credentials = credentials
self.hub = credentials.hub
self.group = credentials.group
self.project = credentials.project
def run(self, qobj):
"""Run qobj asynchronously.
Args:
qobj (dict): description of job
Returns:
IBMQJob: an instance derived from BaseJob
"""
job_class = _job_class_from_backend_support(self)
job = job_class(self, None, self._api,
not self.configuration().simulator, qobj=qobj)
job.submit()
return job
def properties(self):
"""Return the online backend properties.
The return is via QX API call.
Returns:
BackendProperties: The properties of the backend. If the backend
is a simulator, it returns ``None``.
"""
if self.configuration().simulator:
return None
api_properties = self._api.backend_properties(self.name())
return BackendProperties.from_dict(api_properties)
def status(self):
"""Return the online backend status.
Returns:
BackendStatus: The status of the backend.
Raises:
LookupError: If status for the backend can't be found.
IBMQBackendError: If the status can't be formatted properly.
"""
api_status = self._api.backend_status(self.name())
try:
return BackendStatus.from_dict(api_status)
except ValidationError as ex:
raise LookupError(
"Couldn't get backend status: {0}".format(ex))
def jobs(self, limit=50, skip=0, status=None, db_filter=None):
"""Attempt to get the jobs submitted to the backend.
Args:
limit (int): number of jobs to retrieve
skip (int): starting index of retrieval
status (None or JobStatus or str): only get jobs with this status,
where status is e.g. `JobStatus.RUNNING` or `'RUNNING'`
db_filter (dict): `loopback-based filter
<https://loopback.io/doc/en/lb2/Querying-data.html>`_.
This is an interface to a database ``where`` filter. Some
examples of its usage are:
Filter last five jobs with errors::
job_list = backend.jobs(limit=5, status=JobStatus.ERROR)
Filter last five jobs with counts=1024, and counts for
states ``00`` and ``11`` each exceeding 400::
cnts_filter = {'shots': 1024,
'qasms.result.data.counts.00': {'gt': 400},
'qasms.result.data.counts.11': {'gt': 400}}
job_list = backend.jobs(limit=5, db_filter=cnts_filter)
Filter last five jobs from 30 days ago::
past_date = datetime.datetime.now() - datetime.timedelta(days=30)
date_filter = {'creationDate': {'lt': past_date.isoformat()}}
job_list = backend.jobs(limit=5, db_filter=date_filter)
Returns:
list(IBMQJob): list of IBMQJob instances
Raises:
IBMQBackendValueError: status keyword value unrecognized
"""
backend_name = self.name()
api_filter = {'backend.name': backend_name}
if status:
if isinstance(status, str):
status = JobStatus[status]
if status == JobStatus.RUNNING:
this_filter = {'status': 'RUNNING',
'infoQueue': {'exists': False}}
elif status == JobStatus.QUEUED:
this_filter = {'status': 'RUNNING',
'infoQueue.status': 'PENDING_IN_QUEUE'}
elif status == JobStatus.CANCELLED:
this_filter = {'status': 'CANCELLED'}
elif status == JobStatus.DONE:
this_filter = {'status': 'COMPLETED'}
elif status == JobStatus.ERROR:
this_filter = {'status': {'regexp': '^ERROR'}}
else:
raise IBMQBackendValueError('unrecognized value for "status" keyword '
'in job filter')
api_filter.update(this_filter)
if db_filter:
# status takes precedence over db_filter for same keys
api_filter = {**db_filter, **api_filter}
job_info_list = self._api.get_status_jobs(limit=limit, skip=skip,
filter=api_filter)
job_list = []
for job_info in job_info_list:
job_class = _job_class_from_job_response(job_info)
if job_class is IBMQJobPreQobj:
warnings.warn('The result of job {} is in a no longer supported format. '
'These jobs will stop working after Qiskit 0.7. Save the results '
'or send the job with Qiskit 0.7+'.format(job_info.get('id')),
DeprecationWarning)
is_device = not bool(self.configuration().simulator)
job = job_class(self, job_info.get('id'), self._api, is_device,
creation_date=job_info.get('creationDate'),
api_status=job_info.get('status'))
job_list.append(job)
return job_list
def retrieve_job(self, job_id):
"""Attempt to get the specified job by job_id
Args:
job_id (str): the job id of the job to retrieve
Returns:
IBMQJob: class instance
Raises:
IBMQBackendError: if retrieval failed
"""
try:
job_info = self._api.get_status_job(job_id)
if 'error' in job_info:
raise IBMQBackendError('Failed to get job "{}": {}'
.format(job_id, job_info['error']))
except ApiError as ex:
raise IBMQBackendError('Failed to get job "{}":{}'
.format(job_id, str(ex)))
job_class = _job_class_from_job_response(job_info)
if job_class is IBMQJobPreQobj:
warnings.warn('The result of job {} is in a no longer supported format. '
'These jobs will stop working after Qiskit 0.7. Save the results '
'or send the job with Qiskit 0.7+'.format(job_id),
DeprecationWarning)
is_device = not bool(self.configuration().simulator)
job = job_class(self, job_info.get('id'), self._api, is_device,
creation_date=job_info.get('creationDate'),
api_status=job_info.get('status'))
return job
def __repr__(self):
credentials_info = ''
if self.hub:
credentials_info = '{}, {}, {}'.format(self.hub, self.group,
self.project)
return "<{}('{}') from IBMQ({})>".format(
self.__class__.__name__, self.name(), credentials_info)
class IBMQBackendError(QiskitError):
"""IBM Q Backend Errors"""
pass
class IBMQBackendValueError(IBMQBackendError, ValueError):
"""Value errors thrown within IBMQBackend """
pass
def _job_class_from_job_response(job_response):
is_qobj = job_response.get('kind', None) == 'q-object'
return IBMQJob if is_qobj else IBMQJobPreQobj
def _job_class_from_backend_support(backend):
support_qobj = getattr(backend.configuration(), 'allow_q_object', False)
return IBMQJob if support_qobj else IBMQJobPreQobj
<|code_end|>
qiskit/backends/ibmq/ibmqjob.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""IBMQJob module
This module is used for creating asynchronous job objects for the
IBM Q Experience.
"""
from concurrent import futures
import time
import logging
import pprint
import contextlib
import json
import datetime
import numpy
from qiskit.qobj import qobj_to_dict
from qiskit.transpiler import transpile_dag
from qiskit.backends import BaseJob, JobError, JobTimeoutError
from qiskit.backends.jobstatus import JobStatus, JOB_FINAL_STATES
from qiskit.result import Result
from qiskit.result._utils import result_from_old_style_dict
from qiskit.qobj import validate_qobj_against_schema
from .api import ApiError
logger = logging.getLogger(__name__)
API_FINAL_STATES = (
'COMPLETED',
'CANCELLED',
'ERROR_CREATING_JOB',
'ERROR_VALIDATING_JOB',
'ERROR_RUNNING_JOB'
)
class IBMQJob(BaseJob):
"""Represent the jobs that will be executed on IBM-Q simulators and real
devices. Jobs are intended to be created calling ``run()`` on a particular
backend.
Creating a ``Job`` instance does not imply running it. You need to do it in
separate steps::
job = IBMQJob(...)
job.submit() # It won't block.
An error while submitting a job will cause the next call to ``status()`` to
raise. If submitting the job successes, you can inspect the job's status by
using ``status()``. Status can be one of ``JobStatus`` members::
from qiskit.backends.jobstatus import JobStatus
job = IBMQJob(...)
job.submit()
try:
job_status = job.status() # It won't block. It will query the backend API.
if job_status is JobStatus.RUNNING:
print('The job is still running')
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
A call to ``status()`` can raise if something happens at the API level that
prevents Qiskit from determining the status of the job. An example of this
is a temporary connection lose or a network failure.
The ``submit()`` and ``status()`` methods are examples of non-blocking API.
``Job`` instances also have `id()` and ``result()`` methods which will
block::
job = IBMQJob(...)
job.submit()
try:
job_id = job.id() # It will block until completing submission.
print('The job {} was successfully submitted'.format(job_id))
job_result = job.result() # It will block until finishing.
print('The job finished with result {}'.format(job_result))
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
Both methods can raise if something ath the API level happens that prevent
Qiskit from determining the status of the job.
.. NOTE::
When querying the API for getting the status, two kinds of errors are
possible. The most severe is the one preventing Qiskit from getting a
response from the backend. This can be caused by a network failure or a
temporary system break. In these cases, calling ``status()`` will raise.
If Qiskit successfully retrieves the status of a job, it could be it
finished with errors. In that case, ``status()`` will simply return
``JobStatus.ERROR`` and you can call ``error_message()`` to get more
info.
Attributes:
_executor (futures.Executor): executor to handle asynchronous jobs
"""
_executor = futures.ThreadPoolExecutor()
def __init__(self, backend, job_id, api, is_device, qobj=None,
creation_date=None, api_status=None):
"""IBMQJob init function.
We can instantiate jobs from two sources: A QObj, and an already submitted job returned by
the API servers.
Args:
backend (str): The backend instance used to run this job.
job_id (str): The job ID of an already submitted job. Pass `None`
if you are creating a new one.
api (IBMQConnector): IBMQ connector.
is_device (bool): whether backend is a real device # TODO: remove this after Qobj
qobj (Qobj): The Quantum Object. See notes below
creation_date (str): When the job was run.
api_status (str): `status` field directly from the API response.
Notes:
It is mandatory to pass either ``qobj`` or ``job_id``. Passing a ``qobj``
will ignore ``job_id`` and will create an instance to be submitted to the
API server for job creation. Passing only a `job_id`will create an instance
representing an already-created job retrieved from the API server.
"""
super().__init__(backend, job_id)
self._job_data = None
if qobj is not None:
validate_qobj_against_schema(qobj)
self._qobj_payload = qobj_to_dict(qobj, version='1.0.0')
# TODO: No need for this conversion, just use the new equivalent members above
old_qobj = qobj_to_dict(qobj, version='0.0.1')
self._job_data = {
'circuits': old_qobj['circuits'],
'hpc': old_qobj['config'].get('hpc'),
'seed': old_qobj['circuits'][0]['config']['seed'],
'shots': old_qobj['config']['shots'],
'max_credits': old_qobj['config']['max_credits']
}
else:
self._qobj_payload = {}
self._future_captured_exception = None
self._api = api
self._backend = backend
self._cancelled = False
self._status = JobStatus.INITIALIZING
# In case of not providing a `qobj`, it is assumed the job already
# exists in the API (with `job_id`).
if qobj is None:
# Some API calls (`get_status_jobs`, `get_status_job`) provide
# enough information to recreate the `Job`. If that is the case, try
# to make use of that information during instantiation, as
# `self.status()` involves an extra call to the API.
if api_status == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_status == 'COMPLETED':
self._status = JobStatus.DONE
elif api_status == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
else:
self.status()
self._queue_position = None
self._is_device = is_device
def current_utc_time():
"""Gets the current time in UTC format"""
datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
self._creation_date = creation_date or current_utc_time()
self._future = None
self._api_error_msg = None
# pylint: disable=arguments-differ
def result(self, timeout=None, wait=5):
"""Return the result from the job.
Args:
timeout (int): number of seconds to wait for job
wait (int): time between queries to IBM Q server
Returns:
qiskit.Result: Result object
Raises:
JobError: exception raised during job initialization
"""
job_response = self._wait_for_result(timeout=timeout, wait=wait)
return self._result_from_job_response(job_response)
def _wait_for_result(self, timeout=None, wait=5):
self._wait_for_submission()
try:
job_response = self._wait_for_job(timeout=timeout, wait=wait)
except ApiError as api_err:
raise JobError(str(api_err))
status = self.status()
if status is not JobStatus.DONE:
raise JobError('Invalid job state. The job should be DONE but '
'it is {}'.format(str(status)))
return job_response
def _result_from_job_response(self, job_response):
return Result.from_dict(job_response['qObjectResult'])
def cancel(self):
"""Attempt to cancel a job.
Returns:
bool: True if job can be cancelled, else False. Currently this is
only possible on commercial systems.
Raises:
JobError: if there was some unexpected failure in the server
"""
hub = self._api.config.get('hub', None)
group = self._api.config.get('group', None)
project = self._api.config.get('project', None)
try:
response = self._api.cancel_job(self._job_id, hub, group, project)
self._cancelled = 'error' not in response
return self._cancelled
except ApiError as error:
self._cancelled = False
raise JobError('Error cancelling job: %s' % error.usr_msg)
def status(self):
"""Query the API to update the status.
Returns:
JobStatus: The status of the job, once updated.
Raises:
JobError: if there was an exception in the future being executed
or the server sent an unknown answer.
"""
# Implies self._job_id is None
if self._future_captured_exception is not None:
raise JobError(str(self._future_captured_exception))
if self._job_id is None or self._status in JOB_FINAL_STATES:
return self._status
try:
# TODO: See result values
api_job = self._api.get_status_job(self._job_id)
if 'status' not in api_job:
raise JobError('get_status_job didn\'t return status: %s' %
pprint.pformat(api_job))
# pylint: disable=broad-except
except Exception as err:
raise JobError(str(err))
if api_job['status'] == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_job['status'] == 'RUNNING':
self._status = JobStatus.RUNNING
queued, self._queue_position = _is_job_queued(api_job)
if queued:
self._status = JobStatus.QUEUED
elif api_job['status'] == 'COMPLETED':
self._status = JobStatus.DONE
elif api_job['status'] == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
elif 'ERROR' in api_job['status']:
# Error status are of the form "ERROR_*_JOB"
self._status = JobStatus.ERROR
# TODO: This seems to be an inconsistency in the API package.
self._api_error_msg = api_job.get('error') or api_job.get('Error')
else:
raise JobError('Unrecognized answer from server: \n{}'
.format(pprint.pformat(api_job)))
return self._status
def error_message(self):
"""Return the error message returned from the API server response."""
return self._api_error_msg
def queue_position(self):
"""Return the position in the server queue.
Returns:
Number: Position in the queue.
"""
return self._queue_position
def creation_date(self):
"""
Return creation date.
"""
return self._creation_date
def job_id(self):
"""Return backend determined id.
If the Id is not set because the job is already initializing, this call
will block until we have an Id.
"""
self._wait_for_submission()
return self._job_id
def submit(self):
"""Submit job to IBM-Q.
Raises:
JobError: If we have already submitted the job.
"""
# TODO: Validation against the schema should be done here and not
# during initialization. Once done, we should document that the method
# can raise QobjValidationError.
if self._future is not None or self._job_id is not None:
raise JobError("We have already submitted the job!")
self._future = self._executor.submit(self._submit_callback)
def _submit_callback(self):
"""Submit qobj job to IBM-Q.
Returns:
dict: A dictionary with the response of the submitted job
"""
backend_name = self.backend().name()
try:
submit_info = self._api.run_job(self._qobj_payload, backend=backend_name)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submission success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _wait_for_job(self, timeout=60, wait=5):
"""Wait until all online ran circuits of a qobj are 'COMPLETED'.
Args:
timeout (float or None): seconds to wait for job. If None, wait
indefinitely.
wait (float): seconds between queries
Returns:
dict: A dict with the contents of the API request.
Raises:
JobTimeoutError: if the job does not return results before a specified timeout.
JobError: if something wrong happened in some of the server API calls
"""
start_time = time.time()
while self.status() not in JOB_FINAL_STATES:
elapsed_time = time.time() - start_time
if timeout is not None and elapsed_time >= timeout:
raise JobTimeoutError(
'Timeout while waiting for the job: {}'.format(self._job_id)
)
logger.info('status = %s (%d seconds)', self._status, elapsed_time)
time.sleep(wait)
if self._cancelled:
raise JobError(
'Job result impossible to retrieve. The job was cancelled.')
return self._api.get_job(self._job_id)
def _wait_for_submission(self, timeout=60):
"""Waits for the request to return a job ID"""
if self._job_id is None:
if self._future is None:
raise JobError("You have to submit before asking for status or results!")
try:
submit_info = self._future.result(timeout=timeout)
if self._future_captured_exception is not None:
# pylint can't see if catch of None type
# pylint: disable=raising-bad-type
raise self._future_captured_exception
except TimeoutError as ex:
raise JobTimeoutError(
"Timeout waiting for the job being submitted: {}".format(ex)
)
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
raise JobError(str(submit_info['error']))
class IBMQJobPreQobj(IBMQJob):
"""
Subclass of IBMQJob for handling pre-qobj jobs.
"""
def _submit_callback(self):
"""Submit old style qasms job to IBM-Q. Can remove when all devices
understand Qobj.
Returns:
dict: A dictionary with the response of the submitted job
"""
api_jobs = []
circuits = self._job_data['circuits']
for circuit in circuits:
job = _create_api_job_from_circuit(circuit)
api_jobs.append(job)
hpc_camel_cased = _format_hpc_parameters(self._job_data['hpc'])
seed = self._job_data['seed']
shots = self._job_data['shots']
max_credits = self._job_data['max_credits']
try:
submit_info = self._api.run_job(api_jobs, backend=self.backend().name(),
shots=shots, max_credits=max_credits,
seed=seed, hpc=hpc_camel_cased)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submission success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _result_from_job_response(self, job_response):
if self._is_device:
_reorder_bits(job_response)
experiment_results = []
for circuit_result in job_response['qasms']:
this_result = {'data': circuit_result['data'],
'compiled_circuit_qasm': circuit_result.get('qasm'),
'status': circuit_result['status'],
'success': circuit_result['status'] == 'DONE',
'shots': job_response['shots']}
if 'metadata' in circuit_result:
this_result['metadata'] = circuit_result['metadata']
if 'header' in circuit_result['metadata'].get('compiled_circuit', {}):
this_result['header'] = \
circuit_result['metadata']['compiled_circuit']['header']
else:
this_result['header'] = {}
experiment_results.append(this_result)
ret = {
'id': self._job_id,
'status': job_response['status'],
'used_credits': job_response.get('usedCredits'),
'result': experiment_results,
'backend_name': self.backend().name(),
'success': job_response['status'] == 'COMPLETED',
}
# Append header: from the response; from the payload; or none.
header = job_response.get('header',
self._qobj_payload.get('header', {}))
if header:
ret['header'] = header
return result_from_old_style_dict(ret)
def _reorder_bits(job_data):
"""Temporary fix for ibmq backends.
For every ran circuit, get reordering information from qobj
and apply reordering on result.
Args:
job_data (dict): dict with the bare contents of the API.get_job request.
Raises:
JobError: raised if the creg sizes don't add up in result header.
"""
for circuit_result in job_data['qasms']:
if 'metadata' in circuit_result:
circ = circuit_result['metadata'].get('compiled_circuit')
else:
logger.warning('result object missing metadata for reordering'
' bits: bits may be out of order')
return
# device_qubit -> device_clbit (how it should have been)
measure_dict = {op['qubits'][0]: op['clbits'][0]
for op in circ['operations']
if op['name'] == 'measure'}
counts_dict_new = {}
for item in circuit_result['data']['counts'].items():
# fix clbit ordering to what it should have been
bits = list(item[0])
bits.reverse() # lsb in 0th position
count = item[1]
reordered_bits = list('x' * len(bits))
for device_clbit, bit in enumerate(bits):
if device_clbit in measure_dict:
correct_device_clbit = measure_dict[device_clbit]
reordered_bits[correct_device_clbit] = bit
reordered_bits.reverse()
# only keep the clbits specified by circuit, not everything on device
num_clbits = circ['header']['number_of_clbits']
compact_key = reordered_bits[-num_clbits:]
compact_key = "".join([b if b != 'x' else '0'
for b in compact_key])
# insert spaces to signify different classical registers
cregs = circ['header']['clbit_labels']
if sum([creg[1] for creg in cregs]) != num_clbits:
raise JobError("creg sizes don't add up in result header.")
creg_begin_pos = []
creg_end_pos = []
acc = 0
for creg in reversed(cregs):
creg_size = creg[1]
creg_begin_pos.append(acc)
creg_end_pos.append(acc + creg_size)
acc += creg_size
compact_key = " ".join([compact_key[creg_begin_pos[i]:creg_end_pos[i]]
for i in range(len(cregs))])
# marginalize over unwanted measured qubits
if compact_key not in counts_dict_new:
counts_dict_new[compact_key] = count
else:
counts_dict_new[compact_key] += count
circuit_result['data']['counts'] = counts_dict_new
def _numpy_type_converter(obj):
ret = obj
if isinstance(obj, numpy.integer):
ret = int(obj)
elif isinstance(obj, numpy.floating): # pylint: disable=no-member
ret = float(obj)
elif isinstance(obj, numpy.ndarray):
ret = obj.tolist()
return ret
def _create_api_job_from_circuit(circuit):
"""Helper function that creates a special job required by the API, from a circuit."""
api_job = {}
if not circuit.get('compiled_circuit_qasm'):
compiled_circuit = transpile_dag(circuit['circuit'])
circuit['compiled_circuit_qasm'] = compiled_circuit.qasm(qeflag=True)
if isinstance(circuit['compiled_circuit_qasm'], bytes):
api_job['qasm'] = circuit['compiled_circuit_qasm'].decode()
else:
api_job['qasm'] = circuit['compiled_circuit_qasm']
if circuit.get('name'):
api_job['name'] = circuit['name']
# convert numpy types for json serialization
compiled_circuit = json.loads(json.dumps(circuit['compiled_circuit'],
default=_numpy_type_converter))
api_job['metadata'] = {'compiled_circuit': compiled_circuit}
return api_job
def _is_job_queued(api_job_response):
"""Checks whether a job has been queued or not."""
is_queued, position = False, 0
if 'infoQueue' in api_job_response:
if 'status' in api_job_response['infoQueue']:
queue_status = api_job_response['infoQueue']['status']
is_queued = queue_status == 'PENDING_IN_QUEUE'
if 'position' in api_job_response['infoQueue']:
position = api_job_response['infoQueue']['position']
return is_queued, position
def _format_hpc_parameters(hpc):
"""Helper function to get HPC parameters with the correct format"""
if hpc is None:
return None
hpc_camel_cased = None
with contextlib.suppress(KeyError, TypeError):
# Use CamelCase when passing the hpc parameters to the API.
hpc_camel_cased = {
'multiShotOptimization': hpc['multi_shot_optimization'],
'ompNumThreads': hpc['omp_num_threads']
}
return hpc_camel_cased
<|code_end|>
|
Review the messages encouraging the use of slower Python simulators alternatives
### What is the expected enhancement?
After #1484 Python and C++ simulators no longer live under the same `Aer` provider but they are split between `Simulators` and `LegacySimulators` providers respectively. `Simulators` make it clear they are the built-in simulators coming with the foundational Terra element but now, strings such as:
> The 'qasm_simulator' backend is not installed in your system. Consider using a slower backend alternative: 'qasm_simulator_py'
Does not make sense. What should we do? Using `LegacySimulators.get_backend()` prints a deprecated warning. Should we simply remove these messages?
|
qiskit/backends/builtinsimulators/simulatorsprovider.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Provider for built-in simulator backends."""
from collections import OrderedDict
import logging
from qiskit.qiskiterror import QiskitError
from qiskit.backends import BaseProvider
from qiskit.backends.exceptions import QiskitBackendNotFoundError
from qiskit.backends.providerutils import resolve_backend_name, filter_backends
from .qasm_simulator import QasmSimulatorPy
from .statevector_simulator import StatevectorSimulatorPy
from .unitary_simulator import UnitarySimulatorPy
logger = logging.getLogger(__name__)
SIMULATORS = [
QasmSimulatorPy,
StatevectorSimulatorPy,
UnitarySimulatorPy
]
class SimulatorsProvider(BaseProvider):
"""Provider for builtin simulators backends."""
def __init__(self, *args, **kwargs):
super().__init__(args, kwargs)
# Populate the list of builtin simulators backends.
self._backends = self._verify_backends()
def get_backend(self, name=None, **kwargs):
backends = self._backends.values()
# Special handling of the `name` parameter, to support alias resolution
# and deprecated names.
if name:
try:
resolved_name = resolve_backend_name(
name, backends,
self._deprecated_backend_names(),
{},
self._alternative_py_backend_names()
)
name = resolved_name
except LookupError:
raise QiskitBackendNotFoundError(
"The '{}' backend is not installed in your system.".format(name))
return super().get_backend(name=name, **kwargs)
def backends(self, name=None, filters=None, **kwargs):
# pylint: disable=arguments-differ
backends = self._backends.values()
# Special handling of the `name` parameter, to support alias resolution
# and deprecated names.
if name:
try:
resolved_name = resolve_backend_name(
name, backends,
self._deprecated_backend_names(),
{},
self._alternative_py_backend_names()
)
backends = [backend for backend in backends if
backend.name() == resolved_name]
except LookupError:
return []
return filter_backends(backends, filters=filters, **kwargs)
@staticmethod
def _deprecated_backend_names():
"""Returns deprecated backend names."""
return {
'qasm_simulator_py': 'qasm_simulator',
'statevector_simulator_py': 'statevector_simulator',
'unitary_simulator_py': 'unitary_simulator',
'local_qasm_simulator_py': 'qasm_simulator',
'local_statevector_simulator_py': 'statevector_simulator',
'local_unitary_simulator_py': 'unitary_simulator',
'local_unitary_simulator': 'unitary_simulator',
'unitary_simulator': 'unitary_simulator'
}
def _verify_backends(self):
"""
Return the builtin simulators backends in `BACKENDS` that are
effectively available (as some of them might depend on the presence
of an optional dependency or on the existence of a binary).
Returns:
dict[str:BaseBackend]: a dict of builtin simulators backend instances for
the backends that could be instantiated, keyed by backend name.
"""
ret = OrderedDict()
for backend_cls in SIMULATORS:
try:
backend_instance = self._get_backend_instance(backend_cls)
backend_name = backend_instance.name()
ret[backend_name] = backend_instance
except QiskitError as err:
# Ignore backends that could not be initialized.
logger.info('builtin simulators backend %s is not available: %s',
backend_cls, str(err))
return ret
def _get_backend_instance(self, backend_cls):
"""
Return an instance of a backend from its class.
Args:
backend_cls (class): Backend class.
Returns:
BaseBackend: a backend instance.
Raises:
QiskitError: if the backend could not be instantiated.
"""
# Verify that the backend can be instantiated.
try:
backend_instance = backend_cls(provider=self)
except Exception as err:
raise QiskitError('Backend %s could not be instantiated: %s' %
(backend_cls, err))
return backend_instance
def __str__(self):
return 'BasicAer'
@staticmethod
def _alternative_py_backend_names():
"""Return Python alternatives to C++ simulators."""
return {
'qasm_simulator': 'qasm_simulator_py',
'statevector_simulator': 'statevector_simulator_py'
}
<|code_end|>
qiskit/backends/legacysimulators/legacyprovider.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Provider for C++ simulator backends coming from the built-in Aer in versions prior to 0.7"""
import logging
import warnings
from collections import OrderedDict
from qiskit import QiskitError
from qiskit.backends.builtinsimulators import SimulatorsProvider
from .qasm_simulator import QasmSimulator, CliffordSimulator
from .statevector_simulator import StatevectorSimulator
logger = logging.getLogger(__name__)
LEGACY_SIMULATORS = [
QasmSimulator,
StatevectorSimulator,
CliffordSimulator
]
class LegacyProvider(SimulatorsProvider):
"""Provider for legacy simulators backends."""
def get_backend(self, name=None, **kwargs):
warnings.warn('C++ simulators in the `LegacyProvider` are deprecated. Install '
'`qiskit-aer` and import `Aer` from `qiskit` if you want make the most '
'of performance. The `LegacyProvider` will be removed after 0.7',
DeprecationWarning)
return super().get_backend(name=name, **kwargs)
def _verify_backends(self):
"""
Return the legacy simulators backends in `LEGACY_SIMULATORS` that are
effectively available (as some of them might depend on the presence
of an optional dependency or on the existence of a binary).
Returns:
dict[str:BaseBackend]: a dict of legacy simulators backend instances for
the backends that could be instantiated, keyed by backend name.
"""
ret = OrderedDict()
for backend_cls in LEGACY_SIMULATORS:
try:
backend_instance = self._get_backend_instance(backend_cls)
backend_name = backend_instance.name()
ret[backend_name] = backend_instance
except QiskitError as err:
# Ignore backends that could not be initialized.
logger.info('legacy simulator %s is not available: %s',
backend_cls, str(err))
return ret
@staticmethod
def _deprecated_backend_names():
"""Returns deprecated backend names."""
return {
'local_qasm_simulator_cpp': 'qasm_simulator',
'local_statevector_simulator_cpp': 'statevector_simulator',
'local_qiskit_simulator': 'qasm_simulator',
'local_qasm_simulator': 'qasm_simulator',
'local_statevector_simulator': 'statevector_simulator'
}
def __str__(self):
return 'LegacySimulators'
<|code_end|>
qiskit/backends/providerutils.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Utilities for providers."""
import logging
logger = logging.getLogger(__name__)
def filter_backends(backends, filters=None, **kwargs):
"""Return the backends matching the specified filtering.
Filter the `backends` list by their `configuration` or `status`
attributes, or from a boolean callable. The criteria for filtering can
be specified via `**kwargs` or as a callable via `filters`, and the
backends must fulfill all specified conditions.
Args:
backends (list[BaseBackend]): list of backends.
filters (callable): filtering conditions as a callable.
**kwargs (dict): dict of criteria.
Returns:
list[BaseBackend]: a list of backend instances matching the
conditions.
"""
def _match_all(obj, criteria):
"""Return True if all items in criteria matches items in obj."""
return all(getattr(obj, key_, None) == value_ for
key_, value_ in criteria.items())
# Inspect the backends to decide which filters belong to
# backend.configuration and which ones to backend.status, as it does
# not involve querying the API.
configuration_filters = {}
status_filters = {}
for key, value in kwargs.items():
if all(key in backend.configuration() for backend in backends):
configuration_filters[key] = value
else:
status_filters[key] = value
# 1. Apply backend.configuration filtering.
if configuration_filters:
backends = [b for b in backends if
_match_all(b.configuration(), configuration_filters)]
# 2. Apply backend.status filtering (it involves one API call for
# each backend).
if status_filters:
backends = [b for b in backends if
_match_all(b.status(), status_filters)]
# 3. Apply acceptor filter.
backends = list(filter(filters, backends))
return backends
def resolve_backend_name(name, backends, deprecated, aliased, alternatives):
"""Resolve backend name from a deprecated name or an alias.
A group will be resolved in order of member priorities, depending on
availability.
Args:
name (str): name of backend to resolve
backends (list[BaseBackend]): list of available backends.
deprecated (dict[str: str]): dict of deprecated names.
aliased (dict[str: list[str]]): dict of aliased names.
alternatives (dict[str: str]): dict of alternative backends.
Returns:
str: resolved name (name of an available backend)
Raises:
LookupError: if name cannot be resolved through regular available
names, nor deprecated, nor alias names.
"""
available = [backend.name() for backend in backends]
resolved_name = deprecated.get(name, aliased.get(name, name))
if isinstance(resolved_name, list):
resolved_name = next((b for b in resolved_name if b in available), "")
if resolved_name not in available:
if resolved_name in alternatives:
logger.warning("The '%s' backend is not installed in your system. "
"Consider using a slower backend alternative: '%s'",
name,
alternatives[resolved_name])
else:
logger.warning("The '%s' backend is not installed in your system. "
"Consider using one of these slower alternatives: \n%s",
name,
'\n'.join(["- '{}'".format(b) for b in available]))
raise LookupError("backend '{}' not found.".format(name))
if name in deprecated:
logger.warning("WARNING: '%s' is deprecated. Use '%s'.", name, resolved_name)
return resolved_name
<|code_end|>
|
qiskit/backends/builtinsimulators/simulatorsprovider.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Provider for built-in simulator backends."""
from collections import OrderedDict
import logging
from qiskit.qiskiterror import QiskitError
from qiskit.backends import BaseProvider
from qiskit.backends.exceptions import QiskitBackendNotFoundError
from qiskit.backends.providerutils import resolve_backend_name, filter_backends
from .qasm_simulator import QasmSimulatorPy
from .statevector_simulator import StatevectorSimulatorPy
from .unitary_simulator import UnitarySimulatorPy
logger = logging.getLogger(__name__)
SIMULATORS = [
QasmSimulatorPy,
StatevectorSimulatorPy,
UnitarySimulatorPy
]
class SimulatorsProvider(BaseProvider):
"""Provider for builtin simulators backends."""
def __init__(self, *args, **kwargs):
super().__init__(args, kwargs)
# Populate the list of builtin simulators backends.
self._backends = self._verify_backends()
def get_backend(self, name=None, **kwargs):
backends = self._backends.values()
# Special handling of the `name` parameter, to support alias resolution
# and deprecated names.
if name:
try:
resolved_name = resolve_backend_name(
name, backends,
self._deprecated_backend_names(),
{}
)
name = resolved_name
except LookupError:
raise QiskitBackendNotFoundError(
"The '{}' backend is not installed in your system.".format(name))
return super().get_backend(name=name, **kwargs)
def backends(self, name=None, filters=None, **kwargs):
# pylint: disable=arguments-differ
backends = self._backends.values()
# Special handling of the `name` parameter, to support alias resolution
# and deprecated names.
if name:
try:
resolved_name = resolve_backend_name(
name, backends,
self._deprecated_backend_names(),
{}
)
backends = [backend for backend in backends if
backend.name() == resolved_name]
except LookupError:
return []
return filter_backends(backends, filters=filters, **kwargs)
@staticmethod
def _deprecated_backend_names():
"""Returns deprecated backend names."""
return {
'qasm_simulator_py': 'qasm_simulator',
'statevector_simulator_py': 'statevector_simulator',
'unitary_simulator_py': 'unitary_simulator',
'local_qasm_simulator_py': 'qasm_simulator',
'local_statevector_simulator_py': 'statevector_simulator',
'local_unitary_simulator_py': 'unitary_simulator',
'local_unitary_simulator': 'unitary_simulator',
'unitary_simulator': 'unitary_simulator'
}
def _verify_backends(self):
"""
Return the builtin simulators backends in `BACKENDS` that are
effectively available (as some of them might depend on the presence
of an optional dependency or on the existence of a binary).
Returns:
dict[str:BaseBackend]: a dict of builtin simulators backend instances for
the backends that could be instantiated, keyed by backend name.
"""
ret = OrderedDict()
for backend_cls in SIMULATORS:
try:
backend_instance = self._get_backend_instance(backend_cls)
backend_name = backend_instance.name()
ret[backend_name] = backend_instance
except QiskitError as err:
# Ignore backends that could not be initialized.
logger.info('builtin simulators backend %s is not available: %s',
backend_cls, str(err))
return ret
def _get_backend_instance(self, backend_cls):
"""
Return an instance of a backend from its class.
Args:
backend_cls (class): Backend class.
Returns:
BaseBackend: a backend instance.
Raises:
QiskitError: if the backend could not be instantiated.
"""
# Verify that the backend can be instantiated.
try:
backend_instance = backend_cls(provider=self)
except Exception as err:
raise QiskitError('Backend %s could not be instantiated: %s' %
(backend_cls, err))
return backend_instance
def __str__(self):
return 'BasicAer'
<|code_end|>
qiskit/backends/legacysimulators/legacyprovider.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Provider for C++ simulator backends coming from the built-in Aer in versions prior to 0.7"""
import logging
import warnings
from collections import OrderedDict
from qiskit import QiskitError
from qiskit.backends.builtinsimulators import SimulatorsProvider
from .qasm_simulator import QasmSimulator, CliffordSimulator
from .statevector_simulator import StatevectorSimulator
logger = logging.getLogger(__name__)
LEGACY_SIMULATORS = [
QasmSimulator,
StatevectorSimulator,
CliffordSimulator
]
DEPRECATION_MSG = """Simulators in the LegacySimulators provider are deprecated. If you want
maximum compatibility, you can use those in the Simulators provider. If you want to make the most
of performance, consider installing the Qiskit Aer element and user the Aer provider."""
class LegacyProvider(SimulatorsProvider):
"""Provider for legacy simulators backends."""
def backends(self, name=None, filters=None, **kwargs):
warnings.warn(DEPRECATION_MSG, DeprecationWarning)
return super().backends(name=name, filter=filters, **kwargs)
def get_backend(self, name=None, **kwargs):
warnings.warn(DEPRECATION_MSG, DeprecationWarning)
return super().get_backend(name=name, **kwargs)
def _verify_backends(self):
"""
Return the legacy simulators backends in `LEGACY_SIMULATORS` that are
effectively available (as some of them might depend on the presence
of an optional dependency or on the existence of a binary).
Returns:
dict[str:BaseBackend]: a dict of legacy simulators backend instances for
the backends that could be instantiated, keyed by backend name.
"""
ret = OrderedDict()
for backend_cls in LEGACY_SIMULATORS:
try:
backend_instance = self._get_backend_instance(backend_cls)
backend_name = backend_instance.name()
ret[backend_name] = backend_instance
except QiskitError as err:
# Ignore backends that could not be initialized.
logger.info('legacy simulator %s is not available: %s',
backend_cls, str(err))
return ret
@staticmethod
def _deprecated_backend_names():
"""Returns deprecated backend names."""
return {
'local_qasm_simulator_cpp': 'qasm_simulator',
'local_statevector_simulator_cpp': 'statevector_simulator',
'local_qiskit_simulator': 'qasm_simulator',
'local_qasm_simulator': 'qasm_simulator',
'local_statevector_simulator': 'statevector_simulator'
}
def __str__(self):
return 'LegacySimulators'
<|code_end|>
qiskit/backends/providerutils.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Utilities for providers."""
import logging
logger = logging.getLogger(__name__)
def filter_backends(backends, filters=None, **kwargs):
"""Return the backends matching the specified filtering.
Filter the `backends` list by their `configuration` or `status`
attributes, or from a boolean callable. The criteria for filtering can
be specified via `**kwargs` or as a callable via `filters`, and the
backends must fulfill all specified conditions.
Args:
backends (list[BaseBackend]): list of backends.
filters (callable): filtering conditions as a callable.
**kwargs (dict): dict of criteria.
Returns:
list[BaseBackend]: a list of backend instances matching the
conditions.
"""
def _match_all(obj, criteria):
"""Return True if all items in criteria matches items in obj."""
return all(getattr(obj, key_, None) == value_ for
key_, value_ in criteria.items())
# Inspect the backends to decide which filters belong to
# backend.configuration and which ones to backend.status, as it does
# not involve querying the API.
configuration_filters = {}
status_filters = {}
for key, value in kwargs.items():
if all(key in backend.configuration() for backend in backends):
configuration_filters[key] = value
else:
status_filters[key] = value
# 1. Apply backend.configuration filtering.
if configuration_filters:
backends = [b for b in backends if
_match_all(b.configuration(), configuration_filters)]
# 2. Apply backend.status filtering (it involves one API call for
# each backend).
if status_filters:
backends = [b for b in backends if
_match_all(b.status(), status_filters)]
# 3. Apply acceptor filter.
backends = list(filter(filters, backends))
return backends
def resolve_backend_name(name, backends, deprecated, aliased):
"""Resolve backend name from a deprecated name or an alias.
A group will be resolved in order of member priorities, depending on
availability.
Args:
name (str): name of backend to resolve
backends (list[BaseBackend]): list of available backends.
deprecated (dict[str: str]): dict of deprecated names.
aliased (dict[str: list[str]]): dict of aliased names.
Returns:
str: resolved name (name of an available backend)
Raises:
LookupError: if name cannot be resolved through regular available
names, nor deprecated, nor alias names.
"""
available = [backend.name() for backend in backends]
resolved_name = deprecated.get(name, aliased.get(name, name))
if isinstance(resolved_name, list):
resolved_name = next((b for b in resolved_name if b in available), "")
if resolved_name not in available:
raise LookupError("backend '{}' not found.".format(name))
if name in deprecated:
logger.warning("WARNING: '%s' is deprecated. Use '%s'.", name, resolved_name)
return resolved_name
<|code_end|>
|
Remove `deepcopy` from `circuit_to_dag`
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
It's very slow.
|
qiskit/converters/circuit_to_dag.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Helper function for converting a circuit to a dag"""
import copy
from qiskit.circuit.compositegate import CompositeGate
from qiskit.dagcircuit._dagcircuit import DAGCircuit
def circuit_to_dag(circuit):
"""Build a ``DAGCircuit`` object from a ``QuantumCircuit``.
Args:
circuit (QuantumCircuit): the input circuit.
Return:
DAGCircuit: the DAG representing the input circuit.
"""
circuit = copy.deepcopy(circuit)
dagcircuit = DAGCircuit()
dagcircuit.name = circuit.name
for register in circuit.qregs:
dagcircuit.add_qreg(register)
for register in circuit.cregs:
dagcircuit.add_creg(register)
# Add user gate definitions
for name, data in circuit.definitions.items():
dagcircuit.add_basis_element(name, data["n_bits"], 0, data["n_args"])
dagcircuit.add_gate_data(name, data)
# Add instructions
builtins = {
"U": ["U", 1, 0, 3],
"CX": ["CX", 2, 0, 0],
"measure": ["measure", 1, 1, 0],
"reset": ["reset", 1, 0, 0],
"barrier": ["barrier", -1, 0, 0]
}
# Add simulator instructions
simulator_instructions = {
"snapshot": ["snapshot", -1, 0, 1],
"save": ["save", -1, 0, 1],
"load": ["load", -1, 0, 1],
"noise": ["noise", -1, 0, 1]
}
for main_instruction in circuit.data:
# TODO: generate definitions and nodes for CompositeGates,
# for now simply drop their instructions into the DAG
instruction_list = []
is_composite = isinstance(main_instruction, CompositeGate)
if is_composite:
instruction_list = main_instruction.instruction_list()
else:
instruction_list.append(main_instruction)
for instruction in instruction_list:
# Add OpenQASM built-in gates on demand
if instruction.name in builtins:
dagcircuit.add_basis_element(*builtins[instruction.name])
# Add simulator extension instructions
if instruction.name in simulator_instructions:
dagcircuit.add_basis_element(*simulator_instructions[instruction.name])
# Get arguments for classical control (if any)
if instruction.control is None:
control = None
else:
control = (instruction.control[0], instruction.control[1])
dagcircuit.apply_operation_back(instruction, instruction.qargs,
instruction.cargs, control)
return dagcircuit
<|code_end|>
|
qiskit/converters/circuit_to_dag.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Helper function for converting a circuit to a dag"""
from qiskit.circuit.compositegate import CompositeGate
from qiskit.dagcircuit._dagcircuit import DAGCircuit
def circuit_to_dag(circuit):
"""Build a ``DAGCircuit`` object from a ``QuantumCircuit``.
Args:
circuit (QuantumCircuit): the input circuit.
Return:
DAGCircuit: the DAG representing the input circuit.
"""
dagcircuit = DAGCircuit()
dagcircuit.name = circuit.name
for register in circuit.qregs:
dagcircuit.add_qreg(register)
for register in circuit.cregs:
dagcircuit.add_creg(register)
# Add user gate definitions
for name, data in circuit.definitions.items():
dagcircuit.add_basis_element(name, data["n_bits"], 0, data["n_args"])
dagcircuit.add_gate_data(name, data)
# Add instructions
builtins = {
"U": ["U", 1, 0, 3],
"CX": ["CX", 2, 0, 0],
"measure": ["measure", 1, 1, 0],
"reset": ["reset", 1, 0, 0],
"barrier": ["barrier", -1, 0, 0]
}
# Add simulator instructions
simulator_instructions = {
"snapshot": ["snapshot", -1, 0, 1],
"save": ["save", -1, 0, 1],
"load": ["load", -1, 0, 1],
"noise": ["noise", -1, 0, 1]
}
for main_instruction in circuit.data:
# TODO: generate definitions and nodes for CompositeGates,
# for now simply drop their instructions into the DAG
instruction_list = []
is_composite = isinstance(main_instruction, CompositeGate)
if is_composite:
instruction_list = main_instruction.instruction_list()
else:
instruction_list.append(main_instruction)
for instruction in instruction_list:
# Add OpenQASM built-in gates on demand
if instruction.name in builtins:
dagcircuit.add_basis_element(*builtins[instruction.name])
# Add simulator extension instructions
if instruction.name in simulator_instructions:
dagcircuit.add_basis_element(*simulator_instructions[instruction.name])
# Get arguments for classical control (if any)
if instruction.control is None:
control = None
else:
control = (instruction.control[0], instruction.control[1])
def duplicate_instruction(inst):
"""Create a fresh instruction from an input instruction."""
if inst.name == 'barrier':
params = [inst.qargs]
elif inst.name in simulator_instructions.keys():
params = inst.param + [inst.qargs] + [inst.circuit]
else:
params = inst.param + inst.qargs + inst.cargs
new_inst = inst.__class__(*params)
return new_inst
inst = duplicate_instruction(instruction)
dagcircuit.apply_operation_back(inst, inst.qargs,
inst.cargs, control)
return dagcircuit
<|code_end|>
|
Access a job's payload through `job.qobj()`
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
One often wants to know the `job.qobj()` associated with a job as well (right now you can only get `job.result()` for previous jobs).
|
qiskit/providers/builtinsimulators/simulatorsjob.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""This module implements the job class used by simulator backends."""
from concurrent import futures
import logging
import sys
import functools
from qiskit.providers import BaseJob, JobStatus, JobError
from qiskit.qobj import validate_qobj_against_schema
logger = logging.getLogger(__name__)
def requires_submit(func):
"""
Decorator to ensure that a submit has been performed before
calling the method.
Args:
func (callable): test function to be decorated.
Returns:
callable: the decorated function.
"""
@functools.wraps(func)
def _wrapper(self, *args, **kwargs):
if self._future is None:
raise JobError("Job not submitted yet!. You have to .submit() first!")
return func(self, *args, **kwargs)
return _wrapper
class SimulatorsJob(BaseJob):
"""SimulatorsJob class.
Attributes:
_executor (futures.Executor): executor to handle asynchronous jobs
"""
if sys.platform in ['darwin', 'win32']:
_executor = futures.ThreadPoolExecutor()
else:
_executor = futures.ProcessPoolExecutor()
def __init__(self, backend, job_id, fn, qobj):
super().__init__(backend, job_id)
self._fn = fn
self._qobj = qobj
self._future = None
def submit(self):
"""Submit the job to the backend for execution.
Raises:
QobjValidationError: if the JSON serialization of the Qobj passed
during construction does not validate against the Qobj schema.
JobError: if trying to re-submit the job.
"""
if self._future is not None:
raise JobError("We have already submitted the job!")
validate_qobj_against_schema(self._qobj)
self._future = self._executor.submit(self._fn, self._job_id, self._qobj)
@requires_submit
def result(self, timeout=None):
# pylint: disable=arguments-differ
"""Get job result. The behavior is the same as the underlying
concurrent Future objects,
https://docs.python.org/3/library/concurrent.futures.html#future-objects
Args:
timeout (float): number of seconds to wait for results.
Returns:
qiskit.Result: Result object
Raises:
concurrent.futures.TimeoutError: if timeout occurred.
concurrent.futures.CancelledError: if job cancelled before completed.
"""
return self._future.result(timeout=timeout)
@requires_submit
def cancel(self):
return self._future.cancel()
@requires_submit
def status(self):
"""Gets the status of the job by querying the Python's future
Returns:
JobStatus: The current JobStatus
Raises:
JobError: If the future is in unexpected state
concurrent.futures.TimeoutError: if timeout occurred.
"""
# The order is important here
if self._future.running():
_status = JobStatus.RUNNING
elif self._future.cancelled():
_status = JobStatus.CANCELLED
elif self._future.done():
_status = JobStatus.DONE if self._future.exception() is None else JobStatus.ERROR
else:
# Note: There is an undocumented Future state: PENDING, that seems to show up when
# the job is enqueued, waiting for someone to pick it up. We need to deal with this
# state but there's no public API for it, so we are assuming that if the job is not
# in any of the previous states, is PENDING, ergo INITIALIZING for us.
_status = JobStatus.INITIALIZING
return _status
def backend(self):
"""Return the instance of the backend used for this job."""
return self._backend
<|code_end|>
qiskit/providers/ibmq/ibmqjob.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""IBMQJob module
This module is used for creating asynchronous job objects for the
IBM Q Experience.
"""
from concurrent import futures
import time
import logging
import pprint
import contextlib
import json
import datetime
import numpy
from qiskit.qobj import qobj_to_dict
from qiskit.transpiler import transpile_dag
from qiskit.providers import BaseJob, JobError, JobTimeoutError
from qiskit.providers.jobstatus import JobStatus, JOB_FINAL_STATES
from qiskit.result import Result
from qiskit.result._utils import result_from_old_style_dict
from qiskit.qobj import validate_qobj_against_schema
from .api import ApiError
logger = logging.getLogger(__name__)
API_FINAL_STATES = (
'COMPLETED',
'CANCELLED',
'ERROR_CREATING_JOB',
'ERROR_VALIDATING_JOB',
'ERROR_RUNNING_JOB'
)
class IBMQJob(BaseJob):
"""Represent the jobs that will be executed on IBM-Q simulators and real
devices. Jobs are intended to be created calling ``run()`` on a particular
backend.
Creating a ``Job`` instance does not imply running it. You need to do it in
separate steps::
job = IBMQJob(...)
job.submit() # It won't block.
An error while submitting a job will cause the next call to ``status()`` to
raise. If submitting the job successes, you can inspect the job's status by
using ``status()``. Status can be one of ``JobStatus`` members::
from qiskit.backends.jobstatus import JobStatus
job = IBMQJob(...)
job.submit()
try:
job_status = job.status() # It won't block. It will query the backend API.
if job_status is JobStatus.RUNNING:
print('The job is still running')
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
A call to ``status()`` can raise if something happens at the API level that
prevents Qiskit from determining the status of the job. An example of this
is a temporary connection lose or a network failure.
The ``submit()`` and ``status()`` methods are examples of non-blocking API.
``Job`` instances also have `id()` and ``result()`` methods which will
block::
job = IBMQJob(...)
job.submit()
try:
job_id = job.id() # It will block until completing submission.
print('The job {} was successfully submitted'.format(job_id))
job_result = job.result() # It will block until finishing.
print('The job finished with result {}'.format(job_result))
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
Both methods can raise if something ath the API level happens that prevent
Qiskit from determining the status of the job.
.. NOTE::
When querying the API for getting the status, two kinds of errors are
possible. The most severe is the one preventing Qiskit from getting a
response from the backend. This can be caused by a network failure or a
temporary system break. In these cases, calling ``status()`` will raise.
If Qiskit successfully retrieves the status of a job, it could be it
finished with errors. In that case, ``status()`` will simply return
``JobStatus.ERROR`` and you can call ``error_message()`` to get more
info.
Attributes:
_executor (futures.Executor): executor to handle asynchronous jobs
"""
_executor = futures.ThreadPoolExecutor()
def __init__(self, backend, job_id, api, is_device, qobj=None,
creation_date=None, api_status=None):
"""IBMQJob init function.
We can instantiate jobs from two sources: A QObj, and an already submitted job returned by
the API servers.
Args:
backend (str): The backend instance used to run this job.
job_id (str): The job ID of an already submitted job. Pass `None`
if you are creating a new one.
api (IBMQConnector): IBMQ connector.
is_device (bool): whether backend is a real device # TODO: remove this after Qobj
qobj (Qobj): The Quantum Object. See notes below
creation_date (str): When the job was run.
api_status (str): `status` field directly from the API response.
Notes:
It is mandatory to pass either ``qobj`` or ``job_id``. Passing a ``qobj``
will ignore ``job_id`` and will create an instance to be submitted to the
API server for job creation. Passing only a `job_id`will create an instance
representing an already-created job retrieved from the API server.
"""
super().__init__(backend, job_id)
self._job_data = None
if qobj is not None:
validate_qobj_against_schema(qobj)
self._qobj_payload = qobj_to_dict(qobj, version='1.0.0')
# TODO: No need for this conversion, just use the new equivalent members above
old_qobj = qobj_to_dict(qobj, version='0.0.1')
self._job_data = {
'circuits': old_qobj['circuits'],
'hpc': old_qobj['config'].get('hpc'),
'seed': old_qobj['circuits'][0]['config']['seed'],
'shots': old_qobj['config']['shots'],
'max_credits': old_qobj['config']['max_credits']
}
else:
self._qobj_payload = {}
self._future_captured_exception = None
self._api = api
self._backend = backend
self._cancelled = False
self._status = JobStatus.INITIALIZING
# In case of not providing a `qobj`, it is assumed the job already
# exists in the API (with `job_id`).
if qobj is None:
# Some API calls (`get_status_jobs`, `get_status_job`) provide
# enough information to recreate the `Job`. If that is the case, try
# to make use of that information during instantiation, as
# `self.status()` involves an extra call to the API.
if api_status == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_status == 'COMPLETED':
self._status = JobStatus.DONE
elif api_status == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
else:
self.status()
self._queue_position = None
self._is_device = is_device
def current_utc_time():
"""Gets the current time in UTC format"""
datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
self._creation_date = creation_date or current_utc_time()
self._future = None
self._api_error_msg = None
# pylint: disable=arguments-differ
def result(self, timeout=None, wait=5):
"""Return the result from the job.
Args:
timeout (int): number of seconds to wait for job
wait (int): time between queries to IBM Q server
Returns:
qiskit.Result: Result object
Raises:
JobError: exception raised during job initialization
"""
job_response = self._wait_for_result(timeout=timeout, wait=wait)
return self._result_from_job_response(job_response)
def _wait_for_result(self, timeout=None, wait=5):
self._wait_for_submission()
try:
job_response = self._wait_for_job(timeout=timeout, wait=wait)
except ApiError as api_err:
raise JobError(str(api_err))
status = self.status()
if status is not JobStatus.DONE:
raise JobError('Invalid job state. The job should be DONE but '
'it is {}'.format(str(status)))
return job_response
def _result_from_job_response(self, job_response):
return Result.from_dict(job_response['qObjectResult'])
def cancel(self):
"""Attempt to cancel a job.
Returns:
bool: True if job can be cancelled, else False. Currently this is
only possible on commercial systems.
Raises:
JobError: if there was some unexpected failure in the server
"""
hub = self._api.config.get('hub', None)
group = self._api.config.get('group', None)
project = self._api.config.get('project', None)
try:
response = self._api.cancel_job(self._job_id, hub, group, project)
self._cancelled = 'error' not in response
return self._cancelled
except ApiError as error:
self._cancelled = False
raise JobError('Error cancelling job: %s' % error.usr_msg)
def status(self):
"""Query the API to update the status.
Returns:
JobStatus: The status of the job, once updated.
Raises:
JobError: if there was an exception in the future being executed
or the server sent an unknown answer.
"""
# Implies self._job_id is None
if self._future_captured_exception is not None:
raise JobError(str(self._future_captured_exception))
if self._job_id is None or self._status in JOB_FINAL_STATES:
return self._status
try:
# TODO: See result values
api_job = self._api.get_status_job(self._job_id)
if 'status' not in api_job:
raise JobError('get_status_job didn\'t return status: %s' %
pprint.pformat(api_job))
# pylint: disable=broad-except
except Exception as err:
raise JobError(str(err))
if api_job['status'] == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_job['status'] == 'RUNNING':
self._status = JobStatus.RUNNING
queued, self._queue_position = _is_job_queued(api_job)
if queued:
self._status = JobStatus.QUEUED
elif api_job['status'] == 'COMPLETED':
self._status = JobStatus.DONE
elif api_job['status'] == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
elif 'ERROR' in api_job['status']:
# Error status are of the form "ERROR_*_JOB"
self._status = JobStatus.ERROR
# TODO: This seems to be an inconsistency in the API package.
self._api_error_msg = api_job.get('error') or api_job.get('Error')
else:
raise JobError('Unrecognized answer from server: \n{}'
.format(pprint.pformat(api_job)))
return self._status
def error_message(self):
"""Return the error message returned from the API server response."""
return self._api_error_msg
def queue_position(self):
"""Return the position in the server queue.
Returns:
Number: Position in the queue.
"""
return self._queue_position
def creation_date(self):
"""
Return creation date.
"""
return self._creation_date
def job_id(self):
"""Return backend determined id.
If the Id is not set because the job is already initializing, this call
will block until we have an Id.
"""
self._wait_for_submission()
return self._job_id
def submit(self):
"""Submit job to IBM-Q.
Raises:
JobError: If we have already submitted the job.
"""
# TODO: Validation against the schema should be done here and not
# during initialization. Once done, we should document that the method
# can raise QobjValidationError.
if self._future is not None or self._job_id is not None:
raise JobError("We have already submitted the job!")
self._future = self._executor.submit(self._submit_callback)
def _submit_callback(self):
"""Submit qobj job to IBM-Q.
Returns:
dict: A dictionary with the response of the submitted job
"""
backend_name = self.backend().name()
try:
submit_info = self._api.run_job(self._qobj_payload, backend=backend_name)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submission success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _wait_for_job(self, timeout=60, wait=5):
"""Wait until all online ran circuits of a qobj are 'COMPLETED'.
Args:
timeout (float or None): seconds to wait for job. If None, wait
indefinitely.
wait (float): seconds between queries
Returns:
dict: A dict with the contents of the API request.
Raises:
JobTimeoutError: if the job does not return results before a specified timeout.
JobError: if something wrong happened in some of the server API calls
"""
start_time = time.time()
while self.status() not in JOB_FINAL_STATES:
elapsed_time = time.time() - start_time
if timeout is not None and elapsed_time >= timeout:
raise JobTimeoutError(
'Timeout while waiting for the job: {}'.format(self._job_id)
)
logger.info('status = %s (%d seconds)', self._status, elapsed_time)
time.sleep(wait)
if self._cancelled:
raise JobError(
'Job result impossible to retrieve. The job was cancelled.')
return self._api.get_job(self._job_id)
def _wait_for_submission(self, timeout=60):
"""Waits for the request to return a job ID"""
if self._job_id is None:
if self._future is None:
raise JobError("You have to submit before asking for status or results!")
try:
submit_info = self._future.result(timeout=timeout)
if self._future_captured_exception is not None:
# pylint can't see if catch of None type
# pylint: disable=raising-bad-type
raise self._future_captured_exception
except TimeoutError as ex:
raise JobTimeoutError(
"Timeout waiting for the job being submitted: {}".format(ex)
)
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
raise JobError(str(submit_info['error']))
class IBMQJobPreQobj(IBMQJob):
"""
Subclass of IBMQJob for handling pre-qobj jobs.
"""
def _submit_callback(self):
"""Submit old style qasms job to IBM-Q. Can remove when all devices
understand Qobj.
Returns:
dict: A dictionary with the response of the submitted job
"""
api_jobs = []
circuits = self._job_data['circuits']
for circuit in circuits:
job = _create_api_job_from_circuit(circuit)
api_jobs.append(job)
hpc_camel_cased = _format_hpc_parameters(self._job_data['hpc'])
seed = self._job_data['seed']
shots = self._job_data['shots']
max_credits = self._job_data['max_credits']
try:
submit_info = self._api.run_job(api_jobs, backend=self.backend().name(),
shots=shots, max_credits=max_credits,
seed=seed, hpc=hpc_camel_cased)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submission success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _result_from_job_response(self, job_response):
if self._is_device:
_reorder_bits(job_response)
experiment_results = []
for circuit_result in job_response['qasms']:
this_result = {'data': circuit_result['data'],
'compiled_circuit_qasm': circuit_result.get('qasm'),
'status': circuit_result['status'],
'success': circuit_result['status'] == 'DONE',
'shots': job_response['shots']}
if 'metadata' in circuit_result:
this_result['metadata'] = circuit_result['metadata']
if 'header' in circuit_result['metadata'].get('compiled_circuit', {}):
this_result['header'] = \
circuit_result['metadata']['compiled_circuit']['header']
else:
this_result['header'] = {}
experiment_results.append(this_result)
ret = {
'id': self._job_id,
'status': job_response['status'],
'used_credits': job_response.get('usedCredits'),
'result': experiment_results,
'backend_name': self.backend().name(),
'success': job_response['status'] == 'COMPLETED',
}
# Append header: from the response; from the payload; or none.
header = job_response.get('header',
self._qobj_payload.get('header', {}))
if header:
ret['header'] = header
return result_from_old_style_dict(ret)
def _reorder_bits(job_data):
"""Temporary fix for ibmq backends.
For every ran circuit, get reordering information from qobj
and apply reordering on result.
Args:
job_data (dict): dict with the bare contents of the API.get_job request.
Raises:
JobError: raised if the creg sizes don't add up in result header.
"""
for circuit_result in job_data['qasms']:
if 'metadata' in circuit_result:
circ = circuit_result['metadata'].get('compiled_circuit')
else:
logger.warning('result object missing metadata for reordering'
' bits: bits may be out of order')
return
# device_qubit -> device_clbit (how it should have been)
measure_dict = {op['qubits'][0]: op.get('clbits', op.get('memory'))[0]
for op in circ['operations']
if op['name'] == 'measure'}
counts_dict_new = {}
for item in circuit_result['data']['counts'].items():
# fix clbit ordering to what it should have been
bits = list(item[0])
bits.reverse() # lsb in 0th position
count = item[1]
reordered_bits = list('x' * len(bits))
for device_clbit, bit in enumerate(bits):
if device_clbit in measure_dict:
correct_device_clbit = measure_dict[device_clbit]
reordered_bits[correct_device_clbit] = bit
reordered_bits.reverse()
# only keep the clbits specified by circuit, not everything on device
num_clbits = circ['header'].get('number_of_clbits',
circ['header'].get('memory_slots'))
compact_key = reordered_bits[-num_clbits:]
compact_key = "".join([b if b != 'x' else '0'
for b in compact_key])
# insert spaces to signify different classical registers
cregs = circ['header'].get('creg_sizes',
circ['header'].get('clbit_labels'))
if sum([creg[1] for creg in cregs]) != num_clbits:
raise JobError("creg sizes don't add up in result header.")
creg_begin_pos = []
creg_end_pos = []
acc = 0
for creg in reversed(cregs):
creg_size = creg[1]
creg_begin_pos.append(acc)
creg_end_pos.append(acc + creg_size)
acc += creg_size
compact_key = " ".join([compact_key[creg_begin_pos[i]:creg_end_pos[i]]
for i in range(len(cregs))])
# marginalize over unwanted measured qubits
if compact_key not in counts_dict_new:
counts_dict_new[compact_key] = count
else:
counts_dict_new[compact_key] += count
circuit_result['data']['counts'] = counts_dict_new
def _numpy_type_converter(obj):
ret = obj
if isinstance(obj, numpy.integer):
ret = int(obj)
elif isinstance(obj, numpy.floating): # pylint: disable=no-member
ret = float(obj)
elif isinstance(obj, numpy.ndarray):
ret = obj.tolist()
return ret
def _create_api_job_from_circuit(circuit):
"""Helper function that creates a special job required by the API, from a circuit."""
api_job = {}
if not circuit.get('compiled_circuit_qasm'):
compiled_circuit = transpile_dag(circuit['circuit'])
circuit['compiled_circuit_qasm'] = compiled_circuit.qasm(qeflag=True)
if isinstance(circuit['compiled_circuit_qasm'], bytes):
api_job['qasm'] = circuit['compiled_circuit_qasm'].decode()
else:
api_job['qasm'] = circuit['compiled_circuit_qasm']
if circuit.get('name'):
api_job['name'] = circuit['name']
# convert numpy types for json serialization
compiled_circuit = json.loads(json.dumps(circuit['compiled_circuit'],
default=_numpy_type_converter))
api_job['metadata'] = {'compiled_circuit': compiled_circuit}
return api_job
def _is_job_queued(api_job_response):
"""Checks whether a job has been queued or not."""
is_queued, position = False, 0
if 'infoQueue' in api_job_response:
if 'status' in api_job_response['infoQueue']:
queue_status = api_job_response['infoQueue']['status']
is_queued = queue_status == 'PENDING_IN_QUEUE'
if 'position' in api_job_response['infoQueue']:
position = api_job_response['infoQueue']['position']
return is_queued, position
def _format_hpc_parameters(hpc):
"""Helper function to get HPC parameters with the correct format"""
if hpc is None:
return None
hpc_camel_cased = None
with contextlib.suppress(KeyError, TypeError):
# Use CamelCase when passing the hpc parameters to the API.
hpc_camel_cased = {
'multiShotOptimization': hpc['multi_shot_optimization'],
'ompNumThreads': hpc['omp_num_threads']
}
return hpc_camel_cased
<|code_end|>
|
qiskit/providers/builtinsimulators/simulatorsjob.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""This module implements the job class used by simulator backends."""
from concurrent import futures
import logging
import sys
import functools
from qiskit.providers import BaseJob, JobStatus, JobError
from qiskit.qobj import validate_qobj_against_schema
logger = logging.getLogger(__name__)
def requires_submit(func):
"""
Decorator to ensure that a submit has been performed before
calling the method.
Args:
func (callable): test function to be decorated.
Returns:
callable: the decorated function.
"""
@functools.wraps(func)
def _wrapper(self, *args, **kwargs):
if self._future is None:
raise JobError("Job not submitted yet!. You have to .submit() first!")
return func(self, *args, **kwargs)
return _wrapper
class SimulatorsJob(BaseJob):
"""SimulatorsJob class.
Attributes:
_executor (futures.Executor): executor to handle asynchronous jobs
"""
if sys.platform in ['darwin', 'win32']:
_executor = futures.ThreadPoolExecutor()
else:
_executor = futures.ProcessPoolExecutor()
def __init__(self, backend, job_id, fn, qobj):
super().__init__(backend, job_id)
self._fn = fn
self._qobj = qobj
self._future = None
def submit(self):
"""Submit the job to the backend for execution.
Raises:
QobjValidationError: if the JSON serialization of the Qobj passed
during construction does not validate against the Qobj schema.
JobError: if trying to re-submit the job.
"""
if self._future is not None:
raise JobError("We have already submitted the job!")
validate_qobj_against_schema(self._qobj)
self._future = self._executor.submit(self._fn, self._job_id, self._qobj)
@requires_submit
def result(self, timeout=None):
# pylint: disable=arguments-differ
"""Get job result. The behavior is the same as the underlying
concurrent Future objects,
https://docs.python.org/3/library/concurrent.futures.html#future-objects
Args:
timeout (float): number of seconds to wait for results.
Returns:
qiskit.Result: Result object
Raises:
concurrent.futures.TimeoutError: if timeout occurred.
concurrent.futures.CancelledError: if job cancelled before completed.
"""
return self._future.result(timeout=timeout)
@requires_submit
def cancel(self):
return self._future.cancel()
@requires_submit
def status(self):
"""Gets the status of the job by querying the Python's future
Returns:
JobStatus: The current JobStatus
Raises:
JobError: If the future is in unexpected state
concurrent.futures.TimeoutError: if timeout occurred.
"""
# The order is important here
if self._future.running():
_status = JobStatus.RUNNING
elif self._future.cancelled():
_status = JobStatus.CANCELLED
elif self._future.done():
_status = JobStatus.DONE if self._future.exception() is None else JobStatus.ERROR
else:
# Note: There is an undocumented Future state: PENDING, that seems to show up when
# the job is enqueued, waiting for someone to pick it up. We need to deal with this
# state but there's no public API for it, so we are assuming that if the job is not
# in any of the previous states, is PENDING, ergo INITIALIZING for us.
_status = JobStatus.INITIALIZING
return _status
def backend(self):
"""Return the instance of the backend used for this job."""
return self._backend
def qobj(self):
"""Return the Qobj submitted for this job.
Returns:
Qobj: the Qobj submitted for this job.
"""
return self._qobj
<|code_end|>
qiskit/providers/ibmq/ibmqjob.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""IBMQJob module
This module is used for creating asynchronous job objects for the
IBM Q Experience.
"""
import warnings
from concurrent import futures
import time
import logging
import pprint
import contextlib
import json
import datetime
import numpy
from qiskit.qobj import qobj_to_dict, Qobj
from qiskit.transpiler import transpile_dag
from qiskit.providers import BaseJob, JobError, JobTimeoutError
from qiskit.providers.jobstatus import JobStatus, JOB_FINAL_STATES
from qiskit.result import Result
from qiskit.result._utils import result_from_old_style_dict
from qiskit.qobj import validate_qobj_against_schema
from .api import ApiError
logger = logging.getLogger(__name__)
API_FINAL_STATES = (
'COMPLETED',
'CANCELLED',
'ERROR_CREATING_JOB',
'ERROR_VALIDATING_JOB',
'ERROR_RUNNING_JOB'
)
class IBMQJob(BaseJob):
"""Represent the jobs that will be executed on IBM-Q simulators and real
devices. Jobs are intended to be created calling ``run()`` on a particular
backend.
Creating a ``Job`` instance does not imply running it. You need to do it in
separate steps::
job = IBMQJob(...)
job.submit() # It won't block.
An error while submitting a job will cause the next call to ``status()`` to
raise. If submitting the job successes, you can inspect the job's status by
using ``status()``. Status can be one of ``JobStatus`` members::
from qiskit.backends.jobstatus import JobStatus
job = IBMQJob(...)
job.submit()
try:
job_status = job.status() # It won't block. It will query the backend API.
if job_status is JobStatus.RUNNING:
print('The job is still running')
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
A call to ``status()`` can raise if something happens at the API level that
prevents Qiskit from determining the status of the job. An example of this
is a temporary connection lose or a network failure.
The ``submit()`` and ``status()`` methods are examples of non-blocking API.
``Job`` instances also have `id()` and ``result()`` methods which will
block::
job = IBMQJob(...)
job.submit()
try:
job_id = job.id() # It will block until completing submission.
print('The job {} was successfully submitted'.format(job_id))
job_result = job.result() # It will block until finishing.
print('The job finished with result {}'.format(job_result))
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
Both methods can raise if something ath the API level happens that prevent
Qiskit from determining the status of the job.
.. NOTE::
When querying the API for getting the status, two kinds of errors are
possible. The most severe is the one preventing Qiskit from getting a
response from the backend. This can be caused by a network failure or a
temporary system break. In these cases, calling ``status()`` will raise.
If Qiskit successfully retrieves the status of a job, it could be it
finished with errors. In that case, ``status()`` will simply return
``JobStatus.ERROR`` and you can call ``error_message()`` to get more
info.
Attributes:
_executor (futures.Executor): executor to handle asynchronous jobs
"""
_executor = futures.ThreadPoolExecutor()
def __init__(self, backend, job_id, api, is_device, qobj=None,
creation_date=None, api_status=None):
"""IBMQJob init function.
We can instantiate jobs from two sources: A QObj, and an already submitted job returned by
the API servers.
Args:
backend (str): The backend instance used to run this job.
job_id (str): The job ID of an already submitted job. Pass `None`
if you are creating a new one.
api (IBMQConnector): IBMQ connector.
is_device (bool): whether backend is a real device # TODO: remove this after Qobj
qobj (Qobj): The Quantum Object. See notes below
creation_date (str): When the job was run.
api_status (str): `status` field directly from the API response.
Notes:
It is mandatory to pass either ``qobj`` or ``job_id``. Passing a ``qobj``
will ignore ``job_id`` and will create an instance to be submitted to the
API server for job creation. Passing only a `job_id`will create an instance
representing an already-created job retrieved from the API server.
"""
super().__init__(backend, job_id)
self._job_data = None
if qobj is not None:
validate_qobj_against_schema(qobj)
self._qobj_payload = qobj_to_dict(qobj, version='1.0.0')
# TODO: No need for this conversion, just use the new equivalent members above
old_qobj = qobj_to_dict(qobj, version='0.0.1')
self._job_data = {
'circuits': old_qobj['circuits'],
'hpc': old_qobj['config'].get('hpc'),
'seed': old_qobj['circuits'][0]['config']['seed'],
'shots': old_qobj['config']['shots'],
'max_credits': old_qobj['config']['max_credits']
}
else:
self._qobj_payload = {}
self._future_captured_exception = None
self._api = api
self._backend = backend
self._cancelled = False
self._status = JobStatus.INITIALIZING
# In case of not providing a `qobj`, it is assumed the job already
# exists in the API (with `job_id`).
if qobj is None:
# Some API calls (`get_status_jobs`, `get_status_job`) provide
# enough information to recreate the `Job`. If that is the case, try
# to make use of that information during instantiation, as
# `self.status()` involves an extra call to the API.
if api_status == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_status == 'COMPLETED':
self._status = JobStatus.DONE
elif api_status == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
else:
self.status()
self._queue_position = None
self._is_device = is_device
def current_utc_time():
"""Gets the current time in UTC format"""
datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
self._creation_date = creation_date or current_utc_time()
self._future = None
self._api_error_msg = None
# pylint: disable=arguments-differ
def result(self, timeout=None, wait=5):
"""Return the result from the job.
Args:
timeout (int): number of seconds to wait for job
wait (int): time between queries to IBM Q server
Returns:
qiskit.Result: Result object
Raises:
JobError: exception raised during job initialization
"""
job_response = self._wait_for_result(timeout=timeout, wait=wait)
return self._result_from_job_response(job_response)
def _wait_for_result(self, timeout=None, wait=5):
self._wait_for_submission()
try:
job_response = self._wait_for_job(timeout=timeout, wait=wait)
if not self._qobj_payload:
self._qobj_payload = job_response.get('qObject', {})
except ApiError as api_err:
raise JobError(str(api_err))
status = self.status()
if status is not JobStatus.DONE:
raise JobError('Invalid job state. The job should be DONE but '
'it is {}'.format(str(status)))
return job_response
def _result_from_job_response(self, job_response):
return Result.from_dict(job_response['qObjectResult'])
def cancel(self):
"""Attempt to cancel a job.
Returns:
bool: True if job can be cancelled, else False. Currently this is
only possible on commercial systems.
Raises:
JobError: if there was some unexpected failure in the server
"""
hub = self._api.config.get('hub', None)
group = self._api.config.get('group', None)
project = self._api.config.get('project', None)
try:
response = self._api.cancel_job(self._job_id, hub, group, project)
self._cancelled = 'error' not in response
return self._cancelled
except ApiError as error:
self._cancelled = False
raise JobError('Error cancelling job: %s' % error.usr_msg)
def status(self):
"""Query the API to update the status.
Returns:
JobStatus: The status of the job, once updated.
Raises:
JobError: if there was an exception in the future being executed
or the server sent an unknown answer.
"""
# Implies self._job_id is None
if self._future_captured_exception is not None:
raise JobError(str(self._future_captured_exception))
if self._job_id is None or self._status in JOB_FINAL_STATES:
return self._status
try:
# TODO: See result values
api_job = self._api.get_status_job(self._job_id)
if 'status' not in api_job:
raise JobError('get_status_job didn\'t return status: %s' %
pprint.pformat(api_job))
# pylint: disable=broad-except
except Exception as err:
raise JobError(str(err))
if api_job['status'] == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_job['status'] == 'RUNNING':
self._status = JobStatus.RUNNING
queued, self._queue_position = _is_job_queued(api_job)
if queued:
self._status = JobStatus.QUEUED
elif api_job['status'] == 'COMPLETED':
self._status = JobStatus.DONE
elif api_job['status'] == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
elif 'ERROR' in api_job['status']:
# Error status are of the form "ERROR_*_JOB"
self._status = JobStatus.ERROR
# TODO: This seems to be an inconsistency in the API package.
self._api_error_msg = api_job.get('error') or api_job.get('Error')
else:
raise JobError('Unrecognized answer from server: \n{}'
.format(pprint.pformat(api_job)))
return self._status
def error_message(self):
"""Return the error message returned from the API server response."""
return self._api_error_msg
def queue_position(self):
"""Return the position in the server queue.
Returns:
Number: Position in the queue.
"""
return self._queue_position
def creation_date(self):
"""
Return creation date.
"""
return self._creation_date
def job_id(self):
"""Return backend determined id.
If the Id is not set because the job is already initializing, this call
will block until we have an Id.
"""
self._wait_for_submission()
return self._job_id
def submit(self):
"""Submit job to IBM-Q.
Raises:
JobError: If we have already submitted the job.
"""
# TODO: Validation against the schema should be done here and not
# during initialization. Once done, we should document that the method
# can raise QobjValidationError.
if self._future is not None or self._job_id is not None:
raise JobError("We have already submitted the job!")
self._future = self._executor.submit(self._submit_callback)
def _submit_callback(self):
"""Submit qobj job to IBM-Q.
Returns:
dict: A dictionary with the response of the submitted job
"""
backend_name = self.backend().name()
try:
submit_info = self._api.run_job(self._qobj_payload, backend=backend_name)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submission success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _wait_for_job(self, timeout=60, wait=5):
"""Wait until all online ran circuits of a qobj are 'COMPLETED'.
Args:
timeout (float or None): seconds to wait for job. If None, wait
indefinitely.
wait (float): seconds between queries
Returns:
dict: A dict with the contents of the API request.
Raises:
JobTimeoutError: if the job does not return results before a specified timeout.
JobError: if something wrong happened in some of the server API calls
"""
start_time = time.time()
while self.status() not in JOB_FINAL_STATES:
elapsed_time = time.time() - start_time
if timeout is not None and elapsed_time >= timeout:
raise JobTimeoutError(
'Timeout while waiting for the job: {}'.format(self._job_id)
)
logger.info('status = %s (%d seconds)', self._status, elapsed_time)
time.sleep(wait)
if self._cancelled:
raise JobError(
'Job result impossible to retrieve. The job was cancelled.')
return self._api.get_job(self._job_id)
def _wait_for_submission(self, timeout=60):
"""Waits for the request to return a job ID"""
if self._job_id is None:
if self._future is None:
raise JobError("You have to submit before asking for status or results!")
try:
submit_info = self._future.result(timeout=timeout)
if self._future_captured_exception is not None:
# pylint can't see if catch of None type
# pylint: disable=raising-bad-type
raise self._future_captured_exception
except TimeoutError as ex:
raise JobTimeoutError(
"Timeout waiting for the job being submitted: {}".format(ex)
)
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
raise JobError(str(submit_info['error']))
def qobj(self):
"""Return the Qobj submitted for this job.
Note that this method might involve querying the API for results if the
Job has been created in a previous Qiskit session.
Returns:
Qobj: the Qobj submitted for this job.
"""
if not self._qobj_payload:
# Populate self._qobj_payload by retrieving the results.
self._wait_for_result()
return Qobj(**self._qobj_payload)
class IBMQJobPreQobj(IBMQJob):
"""
Subclass of IBMQJob for handling pre-qobj jobs.
"""
def _submit_callback(self):
"""Submit old style qasms job to IBM-Q. Can remove when all devices
understand Qobj.
Returns:
dict: A dictionary with the response of the submitted job
"""
api_jobs = []
circuits = self._job_data['circuits']
for circuit in circuits:
job = _create_api_job_from_circuit(circuit)
api_jobs.append(job)
hpc_camel_cased = _format_hpc_parameters(self._job_data['hpc'])
seed = self._job_data['seed']
shots = self._job_data['shots']
max_credits = self._job_data['max_credits']
try:
submit_info = self._api.run_job(api_jobs, backend=self.backend().name(),
shots=shots, max_credits=max_credits,
seed=seed, hpc=hpc_camel_cased)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submission success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _result_from_job_response(self, job_response):
if self._is_device:
_reorder_bits(job_response)
experiment_results = []
for circuit_result in job_response['qasms']:
this_result = {'data': circuit_result['data'],
'compiled_circuit_qasm': circuit_result.get('qasm'),
'status': circuit_result['status'],
'success': circuit_result['status'] == 'DONE',
'shots': job_response['shots']}
if 'metadata' in circuit_result:
this_result['metadata'] = circuit_result['metadata']
if 'header' in circuit_result['metadata'].get('compiled_circuit', {}):
this_result['header'] = \
circuit_result['metadata']['compiled_circuit']['header']
else:
this_result['header'] = {}
experiment_results.append(this_result)
ret = {
'id': self._job_id,
'status': job_response['status'],
'used_credits': job_response.get('usedCredits'),
'result': experiment_results,
'backend_name': self.backend().name(),
'success': job_response['status'] == 'COMPLETED',
}
# Append header: from the response; from the payload; or none.
header = job_response.get('header',
self._qobj_payload.get('header', {}))
if header:
ret['header'] = header
return result_from_old_style_dict(ret)
def qobj(self):
"""Return the Qobj submitted for this job."""
warnings.warn('This job has not been submitted using Qobj.')
return None
def _reorder_bits(job_data):
"""Temporary fix for ibmq backends.
For every ran circuit, get reordering information from qobj
and apply reordering on result.
Args:
job_data (dict): dict with the bare contents of the API.get_job request.
Raises:
JobError: raised if the creg sizes don't add up in result header.
"""
for circuit_result in job_data['qasms']:
if 'metadata' in circuit_result:
circ = circuit_result['metadata'].get('compiled_circuit')
else:
logger.warning('result object missing metadata for reordering'
' bits: bits may be out of order')
return
# device_qubit -> device_clbit (how it should have been)
measure_dict = {op['qubits'][0]: op.get('clbits', op.get('memory'))[0]
for op in circ['operations']
if op['name'] == 'measure'}
counts_dict_new = {}
for item in circuit_result['data']['counts'].items():
# fix clbit ordering to what it should have been
bits = list(item[0])
bits.reverse() # lsb in 0th position
count = item[1]
reordered_bits = list('x' * len(bits))
for device_clbit, bit in enumerate(bits):
if device_clbit in measure_dict:
correct_device_clbit = measure_dict[device_clbit]
reordered_bits[correct_device_clbit] = bit
reordered_bits.reverse()
# only keep the clbits specified by circuit, not everything on device
num_clbits = circ['header'].get('number_of_clbits',
circ['header'].get('memory_slots'))
compact_key = reordered_bits[-num_clbits:]
compact_key = "".join([b if b != 'x' else '0'
for b in compact_key])
# insert spaces to signify different classical registers
cregs = circ['header'].get('creg_sizes',
circ['header'].get('clbit_labels'))
if sum([creg[1] for creg in cregs]) != num_clbits:
raise JobError("creg sizes don't add up in result header.")
creg_begin_pos = []
creg_end_pos = []
acc = 0
for creg in reversed(cregs):
creg_size = creg[1]
creg_begin_pos.append(acc)
creg_end_pos.append(acc + creg_size)
acc += creg_size
compact_key = " ".join([compact_key[creg_begin_pos[i]:creg_end_pos[i]]
for i in range(len(cregs))])
# marginalize over unwanted measured qubits
if compact_key not in counts_dict_new:
counts_dict_new[compact_key] = count
else:
counts_dict_new[compact_key] += count
circuit_result['data']['counts'] = counts_dict_new
def _numpy_type_converter(obj):
ret = obj
if isinstance(obj, numpy.integer):
ret = int(obj)
elif isinstance(obj, numpy.floating): # pylint: disable=no-member
ret = float(obj)
elif isinstance(obj, numpy.ndarray):
ret = obj.tolist()
return ret
def _create_api_job_from_circuit(circuit):
"""Helper function that creates a special job required by the API, from a circuit."""
api_job = {}
if not circuit.get('compiled_circuit_qasm'):
compiled_circuit = transpile_dag(circuit['circuit'])
circuit['compiled_circuit_qasm'] = compiled_circuit.qasm(qeflag=True)
if isinstance(circuit['compiled_circuit_qasm'], bytes):
api_job['qasm'] = circuit['compiled_circuit_qasm'].decode()
else:
api_job['qasm'] = circuit['compiled_circuit_qasm']
if circuit.get('name'):
api_job['name'] = circuit['name']
# convert numpy types for json serialization
compiled_circuit = json.loads(json.dumps(circuit['compiled_circuit'],
default=_numpy_type_converter))
api_job['metadata'] = {'compiled_circuit': compiled_circuit}
return api_job
def _is_job_queued(api_job_response):
"""Checks whether a job has been queued or not."""
is_queued, position = False, 0
if 'infoQueue' in api_job_response:
if 'status' in api_job_response['infoQueue']:
queue_status = api_job_response['infoQueue']['status']
is_queued = queue_status == 'PENDING_IN_QUEUE'
if 'position' in api_job_response['infoQueue']:
position = api_job_response['infoQueue']['position']
return is_queued, position
def _format_hpc_parameters(hpc):
"""Helper function to get HPC parameters with the correct format"""
if hpc is None:
return None
hpc_camel_cased = None
with contextlib.suppress(KeyError, TypeError):
# Use CamelCase when passing the hpc parameters to the API.
hpc_camel_cased = {
'multiShotOptimization': hpc['multi_shot_optimization'],
'ompNumThreads': hpc['omp_num_threads']
}
return hpc_camel_cased
<|code_end|>
|
bug in latex drawer barrier
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**:
- **Python version**:
- **Operating system**:
### What is the current behavior?
When drawing this circuit, the barrier on the last qubit is not respected.
```python
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.tools.visualization import circuit_drawer
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.x(q[0])
circ.x(q[1])
circ.barrier(q)
circ.measure(q, c)
circuit_drawer(circ, output='latex')
```

The `mpl` drawer works fine.
### Suggested solutions
|
qiskit/tools/visualization/_latex.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""latex circuit visualization backends."""
import collections
import io
import itertools
import json
import math
import operator
import re
import numpy as np
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _qcstyle
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for Qiskit.
"""
def __init__(self, qregs, cregs, ops, scale, style=None,
plot_barriers=True, reverse_bits=False):
"""
Args:
qregs (list): A list of tuples for the quantum registers
cregs (list): A list of tuples for the classical registers
ops (list): A list of dicts where each entry is a operation from
the circuit.
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
"""
# style sheet
self._style = _qcstyle.QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.ops = ops
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
self.reverse_bits = reverse_bits
self.plot_barriers = plot_barriers
#################################
self.qregs = collections.OrderedDict(_get_register_specs(qregs))
self.qubit_list = qregs
self.ordered_regs = qregs + cregs
self.cregs = collections.OrderedDict(_get_register_specs(cregs))
self.clbit_list = cregs
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = io.StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\' + '\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0].name + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0].name + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
VisualizationError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.ops:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's',
'sdg', 't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy',
'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image
# scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['op'].param:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float, str(arg))
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
if len(op['cargs']) != 1 or len(op['qargs']) != 1:
raise _error.VisualizationError("bad operation record")
if 'condition' in op and op['condition']:
raise _error.VisualizationError(
'conditional measures currently not supported.')
qname, qindex = op['qargs'][0]
cname, cindex = op['cargs'][0]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op and op['condition']:
raise _error.VisualizationError(
'conditional reset currently not supported.')
qname, qindex = op['qargs'][0]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] == "barrier":
pass
else:
raise _error.VisualizationError("bad node data")
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns + 1, math.ceil(sum_column_widths) + 4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet
# (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def _get_mask(self, creg_name):
mask = 0
for index, cbit in enumerate(self.clbit_list):
if creg_name == cbit[0]:
mask |= (1 << index)
return mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.ops):
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(op['condition'][1],
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier', 'snapshot', 'load',
'save', 'noise']:
nm = op['name']
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["op"].param[0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["op"].param[0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["op"].param[0], op["op"].param[1])
elif nm == "u3":
self._latex[pos_1][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["op"].param[0],
op["op"].param[1],
op["op"].param[2]))
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["op"].param[0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["op"].param[0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["op"].param[0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["op"].param[0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["op"].param[0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["op"].param[0], op["op"].param[1])
elif nm == "u3":
self._latex[pos_1][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["op"].param[0],
op["op"].param[1],
op["op"].param[2]))
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["op"].param[0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["op"].param[0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["op"].param[0])
elif nm == "reset":
self._latex[pos_1][columns] = (
"\\push{\\rule{.6em}{0em}\\ket{0}\\"
"rule{.2em}{0em}} \\qw")
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'condition' in op and op['condition']:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["op"].param[0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["op"].param[0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["op"].param[0],
op["op"].param[1],
op["op"].param[2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["op"].param[0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["op"].param[0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["op"].param[0],
op["op"].param[1],
op["op"].param[2]))
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'condition' in op and op['condition']:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-0.65em]{')
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(
pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-0.65em]{')
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(
pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
if (len(op['cargs']) != 1
or len(op['qargs']) != 1
or op['op'].param):
raise _error.VisualizationError("bad operation record")
if 'condition' in op and op['condition']:
raise _error.VisualizationError(
"If controlled measures currently not supported.")
qname, qindex = op['qargs'][0]
cname, cindex = op['cargs'][0]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise _error.VisualizationError(
'Error during Latex building: %s' % str(e))
elif op['name'] in ["barrier", 'snapshot', 'load', 'save',
'noise']:
if self.plot_barriers:
qarglist = op['qargs']
indexes = [self._get_qubit_index(x) for x in qarglist]
start_bit = self.qubit_list[min(indexes)]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[start_bit]
span = len(op['qargs']) - 1
self._latex[start][columns] += " \\barrier{" + str(
span) + "}"
else:
raise _error.VisualizationError("bad node data")
def _get_qubit_index(self, qubit):
"""Get the index number for a quantum bit
Args:
qubit (tuple): The tuple of the bit of the form
(register_name, bit_number)
Returns:
int: The index in the bit list
Raises:
VisualizationError: If the bit isn't found
"""
for i, bit in enumerate(self.qubit_list):
if qubit == bit:
qindex = i
break
else:
raise _error.VisualizationError(
"unable to find bit for operation")
return qindex
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
return origin - 1
def _get_register_specs(bit_labels):
"""Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = itertools.groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
<|code_end|>
|
qiskit/tools/visualization/_latex.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""latex circuit visualization backends."""
import collections
import io
import itertools
import json
import math
import operator
import re
import numpy as np
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _qcstyle
class QCircuitImage(object):
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for Qiskit.
"""
def __init__(self, qregs, cregs, ops, scale, style=None,
plot_barriers=True, reverse_bits=False):
"""
Args:
qregs (list): A list of tuples for the quantum registers
cregs (list): A list of tuples for the classical registers
ops (list): A list of dicts where each entry is a operation from
the circuit.
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
"""
# style sheet
self._style = _qcstyle.QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.ops = ops
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
self.reverse_bits = reverse_bits
self.plot_barriers = plot_barriers
#################################
self.qregs = collections.OrderedDict(_get_register_specs(qregs))
self.qubit_list = qregs
self.ordered_regs = qregs + cregs
self.cregs = collections.OrderedDict(_get_register_specs(cregs))
self.clbit_list = cregs
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = io.StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\' + '\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0].name + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0].name + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
VisualizationError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.ops:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's',
'sdg', 't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy',
'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image
# scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['op'].param:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float, str(arg))
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
if len(op['cargs']) != 1 or len(op['qargs']) != 1:
raise _error.VisualizationError("bad operation record")
if 'condition' in op and op['condition']:
raise _error.VisualizationError(
'conditional measures currently not supported.')
qname, qindex = op['qargs'][0]
cname, cindex = op['cargs'][0]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op and op['condition']:
raise _error.VisualizationError(
'conditional reset currently not supported.')
qname, qindex = op['qargs'][0]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] in ["barrier", 'snapshot', 'load', 'save',
'noise']:
if self.plot_barriers:
qarglist = op['qargs']
indexes = [self._get_qubit_index(x) for x in qarglist]
start_bit = self.qubit_list[min(indexes)]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[start_bit]
span = len(op['qargs']) - 1
for i in range(start, span + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(start, span + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
else:
raise _error.VisualizationError("bad node data")
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns + 1, math.ceil(sum_column_widths) + 4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet
# (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def _get_mask(self, creg_name):
mask = 0
for index, cbit in enumerate(self.clbit_list):
if creg_name == cbit[0]:
mask |= (1 << index)
return mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.ops):
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(op['condition'][1],
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier', 'snapshot', 'load',
'save', 'noise']:
nm = op['name']
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["op"].param[0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["op"].param[0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["op"].param[0], op["op"].param[1])
elif nm == "u3":
self._latex[pos_1][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["op"].param[0],
op["op"].param[1],
op["op"].param[2]))
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["op"].param[0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["op"].param[0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["op"].param[0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["op"].param[0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["op"].param[0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["op"].param[0], op["op"].param[1])
elif nm == "u3":
self._latex[pos_1][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["op"].param[0],
op["op"].param[1],
op["op"].param[2]))
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["op"].param[0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["op"].param[0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["op"].param[0])
elif nm == "reset":
self._latex[pos_1][columns] = (
"\\push{\\rule{.6em}{0em}\\ket{0}\\"
"rule{.2em}{0em}} \\qw")
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'condition' in op and op['condition']:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["op"].param[0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["op"].param[0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["op"].param[0],
op["op"].param[1],
op["op"].param[2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["op"].param[0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["op"].param[0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["op"].param[0],
op["op"].param[1],
op["op"].param[2]))
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'condition' in op and op['condition']:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-0.65em]{')
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(
pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-0.65em]{')
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(
pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
if (len(op['cargs']) != 1
or len(op['qargs']) != 1
or op['op'].param):
raise _error.VisualizationError("bad operation record")
if 'condition' in op and op['condition']:
raise _error.VisualizationError(
"If controlled measures currently not supported.")
qname, qindex = op['qargs'][0]
cname, cindex = op['cargs'][0]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise _error.VisualizationError(
'Error during Latex building: %s' % str(e))
elif op['name'] in ["barrier", 'snapshot', 'load', 'save',
'noise']:
if self.plot_barriers:
qarglist = op['qargs']
indexes = [self._get_qubit_index(x) for x in qarglist]
start_bit = self.qubit_list[min(indexes)]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[start_bit]
span = len(op['qargs']) - 1
for i in range(start, span + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(start, span + 1):
is_occupied[j] = True
break
self._latex[start][columns] = "\\qw \\barrier{" + str(
span) + "}"
else:
raise _error.VisualizationError("bad node data")
def _get_qubit_index(self, qubit):
"""Get the index number for a quantum bit
Args:
qubit (tuple): The tuple of the bit of the form
(register_name, bit_number)
Returns:
int: The index in the bit list
Raises:
VisualizationError: If the bit isn't found
"""
for i, bit in enumerate(self.qubit_list):
if qubit == bit:
qindex = i
break
else:
raise _error.VisualizationError(
"unable to find bit for operation")
return qindex
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
return origin - 1
def _get_register_specs(bit_labels):
"""Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = itertools.groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
<|code_end|>
|
timeout setting is not passed to job submission [remote backend]
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: the newest master branch
- **Python version**: 3.6.5
- **Operating system**: macOS 10.13
### What is the current behavior?
`timeout` setting only used for `_wait_for_result` but not `_wait_for_submission`.
So, Qiskit raises `the Timeout error` after 60 seconds regardless of the setting of `timeout`.
related codes:
`_wait_for_result`
https://github.com/Qiskit/qiskit-terra/blob/master/qiskit/backends/ibmq/ibmqjob.py#L190
`_wait_for_submission`
https://github.com/Qiskit/qiskit-terra/blob/master/qiskit/backends/ibmq/ibmqjob.py#L400
### Steps to reproduce the problem
### What is the expected behavior?
`timeout` setting should be passed to `_wait_for_submission` as well.
### Suggested solutions
pass the `timeout` in `_wait_for_result` to `_wait_for_submission`.
|
qiskit/providers/ibmq/ibmqjob.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""IBMQJob module
This module is used for creating asynchronous job objects for the
IBM Q Experience.
"""
import warnings
from concurrent import futures
import time
import logging
import pprint
import contextlib
import json
import datetime
import numpy
from qiskit.qobj import qobj_to_dict, Qobj
from qiskit.transpiler import transpile_dag
from qiskit.providers import BaseJob, JobError, JobTimeoutError
from qiskit.providers.jobstatus import JobStatus, JOB_FINAL_STATES
from qiskit.result import Result
from qiskit.result._utils import result_from_old_style_dict
from qiskit.qobj import validate_qobj_against_schema
from .api import ApiError
logger = logging.getLogger(__name__)
API_FINAL_STATES = (
'COMPLETED',
'CANCELLED',
'ERROR_CREATING_JOB',
'ERROR_VALIDATING_JOB',
'ERROR_RUNNING_JOB'
)
class IBMQJob(BaseJob):
"""Represent the jobs that will be executed on IBM-Q simulators and real
devices. Jobs are intended to be created calling ``run()`` on a particular
backend.
Creating a ``Job`` instance does not imply running it. You need to do it in
separate steps::
job = IBMQJob(...)
job.submit() # It won't block.
An error while submitting a job will cause the next call to ``status()`` to
raise. If submitting the job successes, you can inspect the job's status by
using ``status()``. Status can be one of ``JobStatus`` members::
from qiskit.backends.jobstatus import JobStatus
job = IBMQJob(...)
job.submit()
try:
job_status = job.status() # It won't block. It will query the backend API.
if job_status is JobStatus.RUNNING:
print('The job is still running')
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
A call to ``status()`` can raise if something happens at the API level that
prevents Qiskit from determining the status of the job. An example of this
is a temporary connection lose or a network failure.
The ``submit()`` and ``status()`` methods are examples of non-blocking API.
``Job`` instances also have `id()` and ``result()`` methods which will
block::
job = IBMQJob(...)
job.submit()
try:
job_id = job.id() # It will block until completing submission.
print('The job {} was successfully submitted'.format(job_id))
job_result = job.result() # It will block until finishing.
print('The job finished with result {}'.format(job_result))
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
Both methods can raise if something ath the API level happens that prevent
Qiskit from determining the status of the job.
Note:
When querying the API for getting the status, two kinds of errors are
possible. The most severe is the one preventing Qiskit from getting a
response from the backend. This can be caused by a network failure or a
temporary system break. In these cases, calling ``status()`` will raise.
If Qiskit successfully retrieves the status of a job, it could be it
finished with errors. In that case, ``status()`` will simply return
``JobStatus.ERROR`` and you can call ``error_message()`` to get more
info.
Attributes:
_executor (futures.Executor): executor to handle asynchronous jobs
"""
_executor = futures.ThreadPoolExecutor()
def __init__(self, backend, job_id, api, is_device, qobj=None,
creation_date=None, api_status=None):
"""IBMQJob init function.
We can instantiate jobs from two sources: A QObj, and an already submitted job returned by
the API servers.
Args:
backend (str): The backend instance used to run this job.
job_id (str): The job ID of an already submitted job. Pass `None`
if you are creating a new one.
api (IBMQConnector): IBMQ connector.
is_device (bool): whether backend is a real device # TODO: remove this after Qobj
qobj (Qobj): The Quantum Object. See notes below
creation_date (str): When the job was run.
api_status (str): `status` field directly from the API response.
Notes:
It is mandatory to pass either ``qobj`` or ``job_id``. Passing a ``qobj``
will ignore ``job_id`` and will create an instance to be submitted to the
API server for job creation. Passing only a `job_id` will create an instance
representing an already-created job retrieved from the API server.
"""
super().__init__(backend, job_id)
self._job_data = None
if qobj is not None:
validate_qobj_against_schema(qobj)
self._qobj_payload = qobj_to_dict(qobj, version='1.0.0')
# TODO: No need for this conversion, just use the new equivalent members above
old_qobj = qobj_to_dict(qobj, version='0.0.1')
self._job_data = {
'circuits': old_qobj['circuits'],
'hpc': old_qobj['config'].get('hpc'),
'seed': old_qobj['circuits'][0]['config']['seed'],
'shots': old_qobj['config']['shots'],
'max_credits': old_qobj['config']['max_credits']
}
else:
self._qobj_payload = {}
self._future_captured_exception = None
self._api = api
self._backend = backend
self._cancelled = False
self._status = JobStatus.INITIALIZING
# In case of not providing a `qobj`, it is assumed the job already
# exists in the API (with `job_id`).
if qobj is None:
# Some API calls (`get_status_jobs`, `get_status_job`) provide
# enough information to recreate the `Job`. If that is the case, try
# to make use of that information during instantiation, as
# `self.status()` involves an extra call to the API.
if api_status == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_status == 'COMPLETED':
self._status = JobStatus.DONE
elif api_status == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
else:
self.status()
self._queue_position = None
self._is_device = is_device
def current_utc_time():
"""Gets the current time in UTC format"""
datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
self._creation_date = creation_date or current_utc_time()
self._future = None
self._api_error_msg = None
# pylint: disable=arguments-differ
def result(self, timeout=None, wait=5):
"""Return the result from the job.
Args:
timeout (int): number of seconds to wait for job
wait (int): time between queries to IBM Q server
Returns:
qiskit.Result: Result object
Raises:
JobError: exception raised during job initialization
"""
job_response = self._wait_for_result(timeout=timeout, wait=wait)
return self._result_from_job_response(job_response)
def _wait_for_result(self, timeout=None, wait=5):
self._wait_for_submission()
try:
job_response = self._wait_for_job(timeout=timeout, wait=wait)
if not self._qobj_payload:
self._qobj_payload = job_response.get('qObject', {})
except ApiError as api_err:
raise JobError(str(api_err))
status = self.status()
if status is not JobStatus.DONE:
raise JobError('Invalid job state. The job should be DONE but '
'it is {}'.format(str(status)))
return job_response
def _result_from_job_response(self, job_response):
return Result.from_dict(job_response['qObjectResult'])
def cancel(self):
"""Attempt to cancel a job.
Returns:
bool: True if job can be cancelled, else False. Currently this is
only possible on commercial systems.
Raises:
JobError: if there was some unexpected failure in the server
"""
hub = self._api.config.get('hub', None)
group = self._api.config.get('group', None)
project = self._api.config.get('project', None)
try:
response = self._api.cancel_job(self._job_id, hub, group, project)
self._cancelled = 'error' not in response
return self._cancelled
except ApiError as error:
self._cancelled = False
raise JobError('Error cancelling job: %s' % error.usr_msg)
def status(self):
"""Query the API to update the status.
Returns:
qiskit.providers.JobStatus: The status of the job, once updated.
Raises:
JobError: if there was an exception in the future being executed
or the server sent an unknown answer.
"""
# Implies self._job_id is None
if self._future_captured_exception is not None:
raise JobError(str(self._future_captured_exception))
if self._job_id is None or self._status in JOB_FINAL_STATES:
return self._status
try:
# TODO: See result values
api_job = self._api.get_status_job(self._job_id)
if 'status' not in api_job:
raise JobError('get_status_job didn\'t return status: %s' %
pprint.pformat(api_job))
# pylint: disable=broad-except
except Exception as err:
raise JobError(str(err))
if api_job['status'] == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_job['status'] == 'RUNNING':
self._status = JobStatus.RUNNING
queued, self._queue_position = _is_job_queued(api_job)
if queued:
self._status = JobStatus.QUEUED
elif api_job['status'] == 'COMPLETED':
self._status = JobStatus.DONE
elif api_job['status'] == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
elif 'ERROR' in api_job['status']:
# Error status are of the form "ERROR_*_JOB"
self._status = JobStatus.ERROR
# TODO: This seems to be an inconsistency in the API package.
self._api_error_msg = api_job.get('error') or api_job.get('Error')
else:
raise JobError('Unrecognized answer from server: \n{}'
.format(pprint.pformat(api_job)))
return self._status
def error_message(self):
"""Return the error message returned from the API server response."""
return self._api_error_msg
def queue_position(self):
"""Return the position in the server queue.
Returns:
Number: Position in the queue.
"""
return self._queue_position
def creation_date(self):
"""
Return creation date.
"""
return self._creation_date
def job_id(self):
"""Return backend determined id.
If the Id is not set because the job is already initializing, this call
will block until we have an Id.
"""
self._wait_for_submission()
return self._job_id
def submit(self):
"""Submit job to IBM-Q.
Raises:
JobError: If we have already submitted the job.
"""
# TODO: Validation against the schema should be done here and not
# during initialization. Once done, we should document that the method
# can raise QobjValidationError.
if self._future is not None or self._job_id is not None:
raise JobError("We have already submitted the job!")
self._future = self._executor.submit(self._submit_callback)
def _submit_callback(self):
"""Submit qobj job to IBM-Q.
Returns:
dict: A dictionary with the response of the submitted job
"""
backend_name = self.backend().name()
try:
submit_info = self._api.run_job(self._qobj_payload, backend=backend_name)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submission success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _wait_for_job(self, timeout=60, wait=5):
"""Wait until all online ran circuits of a qobj are 'COMPLETED'.
Args:
timeout (float or None): seconds to wait for job. If None, wait
indefinitely.
wait (float): seconds between queries
Returns:
dict: A dict with the contents of the API request.
Raises:
JobTimeoutError: if the job does not return results before a specified timeout.
JobError: if something wrong happened in some of the server API calls
"""
start_time = time.time()
while self.status() not in JOB_FINAL_STATES:
elapsed_time = time.time() - start_time
if timeout is not None and elapsed_time >= timeout:
raise JobTimeoutError(
'Timeout while waiting for the job: {}'.format(self._job_id)
)
logger.info('status = %s (%d seconds)', self._status, elapsed_time)
time.sleep(wait)
if self._cancelled:
raise JobError(
'Job result impossible to retrieve. The job was cancelled.')
return self._api.get_job(self._job_id)
def _wait_for_submission(self, timeout=60):
"""Waits for the request to return a job ID"""
if self._job_id is None:
if self._future is None:
raise JobError("You have to submit before asking for status or results!")
try:
submit_info = self._future.result(timeout=timeout)
if self._future_captured_exception is not None:
# pylint can't see if catch of None type
# pylint: disable=raising-bad-type
raise self._future_captured_exception
except TimeoutError as ex:
raise JobTimeoutError(
"Timeout waiting for the job being submitted: {}".format(ex)
)
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
raise JobError(str(submit_info['error']))
def qobj(self):
"""Return the Qobj submitted for this job.
Note that this method might involve querying the API for results if the
Job has been created in a previous Qiskit session.
Returns:
Qobj: the Qobj submitted for this job.
"""
if not self._qobj_payload:
# Populate self._qobj_payload by retrieving the results.
self._wait_for_result()
return Qobj(**self._qobj_payload)
class IBMQJobPreQobj(IBMQJob):
"""Subclass of IBMQJob for handling pre-qobj jobs."""
def _submit_callback(self):
"""Submit old style qasms job to IBM-Q. Can remove when all devices
understand Qobj.
Returns:
dict: A dictionary with the response of the submitted job
"""
api_jobs = []
circuits = self._job_data['circuits']
for circuit in circuits:
job = _create_api_job_from_circuit(circuit)
api_jobs.append(job)
hpc_camel_cased = _format_hpc_parameters(self._job_data['hpc'])
seed = self._job_data['seed']
shots = self._job_data['shots']
max_credits = self._job_data['max_credits']
try:
submit_info = self._api.run_job(api_jobs, backend=self.backend().name(),
shots=shots, max_credits=max_credits,
seed=seed, hpc=hpc_camel_cased)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submission success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _result_from_job_response(self, job_response):
if self._is_device:
_reorder_bits(job_response)
experiment_results = []
for circuit_result in job_response['qasms']:
this_result = {'data': circuit_result['data'],
'compiled_circuit_qasm': circuit_result.get('qasm'),
'status': circuit_result['status'],
'success': circuit_result['status'] == 'DONE',
'shots': job_response['shots']}
if 'metadata' in circuit_result:
this_result['metadata'] = circuit_result['metadata']
if 'header' in circuit_result['metadata'].get('compiled_circuit', {}):
this_result['header'] = \
circuit_result['metadata']['compiled_circuit']['header']
else:
this_result['header'] = {}
experiment_results.append(this_result)
ret = {
'id': self._job_id,
'status': job_response['status'],
'used_credits': job_response.get('usedCredits'),
'result': experiment_results,
'backend_name': self.backend().name(),
'success': job_response['status'] == 'COMPLETED',
}
# Append header: from the response; from the payload; or none.
header = job_response.get('header',
self._qobj_payload.get('header', {}))
if header:
ret['header'] = header
return result_from_old_style_dict(ret)
def qobj(self):
"""Return the Qobj submitted for this job."""
warnings.warn('This job has not been submitted using Qobj.')
return None
def _reorder_bits(job_data):
"""Temporary fix for ibmq backends.
For every ran circuit, get reordering information from qobj
and apply reordering on result.
Args:
job_data (dict): dict with the bare contents of the API.get_job request.
Raises:
JobError: raised if the creg sizes don't add up in result header.
"""
for circuit_result in job_data['qasms']:
if 'metadata' in circuit_result:
circ = circuit_result['metadata'].get('compiled_circuit')
else:
logger.warning('result object missing metadata for reordering'
' bits: bits may be out of order')
return
# device_qubit -> device_clbit (how it should have been)
measure_dict = {op['qubits'][0]: op.get('clbits', op.get('memory'))[0]
for op in circ['operations']
if op['name'] == 'measure'}
counts_dict_new = {}
for item in circuit_result['data']['counts'].items():
# fix clbit ordering to what it should have been
bits = list(item[0])
bits.reverse() # lsb in 0th position
count = item[1]
reordered_bits = list('x' * len(bits))
for device_clbit, bit in enumerate(bits):
if device_clbit in measure_dict:
correct_device_clbit = measure_dict[device_clbit]
reordered_bits[correct_device_clbit] = bit
reordered_bits.reverse()
# only keep the clbits specified by circuit, not everything on device
num_clbits = circ['header'].get('number_of_clbits',
circ['header'].get('memory_slots'))
compact_key = reordered_bits[-num_clbits:]
compact_key = "".join([b if b != 'x' else '0'
for b in compact_key])
# insert spaces to signify different classical registers
cregs = circ['header'].get('creg_sizes',
circ['header'].get('clbit_labels'))
if sum([creg[1] for creg in cregs]) != num_clbits:
raise JobError("creg sizes don't add up in result header.")
creg_begin_pos = []
creg_end_pos = []
acc = 0
for creg in reversed(cregs):
creg_size = creg[1]
creg_begin_pos.append(acc)
creg_end_pos.append(acc + creg_size)
acc += creg_size
compact_key = " ".join([compact_key[creg_begin_pos[i]:creg_end_pos[i]]
for i in range(len(cregs))])
# marginalize over unwanted measured qubits
if compact_key not in counts_dict_new:
counts_dict_new[compact_key] = count
else:
counts_dict_new[compact_key] += count
circuit_result['data']['counts'] = counts_dict_new
def _numpy_type_converter(obj):
ret = obj
if isinstance(obj, numpy.integer):
ret = int(obj)
elif isinstance(obj, numpy.floating): # pylint: disable=no-member
ret = float(obj)
elif isinstance(obj, numpy.ndarray):
ret = obj.tolist()
return ret
def _create_api_job_from_circuit(circuit):
"""Helper function that creates a special job required by the API, from a circuit."""
api_job = {}
if not circuit.get('compiled_circuit_qasm'):
compiled_circuit = transpile_dag(circuit['circuit'])
circuit['compiled_circuit_qasm'] = compiled_circuit.qasm(qeflag=True)
if isinstance(circuit['compiled_circuit_qasm'], bytes):
api_job['qasm'] = circuit['compiled_circuit_qasm'].decode()
else:
api_job['qasm'] = circuit['compiled_circuit_qasm']
if circuit.get('name'):
api_job['name'] = circuit['name']
# convert numpy types for json serialization
compiled_circuit = json.loads(json.dumps(circuit['compiled_circuit'],
default=_numpy_type_converter))
api_job['metadata'] = {'compiled_circuit': compiled_circuit}
return api_job
def _is_job_queued(api_job_response):
"""Checks whether a job has been queued or not."""
is_queued, position = False, 0
if 'infoQueue' in api_job_response:
if 'status' in api_job_response['infoQueue']:
queue_status = api_job_response['infoQueue']['status']
is_queued = queue_status == 'PENDING_IN_QUEUE'
if 'position' in api_job_response['infoQueue']:
position = api_job_response['infoQueue']['position']
return is_queued, position
def _format_hpc_parameters(hpc):
"""Helper function to get HPC parameters with the correct format"""
if hpc is None:
return None
hpc_camel_cased = None
with contextlib.suppress(KeyError, TypeError):
# Use CamelCase when passing the hpc parameters to the API.
hpc_camel_cased = {
'multiShotOptimization': hpc['multi_shot_optimization'],
'ompNumThreads': hpc['omp_num_threads']
}
return hpc_camel_cased
<|code_end|>
|
qiskit/providers/ibmq/ibmqjob.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""IBMQJob module
This module is used for creating asynchronous job objects for the
IBM Q Experience.
"""
import warnings
from concurrent import futures
import time
import logging
import pprint
import contextlib
import json
import datetime
import numpy
from qiskit.qobj import qobj_to_dict, Qobj
from qiskit.transpiler import transpile_dag
from qiskit.providers import BaseJob, JobError, JobTimeoutError
from qiskit.providers.jobstatus import JobStatus, JOB_FINAL_STATES
from qiskit.result import Result
from qiskit.result._utils import result_from_old_style_dict
from qiskit.qobj import validate_qobj_against_schema
from .api import ApiError
logger = logging.getLogger(__name__)
API_FINAL_STATES = (
'COMPLETED',
'CANCELLED',
'ERROR_CREATING_JOB',
'ERROR_VALIDATING_JOB',
'ERROR_RUNNING_JOB'
)
class IBMQJob(BaseJob):
"""Represent the jobs that will be executed on IBM-Q simulators and real
devices. Jobs are intended to be created calling ``run()`` on a particular
backend.
Creating a ``Job`` instance does not imply running it. You need to do it in
separate steps::
job = IBMQJob(...)
job.submit() # It won't block.
An error while submitting a job will cause the next call to ``status()`` to
raise. If submitting the job successes, you can inspect the job's status by
using ``status()``. Status can be one of ``JobStatus`` members::
from qiskit.backends.jobstatus import JobStatus
job = IBMQJob(...)
job.submit()
try:
job_status = job.status() # It won't block. It will query the backend API.
if job_status is JobStatus.RUNNING:
print('The job is still running')
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
A call to ``status()`` can raise if something happens at the API level that
prevents Qiskit from determining the status of the job. An example of this
is a temporary connection lose or a network failure.
The ``submit()`` and ``status()`` methods are examples of non-blocking API.
``Job`` instances also have `id()` and ``result()`` methods which will
block::
job = IBMQJob(...)
job.submit()
try:
job_id = job.id() # It will block until completing submission.
print('The job {} was successfully submitted'.format(job_id))
job_result = job.result() # It will block until finishing.
print('The job finished with result {}'.format(job_result))
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
Both methods can raise if something ath the API level happens that prevent
Qiskit from determining the status of the job.
Note:
When querying the API for getting the status, two kinds of errors are
possible. The most severe is the one preventing Qiskit from getting a
response from the backend. This can be caused by a network failure or a
temporary system break. In these cases, calling ``status()`` will raise.
If Qiskit successfully retrieves the status of a job, it could be it
finished with errors. In that case, ``status()`` will simply return
``JobStatus.ERROR`` and you can call ``error_message()`` to get more
info.
Attributes:
_executor (futures.Executor): executor to handle asynchronous jobs
"""
_executor = futures.ThreadPoolExecutor()
def __init__(self, backend, job_id, api, is_device, qobj=None,
creation_date=None, api_status=None):
"""IBMQJob init function.
We can instantiate jobs from two sources: A QObj, and an already submitted job returned by
the API servers.
Args:
backend (str): The backend instance used to run this job.
job_id (str): The job ID of an already submitted job. Pass `None`
if you are creating a new one.
api (IBMQConnector): IBMQ connector.
is_device (bool): whether backend is a real device # TODO: remove this after Qobj
qobj (Qobj): The Quantum Object. See notes below
creation_date (str): When the job was run.
api_status (str): `status` field directly from the API response.
Notes:
It is mandatory to pass either ``qobj`` or ``job_id``. Passing a ``qobj``
will ignore ``job_id`` and will create an instance to be submitted to the
API server for job creation. Passing only a `job_id` will create an instance
representing an already-created job retrieved from the API server.
"""
super().__init__(backend, job_id)
self._job_data = None
if qobj is not None:
validate_qobj_against_schema(qobj)
self._qobj_payload = qobj_to_dict(qobj, version='1.0.0')
# TODO: No need for this conversion, just use the new equivalent members above
old_qobj = qobj_to_dict(qobj, version='0.0.1')
self._job_data = {
'circuits': old_qobj['circuits'],
'hpc': old_qobj['config'].get('hpc'),
'seed': old_qobj['circuits'][0]['config']['seed'],
'shots': old_qobj['config']['shots'],
'max_credits': old_qobj['config']['max_credits']
}
else:
self._qobj_payload = {}
self._future_captured_exception = None
self._api = api
self._backend = backend
self._cancelled = False
self._status = JobStatus.INITIALIZING
# In case of not providing a `qobj`, it is assumed the job already
# exists in the API (with `job_id`).
if qobj is None:
# Some API calls (`get_status_jobs`, `get_status_job`) provide
# enough information to recreate the `Job`. If that is the case, try
# to make use of that information during instantiation, as
# `self.status()` involves an extra call to the API.
if api_status == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_status == 'COMPLETED':
self._status = JobStatus.DONE
elif api_status == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
else:
self.status()
self._queue_position = None
self._is_device = is_device
def current_utc_time():
"""Gets the current time in UTC format"""
datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
self._creation_date = creation_date or current_utc_time()
self._future = None
self._api_error_msg = None
# pylint: disable=arguments-differ
def result(self, timeout=None, wait=5):
"""Return the result from the job.
Args:
timeout (int): number of seconds to wait for job
wait (int): time between queries to IBM Q server
Returns:
qiskit.Result: Result object
Raises:
JobError: exception raised during job initialization
"""
job_response = self._wait_for_result(timeout=timeout, wait=wait)
return self._result_from_job_response(job_response)
def _wait_for_result(self, timeout=None, wait=5):
self._wait_for_submission(timeout)
try:
job_response = self._wait_for_job(timeout=timeout, wait=wait)
if not self._qobj_payload:
self._qobj_payload = job_response.get('qObject', {})
except ApiError as api_err:
raise JobError(str(api_err))
status = self.status()
if status is not JobStatus.DONE:
raise JobError('Invalid job state. The job should be DONE but '
'it is {}'.format(str(status)))
return job_response
def _result_from_job_response(self, job_response):
return Result.from_dict(job_response['qObjectResult'])
def cancel(self):
"""Attempt to cancel a job.
Returns:
bool: True if job can be cancelled, else False. Currently this is
only possible on commercial systems.
Raises:
JobError: if there was some unexpected failure in the server
"""
hub = self._api.config.get('hub', None)
group = self._api.config.get('group', None)
project = self._api.config.get('project', None)
try:
response = self._api.cancel_job(self._job_id, hub, group, project)
self._cancelled = 'error' not in response
return self._cancelled
except ApiError as error:
self._cancelled = False
raise JobError('Error cancelling job: %s' % error.usr_msg)
def status(self):
"""Query the API to update the status.
Returns:
qiskit.providers.JobStatus: The status of the job, once updated.
Raises:
JobError: if there was an exception in the future being executed
or the server sent an unknown answer.
"""
# Implies self._job_id is None
if self._future_captured_exception is not None:
raise JobError(str(self._future_captured_exception))
if self._job_id is None or self._status in JOB_FINAL_STATES:
return self._status
try:
# TODO: See result values
api_job = self._api.get_status_job(self._job_id)
if 'status' not in api_job:
raise JobError('get_status_job didn\'t return status: %s' %
pprint.pformat(api_job))
# pylint: disable=broad-except
except Exception as err:
raise JobError(str(err))
if api_job['status'] == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_job['status'] == 'RUNNING':
self._status = JobStatus.RUNNING
queued, self._queue_position = _is_job_queued(api_job)
if queued:
self._status = JobStatus.QUEUED
elif api_job['status'] == 'COMPLETED':
self._status = JobStatus.DONE
elif api_job['status'] == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
elif 'ERROR' in api_job['status']:
# Error status are of the form "ERROR_*_JOB"
self._status = JobStatus.ERROR
# TODO: This seems to be an inconsistency in the API package.
self._api_error_msg = api_job.get('error') or api_job.get('Error')
else:
raise JobError('Unrecognized answer from server: \n{}'
.format(pprint.pformat(api_job)))
return self._status
def error_message(self):
"""Return the error message returned from the API server response."""
return self._api_error_msg
def queue_position(self):
"""Return the position in the server queue.
Returns:
Number: Position in the queue.
"""
return self._queue_position
def creation_date(self):
"""
Return creation date.
"""
return self._creation_date
def job_id(self):
"""Return backend determined id.
If the Id is not set because the job is already initializing, this call
will block until we have an Id.
"""
self._wait_for_submission()
return self._job_id
def submit(self):
"""Submit job to IBM-Q.
Raises:
JobError: If we have already submitted the job.
"""
# TODO: Validation against the schema should be done here and not
# during initialization. Once done, we should document that the method
# can raise QobjValidationError.
if self._future is not None or self._job_id is not None:
raise JobError("We have already submitted the job!")
self._future = self._executor.submit(self._submit_callback)
def _submit_callback(self):
"""Submit qobj job to IBM-Q.
Returns:
dict: A dictionary with the response of the submitted job
"""
backend_name = self.backend().name()
try:
submit_info = self._api.run_job(self._qobj_payload, backend=backend_name)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submission success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _wait_for_job(self, timeout=60, wait=5):
"""Wait until all online ran circuits of a qobj are 'COMPLETED'.
Args:
timeout (float or None): seconds to wait for job. If None, wait
indefinitely.
wait (float): seconds between queries
Returns:
dict: A dict with the contents of the API request.
Raises:
JobTimeoutError: if the job does not return results before a specified timeout.
JobError: if something wrong happened in some of the server API calls
"""
start_time = time.time()
while self.status() not in JOB_FINAL_STATES:
elapsed_time = time.time() - start_time
if timeout is not None and elapsed_time >= timeout:
raise JobTimeoutError(
'Timeout while waiting for the job: {}'.format(self._job_id)
)
logger.info('status = %s (%d seconds)', self._status, elapsed_time)
time.sleep(wait)
if self._cancelled:
raise JobError(
'Job result impossible to retrieve. The job was cancelled.')
return self._api.get_job(self._job_id)
def _wait_for_submission(self, timeout=60):
"""Waits for the request to return a job ID"""
if self._job_id is None:
if self._future is None:
raise JobError("You have to submit before asking for status or results!")
try:
submit_info = self._future.result(timeout=timeout)
if self._future_captured_exception is not None:
# pylint can't see if catch of None type
# pylint: disable=raising-bad-type
raise self._future_captured_exception
except TimeoutError as ex:
raise JobTimeoutError(
"Timeout waiting for the job being submitted: {}".format(ex)
)
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
raise JobError(str(submit_info['error']))
def qobj(self):
"""Return the Qobj submitted for this job.
Note that this method might involve querying the API for results if the
Job has been created in a previous Qiskit session.
Returns:
Qobj: the Qobj submitted for this job.
"""
if not self._qobj_payload:
# Populate self._qobj_payload by retrieving the results.
self._wait_for_result()
return Qobj(**self._qobj_payload)
class IBMQJobPreQobj(IBMQJob):
"""Subclass of IBMQJob for handling pre-qobj jobs."""
def _submit_callback(self):
"""Submit old style qasms job to IBM-Q. Can remove when all devices
understand Qobj.
Returns:
dict: A dictionary with the response of the submitted job
"""
api_jobs = []
circuits = self._job_data['circuits']
for circuit in circuits:
job = _create_api_job_from_circuit(circuit)
api_jobs.append(job)
hpc_camel_cased = _format_hpc_parameters(self._job_data['hpc'])
seed = self._job_data['seed']
shots = self._job_data['shots']
max_credits = self._job_data['max_credits']
try:
submit_info = self._api.run_job(api_jobs, backend=self.backend().name(),
shots=shots, max_credits=max_credits,
seed=seed, hpc=hpc_camel_cased)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submission success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _result_from_job_response(self, job_response):
if self._is_device:
_reorder_bits(job_response)
experiment_results = []
for circuit_result in job_response['qasms']:
this_result = {'data': circuit_result['data'],
'compiled_circuit_qasm': circuit_result.get('qasm'),
'status': circuit_result['status'],
'success': circuit_result['status'] == 'DONE',
'shots': job_response['shots']}
if 'metadata' in circuit_result:
this_result['metadata'] = circuit_result['metadata']
if 'header' in circuit_result['metadata'].get('compiled_circuit', {}):
this_result['header'] = \
circuit_result['metadata']['compiled_circuit']['header']
else:
this_result['header'] = {}
experiment_results.append(this_result)
ret = {
'id': self._job_id,
'status': job_response['status'],
'used_credits': job_response.get('usedCredits'),
'result': experiment_results,
'backend_name': self.backend().name(),
'success': job_response['status'] == 'COMPLETED',
}
# Append header: from the response; from the payload; or none.
header = job_response.get('header',
self._qobj_payload.get('header', {}))
if header:
ret['header'] = header
return result_from_old_style_dict(ret)
def qobj(self):
"""Return the Qobj submitted for this job."""
warnings.warn('This job has not been submitted using Qobj.')
return None
def _reorder_bits(job_data):
"""Temporary fix for ibmq backends.
For every ran circuit, get reordering information from qobj
and apply reordering on result.
Args:
job_data (dict): dict with the bare contents of the API.get_job request.
Raises:
JobError: raised if the creg sizes don't add up in result header.
"""
for circuit_result in job_data['qasms']:
if 'metadata' in circuit_result:
circ = circuit_result['metadata'].get('compiled_circuit')
else:
logger.warning('result object missing metadata for reordering'
' bits: bits may be out of order')
return
# device_qubit -> device_clbit (how it should have been)
measure_dict = {op['qubits'][0]: op.get('clbits', op.get('memory'))[0]
for op in circ['operations']
if op['name'] == 'measure'}
counts_dict_new = {}
for item in circuit_result['data']['counts'].items():
# fix clbit ordering to what it should have been
bits = list(item[0])
bits.reverse() # lsb in 0th position
count = item[1]
reordered_bits = list('x' * len(bits))
for device_clbit, bit in enumerate(bits):
if device_clbit in measure_dict:
correct_device_clbit = measure_dict[device_clbit]
reordered_bits[correct_device_clbit] = bit
reordered_bits.reverse()
# only keep the clbits specified by circuit, not everything on device
num_clbits = circ['header'].get('number_of_clbits',
circ['header'].get('memory_slots'))
compact_key = reordered_bits[-num_clbits:]
compact_key = "".join([b if b != 'x' else '0'
for b in compact_key])
# insert spaces to signify different classical registers
cregs = circ['header'].get('creg_sizes',
circ['header'].get('clbit_labels'))
if sum([creg[1] for creg in cregs]) != num_clbits:
raise JobError("creg sizes don't add up in result header.")
creg_begin_pos = []
creg_end_pos = []
acc = 0
for creg in reversed(cregs):
creg_size = creg[1]
creg_begin_pos.append(acc)
creg_end_pos.append(acc + creg_size)
acc += creg_size
compact_key = " ".join([compact_key[creg_begin_pos[i]:creg_end_pos[i]]
for i in range(len(cregs))])
# marginalize over unwanted measured qubits
if compact_key not in counts_dict_new:
counts_dict_new[compact_key] = count
else:
counts_dict_new[compact_key] += count
circuit_result['data']['counts'] = counts_dict_new
def _numpy_type_converter(obj):
ret = obj
if isinstance(obj, numpy.integer):
ret = int(obj)
elif isinstance(obj, numpy.floating): # pylint: disable=no-member
ret = float(obj)
elif isinstance(obj, numpy.ndarray):
ret = obj.tolist()
return ret
def _create_api_job_from_circuit(circuit):
"""Helper function that creates a special job required by the API, from a circuit."""
api_job = {}
if not circuit.get('compiled_circuit_qasm'):
compiled_circuit = transpile_dag(circuit['circuit'])
circuit['compiled_circuit_qasm'] = compiled_circuit.qasm(qeflag=True)
if isinstance(circuit['compiled_circuit_qasm'], bytes):
api_job['qasm'] = circuit['compiled_circuit_qasm'].decode()
else:
api_job['qasm'] = circuit['compiled_circuit_qasm']
if circuit.get('name'):
api_job['name'] = circuit['name']
# convert numpy types for json serialization
compiled_circuit = json.loads(json.dumps(circuit['compiled_circuit'],
default=_numpy_type_converter))
api_job['metadata'] = {'compiled_circuit': compiled_circuit}
return api_job
def _is_job_queued(api_job_response):
"""Checks whether a job has been queued or not."""
is_queued, position = False, 0
if 'infoQueue' in api_job_response:
if 'status' in api_job_response['infoQueue']:
queue_status = api_job_response['infoQueue']['status']
is_queued = queue_status == 'PENDING_IN_QUEUE'
if 'position' in api_job_response['infoQueue']:
position = api_job_response['infoQueue']['position']
return is_queued, position
def _format_hpc_parameters(hpc):
"""Helper function to get HPC parameters with the correct format"""
if hpc is None:
return None
hpc_camel_cased = None
with contextlib.suppress(KeyError, TypeError):
# Use CamelCase when passing the hpc parameters to the API.
hpc_camel_cased = {
'multiShotOptimization': hpc['multi_shot_optimization'],
'ompNumThreads': hpc['omp_num_threads']
}
return hpc_camel_cased
<|code_end|>
|
Change the name Lookaheadmapper and basicmapper
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
In the folder, it is not clear what is a mapper and what is not. My view (also @ajavadia) is all steps are a mapper. Mapping is all things combined: swap insertion, fix direction, unroll to native gates, etc.
- [x] Unroller
- [ ] LookaheadSwap
- [ ] StochasticSwap should happend in (#1520)
- [ ] BasicSwap
- [ ] LayoutSelect should happen in (#1499)
- [x] CXDirection (pr #1521)
|
qiskit/transpiler/passes/__init__.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Module containing transpiler pass."""
from .cx_cancellation import CXCancellation
from .fixed_point import FixedPoint
from .optimize_1q_gates import Optimize1qGates
from .decompose import Decompose
from .barrier_before_final_measurements import BarrierBeforeFinalMeasurements
from .mapping.check_map import CheckMap
from .mapping.basic_mapper import BasicMapper
from .mapping.cx_direction import CXDirection
from .mapping.unroller import Unroller
from .mapping.lookahead_mapper import LookaheadMapper
<|code_end|>
qiskit/transpiler/passes/mapping/basic_mapper.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A pass implementing a basic mapper.
The basic mapper is a minimum effort to insert swap gates to map the DAG into a coupling map. When
a cx is not in the coupling map possibilities, it inserts one or more swaps in front to make it
compatible.
"""
from copy import copy
from qiskit.transpiler._basepasses import TransformationPass
from qiskit.dagcircuit import DAGCircuit
from qiskit.mapper import Layout
from qiskit.extensions.standard import SwapGate
class BasicMapper(TransformationPass):
"""
Maps (with minimum effort) a DAGCircuit onto a `coupling_map` adding swap gates.
"""
def __init__(self,
coupling_map,
initial_layout=None):
"""
Maps a DAGCircuit onto a `coupling_map` using swap gates.
Args:
coupling_map (CouplingMap): Directed graph represented a coupling map.
initial_layout (Layout): initial layout of qubits in mapping
"""
super().__init__()
self.coupling_map = coupling_map
self.initial_layout = initial_layout
self.swap_gate = SwapGate
def run(self, dag):
"""
Runs the BasicMapper pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
"""
new_dag = DAGCircuit()
if self.initial_layout is None:
# create a one-to-one layout
self.initial_layout = Layout()
physical_qubit = 0
for qreg in dag.qregs.values():
for index in range(qreg.size):
self.initial_layout[(qreg, index)] = physical_qubit
physical_qubit += 1
current_layout = copy(self.initial_layout)
for layer in dag.serial_layers():
subdag = layer['graph']
for a_cx in subdag.get_cnot_nodes():
physical_q0 = current_layout[a_cx['qargs'][0]]
physical_q1 = current_layout[a_cx['qargs'][1]]
if self.coupling_map.distance(physical_q0, physical_q1) != 1:
# Insert a new layer with the SWAP(s).
swap_layer = DAGCircuit()
path = self.coupling_map.shortest_undirected_path(physical_q0, physical_q1)
for swap in range(len(path) - 2):
connected_wire_1 = path[swap]
connected_wire_2 = path[swap + 1]
qubit_1 = current_layout[connected_wire_1]
qubit_2 = current_layout[connected_wire_2]
# create the involved registers
if qubit_1[0] not in swap_layer.qregs.values():
swap_layer.add_qreg(qubit_1[0])
if qubit_2[0] not in swap_layer.qregs.values():
swap_layer.add_qreg(qubit_2[0])
# create the swap operation
swap_layer.add_basis_element('swap', 2, 0, 0)
swap_layer.apply_operation_back(self.swap_gate(qubit_1, qubit_2),
qargs=[qubit_1, qubit_2])
# layer insertion
edge_map = current_layout.combine_into_edge_map(self.initial_layout)
new_dag.compose_back(swap_layer, edge_map)
# update current_layout
for swap in range(len(path) - 2):
current_layout.swap(path[swap], path[swap + 1])
edge_map = current_layout.combine_into_edge_map(self.initial_layout)
new_dag.extend_back(subdag, edge_map)
return new_dag
<|code_end|>
qiskit/transpiler/passes/mapping/lookahead_mapper.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Implementation of Sven Jandura's swap mapper submission for the 2018 QISKit
Developer Challenge, adapted to integrate into the transpiler architecture.
The role of the mapper pass is to modify the starting circuit to be compatible
with the target device's topology (the set of two-qubit gates available on the
hardware.) To do this, the mapper will insert SWAP gates to relocate the virtual
qubits for each upcoming gate onto a set of coupled physical qubits. However, as
SWAP gates are particularly lossy, the goal is to accomplish this remapping while
introducing the fewest possible additional SWAPs.
This algorithm searches through the available combinations of SWAP gates by means
of a narrowed best first/beam search, described as follows:
- Start with a layout of virtual qubits onto physical qubits.
- Find any gates in the input circuit which can be performed with the current
layout and mark them as mapped.
- For all possible SWAP gates, calculate the layout that would result from their
application and rank them according to the distance of the resulting layout
over upcoming gates (see _calc_layout_distance.)
- For the four (SEARCH_WIDTH) highest-ranking SWAPs, repeat the above process on
the layout that would be generated if they were applied.
- Repeat this process down to a depth of four (SEARCH_DEPTH) SWAPs away from the
initial layout, for a total of 256 (SEARCH_WIDTH^SEARCH_DEPTH) prospective
layouts.
- Choose the layout which maximizes the number of two-qubit which could be
performed. Add its mapped gates, including the SWAPs generated, to the
output circuit.
- Repeat the above until all gates from the initial circuit are mapped.
For more details on the algorithm, see Sven's blog post:
https://medium.com/qiskit/improving-a-quantum-compiler-48410d7a7084
"""
from copy import deepcopy
from qiskit import QuantumRegister
from qiskit.dagcircuit import DAGCircuit
from qiskit.extensions.standard import SwapGate
from qiskit.transpiler._basepasses import TransformationPass
from qiskit.mapper import Layout, remove_last_measurements, return_last_measurements, MapperError
SEARCH_DEPTH = 4
SEARCH_WIDTH = 4
class LookaheadMapper(TransformationPass):
"""Map input circuit onto a backend topology via insertion of SWAPs."""
def __init__(self, coupling_map):
"""Initialize a LookaheadMapper instance.
Arguments:
coupling_map (CouplingMap): CouplingMap of the target backend.
"""
super().__init__()
self._coupling_map = coupling_map
def run(self, dag):
"""Run one pass of the lookahead mapper on the provided DAG.
Args:
dag (DAGCircuit): the directed acyclic graph to be mapped
Returns:
DAGCircuit: A dag mapped to be compatible with the coupling_map in
the property_set.
Raises:
MapperError: If the provided DAG has more qubits than are available
in the coupling map.
"""
# Preserve fix for https://github.com/Qiskit/qiskit-terra/issues/674
removed_measures = remove_last_measurements(dag)
coupling_map = self._coupling_map
ordered_virtual_gates = list(dag.serial_layers())
if len(dag.get_qubits()) > len(coupling_map.physical_qubits):
raise MapperError('DAG contains more qubits than are present in the coupling map.')
dag_qubits = dag.get_qubits()
coupling_qubits = coupling_map.physical_qubits
starting_layout = [dag_qubits[i] if i < len(dag_qubits) else None
for i in range(len(coupling_qubits))]
mapped_gates = []
layout = Layout(starting_layout)
gates_remaining = ordered_virtual_gates.copy()
while gates_remaining:
best_step = _search_forward_n_swaps(layout, gates_remaining,
coupling_map)
layout = best_step['layout']
gates_mapped = best_step['gates_mapped']
gates_remaining = best_step['gates_remaining']
mapped_gates.extend(gates_mapped)
# Preserve input DAG's name, regs, wire_map, etc. but replace the graph.
mapped_dag = _copy_circuit_metadata(dag, coupling_map)
for gate in mapped_gates:
mapped_dag.apply_operation_back(**gate)
return_last_measurements(mapped_dag, removed_measures, layout)
return mapped_dag
def _search_forward_n_swaps(layout, gates, coupling_map,
depth=SEARCH_DEPTH, width=SEARCH_WIDTH):
"""Search for SWAPs which allow for application of largest number of gates.
Arguments:
layout (Layout): Map from virtual qubit index to physical qubit index.
gates (list): Gates to be mapped.
coupling_map (CouplingMap): CouplingMap of the target backend.
depth (int): Number of SWAP layers to search before choosing a result.
width (int): Number of SWAPs to consider at each layer.
Returns:
dict: Describes solution step found.
layout (Layout): Virtual to physical qubit map after SWAPs.
gates_remaining (list): Gates that could not be mapped.
gates_mapped (list): Gates that were mapped, including added SWAPs.
"""
gates_mapped, gates_remaining = _map_free_gates(layout, gates, coupling_map)
base_step = {'layout': layout,
'swaps_added': 0,
'gates_mapped': gates_mapped,
'gates_remaining': gates_remaining}
if not gates_remaining or depth == 0:
return base_step
possible_swaps = coupling_map.get_edges()
def _score_swap(swap):
"""Calculate the relative score for a given SWAP."""
trial_layout = layout.copy()
trial_layout.swap(*swap)
return _calc_layout_distance(gates, coupling_map, trial_layout)
ranked_swaps = sorted(possible_swaps, key=_score_swap)
best_swap, best_step = None, None
for swap in ranked_swaps[:width]:
trial_layout = layout.copy()
trial_layout.swap(*swap)
next_step = _search_forward_n_swaps(trial_layout, gates_remaining,
coupling_map, depth - 1, width)
# ranked_swaps already sorted by distance, so distance is the tie-breaker.
if best_swap is None or _score_step(next_step) > _score_step(best_step):
best_swap, best_step = swap, next_step
best_swap_gate = _swap_ops_from_edge(best_swap, layout)
return {
'layout': best_step['layout'],
'swaps_added': 1 + best_step['swaps_added'],
'gates_remaining': best_step['gates_remaining'],
'gates_mapped': gates_mapped + best_swap_gate + best_step['gates_mapped'],
}
def _map_free_gates(layout, gates, coupling_map):
"""Map all gates that can be executed with the current layout.
Args:
layout (Layout): Map from virtual qubit index to physical qubit index.
gates (list): Gates to be mapped.
coupling_map (CouplingMap): CouplingMap for target device topology.
Returns:
tuple:
mapped_gates (list): ops for gates that can be executed, mapped onto layout.
remaining_gates (list): gates that cannot be executed on the layout.
"""
blocked_qubits = set()
mapped_gates = []
remaining_gates = []
for gate in gates:
# Ignore gates which do not have associated qubits.
if not gate['partition']:
continue
qubits = gate['partition'][0]
if blocked_qubits.intersection(qubits):
blocked_qubits.update(qubits)
remaining_gates.append(gate)
elif len(qubits) == 1:
mapped_gate = _transform_gate_for_layout(gate, layout)
mapped_gates.append(mapped_gate)
elif coupling_map.distance(*[layout[q] for q in qubits]) == 1:
mapped_gate = _transform_gate_for_layout(gate, layout)
mapped_gates.append(mapped_gate)
else:
blocked_qubits.update(qubits)
remaining_gates.append(gate)
return mapped_gates, remaining_gates
def _calc_layout_distance(gates, coupling_map, layout, max_gates=None):
"""Return the sum of the distances of two-qubit pairs in each CNOT in gates
according to the layout and the coupling.
"""
if max_gates is None:
max_gates = 50 + 10 * len(coupling_map.physical_qubits)
return sum(coupling_map.distance(*[layout[q] for q in gate['partition'][0]])
for gate in gates[:max_gates]
if len(gate['partition'][0]) == 2)
def _score_step(step):
"""Count the mapped two-qubit gates, less the number of added SWAPs."""
# Each added swap will add 3 ops to gates_mapped, so subtract 3.
return len([g for g in step['gates_mapped']
if len(g.get('qargs', [])) == 2]) - 3 * step['swaps_added']
def _copy_circuit_metadata(source_dag, coupling_map):
"""Return a copy of source_dag with metadata but without a multi_graph.
Generate only a single qreg in the output DAG, matching the size of the
coupling_map."""
target_dag = DAGCircuit()
target_dag.name = source_dag.name
for creg in source_dag.cregs.values():
target_dag.add_creg(creg)
device_qreg = QuantumRegister(len(coupling_map.physical_qubits), 'q')
target_dag.add_qreg(device_qreg)
for name, (num_qbits, num_cbits, num_params) in source_dag.basis.items():
target_dag.add_basis_element(name, num_qbits, num_cbits, num_params)
for name, gate_data in source_dag.gates.items():
target_dag.add_gate_data(name, gate_data)
return target_dag
def _transform_gate_for_layout(gate, layout):
"""Return op implementing a virtual gate on given layout."""
mapped_op = deepcopy([n for n in gate['graph'].multi_graph.nodes.values()
if n['type'] == 'op'][0])
device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q')
mapped_op['qargs'] = [(device_qreg, layout[a]) for a in mapped_op['qargs']]
mapped_op.pop('type')
mapped_op.pop('name')
return mapped_op
def _swap_ops_from_edge(edge, layout):
"""Generate list of ops to implement a SWAP gate along a coupling edge."""
device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q')
qreg_edge = [(device_qreg, i) for i in edge]
return [
{'op': SwapGate(*qreg_edge), 'qargs': qreg_edge},
]
<|code_end|>
|
qiskit/transpiler/passes/__init__.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Module containing transpiler pass."""
from .cx_cancellation import CXCancellation
from .fixed_point import FixedPoint
from .optimize_1q_gates import Optimize1qGates
from .decompose import Decompose
from .barrier_before_final_measurements import BarrierBeforeFinalMeasurements
from .mapping.check_map import CheckMap
from .mapping.cx_direction import CXDirection
from .mapping.unroller import Unroller
from .mapping.basic_swap import BasicSwap
from .mapping.lookahead_swap import LookaheadSwap
<|code_end|>
qiskit/transpiler/passes/mapping/basic_swap.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A pass implementing a basic mapper.
The basic mapper is a minimum effort to insert swap gates to map the DAG into a coupling map. When
a cx is not in the coupling map possibilities, it inserts one or more swaps in front to make it
compatible.
"""
from copy import copy
from qiskit.transpiler._basepasses import TransformationPass
from qiskit.dagcircuit import DAGCircuit
from qiskit.mapper import Layout
from qiskit.extensions.standard import SwapGate
class BasicSwap(TransformationPass):
"""
Maps (with minimum effort) a DAGCircuit onto a `coupling_map` adding swap gates.
"""
def __init__(self,
coupling_map,
initial_layout=None):
"""
Maps a DAGCircuit onto a `coupling_map` using swap gates.
Args:
coupling_map (CouplingMap): Directed graph represented a coupling map.
initial_layout (Layout): initial layout of qubits in mapping
"""
super().__init__()
self.coupling_map = coupling_map
self.initial_layout = initial_layout
self.swap_gate = SwapGate
def run(self, dag):
"""
Runs the BasicSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
"""
new_dag = DAGCircuit()
if self.initial_layout is None:
# create a one-to-one layout
self.initial_layout = Layout()
physical_qubit = 0
for qreg in dag.qregs.values():
for index in range(qreg.size):
self.initial_layout[(qreg, index)] = physical_qubit
physical_qubit += 1
current_layout = copy(self.initial_layout)
for layer in dag.serial_layers():
subdag = layer['graph']
for a_cx in subdag.get_cnot_nodes():
physical_q0 = current_layout[a_cx['qargs'][0]]
physical_q1 = current_layout[a_cx['qargs'][1]]
if self.coupling_map.distance(physical_q0, physical_q1) != 1:
# Insert a new layer with the SWAP(s).
swap_layer = DAGCircuit()
path = self.coupling_map.shortest_undirected_path(physical_q0, physical_q1)
for swap in range(len(path) - 2):
connected_wire_1 = path[swap]
connected_wire_2 = path[swap + 1]
qubit_1 = current_layout[connected_wire_1]
qubit_2 = current_layout[connected_wire_2]
# create the involved registers
if qubit_1[0] not in swap_layer.qregs.values():
swap_layer.add_qreg(qubit_1[0])
if qubit_2[0] not in swap_layer.qregs.values():
swap_layer.add_qreg(qubit_2[0])
# create the swap operation
swap_layer.add_basis_element('swap', 2, 0, 0)
swap_layer.apply_operation_back(self.swap_gate(qubit_1, qubit_2),
qargs=[qubit_1, qubit_2])
# layer insertion
edge_map = current_layout.combine_into_edge_map(self.initial_layout)
new_dag.compose_back(swap_layer, edge_map)
# update current_layout
for swap in range(len(path) - 2):
current_layout.swap(path[swap], path[swap + 1])
edge_map = current_layout.combine_into_edge_map(self.initial_layout)
new_dag.extend_back(subdag, edge_map)
return new_dag
<|code_end|>
qiskit/transpiler/passes/mapping/lookahead_swap.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Implementation of Sven Jandura's swap mapper submission for the 2018 QISKit
Developer Challenge, adapted to integrate into the transpiler architecture.
The role of the mapper pass is to modify the starting circuit to be compatible
with the target device's topology (the set of two-qubit gates available on the
hardware.) To do this, the mapper will insert SWAP gates to relocate the virtual
qubits for each upcoming gate onto a set of coupled physical qubits. However, as
SWAP gates are particularly lossy, the goal is to accomplish this remapping while
introducing the fewest possible additional SWAPs.
This algorithm searches through the available combinations of SWAP gates by means
of a narrowed best first/beam search, described as follows:
- Start with a layout of virtual qubits onto physical qubits.
- Find any gates in the input circuit which can be performed with the current
layout and mark them as mapped.
- For all possible SWAP gates, calculate the layout that would result from their
application and rank them according to the distance of the resulting layout
over upcoming gates (see _calc_layout_distance.)
- For the four (SEARCH_WIDTH) highest-ranking SWAPs, repeat the above process on
the layout that would be generated if they were applied.
- Repeat this process down to a depth of four (SEARCH_DEPTH) SWAPs away from the
initial layout, for a total of 256 (SEARCH_WIDTH^SEARCH_DEPTH) prospective
layouts.
- Choose the layout which maximizes the number of two-qubit which could be
performed. Add its mapped gates, including the SWAPs generated, to the
output circuit.
- Repeat the above until all gates from the initial circuit are mapped.
For more details on the algorithm, see Sven's blog post:
https://medium.com/qiskit/improving-a-quantum-compiler-48410d7a7084
"""
from copy import deepcopy
from qiskit import QuantumRegister
from qiskit.dagcircuit import DAGCircuit
from qiskit.extensions.standard import SwapGate
from qiskit.transpiler._basepasses import TransformationPass
from qiskit.mapper import Layout, remove_last_measurements, return_last_measurements, MapperError
SEARCH_DEPTH = 4
SEARCH_WIDTH = 4
class LookaheadSwap(TransformationPass):
"""Map input circuit onto a backend topology via insertion of SWAPs."""
def __init__(self, coupling_map):
"""Initialize a LookaheadSwap instance.
Arguments:
coupling_map (CouplingMap): CouplingMap of the target backend.
"""
super().__init__()
self._coupling_map = coupling_map
def run(self, dag):
"""Run one pass of the lookahead mapper on the provided DAG.
Args:
dag (DAGCircuit): the directed acyclic graph to be mapped
Returns:
DAGCircuit: A dag mapped to be compatible with the coupling_map in
the property_set.
Raises:
MapperError: If the provided DAG has more qubits than are available
in the coupling map.
"""
# Preserve fix for https://github.com/Qiskit/qiskit-terra/issues/674
removed_measures = remove_last_measurements(dag)
coupling_map = self._coupling_map
ordered_virtual_gates = list(dag.serial_layers())
if len(dag.get_qubits()) > len(coupling_map.physical_qubits):
raise MapperError('DAG contains more qubits than are present in the coupling map.')
dag_qubits = dag.get_qubits()
coupling_qubits = coupling_map.physical_qubits
starting_layout = [dag_qubits[i] if i < len(dag_qubits) else None
for i in range(len(coupling_qubits))]
mapped_gates = []
layout = Layout(starting_layout)
gates_remaining = ordered_virtual_gates.copy()
while gates_remaining:
best_step = _search_forward_n_swaps(layout, gates_remaining,
coupling_map)
layout = best_step['layout']
gates_mapped = best_step['gates_mapped']
gates_remaining = best_step['gates_remaining']
mapped_gates.extend(gates_mapped)
# Preserve input DAG's name, regs, wire_map, etc. but replace the graph.
mapped_dag = _copy_circuit_metadata(dag, coupling_map)
for gate in mapped_gates:
mapped_dag.apply_operation_back(**gate)
return_last_measurements(mapped_dag, removed_measures, layout)
return mapped_dag
def _search_forward_n_swaps(layout, gates, coupling_map,
depth=SEARCH_DEPTH, width=SEARCH_WIDTH):
"""Search for SWAPs which allow for application of largest number of gates.
Arguments:
layout (Layout): Map from virtual qubit index to physical qubit index.
gates (list): Gates to be mapped.
coupling_map (CouplingMap): CouplingMap of the target backend.
depth (int): Number of SWAP layers to search before choosing a result.
width (int): Number of SWAPs to consider at each layer.
Returns:
dict: Describes solution step found.
layout (Layout): Virtual to physical qubit map after SWAPs.
gates_remaining (list): Gates that could not be mapped.
gates_mapped (list): Gates that were mapped, including added SWAPs.
"""
gates_mapped, gates_remaining = _map_free_gates(layout, gates, coupling_map)
base_step = {'layout': layout,
'swaps_added': 0,
'gates_mapped': gates_mapped,
'gates_remaining': gates_remaining}
if not gates_remaining or depth == 0:
return base_step
possible_swaps = coupling_map.get_edges()
def _score_swap(swap):
"""Calculate the relative score for a given SWAP."""
trial_layout = layout.copy()
trial_layout.swap(*swap)
return _calc_layout_distance(gates, coupling_map, trial_layout)
ranked_swaps = sorted(possible_swaps, key=_score_swap)
best_swap, best_step = None, None
for swap in ranked_swaps[:width]:
trial_layout = layout.copy()
trial_layout.swap(*swap)
next_step = _search_forward_n_swaps(trial_layout, gates_remaining,
coupling_map, depth - 1, width)
# ranked_swaps already sorted by distance, so distance is the tie-breaker.
if best_swap is None or _score_step(next_step) > _score_step(best_step):
best_swap, best_step = swap, next_step
best_swap_gate = _swap_ops_from_edge(best_swap, layout)
return {
'layout': best_step['layout'],
'swaps_added': 1 + best_step['swaps_added'],
'gates_remaining': best_step['gates_remaining'],
'gates_mapped': gates_mapped + best_swap_gate + best_step['gates_mapped'],
}
def _map_free_gates(layout, gates, coupling_map):
"""Map all gates that can be executed with the current layout.
Args:
layout (Layout): Map from virtual qubit index to physical qubit index.
gates (list): Gates to be mapped.
coupling_map (CouplingMap): CouplingMap for target device topology.
Returns:
tuple:
mapped_gates (list): ops for gates that can be executed, mapped onto layout.
remaining_gates (list): gates that cannot be executed on the layout.
"""
blocked_qubits = set()
mapped_gates = []
remaining_gates = []
for gate in gates:
# Ignore gates which do not have associated qubits.
if not gate['partition']:
continue
qubits = gate['partition'][0]
if blocked_qubits.intersection(qubits):
blocked_qubits.update(qubits)
remaining_gates.append(gate)
elif len(qubits) == 1:
mapped_gate = _transform_gate_for_layout(gate, layout)
mapped_gates.append(mapped_gate)
elif coupling_map.distance(*[layout[q] for q in qubits]) == 1:
mapped_gate = _transform_gate_for_layout(gate, layout)
mapped_gates.append(mapped_gate)
else:
blocked_qubits.update(qubits)
remaining_gates.append(gate)
return mapped_gates, remaining_gates
def _calc_layout_distance(gates, coupling_map, layout, max_gates=None):
"""Return the sum of the distances of two-qubit pairs in each CNOT in gates
according to the layout and the coupling.
"""
if max_gates is None:
max_gates = 50 + 10 * len(coupling_map.physical_qubits)
return sum(coupling_map.distance(*[layout[q] for q in gate['partition'][0]])
for gate in gates[:max_gates]
if len(gate['partition'][0]) == 2)
def _score_step(step):
"""Count the mapped two-qubit gates, less the number of added SWAPs."""
# Each added swap will add 3 ops to gates_mapped, so subtract 3.
return len([g for g in step['gates_mapped']
if len(g.get('qargs', [])) == 2]) - 3 * step['swaps_added']
def _copy_circuit_metadata(source_dag, coupling_map):
"""Return a copy of source_dag with metadata but without a multi_graph.
Generate only a single qreg in the output DAG, matching the size of the
coupling_map."""
target_dag = DAGCircuit()
target_dag.name = source_dag.name
for creg in source_dag.cregs.values():
target_dag.add_creg(creg)
device_qreg = QuantumRegister(len(coupling_map.physical_qubits), 'q')
target_dag.add_qreg(device_qreg)
for name, (num_qbits, num_cbits, num_params) in source_dag.basis.items():
target_dag.add_basis_element(name, num_qbits, num_cbits, num_params)
for name, gate_data in source_dag.gates.items():
target_dag.add_gate_data(name, gate_data)
return target_dag
def _transform_gate_for_layout(gate, layout):
"""Return op implementing a virtual gate on given layout."""
mapped_op = deepcopy([n for n in gate['graph'].multi_graph.nodes.values()
if n['type'] == 'op'][0])
device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q')
mapped_op['qargs'] = [(device_qreg, layout[a]) for a in mapped_op['qargs']]
mapped_op.pop('type')
mapped_op.pop('name')
return mapped_op
def _swap_ops_from_edge(edge, layout):
"""Generate list of ops to implement a SWAP gate along a coupling edge."""
device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q')
qreg_edge = [(device_qreg, i) for i in edge]
return [
{'op': SwapGate(*qreg_edge), 'qargs': qreg_edge},
]
<|code_end|>
|
interactive=True has no effect with default drawer output ('text')
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
I think we either convert the text output to an image and make it pop out, or we clearly document that interactive only works when output is 'latex' or 'mpl'. Not the default 'text'
|
qiskit/circuit/quantumcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=cyclic-import,invalid-name
"""
Quantum circuit object.
"""
from collections import OrderedDict
from copy import deepcopy
import itertools
import warnings
import sys
import multiprocessing as mp
from qiskit.qasm import _qasm
from qiskit.qiskiterror import QiskitError
from .quantumregister import QuantumRegister
from .classicalregister import ClassicalRegister
class QuantumCircuit(object):
"""Quantum circuit."""
instances = 0
prefix = 'circuit'
# Class variable OPENQASM header
header = "OPENQASM 2.0;"
# Class variable with gate definitions
# This is a dict whose values are dicts with the
# following keys:
# "print" = True or False
# "opaque" = True or False
# "n_args" = number of real parameters
# "n_bits" = number of qubits
# "args" = list of parameter names
# "bits" = list of qubit names
# "body" = GateBody AST node
definitions = OrderedDict()
def __init__(self, *regs, name=None):
"""Create a new circuit.
A circuit is a list of instructions bound to some registers.
Args:
*regs (Registers): registers to include in the circuit.
name (str or None): the name of the quantum circuit. If
None, an automatically generated string will be assigned.
Raises:
QiskitError: if the circuit name, if given, is not valid.
"""
if name is None:
name = self.cls_prefix() + str(self.cls_instances())
# pylint: disable=not-callable
# (known pylint bug: https://github.com/PyCQA/pylint/issues/1699)
if sys.platform != "win32" and \
isinstance(mp.current_process(), mp.context.ForkProcess):
name += '-{}'.format(mp.current_process().pid)
self._increment_instances()
if not isinstance(name, str):
raise QiskitError("The circuit name should be a string "
"(or None to auto-generate a name).")
self.name = name
# Data contains a list of instructions in the order they were applied.
self.data = []
# This is a map of registers bound to this circuit, by name.
self.qregs = []
self.cregs = []
self.add_register(*regs)
def __str__(self):
return str(self.draw(output='text'))
def __eq__(self, other):
# TODO: removed the DAG from this function
from qiskit.converters import circuit_to_dag
return circuit_to_dag(self) == circuit_to_dag(other)
@classmethod
def _increment_instances(cls):
cls.instances += 1
@classmethod
def cls_instances(cls):
"""Return the current number of instances of this class,
useful for auto naming."""
return cls.instances
@classmethod
def cls_prefix(cls):
"""Return the prefix to use for auto naming."""
return cls.prefix
def has_register(self, register):
"""
Test if this circuit has the register r.
Args:
register (Register): a quantum or classical register.
Returns:
bool: True if the register is contained in this circuit.
"""
has_reg = False
if (isinstance(register, QuantumRegister) and
register in self.qregs):
has_reg = True
elif (isinstance(register, ClassicalRegister) and
register in self.cregs):
has_reg = True
return has_reg
def combine(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Return self + rhs as a new object.
"""
# Check registers in LHS are compatible with RHS
self._check_compatible_regs(rhs)
# Make new circuit with combined registers
combined_qregs = deepcopy(self.qregs)
combined_cregs = deepcopy(self.cregs)
for element in rhs.qregs:
if element not in self.qregs:
combined_qregs.append(element)
for element in rhs.cregs:
if element not in self.cregs:
combined_cregs.append(element)
circuit = QuantumCircuit(*combined_qregs, *combined_cregs)
for gate in itertools.chain(self.data, rhs.data):
gate.reapply(circuit)
return circuit
def extend(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Modify and return self.
"""
# Check registers in LHS are compatible with RHS
self._check_compatible_regs(rhs)
# Add new registers
for element in rhs.qregs:
if element not in self.qregs:
self.qregs.append(element)
for element in rhs.cregs:
if element not in self.cregs:
self.cregs.append(element)
# Add new gates
for gate in rhs.data:
gate.reapply(self)
return self
def __add__(self, rhs):
"""Overload + to implement self.concatenate."""
return self.combine(rhs)
def __iadd__(self, rhs):
"""Overload += to implement self.extend."""
return self.extend(rhs)
def __len__(self):
"""Return number of operations in circuit."""
return len(self.data)
def __getitem__(self, item):
"""Return indexed operation."""
return self.data[item]
def _attach(self, instruction):
"""Attach an instruction."""
self.data.append(instruction)
return instruction
def add_register(self, *regs):
"""Add registers."""
for register in regs:
if register in self.qregs or register in self.cregs:
raise QiskitError("register name \"%s\" already exists"
% register.name)
if isinstance(register, QuantumRegister):
self.qregs.append(register)
elif isinstance(register, ClassicalRegister):
self.cregs.append(register)
else:
raise QiskitError("expected a register")
def add(self, *regs):
"""Add registers."""
warnings.warn('The add() function is deprecated and will be '
'removed in a future release. Instead use '
'QuantumCircuit.add_register().', DeprecationWarning)
self.add_register(*regs)
def _check_qreg(self, register):
"""Raise exception if r is not in this circuit or not qreg."""
if not isinstance(register, QuantumRegister):
raise QiskitError("expected quantum register")
if not self.has_register(register):
raise QiskitError(
"register '%s' not in this circuit" %
register.name)
def _check_qubit(self, qubit):
"""Raise exception if qubit is not in this circuit or bad format."""
if not isinstance(qubit, tuple):
raise QiskitError("%s is not a tuple."
"A qubit should be formated as a tuple." % str(qubit))
if not len(qubit) == 2:
raise QiskitError("%s is not a tuple with two elements, but %i instead" % len(qubit))
if not isinstance(qubit[1], int):
raise QiskitError("The second element of a tuple defining a qubit should be an int:"
"%s was found instead" % type(qubit[1]).__name__)
self._check_qreg(qubit[0])
qubit[0].check_range(qubit[1])
def _check_creg(self, register):
"""Raise exception if r is not in this circuit or not creg."""
if not isinstance(register, ClassicalRegister):
raise QiskitError("Expected ClassicalRegister, but %s given" % type(register))
if not self.has_register(register):
raise QiskitError(
"register '%s' not in this circuit" %
register.name)
def _check_dups(self, qubits):
"""Raise exception if list of qubits contains duplicates."""
squbits = set(qubits)
if len(squbits) != len(qubits):
raise QiskitError("duplicate qubit arguments")
def _check_compatible_regs(self, rhs):
"""Raise exception if the circuits are defined on incompatible registers"""
list1 = self.qregs + self.cregs
list2 = rhs.qregs + rhs.cregs
for element1 in list1:
for element2 in list2:
if element2.name == element1.name:
if element1 != element2:
raise QiskitError("circuits are not compatible")
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.definitions[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.definitions[name]["n_args"] > 0:
out += "(" + ",".join(self.definitions[name]["args"]) + ")"
out += " " + ",".join(self.definitions[name]["bits"])
if self.definitions[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.definitions[name]["body"].qasm() + "}\n"
return out
def qasm(self):
"""Return OPENQASM string."""
string_temp = self.header + "\n"
for gate_name in self.definitions:
if self.definitions[gate_name]["print"]:
string_temp += self._gate_string(gate_name)
for register in self.qregs:
string_temp += register.qasm() + "\n"
for register in self.cregs:
string_temp += register.qasm() + "\n"
for instruction in self.data:
string_temp += instruction.qasm() + "\n"
return string_temp
def draw(self, scale=0.7, filename=None, style=None, output='text',
interactive=False, line_length=None, plot_barriers=True,
reverse_bits=False):
"""Draw the quantum circuit
Using the output parameter you can specify the format. The choices are:
0. text: ASCII art string
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style
file. You can refer to the
:ref:`Style Dict Doc <style-dict-doc>` for more information
on the contents.
output (str): Select the output method to use for drawing the
circuit. Valid choices are `text`, `latex`, `latex_source`,
`mpl`.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the
latex_source output type this has no effect
line_length (int): sets the length of the lines generated by `text`
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image or matplotlib.figure or str or TextDrawing:
* PIL.Image: (output `latex`) an in-memory representation of the
image of the circuit diagram.
* matplotlib.figure: (output `mpl`) a matplotlib figure object
for the circuit diagram.
* str: (output `latex_source`). The LaTeX source code.
* TextDrawing: (output `text`). A drawing that can be printed as
ascii art
Raises:
VisualizationError: when an invalid output method is selected
"""
from qiskit.tools import visualization
return visualization.circuit_drawer(self, scale=scale,
filename=filename, style=style,
output=output,
interactive=interactive,
line_length=line_length,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
def size(self):
"""Return total number of operations in circuit."""
# TODO: removed the DAG from this function
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.size()
def depth(self):
"""Return circuit depth (i.e. length of critical path)."""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.depth()
def width(self):
"""Return number of qubits in circuit."""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.width()
def count_ops(self):
"""Count each operation kind in the circuit.
Returns:
dict: a breakdown of how many operations of each kind.
"""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.count_ops()
def num_tensor_factors(self):
"""How many non-entangled subcircuits can the circuit be factored to."""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.num_tensor_factors()
@staticmethod
def from_qasm_file(path):
"""Take in a QASM file and generate a QuantumCircuit object.
Args:
path (str): Path to the file for a QASM program
Return:
QuantumCircuit: The QuantumCircuit object for the input QASM
"""
qasm = _qasm.Qasm(filename=path)
return _circuit_from_qasm(qasm)
@staticmethod
def from_qasm_str(qasm_str):
"""Take in a QASM string and generate a QuantumCircuit object.
Args:
qasm_str (str): A QASM program string
Return:
QuantumCircuit: The QuantumCircuit object for the input QASM
"""
qasm = _qasm.Qasm(data=qasm_str)
return _circuit_from_qasm(qasm)
def _circuit_from_qasm(qasm):
from qiskit.converters import ast_to_dag
from qiskit.converters import dag_to_circuit
ast = qasm.parse()
dag = ast_to_dag(ast)
return dag_to_circuit(dag)
<|code_end|>
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# TODO(mtreinish): Remove after 0.7 and the deprecated methods are removed
# pylint: disable=unused-argument
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import errno
import logging
import os
import subprocess
import tempfile
import warnings
from PIL import Image
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _latex
from qiskit.tools.visualization import _text
from qiskit.tools.visualization import _utils
from qiskit.tools.visualization import _matplotlib
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
image = circuit_drawer(circuit, scale=scale, style=style)
if image:
image.show()
def circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art TextDrawing that can be printed in the console.
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Args:
circuit (QuantumCircuit): the quantum circuit to draw
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (TextDrawing): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if
one is not specified it will use latex and if that fails fallback
to mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(cannot inline in Jupyter). Note when used with the latex_source
output type this has no effect.
line_length (int): Sets the length of the lines generated by `text`
output type. This useful when the drawing does not fit in the
console. If None (default), it will try to guess the console width
using shutil.get_terminal_size(). However, if you're running in
jupyter the default line length is set to 80 characters. If you
don't want pagination at all, set `line_length=-1`.
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: (output `latex`) an in-memory representation of the image
of the circuit diagram.
matplotlib.figure: (output `mpl`) a matplotlib figure object for the
circuit diagram.
String: (output `latex_source`). The LaTeX source code.
TextDrawing: (output `text`). A drawing that can be printed as ascii art
Raises:
VisualizationError: when an invalid output method is selected
ImportError: when the output methods requieres non-installed libraries.
.. _style-dict-doc:
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defaults to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'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'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
plotbarrier (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True. This is deprecated in the style dict
and will be removed in a future release. Use the `plot_barriers`
kwarg instead.
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
reversebits (bool): When set to True reverse the bit order inside
registers for the output visualization. This is deprecated in the
style dict and will be removed in a future release use the
`reverse_bits` kwarg instead.
"""
image = None
if style:
if 'reversebits' in style:
warnings.warn('The reversebits key in style is deprecated and will'
'not work in the future. Instead use the '
'``reverse_bits`` kwarg.', DeprecationWarning)
reverse_bits = style.get('reversebits')
if 'plotbarrier' in style:
warnings.warn('The plotbarrier key in style is deprecated and will'
'not work in the future. Instead use the '
'``plot_barriers`` kwarg.', DeprecationWarning)
plot_barriers = style.get('plotbarrier')
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'"text" by default', DeprecationWarning)
try:
image = _latex_circuit_drawer(circuit, scale, filename, style)
except (OSError, subprocess.CalledProcessError, FileNotFoundError):
if _matplotlib.HAS_MATPLOTLIB:
image = _matplotlib_circuit_drawer(circuit, scale, filename,
style)
else:
raise ImportError('The default output needs matplotlib. '
'Run "pip install matplotlib" before.')
else:
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename,
line_length=line_length,
reversebits=reverse_bits,
plotbarriers=plot_barriers)
elif output == 'latex':
image = _latex_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'latex_source':
return _generate_latex_source(circuit,
filename=filename, scale=scale,
style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'mpl':
image = _matplotlib_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
else:
raise _error.VisualizationError(
'Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if image and interactive:
image.show()
return image
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
"""Return default style for matplotlib_circuit_drawer (IBM QX style)."""
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None, line_length=None, reversebits=False,
plotbarriers=True):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
reversebits (bool): Rearrange the bits in reverse order.
plotbarriers (bool): Draws the barriers when they are there.
Returns:
TextDrawing: An instances that, when printed, draws the circuit in ascii art.
"""
qregs, cregs, ops = _utils._get_instructions(circuit, reversebits=reversebits)
text_drawing = _text.TextDrawing(qregs, cregs, ops)
text_drawing.plotbarriers = plotbarriers
text_drawing.line_length = line_length
if filename:
text_drawing.dump(filename)
return text_drawing
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath,
scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
image = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as ex:
with open('latex_error.log', 'wb') as error_file:
error_file.write(ex.stdout)
logger.warning('WARNING Unable to compile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
image = Image.open(base + '.png')
image = _utils._trim(image)
os.remove(base + '.png')
if filename:
image.save(filename, 'PNG')
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return image
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
scale=0.7, style=None, reverse_bits=False,
plot_barriers=True):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
str: Latex string appropriate for writing to file.
"""
qregs, cregs, ops = _utils._get_instructions(circuit,
reversebits=reverse_bits)
qcimg = _latex.QCircuitImage(qregs, cregs, ops, scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
matplotlib.figure: a matplotlib figure object for the circuit diagram
"""
qcd = _matplotlib.MatplotlibDrawer(scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
<|code_end|>
|
qiskit/circuit/quantumcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=cyclic-import,invalid-name
"""
Quantum circuit object.
"""
from collections import OrderedDict
from copy import deepcopy
import itertools
import warnings
import sys
import multiprocessing as mp
from qiskit.qasm import _qasm
from qiskit.qiskiterror import QiskitError
from .quantumregister import QuantumRegister
from .classicalregister import ClassicalRegister
class QuantumCircuit(object):
"""Quantum circuit."""
instances = 0
prefix = 'circuit'
# Class variable OPENQASM header
header = "OPENQASM 2.0;"
# Class variable with gate definitions
# This is a dict whose values are dicts with the
# following keys:
# "print" = True or False
# "opaque" = True or False
# "n_args" = number of real parameters
# "n_bits" = number of qubits
# "args" = list of parameter names
# "bits" = list of qubit names
# "body" = GateBody AST node
definitions = OrderedDict()
def __init__(self, *regs, name=None):
"""Create a new circuit.
A circuit is a list of instructions bound to some registers.
Args:
*regs (Registers): registers to include in the circuit.
name (str or None): the name of the quantum circuit. If
None, an automatically generated string will be assigned.
Raises:
QiskitError: if the circuit name, if given, is not valid.
"""
if name is None:
name = self.cls_prefix() + str(self.cls_instances())
# pylint: disable=not-callable
# (known pylint bug: https://github.com/PyCQA/pylint/issues/1699)
if sys.platform != "win32" and \
isinstance(mp.current_process(), mp.context.ForkProcess):
name += '-{}'.format(mp.current_process().pid)
self._increment_instances()
if not isinstance(name, str):
raise QiskitError("The circuit name should be a string "
"(or None to auto-generate a name).")
self.name = name
# Data contains a list of instructions in the order they were applied.
self.data = []
# This is a map of registers bound to this circuit, by name.
self.qregs = []
self.cregs = []
self.add_register(*regs)
def __str__(self):
return str(self.draw(output='text'))
def __eq__(self, other):
# TODO: removed the DAG from this function
from qiskit.converters import circuit_to_dag
return circuit_to_dag(self) == circuit_to_dag(other)
@classmethod
def _increment_instances(cls):
cls.instances += 1
@classmethod
def cls_instances(cls):
"""Return the current number of instances of this class,
useful for auto naming."""
return cls.instances
@classmethod
def cls_prefix(cls):
"""Return the prefix to use for auto naming."""
return cls.prefix
def has_register(self, register):
"""
Test if this circuit has the register r.
Args:
register (Register): a quantum or classical register.
Returns:
bool: True if the register is contained in this circuit.
"""
has_reg = False
if (isinstance(register, QuantumRegister) and
register in self.qregs):
has_reg = True
elif (isinstance(register, ClassicalRegister) and
register in self.cregs):
has_reg = True
return has_reg
def combine(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Return self + rhs as a new object.
"""
# Check registers in LHS are compatible with RHS
self._check_compatible_regs(rhs)
# Make new circuit with combined registers
combined_qregs = deepcopy(self.qregs)
combined_cregs = deepcopy(self.cregs)
for element in rhs.qregs:
if element not in self.qregs:
combined_qregs.append(element)
for element in rhs.cregs:
if element not in self.cregs:
combined_cregs.append(element)
circuit = QuantumCircuit(*combined_qregs, *combined_cregs)
for gate in itertools.chain(self.data, rhs.data):
gate.reapply(circuit)
return circuit
def extend(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Modify and return self.
"""
# Check registers in LHS are compatible with RHS
self._check_compatible_regs(rhs)
# Add new registers
for element in rhs.qregs:
if element not in self.qregs:
self.qregs.append(element)
for element in rhs.cregs:
if element not in self.cregs:
self.cregs.append(element)
# Add new gates
for gate in rhs.data:
gate.reapply(self)
return self
def __add__(self, rhs):
"""Overload + to implement self.concatenate."""
return self.combine(rhs)
def __iadd__(self, rhs):
"""Overload += to implement self.extend."""
return self.extend(rhs)
def __len__(self):
"""Return number of operations in circuit."""
return len(self.data)
def __getitem__(self, item):
"""Return indexed operation."""
return self.data[item]
def _attach(self, instruction):
"""Attach an instruction."""
self.data.append(instruction)
return instruction
def add_register(self, *regs):
"""Add registers."""
for register in regs:
if register in self.qregs or register in self.cregs:
raise QiskitError("register name \"%s\" already exists"
% register.name)
if isinstance(register, QuantumRegister):
self.qregs.append(register)
elif isinstance(register, ClassicalRegister):
self.cregs.append(register)
else:
raise QiskitError("expected a register")
def add(self, *regs):
"""Add registers."""
warnings.warn('The add() function is deprecated and will be '
'removed in a future release. Instead use '
'QuantumCircuit.add_register().', DeprecationWarning)
self.add_register(*regs)
def _check_qreg(self, register):
"""Raise exception if r is not in this circuit or not qreg."""
if not isinstance(register, QuantumRegister):
raise QiskitError("expected quantum register")
if not self.has_register(register):
raise QiskitError(
"register '%s' not in this circuit" %
register.name)
def _check_qubit(self, qubit):
"""Raise exception if qubit is not in this circuit or bad format."""
if not isinstance(qubit, tuple):
raise QiskitError("%s is not a tuple."
"A qubit should be formated as a tuple." % str(qubit))
if not len(qubit) == 2:
raise QiskitError("%s is not a tuple with two elements, but %i instead" % len(qubit))
if not isinstance(qubit[1], int):
raise QiskitError("The second element of a tuple defining a qubit should be an int:"
"%s was found instead" % type(qubit[1]).__name__)
self._check_qreg(qubit[0])
qubit[0].check_range(qubit[1])
def _check_creg(self, register):
"""Raise exception if r is not in this circuit or not creg."""
if not isinstance(register, ClassicalRegister):
raise QiskitError("Expected ClassicalRegister, but %s given" % type(register))
if not self.has_register(register):
raise QiskitError(
"register '%s' not in this circuit" %
register.name)
def _check_dups(self, qubits):
"""Raise exception if list of qubits contains duplicates."""
squbits = set(qubits)
if len(squbits) != len(qubits):
raise QiskitError("duplicate qubit arguments")
def _check_compatible_regs(self, rhs):
"""Raise exception if the circuits are defined on incompatible registers"""
list1 = self.qregs + self.cregs
list2 = rhs.qregs + rhs.cregs
for element1 in list1:
for element2 in list2:
if element2.name == element1.name:
if element1 != element2:
raise QiskitError("circuits are not compatible")
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.definitions[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.definitions[name]["n_args"] > 0:
out += "(" + ",".join(self.definitions[name]["args"]) + ")"
out += " " + ",".join(self.definitions[name]["bits"])
if self.definitions[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.definitions[name]["body"].qasm() + "}\n"
return out
def qasm(self):
"""Return OPENQASM string."""
string_temp = self.header + "\n"
for gate_name in self.definitions:
if self.definitions[gate_name]["print"]:
string_temp += self._gate_string(gate_name)
for register in self.qregs:
string_temp += register.qasm() + "\n"
for register in self.cregs:
string_temp += register.qasm() + "\n"
for instruction in self.data:
string_temp += instruction.qasm() + "\n"
return string_temp
def draw(self, scale=0.7, filename=None, style=None, output='text',
interactive=False, line_length=None, plot_barriers=True,
reverse_bits=False):
"""Draw the quantum circuit
Using the output parameter you can specify the format. The choices are:
0. text: ASCII art string
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style
file. You can refer to the
:ref:`Style Dict Doc <style-dict-doc>` for more information
on the contents.
output (str): Select the output method to use for drawing the
circuit. Valid choices are `text`, `latex`, `latex_source`,
`mpl`.
interactive (bool): when set true show the circuit in a new window
(for `mpl` this depends on the matplotlib backend being used
supporting this). Note when used with either the `text` or the
`latex_source` output type this has no effect and will be
silently ignored.
line_length (int): sets the length of the lines generated by `text`
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image or matplotlib.figure or str or TextDrawing:
* PIL.Image: (output `latex`) an in-memory representation of the
image of the circuit diagram.
* matplotlib.figure: (output `mpl`) a matplotlib figure object
for the circuit diagram.
* str: (output `latex_source`). The LaTeX source code.
* TextDrawing: (output `text`). A drawing that can be printed as
ascii art
Raises:
VisualizationError: when an invalid output method is selected
"""
from qiskit.tools import visualization
return visualization.circuit_drawer(self, scale=scale,
filename=filename, style=style,
output=output,
interactive=interactive,
line_length=line_length,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
def size(self):
"""Return total number of operations in circuit."""
# TODO: removed the DAG from this function
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.size()
def depth(self):
"""Return circuit depth (i.e. length of critical path)."""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.depth()
def width(self):
"""Return number of qubits in circuit."""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.width()
def count_ops(self):
"""Count each operation kind in the circuit.
Returns:
dict: a breakdown of how many operations of each kind.
"""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.count_ops()
def num_tensor_factors(self):
"""How many non-entangled subcircuits can the circuit be factored to."""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.num_tensor_factors()
@staticmethod
def from_qasm_file(path):
"""Take in a QASM file and generate a QuantumCircuit object.
Args:
path (str): Path to the file for a QASM program
Return:
QuantumCircuit: The QuantumCircuit object for the input QASM
"""
qasm = _qasm.Qasm(filename=path)
return _circuit_from_qasm(qasm)
@staticmethod
def from_qasm_str(qasm_str):
"""Take in a QASM string and generate a QuantumCircuit object.
Args:
qasm_str (str): A QASM program string
Return:
QuantumCircuit: The QuantumCircuit object for the input QASM
"""
qasm = _qasm.Qasm(data=qasm_str)
return _circuit_from_qasm(qasm)
def _circuit_from_qasm(qasm):
from qiskit.converters import ast_to_dag
from qiskit.converters import dag_to_circuit
ast = qasm.parse()
dag = ast_to_dag(ast)
return dag_to_circuit(dag)
<|code_end|>
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# TODO(mtreinish): Remove after 0.7 and the deprecated methods are removed
# pylint: disable=unused-argument
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import errno
import logging
import os
import subprocess
import tempfile
import warnings
from PIL import Image
from qiskit.tools.visualization import _error
from qiskit.tools.visualization import _latex
from qiskit.tools.visualization import _text
from qiskit.tools.visualization import _utils
from qiskit.tools.visualization import _matplotlib
logger = logging.getLogger(__name__)
def plot_circuit(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
style=None):
"""Plot and show circuit (opens new window, cannot inline in Jupyter)"""
warnings.warn('The plot_circuit() function is deprecated and will be '
'removed in the future. Instead use circuit_drawer() with '
'the `interactive` flag set true', DeprecationWarning)
image = circuit_drawer(circuit, scale=scale, style=style)
if image:
image.show()
def circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
output=None,
interactive=False,
line_length=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art TextDrawing that can be printed in the console.
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Args:
circuit (QuantumCircuit): the quantum circuit to draw
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (TextDrawing): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if
one is not specified it will use latex and if that fails fallback
to mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(for `mpl` this depends on the matplotlib backend being used
supporting this). Note when used with either the `text` or the
`latex_source` output type this has no effect and will be silently
ignored.
line_length (int): Sets the length of the lines generated by `text`
output type. This useful when the drawing does not fit in the
console. If None (default), it will try to guess the console width
using shutil.get_terminal_size(). However, if you're running in
jupyter the default line length is set to 80 characters. If you
don't want pagination at all, set `line_length=-1`.
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: (output `latex`) an in-memory representation of the image
of the circuit diagram.
matplotlib.figure: (output `mpl`) a matplotlib figure object for the
circuit diagram.
String: (output `latex_source`). The LaTeX source code.
TextDrawing: (output `text`). A drawing that can be printed as ascii art
Raises:
VisualizationError: when an invalid output method is selected
ImportError: when the output methods requieres non-installed libraries.
.. _style-dict-doc:
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defaults to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'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'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
plotbarrier (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True. This is deprecated in the style dict
and will be removed in a future release. Use the `plot_barriers`
kwarg instead.
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
reversebits (bool): When set to True reverse the bit order inside
registers for the output visualization. This is deprecated in the
style dict and will be removed in a future release use the
`reverse_bits` kwarg instead.
"""
image = None
if style:
if 'reversebits' in style:
warnings.warn('The reversebits key in style is deprecated and will'
'not work in the future. Instead use the '
'``reverse_bits`` kwarg.', DeprecationWarning)
reverse_bits = style.get('reversebits')
if 'plotbarrier' in style:
warnings.warn('The plotbarrier key in style is deprecated and will'
'not work in the future. Instead use the '
'``plot_barriers`` kwarg.', DeprecationWarning)
plot_barriers = style.get('plotbarrier')
if not output:
warnings.warn('The current behavior for the default output will change'
' in a future release. Instead of trying latex and '
'falling back to mpl on failure it will just use '
'"text" by default', DeprecationWarning)
try:
image = _latex_circuit_drawer(circuit, scale, filename, style)
except (OSError, subprocess.CalledProcessError, FileNotFoundError):
if _matplotlib.HAS_MATPLOTLIB:
image = _matplotlib_circuit_drawer(circuit, scale, filename,
style)
else:
raise ImportError('The default output needs matplotlib. '
'Run "pip install matplotlib" before.')
else:
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename,
line_length=line_length,
reversebits=reverse_bits,
plotbarriers=plot_barriers)
elif output == 'latex':
image = _latex_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'latex_source':
return _generate_latex_source(circuit,
filename=filename, scale=scale,
style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'mpl':
image = _matplotlib_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
else:
raise _error.VisualizationError(
'Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if image and interactive:
image.show()
return image
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
"""Return default style for matplotlib_circuit_drawer (IBM QX style)."""
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None, line_length=None, reversebits=False,
plotbarriers=True):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
reversebits (bool): Rearrange the bits in reverse order.
plotbarriers (bool): Draws the barriers when they are there.
Returns:
TextDrawing: An instances that, when printed, draws the circuit in ascii art.
"""
qregs, cregs, ops = _utils._get_instructions(circuit, reversebits=reversebits)
text_drawing = _text.TextDrawing(qregs, cregs, ops)
text_drawing.plotbarriers = plotbarriers
text_drawing.line_length = line_length
if filename:
text_drawing.dump(filename)
return text_drawing
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def latex_circuit_drawer(circuit,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
warnings.warn('The latex_circuit_drawer() function is deprecated and will '
'be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex`.', DeprecationWarning)
return _latex_circuit_drawer(circuit, scale=scale,
filename=filename, style=style)
def _latex_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath,
scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
image = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as ex:
with open('latex_error.log', 'wb') as error_file:
error_file.write(ex.stdout)
logger.warning('WARNING Unable to compile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
image = Image.open(base + '.png')
image = _utils._trim(image)
os.remove(base + '.png')
if filename:
image.save(filename, 'PNG')
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return image
def generate_latex_source(circuit, filename=None,
basis="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
"cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap",
scale=0.7, style=None):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
basis (str): optional comma-separated list of gate names
style (dict or str): dictionary of style or file name of style file
Returns:
str: Latex string appropriate for writing to file.
"""
warnings.warn('The generate_latex_source() function is deprecated and will'
' be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`latex_source`.', DeprecationWarning)
return _generate_latex_source(circuit, filename=filename,
scale=scale, style=style)
def _generate_latex_source(circuit, filename=None,
scale=0.7, style=None, reverse_bits=False,
plot_barriers=True):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
str: Latex string appropriate for writing to file.
"""
qregs, cregs, ops = _utils._get_instructions(circuit,
reversebits=reverse_bits)
qcimg = _latex.QCircuitImage(qregs, cregs, ops, scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def matplotlib_circuit_drawer(circuit,
basis='id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap',
scale=0.7,
filename=None,
style=None):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
basis (str): comma separated list of gates
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
Returns:
PIL.Image: an in-memory representation of the circuit diagram
"""
warnings.warn('The matplotlib_circuit_drawer() function is deprecated and '
'will be removed in a future release. Instead use the '
'circuit_drawer() function with the `output` kwarg set to '
'`mpl`.', DeprecationWarning)
return _matplotlib_circuit_drawer(circuit, scale=scale,
filename=filename, style=style)
def _matplotlib_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
matplotlib.figure: a matplotlib figure object for the circuit diagram
"""
qcd = _matplotlib.MatplotlibDrawer(scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
<|code_end|>
|
IBMQjob Seed
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: master
- **Python version**: 3.6.6
- **Operating system**: OSX
### What is the current behavior?
[IBMQJob `_job_data` tries to directly access seed] (https://github.com/Qiskit/qiskit-terra/blob/37e4f3540e2fc1c9ab4b37c6cc5a449c82fb2391/qiskit/providers/ibmq/ibmqjob.py#L150).
### Steps to reproduce the problem
### What is the expected behaviour?
It should not fail on pulse qobj's missing this seed.
### Suggested solutions
`seed': old_qobj['circuits'][0]['config'].get('seed')`
|
qiskit/providers/ibmq/ibmqjob.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""IBMQJob module
This module is used for creating asynchronous job objects for the
IBM Q Experience.
"""
import warnings
from concurrent import futures
import time
import logging
import pprint
import contextlib
import json
import datetime
import numpy
from qiskit.qobj import qobj_to_dict, Qobj
from qiskit.transpiler import transpile_dag
from qiskit.providers import BaseJob, JobError, JobTimeoutError
from qiskit.providers.jobstatus import JobStatus, JOB_FINAL_STATES
from qiskit.result import Result
from qiskit.result._utils import result_from_old_style_dict
from qiskit.qobj import validate_qobj_against_schema
from .api import ApiError
logger = logging.getLogger(__name__)
API_FINAL_STATES = (
'COMPLETED',
'CANCELLED',
'ERROR_CREATING_JOB',
'ERROR_VALIDATING_JOB',
'ERROR_RUNNING_JOB'
)
class IBMQJob(BaseJob):
"""Represent the jobs that will be executed on IBM-Q simulators and real
devices. Jobs are intended to be created calling ``run()`` on a particular
backend.
Creating a ``Job`` instance does not imply running it. You need to do it in
separate steps::
job = IBMQJob(...)
job.submit() # It won't block.
An error while submitting a job will cause the next call to ``status()`` to
raise. If submitting the job successes, you can inspect the job's status by
using ``status()``. Status can be one of ``JobStatus`` members::
from qiskit.backends.jobstatus import JobStatus
job = IBMQJob(...)
job.submit()
try:
job_status = job.status() # It won't block. It will query the backend API.
if job_status is JobStatus.RUNNING:
print('The job is still running')
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
A call to ``status()`` can raise if something happens at the API level that
prevents Qiskit from determining the status of the job. An example of this
is a temporary connection lose or a network failure.
The ``submit()`` and ``status()`` methods are examples of non-blocking API.
``Job`` instances also have `id()` and ``result()`` methods which will
block::
job = IBMQJob(...)
job.submit()
try:
job_id = job.id() # It will block until completing submission.
print('The job {} was successfully submitted'.format(job_id))
job_result = job.result() # It will block until finishing.
print('The job finished with result {}'.format(job_result))
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
Both methods can raise if something ath the API level happens that prevent
Qiskit from determining the status of the job.
Note:
When querying the API for getting the status, two kinds of errors are
possible. The most severe is the one preventing Qiskit from getting a
response from the backend. This can be caused by a network failure or a
temporary system break. In these cases, calling ``status()`` will raise.
If Qiskit successfully retrieves the status of a job, it could be it
finished with errors. In that case, ``status()`` will simply return
``JobStatus.ERROR`` and you can call ``error_message()`` to get more
info.
Attributes:
_executor (futures.Executor): executor to handle asynchronous jobs
"""
_executor = futures.ThreadPoolExecutor()
def __init__(self, backend, job_id, api, is_device, qobj=None,
creation_date=None, api_status=None):
"""IBMQJob init function.
We can instantiate jobs from two sources: A QObj, and an already submitted job returned by
the API servers.
Args:
backend (str): The backend instance used to run this job.
job_id (str): The job ID of an already submitted job. Pass `None`
if you are creating a new one.
api (IBMQConnector): IBMQ connector.
is_device (bool): whether backend is a real device # TODO: remove this after Qobj
qobj (Qobj): The Quantum Object. See notes below
creation_date (str): When the job was run.
api_status (str): `status` field directly from the API response.
Notes:
It is mandatory to pass either ``qobj`` or ``job_id``. Passing a ``qobj``
will ignore ``job_id`` and will create an instance to be submitted to the
API server for job creation. Passing only a `job_id` will create an instance
representing an already-created job retrieved from the API server.
"""
super().__init__(backend, job_id)
self._job_data = None
if qobj is not None:
validate_qobj_against_schema(qobj)
self._qobj_payload = qobj_to_dict(qobj, version='1.0.0')
# TODO: No need for this conversion, just use the new equivalent members above
old_qobj = qobj_to_dict(qobj, version='0.0.1')
self._job_data = {
'circuits': old_qobj['circuits'],
'hpc': old_qobj['config'].get('hpc'),
'seed': old_qobj['circuits'][0]['config']['seed'],
'shots': old_qobj['config']['shots'],
'max_credits': old_qobj['config']['max_credits']
}
else:
self._qobj_payload = {}
self._future_captured_exception = None
self._api = api
self._backend = backend
self._cancelled = False
self._status = JobStatus.INITIALIZING
# In case of not providing a `qobj`, it is assumed the job already
# exists in the API (with `job_id`).
if qobj is None:
# Some API calls (`get_status_jobs`, `get_status_job`) provide
# enough information to recreate the `Job`. If that is the case, try
# to make use of that information during instantiation, as
# `self.status()` involves an extra call to the API.
if api_status == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_status == 'COMPLETED':
self._status = JobStatus.DONE
elif api_status == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
else:
self.status()
self._queue_position = None
self._is_device = is_device
def current_utc_time():
"""Gets the current time in UTC format"""
datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
self._creation_date = creation_date or current_utc_time()
self._future = None
self._api_error_msg = None
# pylint: disable=arguments-differ
def result(self, timeout=None, wait=5):
"""Return the result from the job.
Args:
timeout (int): number of seconds to wait for job
wait (int): time between queries to IBM Q server
Returns:
qiskit.Result: Result object
Raises:
JobError: exception raised during job initialization
"""
job_response = self._wait_for_result(timeout=timeout, wait=wait)
return self._result_from_job_response(job_response)
def _wait_for_result(self, timeout=None, wait=5):
self._wait_for_submission(timeout)
try:
job_response = self._wait_for_job(timeout=timeout, wait=wait)
if not self._qobj_payload:
self._qobj_payload = job_response.get('qObject', {})
except ApiError as api_err:
raise JobError(str(api_err))
status = self.status()
if status is not JobStatus.DONE:
raise JobError('Invalid job state. The job should be DONE but '
'it is {}'.format(str(status)))
return job_response
def _result_from_job_response(self, job_response):
return Result.from_dict(job_response['qObjectResult'])
def cancel(self):
"""Attempt to cancel a job.
Returns:
bool: True if job can be cancelled, else False. Currently this is
only possible on commercial systems.
Raises:
JobError: if there was some unexpected failure in the server
"""
hub = self._api.config.get('hub', None)
group = self._api.config.get('group', None)
project = self._api.config.get('project', None)
try:
response = self._api.cancel_job(self._job_id, hub, group, project)
self._cancelled = 'error' not in response
return self._cancelled
except ApiError as error:
self._cancelled = False
raise JobError('Error cancelling job: %s' % error.usr_msg)
def status(self):
"""Query the API to update the status.
Returns:
qiskit.providers.JobStatus: The status of the job, once updated.
Raises:
JobError: if there was an exception in the future being executed
or the server sent an unknown answer.
"""
# Implies self._job_id is None
if self._future_captured_exception is not None:
raise JobError(str(self._future_captured_exception))
if self._job_id is None or self._status in JOB_FINAL_STATES:
return self._status
try:
# TODO: See result values
api_job = self._api.get_status_job(self._job_id)
if 'status' not in api_job:
raise JobError('get_status_job didn\'t return status: %s' %
pprint.pformat(api_job))
# pylint: disable=broad-except
except Exception as err:
raise JobError(str(err))
if api_job['status'] == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_job['status'] == 'RUNNING':
self._status = JobStatus.RUNNING
queued, self._queue_position = _is_job_queued(api_job)
if queued:
self._status = JobStatus.QUEUED
elif api_job['status'] == 'COMPLETED':
self._status = JobStatus.DONE
elif api_job['status'] == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
elif 'ERROR' in api_job['status']:
# Error status are of the form "ERROR_*_JOB"
self._status = JobStatus.ERROR
# TODO: This seems to be an inconsistency in the API package.
self._api_error_msg = api_job.get('error') or api_job.get('Error')
else:
raise JobError('Unrecognized answer from server: \n{}'
.format(pprint.pformat(api_job)))
return self._status
def error_message(self):
"""Return the error message returned from the API server response."""
return self._api_error_msg
def queue_position(self):
"""Return the position in the server queue.
Returns:
Number: Position in the queue.
"""
return self._queue_position
def creation_date(self):
"""
Return creation date.
"""
return self._creation_date
def job_id(self):
"""Return backend determined id.
If the Id is not set because the job is already initializing, this call
will block until we have an Id.
"""
self._wait_for_submission()
return self._job_id
def submit(self):
"""Submit job to IBM-Q.
Raises:
JobError: If we have already submitted the job.
"""
# TODO: Validation against the schema should be done here and not
# during initialization. Once done, we should document that the method
# can raise QobjValidationError.
if self._future is not None or self._job_id is not None:
raise JobError("We have already submitted the job!")
self._future = self._executor.submit(self._submit_callback)
def _submit_callback(self):
"""Submit qobj job to IBM-Q.
Returns:
dict: A dictionary with the response of the submitted job
"""
backend_name = self.backend().name()
try:
submit_info = self._api.run_job(self._qobj_payload, backend=backend_name)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submission success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _wait_for_job(self, timeout=60, wait=5):
"""Wait until all online ran circuits of a qobj are 'COMPLETED'.
Args:
timeout (float or None): seconds to wait for job. If None, wait
indefinitely.
wait (float): seconds between queries
Returns:
dict: A dict with the contents of the API request.
Raises:
JobTimeoutError: if the job does not return results before a specified timeout.
JobError: if something wrong happened in some of the server API calls
"""
start_time = time.time()
while self.status() not in JOB_FINAL_STATES:
elapsed_time = time.time() - start_time
if timeout is not None and elapsed_time >= timeout:
raise JobTimeoutError(
'Timeout while waiting for the job: {}'.format(self._job_id)
)
logger.info('status = %s (%d seconds)', self._status, elapsed_time)
time.sleep(wait)
if self._cancelled:
raise JobError(
'Job result impossible to retrieve. The job was cancelled.')
return self._api.get_job(self._job_id)
def _wait_for_submission(self, timeout=60):
"""Waits for the request to return a job ID"""
if self._job_id is None:
if self._future is None:
raise JobError("You have to submit before asking for status or results!")
try:
submit_info = self._future.result(timeout=timeout)
if self._future_captured_exception is not None:
# pylint can't see if catch of None type
# pylint: disable=raising-bad-type
raise self._future_captured_exception
except TimeoutError as ex:
raise JobTimeoutError(
"Timeout waiting for the job being submitted: {}".format(ex)
)
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
raise JobError(str(submit_info['error']))
def qobj(self):
"""Return the Qobj submitted for this job.
Note that this method might involve querying the API for results if the
Job has been created in a previous Qiskit session.
Returns:
Qobj: the Qobj submitted for this job.
"""
if not self._qobj_payload:
# Populate self._qobj_payload by retrieving the results.
self._wait_for_result()
return Qobj(**self._qobj_payload)
class IBMQJobPreQobj(IBMQJob):
"""Subclass of IBMQJob for handling pre-qobj jobs."""
def _submit_callback(self):
"""Submit old style qasms job to IBM-Q. Can remove when all devices
understand Qobj.
Returns:
dict: A dictionary with the response of the submitted job
"""
api_jobs = []
circuits = self._job_data['circuits']
for circuit in circuits:
job = _create_api_job_from_circuit(circuit)
api_jobs.append(job)
hpc_camel_cased = _format_hpc_parameters(self._job_data['hpc'])
seed = self._job_data['seed']
shots = self._job_data['shots']
max_credits = self._job_data['max_credits']
try:
submit_info = self._api.run_job(api_jobs, backend=self.backend().name(),
shots=shots, max_credits=max_credits,
seed=seed, hpc=hpc_camel_cased)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submission success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _result_from_job_response(self, job_response):
if self._is_device:
_reorder_bits(job_response)
experiment_results = []
for circuit_result in job_response['qasms']:
this_result = {'data': circuit_result['data'],
'compiled_circuit_qasm': circuit_result.get('qasm'),
'status': circuit_result['status'],
'success': circuit_result['status'] == 'DONE',
'shots': job_response['shots']}
if 'metadata' in circuit_result:
this_result['metadata'] = circuit_result['metadata']
if 'header' in circuit_result['metadata'].get('compiled_circuit', {}):
this_result['header'] = \
circuit_result['metadata']['compiled_circuit']['header']
else:
this_result['header'] = {}
experiment_results.append(this_result)
ret = {
'id': self._job_id,
'status': job_response['status'],
'used_credits': job_response.get('usedCredits'),
'result': experiment_results,
'backend_name': self.backend().name(),
'success': job_response['status'] == 'COMPLETED',
}
# Append header: from the response; from the payload; or none.
header = job_response.get('header',
self._qobj_payload.get('header', {}))
if header:
ret['header'] = header
return result_from_old_style_dict(ret)
def qobj(self):
"""Return the Qobj submitted for this job."""
warnings.warn('This job has not been submitted using Qobj.')
return None
def _reorder_bits(job_data):
"""Temporary fix for ibmq backends.
For every ran circuit, get reordering information from qobj
and apply reordering on result.
Args:
job_data (dict): dict with the bare contents of the API.get_job request.
Raises:
JobError: raised if the creg sizes don't add up in result header.
"""
for circuit_result in job_data['qasms']:
if 'metadata' in circuit_result:
circ = circuit_result['metadata'].get('compiled_circuit')
else:
logger.warning('result object missing metadata for reordering'
' bits: bits may be out of order')
return
# device_qubit -> device_clbit (how it should have been)
measure_dict = {op['qubits'][0]: op.get('clbits', op.get('memory'))[0]
for op in circ['operations']
if op['name'] == 'measure'}
counts_dict_new = {}
for item in circuit_result['data']['counts'].items():
# fix clbit ordering to what it should have been
bits = list(item[0])
bits.reverse() # lsb in 0th position
count = item[1]
reordered_bits = list('x' * len(bits))
for device_clbit, bit in enumerate(bits):
if device_clbit in measure_dict:
correct_device_clbit = measure_dict[device_clbit]
reordered_bits[correct_device_clbit] = bit
reordered_bits.reverse()
# only keep the clbits specified by circuit, not everything on device
num_clbits = circ['header'].get('number_of_clbits',
circ['header'].get('memory_slots'))
compact_key = reordered_bits[-num_clbits:]
compact_key = "".join([b if b != 'x' else '0'
for b in compact_key])
# insert spaces to signify different classical registers
cregs = circ['header'].get('creg_sizes',
circ['header'].get('clbit_labels'))
if sum([creg[1] for creg in cregs]) != num_clbits:
raise JobError("creg sizes don't add up in result header.")
creg_begin_pos = []
creg_end_pos = []
acc = 0
for creg in reversed(cregs):
creg_size = creg[1]
creg_begin_pos.append(acc)
creg_end_pos.append(acc + creg_size)
acc += creg_size
compact_key = " ".join([compact_key[creg_begin_pos[i]:creg_end_pos[i]]
for i in range(len(cregs))])
# marginalize over unwanted measured qubits
if compact_key not in counts_dict_new:
counts_dict_new[compact_key] = count
else:
counts_dict_new[compact_key] += count
circuit_result['data']['counts'] = counts_dict_new
def _numpy_type_converter(obj):
ret = obj
if isinstance(obj, numpy.integer):
ret = int(obj)
elif isinstance(obj, numpy.floating): # pylint: disable=no-member
ret = float(obj)
elif isinstance(obj, numpy.ndarray):
ret = obj.tolist()
return ret
def _create_api_job_from_circuit(circuit):
"""Helper function that creates a special job required by the API, from a circuit."""
api_job = {}
if not circuit.get('compiled_circuit_qasm'):
compiled_circuit = transpile_dag(circuit['circuit'])
circuit['compiled_circuit_qasm'] = compiled_circuit.qasm(qeflag=True)
if isinstance(circuit['compiled_circuit_qasm'], bytes):
api_job['qasm'] = circuit['compiled_circuit_qasm'].decode()
else:
api_job['qasm'] = circuit['compiled_circuit_qasm']
if circuit.get('name'):
api_job['name'] = circuit['name']
# convert numpy types for json serialization
compiled_circuit = json.loads(json.dumps(circuit['compiled_circuit'],
default=_numpy_type_converter))
api_job['metadata'] = {'compiled_circuit': compiled_circuit}
return api_job
def _is_job_queued(api_job_response):
"""Checks whether a job has been queued or not."""
is_queued, position = False, 0
if 'infoQueue' in api_job_response:
if 'status' in api_job_response['infoQueue']:
queue_status = api_job_response['infoQueue']['status']
is_queued = queue_status == 'PENDING_IN_QUEUE'
if 'position' in api_job_response['infoQueue']:
position = api_job_response['infoQueue']['position']
return is_queued, position
def _format_hpc_parameters(hpc):
"""Helper function to get HPC parameters with the correct format"""
if hpc is None:
return None
hpc_camel_cased = None
with contextlib.suppress(KeyError, TypeError):
# Use CamelCase when passing the hpc parameters to the API.
hpc_camel_cased = {
'multiShotOptimization': hpc['multi_shot_optimization'],
'ompNumThreads': hpc['omp_num_threads']
}
return hpc_camel_cased
<|code_end|>
|
qiskit/providers/ibmq/ibmqjob.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""IBMQJob module
This module is used for creating asynchronous job objects for the
IBM Q Experience.
"""
import warnings
from concurrent import futures
import time
import logging
import pprint
import contextlib
import json
import datetime
import numpy
from qiskit.qobj import qobj_to_dict, Qobj
from qiskit.transpiler import transpile_dag
from qiskit.providers import BaseJob, JobError, JobTimeoutError
from qiskit.providers.jobstatus import JobStatus, JOB_FINAL_STATES
from qiskit.result import Result
from qiskit.result._utils import result_from_old_style_dict
from qiskit.qobj import validate_qobj_against_schema
from .api import ApiError
logger = logging.getLogger(__name__)
API_FINAL_STATES = (
'COMPLETED',
'CANCELLED',
'ERROR_CREATING_JOB',
'ERROR_VALIDATING_JOB',
'ERROR_RUNNING_JOB'
)
class IBMQJob(BaseJob):
"""Represent the jobs that will be executed on IBM-Q simulators and real
devices. Jobs are intended to be created calling ``run()`` on a particular
backend.
Creating a ``Job`` instance does not imply running it. You need to do it in
separate steps::
job = IBMQJob(...)
job.submit() # It won't block.
An error while submitting a job will cause the next call to ``status()`` to
raise. If submitting the job successes, you can inspect the job's status by
using ``status()``. Status can be one of ``JobStatus`` members::
from qiskit.backends.jobstatus import JobStatus
job = IBMQJob(...)
job.submit()
try:
job_status = job.status() # It won't block. It will query the backend API.
if job_status is JobStatus.RUNNING:
print('The job is still running')
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
A call to ``status()`` can raise if something happens at the API level that
prevents Qiskit from determining the status of the job. An example of this
is a temporary connection lose or a network failure.
The ``submit()`` and ``status()`` methods are examples of non-blocking API.
``Job`` instances also have `id()` and ``result()`` methods which will
block::
job = IBMQJob(...)
job.submit()
try:
job_id = job.id() # It will block until completing submission.
print('The job {} was successfully submitted'.format(job_id))
job_result = job.result() # It will block until finishing.
print('The job finished with result {}'.format(job_result))
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
Both methods can raise if something ath the API level happens that prevent
Qiskit from determining the status of the job.
Note:
When querying the API for getting the status, two kinds of errors are
possible. The most severe is the one preventing Qiskit from getting a
response from the backend. This can be caused by a network failure or a
temporary system break. In these cases, calling ``status()`` will raise.
If Qiskit successfully retrieves the status of a job, it could be it
finished with errors. In that case, ``status()`` will simply return
``JobStatus.ERROR`` and you can call ``error_message()`` to get more
info.
Attributes:
_executor (futures.Executor): executor to handle asynchronous jobs
"""
_executor = futures.ThreadPoolExecutor()
def __init__(self, backend, job_id, api, is_device, qobj=None,
creation_date=None, api_status=None):
"""IBMQJob init function.
We can instantiate jobs from two sources: A QObj, and an already submitted job returned by
the API servers.
Args:
backend (str): The backend instance used to run this job.
job_id (str): The job ID of an already submitted job. Pass `None`
if you are creating a new one.
api (IBMQConnector): IBMQ connector.
is_device (bool): whether backend is a real device # TODO: remove this after Qobj
qobj (Qobj): The Quantum Object. See notes below
creation_date (str): When the job was run.
api_status (str): `status` field directly from the API response.
Notes:
It is mandatory to pass either ``qobj`` or ``job_id``. Passing a ``qobj``
will ignore ``job_id`` and will create an instance to be submitted to the
API server for job creation. Passing only a `job_id` will create an instance
representing an already-created job retrieved from the API server.
"""
super().__init__(backend, job_id)
self._job_data = None
if qobj is not None:
validate_qobj_against_schema(qobj)
self._qobj_payload = qobj_to_dict(qobj, version='1.0.0')
# TODO: No need for this conversion, just use the new equivalent members above
old_qobj = qobj_to_dict(qobj, version='0.0.1')
self._job_data = {
'circuits': old_qobj['circuits'],
'hpc': old_qobj['config'].get('hpc'),
'seed': old_qobj['circuits'][0]['config'].get('seed'),
'shots': old_qobj['config']['shots'],
'max_credits': old_qobj['config']['max_credits']
}
else:
self._qobj_payload = {}
self._future_captured_exception = None
self._api = api
self._backend = backend
self._cancelled = False
self._status = JobStatus.INITIALIZING
# In case of not providing a `qobj`, it is assumed the job already
# exists in the API (with `job_id`).
if qobj is None:
# Some API calls (`get_status_jobs`, `get_status_job`) provide
# enough information to recreate the `Job`. If that is the case, try
# to make use of that information during instantiation, as
# `self.status()` involves an extra call to the API.
if api_status == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_status == 'COMPLETED':
self._status = JobStatus.DONE
elif api_status == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
else:
self.status()
self._queue_position = None
self._is_device = is_device
def current_utc_time():
"""Gets the current time in UTC format"""
datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
self._creation_date = creation_date or current_utc_time()
self._future = None
self._api_error_msg = None
# pylint: disable=arguments-differ
def result(self, timeout=None, wait=5):
"""Return the result from the job.
Args:
timeout (int): number of seconds to wait for job
wait (int): time between queries to IBM Q server
Returns:
qiskit.Result: Result object
Raises:
JobError: exception raised during job initialization
"""
job_response = self._wait_for_result(timeout=timeout, wait=wait)
return self._result_from_job_response(job_response)
def _wait_for_result(self, timeout=None, wait=5):
self._wait_for_submission(timeout)
try:
job_response = self._wait_for_job(timeout=timeout, wait=wait)
if not self._qobj_payload:
self._qobj_payload = job_response.get('qObject', {})
except ApiError as api_err:
raise JobError(str(api_err))
status = self.status()
if status is not JobStatus.DONE:
raise JobError('Invalid job state. The job should be DONE but '
'it is {}'.format(str(status)))
return job_response
def _result_from_job_response(self, job_response):
return Result.from_dict(job_response['qObjectResult'])
def cancel(self):
"""Attempt to cancel a job.
Returns:
bool: True if job can be cancelled, else False. Currently this is
only possible on commercial systems.
Raises:
JobError: if there was some unexpected failure in the server
"""
hub = self._api.config.get('hub', None)
group = self._api.config.get('group', None)
project = self._api.config.get('project', None)
try:
response = self._api.cancel_job(self._job_id, hub, group, project)
self._cancelled = 'error' not in response
return self._cancelled
except ApiError as error:
self._cancelled = False
raise JobError('Error cancelling job: %s' % error.usr_msg)
def status(self):
"""Query the API to update the status.
Returns:
qiskit.providers.JobStatus: The status of the job, once updated.
Raises:
JobError: if there was an exception in the future being executed
or the server sent an unknown answer.
"""
# Implies self._job_id is None
if self._future_captured_exception is not None:
raise JobError(str(self._future_captured_exception))
if self._job_id is None or self._status in JOB_FINAL_STATES:
return self._status
try:
# TODO: See result values
api_job = self._api.get_status_job(self._job_id)
if 'status' not in api_job:
raise JobError('get_status_job didn\'t return status: %s' %
pprint.pformat(api_job))
# pylint: disable=broad-except
except Exception as err:
raise JobError(str(err))
if api_job['status'] == 'VALIDATING':
self._status = JobStatus.VALIDATING
elif api_job['status'] == 'RUNNING':
self._status = JobStatus.RUNNING
queued, self._queue_position = _is_job_queued(api_job)
if queued:
self._status = JobStatus.QUEUED
elif api_job['status'] == 'COMPLETED':
self._status = JobStatus.DONE
elif api_job['status'] == 'CANCELLED':
self._status = JobStatus.CANCELLED
self._cancelled = True
elif 'ERROR' in api_job['status']:
# Error status are of the form "ERROR_*_JOB"
self._status = JobStatus.ERROR
# TODO: This seems to be an inconsistency in the API package.
self._api_error_msg = api_job.get('error') or api_job.get('Error')
else:
raise JobError('Unrecognized answer from server: \n{}'
.format(pprint.pformat(api_job)))
return self._status
def error_message(self):
"""Return the error message returned from the API server response."""
return self._api_error_msg
def queue_position(self):
"""Return the position in the server queue.
Returns:
Number: Position in the queue.
"""
return self._queue_position
def creation_date(self):
"""
Return creation date.
"""
return self._creation_date
def job_id(self):
"""Return backend determined id.
If the Id is not set because the job is already initializing, this call
will block until we have an Id.
"""
self._wait_for_submission()
return self._job_id
def submit(self):
"""Submit job to IBM-Q.
Raises:
JobError: If we have already submitted the job.
"""
# TODO: Validation against the schema should be done here and not
# during initialization. Once done, we should document that the method
# can raise QobjValidationError.
if self._future is not None or self._job_id is not None:
raise JobError("We have already submitted the job!")
self._future = self._executor.submit(self._submit_callback)
def _submit_callback(self):
"""Submit qobj job to IBM-Q.
Returns:
dict: A dictionary with the response of the submitted job
"""
backend_name = self.backend().name()
try:
submit_info = self._api.run_job(self._qobj_payload, backend=backend_name)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submission success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _wait_for_job(self, timeout=60, wait=5):
"""Wait until all online ran circuits of a qobj are 'COMPLETED'.
Args:
timeout (float or None): seconds to wait for job. If None, wait
indefinitely.
wait (float): seconds between queries
Returns:
dict: A dict with the contents of the API request.
Raises:
JobTimeoutError: if the job does not return results before a specified timeout.
JobError: if something wrong happened in some of the server API calls
"""
start_time = time.time()
while self.status() not in JOB_FINAL_STATES:
elapsed_time = time.time() - start_time
if timeout is not None and elapsed_time >= timeout:
raise JobTimeoutError(
'Timeout while waiting for the job: {}'.format(self._job_id)
)
logger.info('status = %s (%d seconds)', self._status, elapsed_time)
time.sleep(wait)
if self._cancelled:
raise JobError(
'Job result impossible to retrieve. The job was cancelled.')
return self._api.get_job(self._job_id)
def _wait_for_submission(self, timeout=60):
"""Waits for the request to return a job ID"""
if self._job_id is None:
if self._future is None:
raise JobError("You have to submit before asking for status or results!")
try:
submit_info = self._future.result(timeout=timeout)
if self._future_captured_exception is not None:
# pylint can't see if catch of None type
# pylint: disable=raising-bad-type
raise self._future_captured_exception
except TimeoutError as ex:
raise JobTimeoutError(
"Timeout waiting for the job being submitted: {}".format(ex)
)
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
raise JobError(str(submit_info['error']))
def qobj(self):
"""Return the Qobj submitted for this job.
Note that this method might involve querying the API for results if the
Job has been created in a previous Qiskit session.
Returns:
Qobj: the Qobj submitted for this job.
"""
if not self._qobj_payload:
# Populate self._qobj_payload by retrieving the results.
self._wait_for_result()
return Qobj(**self._qobj_payload)
class IBMQJobPreQobj(IBMQJob):
"""Subclass of IBMQJob for handling pre-qobj jobs."""
def _submit_callback(self):
"""Submit old style qasms job to IBM-Q. Can remove when all devices
understand Qobj.
Returns:
dict: A dictionary with the response of the submitted job
"""
api_jobs = []
circuits = self._job_data['circuits']
for circuit in circuits:
job = _create_api_job_from_circuit(circuit)
api_jobs.append(job)
hpc_camel_cased = _format_hpc_parameters(self._job_data['hpc'])
seed = self._job_data['seed']
shots = self._job_data['shots']
max_credits = self._job_data['max_credits']
try:
submit_info = self._api.run_job(api_jobs, backend=self.backend().name(),
shots=shots, max_credits=max_credits,
seed=seed, hpc=hpc_camel_cased)
# pylint: disable=broad-except
except Exception as err:
# Undefined error during submission:
# Capture and keep it for raising it when calling status().
self._future_captured_exception = err
return None
# Error in the job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
return submit_info
# Submission success.
self._creation_date = submit_info.get('creationDate')
self._status = JobStatus.QUEUED
self._job_id = submit_info.get('id')
return submit_info
def _result_from_job_response(self, job_response):
if self._is_device:
_reorder_bits(job_response)
experiment_results = []
for circuit_result in job_response['qasms']:
this_result = {'data': circuit_result['data'],
'compiled_circuit_qasm': circuit_result.get('qasm'),
'status': circuit_result['status'],
'success': circuit_result['status'] == 'DONE',
'shots': job_response['shots']}
if 'metadata' in circuit_result:
this_result['metadata'] = circuit_result['metadata']
if 'header' in circuit_result['metadata'].get('compiled_circuit', {}):
this_result['header'] = \
circuit_result['metadata']['compiled_circuit']['header']
else:
this_result['header'] = {}
experiment_results.append(this_result)
ret = {
'id': self._job_id,
'status': job_response['status'],
'used_credits': job_response.get('usedCredits'),
'result': experiment_results,
'backend_name': self.backend().name(),
'success': job_response['status'] == 'COMPLETED',
}
# Append header: from the response; from the payload; or none.
header = job_response.get('header',
self._qobj_payload.get('header', {}))
if header:
ret['header'] = header
return result_from_old_style_dict(ret)
def qobj(self):
"""Return the Qobj submitted for this job."""
warnings.warn('This job has not been submitted using Qobj.')
return None
def _reorder_bits(job_data):
"""Temporary fix for ibmq backends.
For every ran circuit, get reordering information from qobj
and apply reordering on result.
Args:
job_data (dict): dict with the bare contents of the API.get_job request.
Raises:
JobError: raised if the creg sizes don't add up in result header.
"""
for circuit_result in job_data['qasms']:
if 'metadata' in circuit_result:
circ = circuit_result['metadata'].get('compiled_circuit')
else:
logger.warning('result object missing metadata for reordering'
' bits: bits may be out of order')
return
# device_qubit -> device_clbit (how it should have been)
measure_dict = {op['qubits'][0]: op.get('clbits', op.get('memory'))[0]
for op in circ['operations']
if op['name'] == 'measure'}
counts_dict_new = {}
for item in circuit_result['data']['counts'].items():
# fix clbit ordering to what it should have been
bits = list(item[0])
bits.reverse() # lsb in 0th position
count = item[1]
reordered_bits = list('x' * len(bits))
for device_clbit, bit in enumerate(bits):
if device_clbit in measure_dict:
correct_device_clbit = measure_dict[device_clbit]
reordered_bits[correct_device_clbit] = bit
reordered_bits.reverse()
# only keep the clbits specified by circuit, not everything on device
num_clbits = circ['header'].get('number_of_clbits',
circ['header'].get('memory_slots'))
compact_key = reordered_bits[-num_clbits:]
compact_key = "".join([b if b != 'x' else '0'
for b in compact_key])
# insert spaces to signify different classical registers
cregs = circ['header'].get('creg_sizes',
circ['header'].get('clbit_labels'))
if sum([creg[1] for creg in cregs]) != num_clbits:
raise JobError("creg sizes don't add up in result header.")
creg_begin_pos = []
creg_end_pos = []
acc = 0
for creg in reversed(cregs):
creg_size = creg[1]
creg_begin_pos.append(acc)
creg_end_pos.append(acc + creg_size)
acc += creg_size
compact_key = " ".join([compact_key[creg_begin_pos[i]:creg_end_pos[i]]
for i in range(len(cregs))])
# marginalize over unwanted measured qubits
if compact_key not in counts_dict_new:
counts_dict_new[compact_key] = count
else:
counts_dict_new[compact_key] += count
circuit_result['data']['counts'] = counts_dict_new
def _numpy_type_converter(obj):
ret = obj
if isinstance(obj, numpy.integer):
ret = int(obj)
elif isinstance(obj, numpy.floating): # pylint: disable=no-member
ret = float(obj)
elif isinstance(obj, numpy.ndarray):
ret = obj.tolist()
return ret
def _create_api_job_from_circuit(circuit):
"""Helper function that creates a special job required by the API, from a circuit."""
api_job = {}
if not circuit.get('compiled_circuit_qasm'):
compiled_circuit = transpile_dag(circuit['circuit'])
circuit['compiled_circuit_qasm'] = compiled_circuit.qasm(qeflag=True)
if isinstance(circuit['compiled_circuit_qasm'], bytes):
api_job['qasm'] = circuit['compiled_circuit_qasm'].decode()
else:
api_job['qasm'] = circuit['compiled_circuit_qasm']
if circuit.get('name'):
api_job['name'] = circuit['name']
# convert numpy types for json serialization
compiled_circuit = json.loads(json.dumps(circuit['compiled_circuit'],
default=_numpy_type_converter))
api_job['metadata'] = {'compiled_circuit': compiled_circuit}
return api_job
def _is_job_queued(api_job_response):
"""Checks whether a job has been queued or not."""
is_queued, position = False, 0
if 'infoQueue' in api_job_response:
if 'status' in api_job_response['infoQueue']:
queue_status = api_job_response['infoQueue']['status']
is_queued = queue_status == 'PENDING_IN_QUEUE'
if 'position' in api_job_response['infoQueue']:
position = api_job_response['infoQueue']['position']
return is_queued, position
def _format_hpc_parameters(hpc):
"""Helper function to get HPC parameters with the correct format"""
if hpc is None:
return None
hpc_camel_cased = None
with contextlib.suppress(KeyError, TypeError):
# Use CamelCase when passing the hpc parameters to the API.
hpc_camel_cased = {
'multiShotOptimization': hpc['multi_shot_optimization'],
'ompNumThreads': hpc['omp_num_threads']
}
return hpc_camel_cased
<|code_end|>
|
BasicSwap cannot handle move_measurements.qasm
In the process to understand #1575, I noticed that `BasicSwap` also fails with that example (in which `move_measurements.qasm` tries to be mapped). I managed to extract a minimal example:
```
coupling = CouplingMap([[0, 1], [1, 2]])
qr0 = QuantumRegister(1, 'q0')
qr1 = QuantumRegister(1, 'q1')
qr2 = QuantumRegister(1, 'q2')
circuit = QuantumCircuit(qr0, qr1, qr2)
circuit.cx(qr1[0], qr2[0])
dag = circuit_to_dag(circuit)
layout = Layout([(qr1, 0), (qr0, 0), (qr2, 0)])
pass_ = BasicSwap(coupling, initial_layout=layout)
after = pass_.run(dag)
```
This fails with `qiskit.dagcircuit.exceptions.DAGCircuitError: 'invalid wire mapping key q2[0]'`.
|
qiskit/mapper/_layout.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A two-ways dict that represent a layout.
Layout is the relation between virtual (qu)bits and physical (qu)bits.
Virtual (qu)bits are tuples (eg, `(QuantumRegister(3, 'qr'),2)`.
Physical (qu)bits are numbers.
"""
from qiskit.mapper.exceptions import LayoutError
from qiskit.circuit.register import Register
class Layout(dict):
""" Two-ways dict to represent a Layout."""
def __init__(self, input_=None):
dict.__init__(self)
if isinstance(input_, dict):
self.from_dict(input_)
if isinstance(input_, list):
self.from_list(input_)
def from_dict(self, input_dict):
"""
Populates a Layout from a dictionary.
Args:
input_dict (dict): For example,
{(QuantumRegister(3, 'qr'), 0): 0,
(QuantumRegister(3, 'qr'), 1): 1,
(QuantumRegister(3, 'qr'), 2): 2}
"""
for key, value in input_dict.items():
self[key] = value
def from_list(self, input_list):
"""
Populates a Layout from a list.
Args:
input_list (list): For example,
[(QuantumRegister(3, 'qr'), 0), None,
(QuantumRegister(3, 'qr'), 2), (QuantumRegister(3, 'qr'), 3)]
"""
for key, value in enumerate(input_list):
self[key] = value
def __getitem__(self, item):
if isinstance(item, int) and item < len(self) and item not in self:
return None
return dict.__getitem__(self, item)
def __setitem__(self, key, value):
Layout._checktype(key)
Layout._checktype(value)
if isinstance(key, type(value)):
raise LayoutError('Key (%s) and value (%s) cannot have the same type' % (key, value))
if key in self:
del self[key]
if value in self:
del self[value]
if key is not None:
dict.__setitem__(self, key, value)
if value is not None:
dict.__setitem__(self, value, key)
def __delitem__(self, key):
dict.__delitem__(self, self[key])
dict.__delitem__(self, key)
@staticmethod
def _checktype(thing):
"""Checks if thing is a valid type"""
if thing is None:
return
if isinstance(thing, int):
return
if isinstance(thing, tuple) and \
len(thing) == 2 and \
isinstance(thing[0], Register) and isinstance(thing[1], int):
return
raise LayoutError(
'The element %s should be a (Register, integer) tuple or an integer' % (thing,))
def __len__(self):
return max([key for key in self.keys() if isinstance(key, int)], default=-1) + 1
# Override dict's built-in copy method which would return a dict instead of a Layout.
def copy(self):
return type(self)(self)
def add(self, virtual_bit, physical_bit=None):
"""
Adds a map element between `bit` and `physical_bit`. If `physical_bit` is not
defined, `bit` will be mapped to a new physical bit (extending the length of the
layout by one.)
Args:
virtual_bit (tuple): A (qu)bit. For example, (QuantumRegister(3, 'qr'),2).
physical_bit (int): A physical bit. For example, 3.
"""
if physical_bit is None:
physical_bit = len(self)
self[virtual_bit] = physical_bit
def add_register(self, reg):
"""
Adds at the end physical_qubits that map each bit in reg.
Args:
reg (Register): A (qu)bit Register. For example, QuantumRegister(3, 'qr').
"""
for bit in reg:
self.add(bit)
def set_length(self, amount_of_physical_bits):
"""
Extends the layout length to `amount_of_physical_bits`.
Args:
amount_of_physical_bits (int): The amount of physical_qubits to
set in the layout.
Raises:
LayoutError: If amount_of_physical_bits is used to reduced the
length instead of extending it.
"""
current_length = len(self)
if amount_of_physical_bits < current_length:
raise LayoutError('Lenght setting cannot be smaller than the current amount of physical'
' (qu)bits.')
for new_physical_bit in range(current_length, amount_of_physical_bits):
self[new_physical_bit] = None
def idle_physical_bits(self):
"""
Returns a list of physical (qu)bits that are not mapped to a virtual (qu)bit.
"""
idle_physical_bit_list = []
for physical_bit in range(self.__len__()):
if self[physical_bit] is None:
idle_physical_bit_list.append(physical_bit)
return idle_physical_bit_list
def get_virtual_bits(self):
"""
Returns the dictionary where the keys are virtual (qu)bits and the
values are physical (qu)bits.
"""
return {key: value for key, value in self.items() if isinstance(key, tuple)}
def get_physical_bits(self):
"""
Returns the dictionary where the keys are physical (qu)bits and the
values are virtual (qu)bits.
"""
return {key: value for key, value in self.items() if isinstance(key, int)}
def swap(self, left, right):
""" Swaps the map between left and right.
Args:
left (tuple or int): Item to swap with right.
right (tuple or int): Item to swap with left.
Raises:
LayoutError: If left and right have not the same type.
"""
if type(left) is not type(right):
raise LayoutError('The method swap only works with elements of the same type.')
temp = self[left]
self[left] = self[right]
self[right] = temp
def combine_into_edge_map(self, another_layout):
""" Combines self and another_layout into an "edge map".
For example::
self another_layout resulting edge map
qr_1 -> 0 0 <- q_2 qr_1 -> q_2
qr_2 -> 2 2 <- q_1 qr_2 -> q_1
qr_3 -> 3 3 <- q_0 qr_3 -> q_0
The edge map is used to compose dags via, for example, compose_back.
Args:
another_layout (Layout): The other layout to combine.
Returns:
dict: A "edge map".
Raises:
LayoutError: another_layout can be bigger than self, but not smaller. Otherwise, raises.
"""
edge_map = dict()
for virtual, physical in self.get_virtual_bits().items():
if physical not in another_layout:
raise LayoutError('The wire_map_from_layouts() method does not support when the'
' other layout (another_layout) is smaller.')
edge_map[virtual] = another_layout[physical]
return edge_map
@staticmethod
def generate_trivial_layout(*regs):
"""
Creates a trivial ("one-to-one") Layout with the registers in `regs`.
Args:
*regs (Registers): registers to include in the layout.
Returns:
Layout: A layout with all the `regs` in the given order.
"""
layout = Layout()
for reg in regs:
layout.add_register(reg)
return layout
<|code_end|>
qiskit/transpiler/passes/mapping/basic_swap.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A pass implementing a basic mapper.
The basic mapper is a minimum effort to insert swap gates to map the DAG into a coupling map. When
a cx is not in the coupling map possibilities, it inserts one or more swaps in front to make it
compatible.
"""
from copy import copy
from qiskit.transpiler._basepasses import TransformationPass
from qiskit.dagcircuit import DAGCircuit
from qiskit.mapper import Layout
from qiskit.extensions.standard import SwapGate
from .barrier_before_final_measurements import BarrierBeforeFinalMeasurements
class BasicSwap(TransformationPass):
"""
Maps (with minimum effort) a DAGCircuit onto a `coupling_map` adding swap gates.
"""
def __init__(self,
coupling_map,
initial_layout=None):
"""
Maps a DAGCircuit onto a `coupling_map` using swap gates.
Args:
coupling_map (CouplingMap): Directed graph represented a coupling map.
initial_layout (Layout): initial layout of qubits in mapping
"""
super().__init__()
self.coupling_map = coupling_map
self.initial_layout = initial_layout
self.swap_gate = SwapGate
self.requires.append(BarrierBeforeFinalMeasurements())
def run(self, dag):
"""
Runs the BasicSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
"""
new_dag = DAGCircuit()
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
current_layout = copy(self.initial_layout)
for layer in dag.serial_layers():
subdag = layer['graph']
for gate in subdag.get_2q_nodes():
physical_q0 = current_layout[gate['qargs'][0]]
physical_q1 = current_layout[gate['qargs'][1]]
if self.coupling_map.distance(physical_q0, physical_q1) != 1:
# Insert a new layer with the SWAP(s).
swap_layer = DAGCircuit()
path = self.coupling_map.shortest_undirected_path(physical_q0, physical_q1)
for swap in range(len(path) - 2):
connected_wire_1 = path[swap]
connected_wire_2 = path[swap + 1]
qubit_1 = current_layout[connected_wire_1]
qubit_2 = current_layout[connected_wire_2]
# create the involved registers
if qubit_1[0] not in swap_layer.qregs.values():
swap_layer.add_qreg(qubit_1[0])
if qubit_2[0] not in swap_layer.qregs.values():
swap_layer.add_qreg(qubit_2[0])
# create the swap operation
swap_layer.add_basis_element('swap', 2, 0, 0)
swap_layer.apply_operation_back(self.swap_gate(qubit_1, qubit_2),
qargs=[qubit_1, qubit_2])
# layer insertion
edge_map = current_layout.combine_into_edge_map(self.initial_layout)
new_dag.compose_back(swap_layer, edge_map)
# update current_layout
for swap in range(len(path) - 2):
current_layout.swap(path[swap], path[swap + 1])
edge_map = current_layout.combine_into_edge_map(self.initial_layout)
new_dag.extend_back(subdag, edge_map)
return new_dag
<|code_end|>
|
qiskit/mapper/_layout.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A two-ways dict that represent a layout.
Layout is the relation between virtual (qu)bits and physical (qu)bits.
Virtual (qu)bits are tuples (eg, `(QuantumRegister(3, 'qr'),2)`.
Physical (qu)bits are numbers.
"""
from qiskit.mapper.exceptions import LayoutError
from qiskit.circuit.register import Register
class Layout(dict):
""" Two-ways dict to represent a Layout."""
def __init__(self, input_=None):
dict.__init__(self)
if isinstance(input_, dict):
self.from_dict(input_)
if isinstance(input_, list):
self.from_list(input_)
def from_dict(self, input_dict):
"""
Populates a Layout from a dictionary.
Args:
input_dict (dict): For example,
{(QuantumRegister(3, 'qr'), 0): 0,
(QuantumRegister(3, 'qr'), 1): 1,
(QuantumRegister(3, 'qr'), 2): 2}
"""
for key, value in input_dict.items():
self[key] = value
def from_list(self, input_list):
"""
Populates a Layout from a list.
Args:
input_list (list): For example,
[(QuantumRegister(3, 'qr'), 0), None,
(QuantumRegister(3, 'qr'), 2), (QuantumRegister(3, 'qr'), 3)]
"""
for key, value in enumerate(input_list):
self[key] = value
def __getitem__(self, item):
if isinstance(item, int) and item < len(self) and item not in self:
return None
return dict.__getitem__(self, item)
def __setitem__(self, key, value):
Layout._checktype(key)
Layout._checktype(value)
if isinstance(key, type(value)):
raise LayoutError('Key (%s) and value (%s) cannot have the same type' % (key, value))
if key in self:
del self[key]
if value in self:
del self[value]
if key is not None:
dict.__setitem__(self, key, value)
if value is not None:
dict.__setitem__(self, value, key)
def __delitem__(self, key):
dict.__delitem__(self, self[key])
dict.__delitem__(self, key)
@staticmethod
def _checktype(thing):
"""Checks if thing is a valid type"""
if thing is None:
return
if isinstance(thing, int):
return
if isinstance(thing, tuple) and \
len(thing) == 2 and \
isinstance(thing[0], Register) and isinstance(thing[1], int):
return
raise LayoutError(
'The element %s should be a (Register, integer) tuple or an integer' % (thing,))
def __len__(self):
return max([key for key in self.keys() if isinstance(key, int)], default=-1) + 1
# Override dict's built-in copy method which would return a dict instead of a Layout.
def copy(self):
return type(self)(self)
def add(self, virtual_bit, physical_bit=None):
"""
Adds a map element between `bit` and `physical_bit`. If `physical_bit` is not
defined, `bit` will be mapped to a new physical bit (extending the length of the
layout by one.)
Args:
virtual_bit (tuple): A (qu)bit. For example, (QuantumRegister(3, 'qr'),2).
physical_bit (int): A physical bit. For example, 3.
"""
if physical_bit is None:
physical_bit = len(self)
self[virtual_bit] = physical_bit
def add_register(self, reg):
"""
Adds at the end physical_qubits that map each bit in reg.
Args:
reg (Register): A (qu)bit Register. For example, QuantumRegister(3, 'qr').
"""
for bit in reg:
self.add(bit)
def get_registers(self):
"""
Returns the registers in the layout [QuantumRegister(2, 'qr0'), QuantumRegister(3, 'qr1')]
Returns:
List: A list of Register in the layout
"""
return list(self.get_virtual_bits().keys())
def set_length(self, amount_of_physical_bits):
"""
Extends the layout length to `amount_of_physical_bits`.
Args:
amount_of_physical_bits (int): The amount of physical_qubits to
set in the layout.
Raises:
LayoutError: If amount_of_physical_bits is used to reduced the
length instead of extending it.
"""
current_length = len(self)
if amount_of_physical_bits < current_length:
raise LayoutError('Lenght setting cannot be smaller than the current amount of physical'
' (qu)bits.')
for new_physical_bit in range(current_length, amount_of_physical_bits):
self[new_physical_bit] = None
def idle_physical_bits(self):
"""
Returns a list of physical (qu)bits that are not mapped to a virtual (qu)bit.
"""
idle_physical_bit_list = []
for physical_bit in range(self.__len__()):
if self[physical_bit] is None:
idle_physical_bit_list.append(physical_bit)
return idle_physical_bit_list
def get_virtual_bits(self):
"""
Returns the dictionary where the keys are virtual (qu)bits and the
values are physical (qu)bits.
"""
return {key: value for key, value in self.items() if isinstance(key, tuple)}
def get_physical_bits(self):
"""
Returns the dictionary where the keys are physical (qu)bits and the
values are virtual (qu)bits.
"""
return {key: value for key, value in self.items() if isinstance(key, int)}
def swap(self, left, right):
""" Swaps the map between left and right.
Args:
left (tuple or int): Item to swap with right.
right (tuple or int): Item to swap with left.
Raises:
LayoutError: If left and right have not the same type.
"""
if type(left) is not type(right):
raise LayoutError('The method swap only works with elements of the same type.')
temp = self[left]
self[left] = self[right]
self[right] = temp
def combine_into_edge_map(self, another_layout):
""" Combines self and another_layout into an "edge map".
For example::
self another_layout resulting edge map
qr_1 -> 0 0 <- q_2 qr_1 -> q_2
qr_2 -> 2 2 <- q_1 qr_2 -> q_1
qr_3 -> 3 3 <- q_0 qr_3 -> q_0
The edge map is used to compose dags via, for example, compose_back.
Args:
another_layout (Layout): The other layout to combine.
Returns:
dict: A "edge map".
Raises:
LayoutError: another_layout can be bigger than self, but not smaller. Otherwise, raises.
"""
edge_map = dict()
for virtual, physical in self.get_virtual_bits().items():
if physical not in another_layout:
raise LayoutError('The wire_map_from_layouts() method does not support when the'
' other layout (another_layout) is smaller.')
edge_map[virtual] = another_layout[physical]
return edge_map
@staticmethod
def generate_trivial_layout(*regs):
"""
Creates a trivial ("one-to-one") Layout with the registers in `regs`.
Args:
*regs (Registers): registers to include in the layout.
Returns:
Layout: A layout with all the `regs` in the given order.
"""
layout = Layout()
for reg in regs:
layout.add_register(reg)
return layout
<|code_end|>
qiskit/transpiler/passes/mapping/basic_swap.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A pass implementing a basic mapper.
The basic mapper is a minimum effort to insert swap gates to map the DAG into a coupling map. When
a cx is not in the coupling map possibilities, it inserts one or more swaps in front to make it
compatible.
"""
from copy import copy
from qiskit.transpiler._basepasses import TransformationPass
from qiskit.dagcircuit import DAGCircuit
from qiskit.mapper import Layout
from qiskit.extensions.standard import SwapGate
from .barrier_before_final_measurements import BarrierBeforeFinalMeasurements
class BasicSwap(TransformationPass):
"""
Maps (with minimum effort) a DAGCircuit onto a `coupling_map` adding swap gates.
"""
def __init__(self,
coupling_map,
initial_layout=None):
"""
Maps a DAGCircuit onto a `coupling_map` using swap gates.
Args:
coupling_map (CouplingMap): Directed graph represented a coupling map.
initial_layout (Layout): initial layout of qubits in mapping
"""
super().__init__()
self.coupling_map = coupling_map
self.initial_layout = initial_layout
self.swap_gate = SwapGate
self.requires.append(BarrierBeforeFinalMeasurements())
def run(self, dag):
"""
Runs the BasicSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
"""
new_dag = DAGCircuit()
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
current_layout = copy(self.initial_layout)
for layer in dag.serial_layers():
subdag = layer['graph']
for gate in subdag.get_2q_nodes():
physical_q0 = current_layout[gate['qargs'][0]]
physical_q1 = current_layout[gate['qargs'][1]]
if self.coupling_map.distance(physical_q0, physical_q1) != 1:
# Insert a new layer with the SWAP(s).
swap_layer = DAGCircuit()
path = self.coupling_map.shortest_undirected_path(physical_q0, physical_q1)
for swap in range(len(path) - 2):
connected_wire_1 = path[swap]
connected_wire_2 = path[swap + 1]
qubit_1 = current_layout[connected_wire_1]
qubit_2 = current_layout[connected_wire_2]
# create qregs
for qreg in current_layout.get_registers():
if qreg[0] not in swap_layer.qregs.values():
swap_layer.add_qreg(qreg[0])
# create the swap operation
swap_layer.add_basis_element('swap', 2, 0, 0)
swap_layer.apply_operation_back(self.swap_gate(qubit_1, qubit_2),
qargs=[qubit_1, qubit_2])
# layer insertion
edge_map = current_layout.combine_into_edge_map(self.initial_layout)
new_dag.compose_back(swap_layer, edge_map)
# update current_layout
for swap in range(len(path) - 2):
current_layout.swap(path[swap], path[swap + 1])
edge_map = current_layout.combine_into_edge_map(self.initial_layout)
new_dag.extend_back(subdag, edge_map)
return new_dag
<|code_end|>
|
remove the folder wrappers (post 0.7)
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected behavior?
After 0.7 we don't this folder anymore.
|
qiskit/__init__.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import _util
# qiskit errors operator
from .exceptions import QiskitError, QISKitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
from .tools.compiler import (compile, execute)
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions.standard
import qiskit.extensions.quantum_initializer
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.ibmq import IBMQ
from qiskit.providers.builtinsimulators import BasicAer
from qiskit.providers.legacysimulators import LegacySimulators
# Try to import the Aer provider if th Aer element is installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# TODO: Remove
from .wrapper._wrapper import (load_qasm_string, load_qasm_file)
from .version import __version__
<|code_end|>
qiskit/wrapper/__init__.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Helper module for simplified Qiskit usage.
The functions in this module provide convenience helpers for accessing commonly
used features of the SDK in a simplified way. They support a small subset of
scenarios and flows: for more advanced usage, it is encouraged to instead
refer to the documentation of each component and use them separately.
"""
from ._wrapper import (load_qasm_string, load_qasm_file)
<|code_end|>
qiskit/wrapper/_wrapper.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Helper module for simplified Qiskit usage."""
import logging
import warnings
from qiskit.circuit.quantumcircuit import QuantumCircuit
logger = logging.getLogger(__name__)
# Functions for importing qasm
def load_qasm_string(qasm_string, name=None):
"""Construct a quantum circuit from a qasm representation (string).
Args:
qasm_string (str): a string of qasm, or a filename containing qasm.
name (str or None): the name of the quantum circuit after loading qasm
text into it. If no name given, assign automatically.
Returns:
QuantumCircuit: circuit constructed from qasm.
"""
warnings.warn('The load_qasm_string() function is deprecated and will be '
'removed in a future release. Instead use '
'QuantumCircuit.from_qasm_str().', DeprecationWarning)
qc = QuantumCircuit.from_qasm_str(qasm_string)
if name:
qc.name = name
return qc
def load_qasm_file(qasm_file, name=None):
"""Construct a quantum circuit from a qasm representation (file).
Args:
qasm_file (str): a string for the filename including its location.
name (str or None): the name of the quantum circuit after
loading qasm text into it. If no name is give the name is of
the text file.
Returns:
QuantumCircuit: circuit constructed from qasm.
"""
warnings.warn('The load_qasm_file() function is deprecated and will be '
'removed in a future release. Instead use '
'QuantumCircuit.from_qasm_file().', DeprecationWarning)
qc = QuantumCircuit.from_qasm_file(qasm_file)
if name:
qc.name = name
return qc
<|code_end|>
|
qiskit/__init__.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import _util
# qiskit errors operator
from .exceptions import QiskitError, QISKitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
from .tools.compiler import (compile, execute)
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions.standard
import qiskit.extensions.quantum_initializer
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.ibmq import IBMQ
from qiskit.providers.builtinsimulators import BasicAer
from qiskit.providers.legacysimulators import LegacySimulators
# Try to import the Aer provider if th Aer element is installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
from .version import __version__
<|code_end|>
qiskit/wrapper/__init__.py
<|code_start|><|code_end|>
qiskit/wrapper/_wrapper.py
<|code_start|><|code_end|>
|
Mapping Error in BasicAer
`'OPENQASM 2.0;\ninclude "qelib1.inc";\nqreg q0[5];\ncreg c0[3];\nx q0[4];\nmeasure q0[1] -> c0[0];\nmeasure q0[3] -> c0[1];\nmeasure q0[4] -> c0[2];\n'`
The above qasm should give all shots in `100`, but they are all in `000`. Only happens in `BasicAer`, not in `Aer`.
### Informations
- **Qiskit Terra version**: 0.7
- **Python version**: 3.6
- **Operating system**:
### What is the current behavior?
### Steps to reproduce the problem
### What is the expected behavior?
### Suggested solutions
|
qiskit/providers/builtinsimulators/qasm_simulator.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
# pylint: disable=arguments-differ
"""Contains a (slow) python simulator.
It simulates a qasm quantum circuit (an experiment) that has been compiled
to run on the simulator. It is exponential in the number of qubits.
The simulator is run using
.. code-block:: python
QasmSimulatorPy().run(qobj)
Where the input is a Qobj object and the output is a SimulatorsJob object, which can
later be queried for the Result object. The result will contain a 'memory' data
field, which is a result of measurements for each shot.
"""
import uuid
import time
import logging
from math import log2
from collections import Counter
import numpy as np
from qiskit._util import local_hardware_info
from qiskit.providers.models import BackendConfiguration
from qiskit.result import Result
from qiskit.providers import BaseBackend
from qiskit.providers.builtinsimulators.simulatorsjob import SimulatorsJob
from .exceptions import SimulatorError
from ._simulatortools import single_gate_matrix
from ._simulatortools import cx_gate_matrix
from ._simulatortools import einsum_vecmul_index
logger = logging.getLogger(__name__)
class QasmSimulatorPy(BaseBackend):
"""Python implementation of a qasm simulator."""
MAX_QUBITS_MEMORY = int(log2(local_hardware_info()['memory'] * (1024 ** 3) / 16))
DEFAULT_CONFIGURATION = {
'backend_name': 'qasm_simulator',
'backend_version': '2.0.0',
'n_qubits': min(24, MAX_QUBITS_MEMORY),
'url': 'https://github.com/Qiskit/qiskit-terra',
'simulator': True,
'local': True,
'conditional': True,
'open_pulse': False,
'memory': True,
'max_shots': 65536,
'description': 'A python simulator for qasm experiments',
'basis_gates': ['u1', 'u2', 'u3', 'cx', 'id'],
'gates': [
{
'name': 'u1',
'parameters': ['lambda'],
'qasm_def': 'gate u1(lambda) q { U(0,0,lambda) q; }'
},
{
'name': 'u2',
'parameters': ['phi', 'lambda'],
'qasm_def': 'gate u2(phi,lambda) q { U(pi/2,phi,lambda) q; }'
},
{
'name': 'u3',
'parameters': ['theta', 'phi', 'lambda'],
'qasm_def': 'gate u3(theta,phi,lambda) q { U(theta,phi,lambda) q; }'
},
{
'name': 'cx',
'parameters': ['c', 't'],
'qasm_def': 'gate cx c,t { CX c,t; }'
},
{
'name': 'id',
'parameters': ['a'],
'qasm_def': 'gate id a { U(0,0,0) a; }'
}
]
}
DEFAULT_OPTIONS = {
"initial_statevector": None,
"chop_threshold": 1e-15
}
# Class level variable to return the final state at the end of simulation
# This should be set to True for the statevector simulator
SHOW_FINAL_STATE = False
def __init__(self, configuration=None, provider=None):
super().__init__(configuration=(configuration or
BackendConfiguration.from_dict(self.DEFAULT_CONFIGURATION)),
provider=provider)
# Define attributes in __init__.
self._local_random = np.random.RandomState()
self._classical_state = 0
self._statevector = 0
self._number_of_cbits = 0
self._number_of_qubits = 0
self._shots = 0
self._memory = False
self._initial_statevector = self.DEFAULT_OPTIONS["initial_statevector"]
self._chop_threshold = self.DEFAULT_OPTIONS["chop_threshold"]
self._qobj_config = None
# TEMP
self._sample_measure = False
def _add_unitary_single(self, gate, qubit):
"""Apply an arbitrary 1-qubit unitary matrix.
Args:
gate (matrix_like): a single qubit gate matrix
qubit (int): the qubit to apply gate to
"""
# Compute einsum index string for 1-qubit matrix multiplication
indexes = einsum_vecmul_index([qubit], self._number_of_qubits)
# Convert to complex rank-2 tensor
gate_tensor = np.array(gate, dtype=complex)
# Apply matrix multiplication
self._statevector = np.einsum(indexes, gate_tensor,
self._statevector,
dtype=complex,
casting='no')
def _add_unitary_two(self, gate, qubit0, qubit1):
"""Apply a two-qubit unitary matrix.
Args:
gate (matrix_like): a the two-qubit gate matrix
qubit0 (int): gate qubit-0
qubit1 (int): gate qubit-1
"""
# Compute einsum index string for 1-qubit matrix multiplication
indexes = einsum_vecmul_index([qubit0, qubit1], self._number_of_qubits)
# Convert to complex rank-4 tensor
gate_tensor = np.reshape(np.array(gate, dtype=complex), 4 * [2])
# Apply matrix multiplication
self._statevector = np.einsum(indexes, gate_tensor,
self._statevector,
dtype=complex,
casting='no')
def _get_measure_outcome(self, qubit):
"""Simulate the outcome of measurement of a qubit.
Args:
qubit (int): the qubit to measure
Return:
tuple: pair (outcome, probability) where outcome is '0' or '1' and
probability is the probability of the returned outcome.
"""
# Axis for numpy.sum to compute probabilities
axis = list(range(self._number_of_qubits))
axis.remove(self._number_of_qubits - 1 - qubit)
probabilities = np.sum(np.abs(self._statevector) ** 2, axis=tuple(axis))
# Compute einsum index string for 1-qubit matrix multiplication
random_number = self._local_random.rand()
if random_number < probabilities[0]:
return '0', probabilities[0]
# Else outcome was '1'
return '1', probabilities[1]
def _add_sample_measure(self, measure_params, num_samples):
"""Generate memory samples from current statevector.
Args:
measure_params (list): List of (qubit, clbit) values for
measure instructions to sample.
num_samples (int): The number of memory samples to generate.
Returns:
list: A list of memory values in hex format.
"""
# Get unique qubits that are actually measured
measured_qubits = list({qubit for qubit, clbit in measure_params})
num_measured = len(measured_qubits)
# Axis for numpy.sum to compute probabilities
axis = list(range(self._number_of_qubits))
for qubit in reversed(measured_qubits):
# Remove from largest qubit to smallest so list position is correct
# with respect to position from end of the list
axis.remove(self._number_of_qubits - 1 - qubit)
probabilities = np.reshape(np.sum(np.abs(self._statevector) ** 2,
axis=tuple(axis)),
2 ** num_measured)
# Generate samples on measured qubits
samples = self._local_random.choice(range(2 ** num_measured),
num_samples, p=probabilities)
# Convert to bit-strings
memory = []
for sample in samples:
classical_state = self._classical_state
for qubit, cbit in measure_params:
qubit_outcome = int((sample & (1 << qubit)) >> qubit)
bit = 1 << cbit
classical_state = (classical_state & (~bit)) | (qubit_outcome << cbit)
value = bin(classical_state)[2:]
memory.append(hex(int(value, 2)))
return memory
def _add_qasm_measure(self, qubit, cbit):
"""Apply a measure instruction to a qubit.
Args:
qubit (int): qubit is the qubit measured.
cbit (int): is the classical bit to store outcome in.
"""
# get measure outcome
outcome, probability = self._get_measure_outcome(qubit)
# update classical state
bit = 1 << cbit
self._classical_state = (self._classical_state & (~bit)) | (int(outcome) << cbit)
# update quantum state
if outcome == '0':
update_diag = [[1 / np.sqrt(probability), 0], [0, 0]]
else:
update_diag = [[0, 0], [0, 1 / np.sqrt(probability)]]
# update classical state
self._add_unitary_single(update_diag, qubit)
def _add_qasm_reset(self, qubit):
"""Apply a reset instruction to a qubit.
Args:
qubit (int): the qubit being rest
This is done by doing a simulating a measurement
outcome and projecting onto the outcome state while
renormalizing.
"""
# get measure outcome
outcome, probability = self._get_measure_outcome(qubit)
# update quantum state
if outcome == '0':
update = [[1 / np.sqrt(probability), 0], [0, 0]]
self._add_unitary_single(update, qubit)
else:
update = [[0, 1 / np.sqrt(probability)], [0, 0]]
self._add_unitary_single(update, qubit)
def _validate_initial_statevector(self):
"""Validate an initial statevector"""
# If initial statevector isn't set we don't need to validate
if self._initial_statevector is None:
return
# Check statevector is correct length for number of qubits
length = len(self._initial_statevector)
required_dim = 2 ** self._number_of_qubits
if length != required_dim:
raise SimulatorError('initial statevector is incorrect length: ' +
'{} != {}'.format(length, required_dim))
def _set_options(self, qobj_config=None, backend_options=None):
"""Set the backend options for all experiments in a qobj"""
# Reset default options
self._initial_statevector = self.DEFAULT_OPTIONS["initial_statevector"]
self._chop_threshold = self.DEFAULT_OPTIONS["chop_threshold"]
if backend_options is None:
backend_options = {}
# Check for custom initial statevector in backend_options first,
# then config second
if 'initial_statevector' in backend_options:
self._initial_statevector = np.array(backend_options['initial_statevector'],
dtype=complex)
elif hasattr(qobj_config, 'initial_statevector'):
self._initial_statevector = np.array(qobj_config.initial_statevector,
dtype=complex)
if self._initial_statevector is not None:
# Check the initial statevector is normalized
norm = np.linalg.norm(self._initial_statevector)
if round(norm, 12) != 1:
raise SimulatorError('initial statevector is not normalized: ' +
'norm {} != 1'.format(norm))
# Check for custom chop threshold
# Replace with custom options
if 'chop_threshold' in backend_options:
self._chop_threshold = backend_options['chop_threshold']
elif hasattr(qobj_config, 'chop_threshold'):
self._chop_threshold = qobj_config.chop_threshold
def _initialize_statevector(self):
"""Set the initial statevector for simulation"""
if self._initial_statevector is None:
# Set to default state of all qubits in |0>
self._statevector = np.zeros(2 ** self._number_of_qubits,
dtype=complex)
self._statevector[0] = 1
else:
self._statevector = self._initial_statevector.copy()
# Reshape to rank-N tensor
self._statevector = np.reshape(self._statevector,
self._number_of_qubits * [2])
def _get_statevector(self):
"""Return the current statevector in JSON Result spec format"""
vec = np.reshape(self._statevector, 2 ** self._number_of_qubits)
# Expand complex numbers
vec = np.stack([vec.real, vec.imag], axis=1)
# Truncate small values
vec[abs(vec) < self._chop_threshold] = 0.0
return vec
def _validate_measure_sampling(self, experiment):
"""Determine if measure sampling is allowed for an experiment
Args:
experiment (QobjExperiment): a qobj experiment.
"""
# Check for config flag
if hasattr(experiment.config, 'allows_measure_sampling'):
self._sample_measure = experiment.config.allows_measure_sampling
# If flag isn't found do a simple test to see if a circuit contains
# no reset instructions, and no gates instructions after
# the first measure.
else:
measure_flag = False
for instruction in experiment.instructions:
# If circuit contains reset operations we cannot sample
if instruction.name == "reset":
self._sample_measure = False
return
# If circuit contains a measure option then we can
# sample only if all following operations are measures
if measure_flag:
# If we find a non-measure instruction
# we cannot do measure sampling
if instruction.name not in ["measure", "barrier", "id", "u0"]:
self._sample_measure = False
return
elif instruction.name == "measure":
measure_flag = True
# If we made it to the end of the circuit without returning
# measure sampling is allowed
self._sample_measure = True
def run(self, qobj, backend_options=None):
"""Run qobj asynchronously.
Args:
qobj (Qobj): payload of the experiment
backend_options (dict): backend options
Returns:
SimulatorsJob: derived from BaseJob
Additional Information:
backend_options: Is a dict of options for the backend. It may contain
* "initial_statevector": vector_like
The "initial_statevector" option specifies a custom initial
initial statevector for the simulator to be used instead of the all
zero state. This size of this vector must be correct for the number
of qubits in all experiments in the qobj.
Example::
backend_options = {
"initial_statevector": np.array([1, 0, 0, 1j]) / np.sqrt(2),
}
"""
self._set_options(qobj_config=qobj.config,
backend_options=backend_options)
job_id = str(uuid.uuid4())
job = SimulatorsJob(self, job_id, self._run_job, qobj)
job.submit()
return job
def _run_job(self, job_id, qobj):
"""Run experiments in qobj
Args:
job_id (str): unique id for the job.
qobj (Qobj): job description
Returns:
Result: Result object
"""
self._validate(qobj)
result_list = []
self._shots = qobj.config.shots
self._memory = qobj.config.memory
self._qobj_config = qobj.config
start = time.time()
for experiment in qobj.experiments:
result_list.append(self.run_experiment(experiment))
end = time.time()
result = {'backend_name': self.name(),
'backend_version': self._configuration.backend_version,
'qobj_id': qobj.qobj_id,
'job_id': job_id,
'results': result_list,
'status': 'COMPLETED',
'success': True,
'time_taken': (end - start),
'header': qobj.header.as_dict()}
return Result.from_dict(result)
def run_experiment(self, experiment):
"""Run an experiment (circuit) and return a single experiment result.
Args:
experiment (QobjExperiment): experiment from qobj experiments list
Returns:
dict: A result dictionary which looks something like::
{
"name": name of this experiment (obtained from qobj.experiment header)
"seed": random seed used for simulation
"shots": number of shots used in the simulation
"data":
{
"counts": {'0x9: 5, ...},
"memory": ['0x9', '0xF', '0x1D', ..., '0x9']
},
"status": status string for the simulation
"success": boolean
"time_taken": simulation time of this single experiment
}
Raises:
SimulatorError: if an error occurred.
"""
start = time.time()
self._number_of_qubits = experiment.config.n_qubits
self._number_of_cbits = experiment.config.memory_slots
self._statevector = 0
self._classical_state = 0
self._sample_measure = False
# Validate the dimension of initial statevector if set
self._validate_initial_statevector()
# Get the seed looking in circuit, qobj, and then random.
if hasattr(experiment.config, 'seed'):
seed = experiment.config.seed
elif hasattr(self._qobj_config, 'seed'):
seed = self._qobj_config.seed
else:
# For compatibility on Windows force dyte to be int32
# and set the maximum value to be (2 ** 31) - 1
seed = np.random.randint(2147483647, dtype='int32')
self._local_random.seed(seed)
# Check if measure sampling is supported for current circuit
self._validate_measure_sampling(experiment)
# List of final counts for all shots
memory = []
# Check if we can sample measurements, if so we only perform 1 shot
# and sample all outcomes from the final state vector
if self._sample_measure:
shots = 1
# Store (qubit, cbit) pairs for all measure ops in circuit to
# be sampled
measure_sample_ops = []
else:
shots = self._shots
for _ in range(shots):
self._initialize_statevector()
# Initialize classical memory to all 0
self._classical_state = 0
for operation in experiment.instructions:
if getattr(operation, 'conditional', None):
mask = int(operation.conditional.mask, 16)
if mask > 0:
value = self._classical_state & mask
while (mask & 0x1) == 0:
mask >>= 1
value >>= 1
if value != int(operation.conditional.val, 16):
continue
# Check if single gate
if operation.name in ('U', 'u1', 'u2', 'u3'):
params = getattr(operation, 'params', None)
qubit = operation.qubits[0]
gate = single_gate_matrix(operation.name, params)
self._add_unitary_single(gate, qubit)
# Check if CX gate
elif operation.name in ('id', 'u0'):
pass
elif operation.name in ('CX', 'cx'):
qubit0 = operation.qubits[0]
qubit1 = operation.qubits[1]
gate = cx_gate_matrix()
self._add_unitary_two(gate, qubit0, qubit1)
# Check if reset
elif operation.name == 'reset':
qubit = operation.qubits[0]
self._add_qasm_reset(qubit)
# Check if barrier
elif operation.name == 'barrier':
pass
# Check if measure
elif operation.name == 'measure':
qubit = operation.qubits[0]
cbit = operation.memory[0]
if self._sample_measure:
# If sampling measurements record the qubit and cbit
# for this measurement for later sampling
measure_sample_ops.append((qubit, cbit))
else:
# If not sampling perform measurement as normal
self._add_qasm_measure(qubit, cbit)
else:
backend = self.name()
err_msg = '{0} encountered unrecognized operation "{1}"'
raise SimulatorError(err_msg.format(backend, operation.name))
# Add final creg data to memory list
if self._number_of_cbits > 0:
if self._sample_measure:
# If sampling we generate all shot samples from the final statevector
memory = self._add_sample_measure(measure_sample_ops, self._shots)
else:
# Turn classical_state (int) into bit string and pad zero for unused cbits
outcome = bin(self._classical_state)[2:]
memory.append(hex(int(outcome, 2)))
# Add data
data = {'counts': dict(Counter(memory))}
# Optionally add memory list
if self._memory:
data['memory'] = memory
# Optionally add final statevector
if self.SHOW_FINAL_STATE:
data['statevector'] = self._get_statevector()
# Remove empty counts and memory for statevector simulator
if not data['counts']:
data.pop('counts')
if 'memory' in data and not data['memory']:
data.pop('memory')
end = time.time()
return {'name': experiment.header.name,
'seed': seed,
'shots': self._shots,
'data': data,
'status': 'DONE',
'success': True,
'time_taken': (end - start),
'header': experiment.header.as_dict()}
def _validate(self, qobj):
"""Semantic validations of the qobj which cannot be done via schemas."""
n_qubits = qobj.config.n_qubits
max_qubits = self.configuration().n_qubits
if n_qubits > max_qubits:
raise SimulatorError('Number of qubits {} '.format(n_qubits) +
'is greater than maximum ({}) '.format(max_qubits) +
'for "{}".'.format(self.name()))
for experiment in qobj.experiments:
name = experiment.header.name
if experiment.config.memory_slots == 0:
logger.warning('No classical registers in circuit "%s", '
'counts will be empty.', name)
elif 'measure' not in [op.name for op in experiment.instructions]:
logger.warning('No measurements in circuit "%s", '
'classical register will remain all zeros.', name)
<|code_end|>
|
qiskit/providers/builtinsimulators/qasm_simulator.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
# pylint: disable=arguments-differ
"""Contains a (slow) python simulator.
It simulates a qasm quantum circuit (an experiment) that has been compiled
to run on the simulator. It is exponential in the number of qubits.
The simulator is run using
.. code-block:: python
QasmSimulatorPy().run(qobj)
Where the input is a Qobj object and the output is a SimulatorsJob object, which can
later be queried for the Result object. The result will contain a 'memory' data
field, which is a result of measurements for each shot.
"""
import uuid
import time
import logging
from math import log2
from collections import Counter
import numpy as np
from qiskit._util import local_hardware_info
from qiskit.providers.models import BackendConfiguration
from qiskit.result import Result
from qiskit.providers import BaseBackend
from qiskit.providers.builtinsimulators.simulatorsjob import SimulatorsJob
from .exceptions import SimulatorError
from ._simulatortools import single_gate_matrix
from ._simulatortools import cx_gate_matrix
from ._simulatortools import einsum_vecmul_index
logger = logging.getLogger(__name__)
class QasmSimulatorPy(BaseBackend):
"""Python implementation of a qasm simulator."""
MAX_QUBITS_MEMORY = int(log2(local_hardware_info()['memory'] * (1024 ** 3) / 16))
DEFAULT_CONFIGURATION = {
'backend_name': 'qasm_simulator',
'backend_version': '2.0.0',
'n_qubits': min(24, MAX_QUBITS_MEMORY),
'url': 'https://github.com/Qiskit/qiskit-terra',
'simulator': True,
'local': True,
'conditional': True,
'open_pulse': False,
'memory': True,
'max_shots': 65536,
'description': 'A python simulator for qasm experiments',
'basis_gates': ['u1', 'u2', 'u3', 'cx', 'id'],
'gates': [
{
'name': 'u1',
'parameters': ['lambda'],
'qasm_def': 'gate u1(lambda) q { U(0,0,lambda) q; }'
},
{
'name': 'u2',
'parameters': ['phi', 'lambda'],
'qasm_def': 'gate u2(phi,lambda) q { U(pi/2,phi,lambda) q; }'
},
{
'name': 'u3',
'parameters': ['theta', 'phi', 'lambda'],
'qasm_def': 'gate u3(theta,phi,lambda) q { U(theta,phi,lambda) q; }'
},
{
'name': 'cx',
'parameters': ['c', 't'],
'qasm_def': 'gate cx c,t { CX c,t; }'
},
{
'name': 'id',
'parameters': ['a'],
'qasm_def': 'gate id a { U(0,0,0) a; }'
}
]
}
DEFAULT_OPTIONS = {
"initial_statevector": None,
"chop_threshold": 1e-15
}
# Class level variable to return the final state at the end of simulation
# This should be set to True for the statevector simulator
SHOW_FINAL_STATE = False
def __init__(self, configuration=None, provider=None):
super().__init__(configuration=(configuration or
BackendConfiguration.from_dict(self.DEFAULT_CONFIGURATION)),
provider=provider)
# Define attributes in __init__.
self._local_random = np.random.RandomState()
self._classical_state = 0
self._statevector = 0
self._number_of_cbits = 0
self._number_of_qubits = 0
self._shots = 0
self._memory = False
self._initial_statevector = self.DEFAULT_OPTIONS["initial_statevector"]
self._chop_threshold = self.DEFAULT_OPTIONS["chop_threshold"]
self._qobj_config = None
# TEMP
self._sample_measure = False
def _add_unitary_single(self, gate, qubit):
"""Apply an arbitrary 1-qubit unitary matrix.
Args:
gate (matrix_like): a single qubit gate matrix
qubit (int): the qubit to apply gate to
"""
# Compute einsum index string for 1-qubit matrix multiplication
indexes = einsum_vecmul_index([qubit], self._number_of_qubits)
# Convert to complex rank-2 tensor
gate_tensor = np.array(gate, dtype=complex)
# Apply matrix multiplication
self._statevector = np.einsum(indexes, gate_tensor,
self._statevector,
dtype=complex,
casting='no')
def _add_unitary_two(self, gate, qubit0, qubit1):
"""Apply a two-qubit unitary matrix.
Args:
gate (matrix_like): a the two-qubit gate matrix
qubit0 (int): gate qubit-0
qubit1 (int): gate qubit-1
"""
# Compute einsum index string for 1-qubit matrix multiplication
indexes = einsum_vecmul_index([qubit0, qubit1], self._number_of_qubits)
# Convert to complex rank-4 tensor
gate_tensor = np.reshape(np.array(gate, dtype=complex), 4 * [2])
# Apply matrix multiplication
self._statevector = np.einsum(indexes, gate_tensor,
self._statevector,
dtype=complex,
casting='no')
def _get_measure_outcome(self, qubit):
"""Simulate the outcome of measurement of a qubit.
Args:
qubit (int): the qubit to measure
Return:
tuple: pair (outcome, probability) where outcome is '0' or '1' and
probability is the probability of the returned outcome.
"""
# Axis for numpy.sum to compute probabilities
axis = list(range(self._number_of_qubits))
axis.remove(self._number_of_qubits - 1 - qubit)
probabilities = np.sum(np.abs(self._statevector) ** 2, axis=tuple(axis))
# Compute einsum index string for 1-qubit matrix multiplication
random_number = self._local_random.rand()
if random_number < probabilities[0]:
return '0', probabilities[0]
# Else outcome was '1'
return '1', probabilities[1]
def _add_sample_measure(self, measure_params, num_samples):
"""Generate memory samples from current statevector.
Args:
measure_params (list): List of (qubit, clbit) values for
measure instructions to sample.
num_samples (int): The number of memory samples to generate.
Returns:
list: A list of memory values in hex format.
"""
# Get unique qubits that are actually measured
measured_qubits = list({qubit for qubit, clbit in measure_params})
num_measured = len(measured_qubits)
# Axis for numpy.sum to compute probabilities
axis = list(range(self._number_of_qubits))
for qubit in reversed(measured_qubits):
# Remove from largest qubit to smallest so list position is correct
# with respect to position from end of the list
axis.remove(self._number_of_qubits - 1 - qubit)
probabilities = np.reshape(np.sum(np.abs(self._statevector) ** 2,
axis=tuple(axis)),
2 ** num_measured)
# Generate samples on measured qubits
samples = self._local_random.choice(range(2 ** num_measured),
num_samples, p=probabilities)
# Convert to bit-strings
memory = []
for sample in samples:
classical_state = self._classical_state
for count, (qubit, cbit) in enumerate(sorted(measure_params)):
qubit_outcome = int((sample & (1 << count)) >> count)
bit = 1 << cbit
classical_state = (classical_state & (~bit)) | (qubit_outcome << cbit)
value = bin(classical_state)[2:]
memory.append(hex(int(value, 2)))
return memory
def _add_qasm_measure(self, qubit, cbit):
"""Apply a measure instruction to a qubit.
Args:
qubit (int): qubit is the qubit measured.
cbit (int): is the classical bit to store outcome in.
"""
# get measure outcome
outcome, probability = self._get_measure_outcome(qubit)
# update classical state
bit = 1 << cbit
self._classical_state = (self._classical_state & (~bit)) | (int(outcome) << cbit)
# update quantum state
if outcome == '0':
update_diag = [[1 / np.sqrt(probability), 0], [0, 0]]
else:
update_diag = [[0, 0], [0, 1 / np.sqrt(probability)]]
# update classical state
self._add_unitary_single(update_diag, qubit)
def _add_qasm_reset(self, qubit):
"""Apply a reset instruction to a qubit.
Args:
qubit (int): the qubit being rest
This is done by doing a simulating a measurement
outcome and projecting onto the outcome state while
renormalizing.
"""
# get measure outcome
outcome, probability = self._get_measure_outcome(qubit)
# update quantum state
if outcome == '0':
update = [[1 / np.sqrt(probability), 0], [0, 0]]
self._add_unitary_single(update, qubit)
else:
update = [[0, 1 / np.sqrt(probability)], [0, 0]]
self._add_unitary_single(update, qubit)
def _validate_initial_statevector(self):
"""Validate an initial statevector"""
# If initial statevector isn't set we don't need to validate
if self._initial_statevector is None:
return
# Check statevector is correct length for number of qubits
length = len(self._initial_statevector)
required_dim = 2 ** self._number_of_qubits
if length != required_dim:
raise SimulatorError('initial statevector is incorrect length: ' +
'{} != {}'.format(length, required_dim))
def _set_options(self, qobj_config=None, backend_options=None):
"""Set the backend options for all experiments in a qobj"""
# Reset default options
self._initial_statevector = self.DEFAULT_OPTIONS["initial_statevector"]
self._chop_threshold = self.DEFAULT_OPTIONS["chop_threshold"]
if backend_options is None:
backend_options = {}
# Check for custom initial statevector in backend_options first,
# then config second
if 'initial_statevector' in backend_options:
self._initial_statevector = np.array(backend_options['initial_statevector'],
dtype=complex)
elif hasattr(qobj_config, 'initial_statevector'):
self._initial_statevector = np.array(qobj_config.initial_statevector,
dtype=complex)
if self._initial_statevector is not None:
# Check the initial statevector is normalized
norm = np.linalg.norm(self._initial_statevector)
if round(norm, 12) != 1:
raise SimulatorError('initial statevector is not normalized: ' +
'norm {} != 1'.format(norm))
# Check for custom chop threshold
# Replace with custom options
if 'chop_threshold' in backend_options:
self._chop_threshold = backend_options['chop_threshold']
elif hasattr(qobj_config, 'chop_threshold'):
self._chop_threshold = qobj_config.chop_threshold
def _initialize_statevector(self):
"""Set the initial statevector for simulation"""
if self._initial_statevector is None:
# Set to default state of all qubits in |0>
self._statevector = np.zeros(2 ** self._number_of_qubits,
dtype=complex)
self._statevector[0] = 1
else:
self._statevector = self._initial_statevector.copy()
# Reshape to rank-N tensor
self._statevector = np.reshape(self._statevector,
self._number_of_qubits * [2])
def _get_statevector(self):
"""Return the current statevector in JSON Result spec format"""
vec = np.reshape(self._statevector, 2 ** self._number_of_qubits)
# Expand complex numbers
vec = np.stack([vec.real, vec.imag], axis=1)
# Truncate small values
vec[abs(vec) < self._chop_threshold] = 0.0
return vec
def _validate_measure_sampling(self, experiment):
"""Determine if measure sampling is allowed for an experiment
Args:
experiment (QobjExperiment): a qobj experiment.
"""
# Check for config flag
if hasattr(experiment.config, 'allows_measure_sampling'):
self._sample_measure = experiment.config.allows_measure_sampling
# If flag isn't found do a simple test to see if a circuit contains
# no reset instructions, and no gates instructions after
# the first measure.
else:
measure_flag = False
for instruction in experiment.instructions:
# If circuit contains reset operations we cannot sample
if instruction.name == "reset":
self._sample_measure = False
return
# If circuit contains a measure option then we can
# sample only if all following operations are measures
if measure_flag:
# If we find a non-measure instruction
# we cannot do measure sampling
if instruction.name not in ["measure", "barrier", "id", "u0"]:
self._sample_measure = False
return
elif instruction.name == "measure":
measure_flag = True
# If we made it to the end of the circuit without returning
# measure sampling is allowed
self._sample_measure = True
def run(self, qobj, backend_options=None):
"""Run qobj asynchronously.
Args:
qobj (Qobj): payload of the experiment
backend_options (dict): backend options
Returns:
SimulatorsJob: derived from BaseJob
Additional Information:
backend_options: Is a dict of options for the backend. It may contain
* "initial_statevector": vector_like
The "initial_statevector" option specifies a custom initial
initial statevector for the simulator to be used instead of the all
zero state. This size of this vector must be correct for the number
of qubits in all experiments in the qobj.
Example::
backend_options = {
"initial_statevector": np.array([1, 0, 0, 1j]) / np.sqrt(2),
}
"""
self._set_options(qobj_config=qobj.config,
backend_options=backend_options)
job_id = str(uuid.uuid4())
job = SimulatorsJob(self, job_id, self._run_job, qobj)
job.submit()
return job
def _run_job(self, job_id, qobj):
"""Run experiments in qobj
Args:
job_id (str): unique id for the job.
qobj (Qobj): job description
Returns:
Result: Result object
"""
self._validate(qobj)
result_list = []
self._shots = qobj.config.shots
self._memory = qobj.config.memory
self._qobj_config = qobj.config
start = time.time()
for experiment in qobj.experiments:
result_list.append(self.run_experiment(experiment))
end = time.time()
result = {'backend_name': self.name(),
'backend_version': self._configuration.backend_version,
'qobj_id': qobj.qobj_id,
'job_id': job_id,
'results': result_list,
'status': 'COMPLETED',
'success': True,
'time_taken': (end - start),
'header': qobj.header.as_dict()}
return Result.from_dict(result)
def run_experiment(self, experiment):
"""Run an experiment (circuit) and return a single experiment result.
Args:
experiment (QobjExperiment): experiment from qobj experiments list
Returns:
dict: A result dictionary which looks something like::
{
"name": name of this experiment (obtained from qobj.experiment header)
"seed": random seed used for simulation
"shots": number of shots used in the simulation
"data":
{
"counts": {'0x9: 5, ...},
"memory": ['0x9', '0xF', '0x1D', ..., '0x9']
},
"status": status string for the simulation
"success": boolean
"time_taken": simulation time of this single experiment
}
Raises:
SimulatorError: if an error occurred.
"""
start = time.time()
self._number_of_qubits = experiment.config.n_qubits
self._number_of_cbits = experiment.config.memory_slots
self._statevector = 0
self._classical_state = 0
self._sample_measure = False
# Validate the dimension of initial statevector if set
self._validate_initial_statevector()
# Get the seed looking in circuit, qobj, and then random.
if hasattr(experiment.config, 'seed'):
seed = experiment.config.seed
elif hasattr(self._qobj_config, 'seed'):
seed = self._qobj_config.seed
else:
# For compatibility on Windows force dyte to be int32
# and set the maximum value to be (2 ** 31) - 1
seed = np.random.randint(2147483647, dtype='int32')
self._local_random.seed(seed)
# Check if measure sampling is supported for current circuit
self._validate_measure_sampling(experiment)
# List of final counts for all shots
memory = []
# Check if we can sample measurements, if so we only perform 1 shot
# and sample all outcomes from the final state vector
if self._sample_measure:
shots = 1
# Store (qubit, cbit) pairs for all measure ops in circuit to
# be sampled
measure_sample_ops = []
else:
shots = self._shots
for _ in range(shots):
self._initialize_statevector()
# Initialize classical memory to all 0
self._classical_state = 0
for operation in experiment.instructions:
if getattr(operation, 'conditional', None):
mask = int(operation.conditional.mask, 16)
if mask > 0:
value = self._classical_state & mask
while (mask & 0x1) == 0:
mask >>= 1
value >>= 1
if value != int(operation.conditional.val, 16):
continue
# Check if single gate
if operation.name in ('U', 'u1', 'u2', 'u3'):
params = getattr(operation, 'params', None)
qubit = operation.qubits[0]
gate = single_gate_matrix(operation.name, params)
self._add_unitary_single(gate, qubit)
# Check if CX gate
elif operation.name in ('id', 'u0'):
pass
elif operation.name in ('CX', 'cx'):
qubit0 = operation.qubits[0]
qubit1 = operation.qubits[1]
gate = cx_gate_matrix()
self._add_unitary_two(gate, qubit0, qubit1)
# Check if reset
elif operation.name == 'reset':
qubit = operation.qubits[0]
self._add_qasm_reset(qubit)
# Check if barrier
elif operation.name == 'barrier':
pass
# Check if measure
elif operation.name == 'measure':
qubit = operation.qubits[0]
cbit = operation.memory[0]
if self._sample_measure:
# If sampling measurements record the qubit and cbit
# for this measurement for later sampling
measure_sample_ops.append((qubit, cbit))
else:
# If not sampling perform measurement as normal
self._add_qasm_measure(qubit, cbit)
else:
backend = self.name()
err_msg = '{0} encountered unrecognized operation "{1}"'
raise SimulatorError(err_msg.format(backend, operation.name))
# Add final creg data to memory list
if self._number_of_cbits > 0:
if self._sample_measure:
# If sampling we generate all shot samples from the final statevector
memory = self._add_sample_measure(measure_sample_ops, self._shots)
else:
# Turn classical_state (int) into bit string and pad zero for unused cbits
outcome = bin(self._classical_state)[2:]
memory.append(hex(int(outcome, 2)))
# Add data
data = {'counts': dict(Counter(memory))}
# Optionally add memory list
if self._memory:
data['memory'] = memory
# Optionally add final statevector
if self.SHOW_FINAL_STATE:
data['statevector'] = self._get_statevector()
# Remove empty counts and memory for statevector simulator
if not data['counts']:
data.pop('counts')
if 'memory' in data and not data['memory']:
data.pop('memory')
end = time.time()
return {'name': experiment.header.name,
'seed': seed,
'shots': self._shots,
'data': data,
'status': 'DONE',
'success': True,
'time_taken': (end - start),
'header': experiment.header.as_dict()}
def _validate(self, qobj):
"""Semantic validations of the qobj which cannot be done via schemas."""
n_qubits = qobj.config.n_qubits
max_qubits = self.configuration().n_qubits
if n_qubits > max_qubits:
raise SimulatorError('Number of qubits {} '.format(n_qubits) +
'is greater than maximum ({}) '.format(max_qubits) +
'for "{}".'.format(self.name()))
for experiment in qobj.experiments:
name = experiment.header.name
if experiment.config.memory_slots == 0:
logger.warning('No classical registers in circuit "%s", '
'counts will be empty.', name)
elif 'measure' not in [op.name for op in experiment.instructions]:
logger.warning('No measurements in circuit "%s", '
'classical register will remain all zeros.', name)
<|code_end|>
|
Cleanup mpl circuit_drawer module (post 0.7)
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
As pointed out in the review for https://github.com/Qiskit/qiskit-terra/pull/1450 there are a few artifacts leftover from the json->dag conversion for the mpl backend. Things like misleading variable names and out of date notes and comments. After the 0.7 release it would be good to go through the module and clean this up to make maintenance easier.
|
qiskit/tools/visualization/_matplotlib.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""mpl circuit visualization backend."""
import collections
import fractions
import itertools
import json
import logging
import math
import numpy as np
try:
from matplotlib import patches
from matplotlib import pyplot as plt
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
from qiskit.tools.visualization import exceptions
from qiskit.tools.visualization import _qcstyle
from qiskit.tools.visualization import _utils
logger = logging.getLogger(__name__)
Register = collections.namedtuple('Register', 'name index')
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
scale=1.0, style=None, plot_barriers=True,
reverse_bits=False):
if not HAS_MATPLOTLIB:
raise ImportError('The class MatplotlibDrawer needs matplotlib. '
'Run "pip install matplotlib" before.')
self._ast = None
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = collections.OrderedDict()
self._creg_dict = collections.OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = _qcstyle.QCStyle()
self.plot_barriers = plot_barriers
self.reverse_bits = reverse_bits
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False,
labelleft=False, labelright=False)
def parse_circuit(self, circuit):
qregs, cregs, ops = _utils._get_instructions(
circuit, reversebits=self.reverse_bits)
self._registers(cregs, qregs)
self._ops = ops
def _registers(self, creg, qreg):
# NOTE: formats of clbit and qubit are different!
self._creg = []
for e in creg:
self._creg.append(Register(name=e[0], index=e[1]))
self._qreg = []
for e in qreg:
self._qreg.append(Register(name=e[0], index=e[1]))
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(
xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center',
va='center', fontsize=self._style.fs,
color=self._style.gt, clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.sc, clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7,
height=HIG * 0.7, theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID],
[qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy + 0.35 * WID], lc=self._style.cc,
ls=self._style.cline)
arrowhead = patches.Polygon(((cx - 0.20 * WID, cy + 0.35 * WID),
(cx + 0.20 * WID, cy + 0.35 * WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'],
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
plt.close(self.figure)
return self.figure
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.name.name, reg.index)
else:
label = '${}$'.format(reg.name.name)
pos = -ii
self._qreg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(itertools.zip_longest(
self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.name.name)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
if not (not nreg or reg.name != nreg.name):
continue
else:
label = '${}_{{{}}}$'.format(reg.name.name, reg.index)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.name
}
self._cond['n_lines'] += 1
idx += 1
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left',
va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc,
ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(
itertools.zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qargs' in op.keys():
q_idxs = []
for qarg in op['qargs']:
for index, reg in self._qreg_dict.items():
if (reg['group'] == qarg[0] and
reg['index'] == qarg[1]):
q_idxs.append(index)
break
else:
q_idxs = []
# get creg index
if 'cargs' in op.keys():
c_idxs = []
for carg in op['cargs']:
for index, reg in self._creg_dict.items():
if (reg['group'] == carg[0] and
reg['index'] == carg[1]):
c_idxs.append(index)
break
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or (
'condition' in op.keys() and op['condition']) or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied),
max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(
this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] in [
'barrier', 'snapshot', 'load', 'save',
'noise'] and not self.plot_barriers:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg coordinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'op' in op.keys() and hasattr(op['op'], 'param'):
param = self.param_parse(op['op'].param, self._style.pimode)
else:
param = None
# conditional gate
if 'condition' in op.keys() and op['condition']:
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for
ii in self._creg_dict]
mask = 0
for index, cbit in enumerate(self._creg):
if cbit.name == op['condition'][0]:
mask |= (1 << index)
val = op['condition'][1]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, hex(val))
self._line(qreg_t, creg_b, lc=self._style.cc,
ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] in ['barrier', 'snapshot', 'load', 'save',
'noise']:
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self.plot_barriers:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise exceptions.VisualizationError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (
self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.tc, clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if math.isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if math.isclose(math.fmod(abs_val, 1.0),
0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
if 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if math.isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return fractions.Fraction(i, j)
return None
<|code_end|>
|
qiskit/tools/visualization/_matplotlib.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""mpl circuit visualization backend."""
import collections
import fractions
import itertools
import json
import logging
import math
import numpy as np
try:
from matplotlib import patches
from matplotlib import pyplot as plt
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
from qiskit.tools.visualization import exceptions
from qiskit.tools.visualization import _qcstyle
from qiskit.tools.visualization import _utils
logger = logging.getLogger(__name__)
Register = collections.namedtuple('Register', 'reg index')
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
scale=1.0, style=None, plot_barriers=True,
reverse_bits=False):
if not HAS_MATPLOTLIB:
raise ImportError('The class MatplotlibDrawer needs matplotlib. '
'Run "pip install matplotlib" before.')
self._ast = None
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = collections.OrderedDict()
self._creg_dict = collections.OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = _qcstyle.QCStyle()
self.plot_barriers = plot_barriers
self.reverse_bits = reverse_bits
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False,
labelleft=False, labelright=False)
def parse_circuit(self, circuit):
qregs, cregs, ops = _utils._get_instructions(
circuit, reversebits=self.reverse_bits)
self._registers(cregs, qregs)
self._ops = ops
def _registers(self, creg, qreg):
self._creg = []
for e in creg:
self._creg.append(Register(reg=e[0], index=e[1]))
self._qreg = []
for e in qreg:
self._qreg.append(Register(reg=e[0], index=e[1]))
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(
xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center',
va='center', fontsize=self._style.fs,
color=self._style.gt, clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.sc, clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7,
height=HIG * 0.7, theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID],
[qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy + 0.35 * WID], lc=self._style.cc,
ls=self._style.cline)
arrowhead = patches.Polygon(((cx - 0.20 * WID, cy + 0.35 * WID),
(cx + 0.20 * WID, cy + 0.35 * WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'],
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
plt.close(self.figure)
return self.figure
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.reg.name, reg.index)
else:
label = '${}$'.format(reg.reg.name)
pos = -ii
self._qreg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.reg
}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(itertools.zip_longest(
self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.reg.name)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.reg
}
if not (not nreg or reg.reg != nreg.reg):
continue
else:
label = '${}_{{{}}}$'.format(reg.reg.name, reg.index)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.reg
}
self._cond['n_lines'] += 1
idx += 1
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left',
va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc,
ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(
itertools.zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qargs' in op.keys():
q_idxs = []
for qarg in op['qargs']:
for index, reg in self._qreg_dict.items():
if (reg['group'] == qarg[0] and
reg['index'] == qarg[1]):
q_idxs.append(index)
break
else:
q_idxs = []
# get creg index
if 'cargs' in op.keys():
c_idxs = []
for carg in op['cargs']:
for index, reg in self._creg_dict.items():
if (reg['group'] == carg[0] and
reg['index'] == carg[1]):
c_idxs.append(index)
break
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or (
'condition' in op.keys() and op['condition']) or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied),
max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(
this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] in [
'barrier', 'snapshot', 'load', 'save',
'noise'] and not self.plot_barriers:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg coordinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'op' in op.keys() and hasattr(op['op'], 'param'):
param = self.param_parse(op['op'].param, self._style.pimode)
else:
param = None
# conditional gate
if 'condition' in op.keys() and op['condition']:
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for
ii in self._creg_dict]
mask = 0
for index, cbit in enumerate(self._creg):
if cbit.name == op['condition'][0]:
mask |= (1 << index)
val = op['condition'][1]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, hex(val))
self._line(qreg_t, creg_b, lc=self._style.cc,
ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] in ['barrier', 'snapshot', 'load', 'save',
'noise']:
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self.plot_barriers:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise exceptions.VisualizationError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (
self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.tc, clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if math.isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if math.isclose(math.fmod(abs_val, 1.0),
0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
if 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if math.isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return fractions.Fraction(i, j)
return None
<|code_end|>
|
remove ghpages_documentation_deploy.sh
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
since all the documentation is now in qiskit/qiskit we should remove this script.
|
setup.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
from setuptools import setup, find_packages
requirements = [
"jsonschema>=2.6,<2.7",
"marshmallow>=2.17.0,<3",
"marshmallow_polyfield>=3.2,<4",
"networkx>=2.2",
"numpy>=1.13",
"pillow>=4.2.1",
"ply>=3.10",
"psutil>=5",
"requests>=2.19",
"requests-ntlm>=1.1.0",
"scipy>=0.19,!=0.19.1",
"sympy>=1.3"
]
setup(
name="qiskit-terra",
version="0.8.0",
description="Software for developing quantum computing programs",
long_description="""Terra provides the foundations for Qiskit. It allows the user to write
quantum circuits easily, and takes care of the constraints of real hardware.""",
url="https://github.com/Qiskit/qiskit-terra",
author="Qiskit Development Team",
author_email="qiskit@qiskit.org",
license="Apache 2.0",
classifiers=[
"Environment :: Console",
"License :: OSI Approved :: Apache Software License",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"Operating System :: Microsoft :: Windows",
"Operating System :: MacOS",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Topic :: Scientific/Engineering",
],
keywords="qiskit sdk quantum",
packages=find_packages(exclude=['test*']),
install_requires=requirements,
include_package_data=True,
python_requires=">=3.5",
extra_requires={
'visualization': ['matplotlib>=2.1', 'nxpd>=0.2', 'ipywidgets>=7.3.0',
'pydot'],
'full-featured-simulators': ['qiskit-aer>=0.1']
}
)
<|code_end|>
|
setup.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
from setuptools import setup, find_packages
requirements = [
"jsonschema>=2.6,<2.7",
"marshmallow>=2.17.0,<3",
"marshmallow_polyfield>=3.2,<4",
"networkx>=2.2",
"numpy>=1.13,<1.16",
"pillow>=4.2.1",
"ply>=3.10",
"psutil>=5",
"requests>=2.19",
"requests-ntlm>=1.1.0",
"scipy>=0.19,!=0.19.1",
"sympy>=1.3"
]
setup(
name="qiskit-terra",
version="0.8.0",
description="Software for developing quantum computing programs",
long_description="""Terra provides the foundations for Qiskit. It allows the user to write
quantum circuits easily, and takes care of the constraints of real hardware.""",
url="https://github.com/Qiskit/qiskit-terra",
author="Qiskit Development Team",
author_email="qiskit@qiskit.org",
license="Apache 2.0",
classifiers=[
"Environment :: Console",
"License :: OSI Approved :: Apache Software License",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"Operating System :: Microsoft :: Windows",
"Operating System :: MacOS",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Topic :: Scientific/Engineering",
],
keywords="qiskit sdk quantum",
packages=find_packages(exclude=['test*']),
install_requires=requirements,
include_package_data=True,
python_requires=">=3.5",
extra_requires={
'visualization': ['matplotlib>=2.1', 'nxpd>=0.2', 'ipywidgets>=7.3.0',
'pydot'],
'full-featured-simulators': ['qiskit-aer>=0.1']
}
)
<|code_end|>
|
Consistent gates order in visualizations (and DAG?)
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
As a spin-off from #1617 (thanks @Exferro!) , during that PR it was detected that the same `QuantumCircuit` produces different visualizations between Python [3.5](https://github.com/Qiskit/qiskit-terra/blob/73d47fd924edd948aee51b648b15d06211a17a20/test/python/tools/visualization/references/3.5/deep/mpl.png) and [3.6/3.7](https://github.com/Qiskit/qiskit-terra/blob/73d47fd924edd948aee51b648b15d06211a17a20/test/python/tools/visualization/references/3.6/deep/mpl.png) - the order in which `measure`s are drawn is different.
Digging a bit deeper, it seems it might be a mixture of two issues:
* the order of the instructions in the circuit (`circuit.data`) is not preserved in the final visualization
* potentially, there might be some `dict` vs `OrderedDict` issue involved (based on the example at #1617 producing the _same_ result in 3.6/3.7, and a different one in 3.5) - this is not confirmed.
### Desired behaviour
Ideally, we should be able to at least guarantee a "consistent" order (same visualization is produced regardless of Python version), and hopefully one that respects the original instruction order.
### Proposed solution
The main flow when producing a visualization is through [`_get_instructions()`](
https://github.com/Qiskit/qiskit-terra/blob/179290f082a9c4b905402db8a60fe7bb899f79e8/qiskit/tools/visualization/_utils.py#L68), which in turn ends up invoking [`node_nums_in_topological_order()`](https://github.com/Qiskit/qiskit-terra/blob/179290f082a9c4b905402db8a60fe7bb899f79e8/qiskit/dagcircuit/_dagcircuit.py#L984). A possible solution might involve ensuring that the topological sorting always return the same solution, for example "tagging" or adding extra information to the DAG for allowing it to restore the order in which gates were added to the circuit (@ajavadia can ellaborate into the idea).
## Good first contribution!
I am actually tagging this as `good first contribution`, as I believe is an interesting change to explore both the circuits/dags and the visualization sides of Terra - and with a cool end result! If somebody is interested, please ping us by replying to this issue :tada:
|
qiskit/converters/circuit_to_dag.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Helper function for converting a circuit to a dag"""
from qiskit.circuit.compositegate import CompositeGate
from qiskit.dagcircuit._dagcircuit import DAGCircuit
def circuit_to_dag(circuit):
"""Build a ``DAGCircuit`` object from a ``QuantumCircuit``.
Args:
circuit (QuantumCircuit): the input circuit.
Return:
DAGCircuit: the DAG representing the input circuit.
"""
dagcircuit = DAGCircuit()
dagcircuit.name = circuit.name
for register in circuit.qregs:
dagcircuit.add_qreg(register)
for register in circuit.cregs:
dagcircuit.add_creg(register)
# Add user gate definitions
for name, data in circuit.definitions.items():
dagcircuit.add_basis_element(name, data["n_bits"], 0, data["n_args"])
dagcircuit.add_gate_data(name, data)
# Add instructions
builtins = {
"U": ["U", 1, 0, 3],
"CX": ["CX", 2, 0, 0],
"measure": ["measure", 1, 1, 0],
"reset": ["reset", 1, 0, 0],
"barrier": ["barrier", -1, 0, 0]
}
# Add simulator instructions
simulator_instructions = {
"snapshot": ["snapshot", -1, 0, 1],
"save": ["save", -1, 0, 1],
"load": ["load", -1, 0, 1],
"noise": ["noise", -1, 0, 1]
}
for main_instruction in circuit.data:
# TODO: generate definitions and nodes for CompositeGates,
# for now simply drop their instructions into the DAG
instruction_list = []
is_composite = isinstance(main_instruction, CompositeGate)
if is_composite:
instruction_list = main_instruction.instruction_list()
else:
instruction_list.append(main_instruction)
for instruction in instruction_list:
# Add OpenQASM built-in gates on demand
if instruction.name in builtins:
dagcircuit.add_basis_element(*builtins[instruction.name])
# Add simulator extension instructions
if instruction.name in simulator_instructions:
dagcircuit.add_basis_element(*simulator_instructions[instruction.name])
# Get arguments for classical control (if any)
if instruction.control is None:
control = None
else:
control = (instruction.control[0], instruction.control[1])
def duplicate_instruction(inst):
"""Create a fresh instruction from an input instruction."""
if inst.name == 'barrier':
params = [inst.qargs]
elif inst.name in simulator_instructions.keys():
params = inst.params + [inst.qargs] + [inst.circuit]
else:
params = inst.params + inst.qargs + inst.cargs
new_inst = inst.__class__(*params)
return new_inst
inst = duplicate_instruction(instruction)
dagcircuit.apply_operation_back(inst, inst.qargs,
inst.cargs, control)
return dagcircuit
<|code_end|>
qiskit/dagcircuit/_dagcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Object to represent a quantum circuit as a directed acyclic graph.
The nodes in the graph are either input/output nodes or operation nodes.
The operation nodes are elements of a basis that is part of the circuit.
The QASM definitions of the basis elements are carried with the circuit.
The edges correspond to qubits or bits in the circuit. A directed edge
from node A to node B means that the (qu)bit passes from the output of A
to the input of B. The object's methods allow circuits to be constructed,
composed, and modified. Some natural properties like depth can be computed
directly from the graph.
"""
import re
from collections import OrderedDict
import copy
import itertools
import networkx as nx
from qiskit.circuit.quantumregister import QuantumRegister
from qiskit.circuit.classicalregister import ClassicalRegister
from qiskit.circuit.gate import Gate
from .exceptions import DAGCircuitError
class DAGCircuit:
"""
Quantum circuit as a directed acyclic graph.
There are 3 types of nodes in the graph: inputs, outputs, and operations.
The nodes are connected by directed edges that correspond to qubits and
bits.
"""
# pylint: disable=invalid-name
def __init__(self):
"""Create an empty circuit."""
# Circuit name. Generally, this corresponds to the name
# of the QuantumCircuit from which the DAG was generated.
self.name = None
# Set of wires (Register,idx) in the dag
self.wires = []
# Map from wire (Register,idx) to input nodes of the graph
self.input_map = OrderedDict()
# Map from wire (Register,idx) to output nodes of the graph
self.output_map = OrderedDict()
# Running count of the total number of nodes
self.node_counter = 0
# Map of user defined gates to ast nodes defining them
self.gates = OrderedDict()
# Map of named operations in this circuit and their signatures.
# The signature is an integer tuple (nq,nc,np) specifying the
# number of input qubits, input bits, and real parameters.
# The definition is external to the circuit object.
self.basis = OrderedDict()
self.add_basis_element(name="U", number_qubits=1,
number_classical=0, number_parameters=3)
self.add_basis_element("CX", 2, 0, 0)
self.add_basis_element("measure", 1, 1, 0)
self.add_basis_element("reset", 1, 0, 0)
self.add_basis_element("barrier", -1)
# Directed multigraph whose nodes are inputs, outputs, or operations.
# Operation nodes have equal in- and out-degrees and carry
# additional data about the operation, including the argument order
# and parameter values.
# Input nodes have out-degree 1 and output nodes have in-degree 1.
# Edges carry wire labels (reg,idx) and each operation has
# corresponding in- and out-edges with the same wire labels.
self.multi_graph = nx.MultiDiGraph()
# Map of qreg name to QuantumRegister object
self.qregs = OrderedDict()
# Map of creg name to ClassicalRegister object
self.cregs = OrderedDict()
def get_qubits(self):
"""Return a list of qubits as (QuantumRegister, index) pairs."""
return [(v, i) for k, v in self.qregs.items() for i in range(v.size)]
def get_bits(self):
"""Return a list of bits as (ClassicalRegister, index) pairs."""
return [(v, i) for k, v in self.cregs.items() for i in range(v.size)]
# TODO: unused function. is it needed?
def rename_register(self, regname, newname):
"""Rename a classical or quantum register throughout the circuit.
regname = existing register name string
newname = replacement register name string
"""
if regname == newname:
return
if newname in self.qregs or newname in self.cregs:
raise DAGCircuitError("duplicate register name %s" % newname)
if regname not in self.qregs and regname not in self.cregs:
raise DAGCircuitError("no register named %s" % regname)
if regname in self.qregs:
reg = self.qregs[regname]
reg.name = newname
self.qregs[newname] = reg
self.qregs.pop(regname, None)
if regname in self.cregs:
reg = self.cregs[regname]
reg.name = newname
self.qregs[newname] = reg
self.qregs.pop(regname, None)
# n node d = data
for _, d in self.multi_graph.nodes(data=True):
if d["type"] == "in" or d["type"] == "out":
if regname in d["name"]:
d["name"] = re.sub(regname, newname, d["name"])
elif d["type"] == "op":
qa = []
for a in d["qargs"]:
if a[0] == regname:
a = (newname, a[1])
qa.append(a)
d["qargs"] = qa
ca = []
for a in d["cargs"]:
if a[0] == regname:
a = (newname, a[1])
ca.append(a)
d["cargs"] = ca
if d["condition"] is not None:
if d["condition"][0] == regname:
d["condition"] = (newname, d["condition"][1])
# eX = edge, d= data
for _, _, d in self.multi_graph.edges(data=True):
if regname in d["name"]:
d["name"] = re.sub(regname, newname, d["name"])
def remove_all_ops_named(self, opname):
"""Remove all operation nodes with the given name."""
for n in self.get_named_nodes(opname):
self._remove_op_node(n)
def add_qreg(self, qreg):
"""Add all wires in a quantum register."""
if not isinstance(qreg, QuantumRegister):
raise DAGCircuitError("not a QuantumRegister instance.")
if qreg.name in self.qregs:
raise DAGCircuitError("duplicate register %s" % qreg.name)
self.qregs[qreg.name] = qreg
for j in range(qreg.size):
self._add_wire((qreg, j))
def add_creg(self, creg):
"""Add all wires in a classical register."""
if not isinstance(creg, ClassicalRegister):
raise DAGCircuitError("not a ClassicalRegister instance.")
if creg.name in self.cregs:
raise DAGCircuitError("duplicate register %s" % creg.name)
self.cregs[creg.name] = creg
for j in range(creg.size):
self._add_wire((creg, j))
def _add_wire(self, wire):
"""Add a qubit or bit to the circuit.
Args:
wire (tuple): (Register,int) containing a register instance and index
This adds a pair of in and out nodes connected by an edge.
Raises:
DAGCircuitError: if trying to add duplicate wire
"""
if wire not in self.wires:
self.wires.append(wire)
self.node_counter += 1
self.input_map[wire] = self.node_counter
self.node_counter += 1
self.output_map[wire] = self.node_counter
in_node = self.input_map[wire]
out_node = self.output_map[wire]
self.multi_graph.add_edge(in_node, out_node)
self.multi_graph.node[in_node]["type"] = "in"
self.multi_graph.node[out_node]["type"] = "out"
self.multi_graph.node[in_node]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.node[out_node]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.node[in_node]["wire"] = wire
self.multi_graph.node[out_node]["wire"] = wire
self.multi_graph.adj[in_node][out_node][0]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.adj[in_node][out_node][0]["wire"] = wire
else:
raise DAGCircuitError("duplicate wire %s" % (wire,))
def add_basis_element(self, name, number_qubits,
number_classical=0, number_parameters=0):
"""Add an operation to the basis.
name is string label for operation
number_qubits is number of qubit arguments
number_classical is number of bit arguments
number_parameters is number of real parameters
The parameters (nq,nc,np) are ignored for the special case
when name = "barrier". The barrier instruction has a variable
number of qubit arguments.
"""
if name not in self.basis:
self.basis[name] = (
number_qubits,
number_classical,
number_parameters)
if name in self.gates:
if self.gates[name]["n_args"] != number_parameters or \
self.gates[name]["n_bits"] != number_qubits or number_classical != 0:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def add_gate_data(self, name, gatedata):
"""Add the definition of a gate.
gatedata is dict with fields:
"print" = True or False
"opaque" = True or False
"n_args" = number of real parameters
"n_bits" = number of qubits
"args" = list of parameter names
"bits" = list of qubit names
"body" = GateBody AST node
"""
if name not in self.gates:
self.gates[name] = gatedata
if name in self.basis:
if self.basis[name][0] != self.gates[name]["n_bits"] or \
self.basis[name][1] != 0 or \
self.basis[name][2] != self.gates[name]["n_args"]:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def _check_basis_data(self, op, qargs, cargs):
"""Check the arguments against the data for this operation.
Args:
op (Instruction): a quantum operation
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple]): cbits that op will be applied to
Raises:
DAGCircuitError: If the check fails.
"""
# Check that we have this operation
if op.name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations" % op.name)
# Check the number of arguments matches the signature
if op.name in ["barrier"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s" % op.name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s" % op.name)
elif op.name in ["snapshot", "noise", "save", "load"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s" % op.name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s" % op.name)
else:
if len(qargs) != self.basis[op.name][0]:
raise DAGCircuitError("incorrect number of qubits for %s" % op.name)
if len(cargs) != self.basis[op.name][1]:
raise DAGCircuitError("incorrect number of bits for %s" % op.name)
def _check_condition(self, name, condition):
"""Verify that the condition is valid.
Args:
name (string): used for error reporting
condition (tuple or None): a condition tuple (ClassicalRegister,int)
Raises:
DAGCircuitError: if conditioning on an invalid register
"""
# Verify creg exists
if condition is not None and condition[0].name not in self.cregs:
raise DAGCircuitError("invalid creg in condition for %s" % name)
def _check_bits(self, args, amap):
"""Check the values of a list of (qu)bit arguments.
For each element of args, check that amap contains it.
Args:
args (list): (register,idx) tuples
amap (dict): a dictionary keyed on (register,idx) tuples
Raises:
DAGCircuitError: if a qubit is not contained in amap
"""
# Check for each wire
for wire in args:
if wire not in amap:
raise DAGCircuitError("(qu)bit %s[%d] not found" % (wire[0].name, wire[1]))
def _bits_in_condition(self, cond):
"""Return a list of bits in the given condition.
Args:
cond (tuple or None): optional condition (ClassicalRegister, int)
Returns:
list[(ClassicalRegister, idx)]: list of bits
"""
all_bits = []
if cond is not None:
all_bits.extend([(cond[0], j) for j in range(self.cregs[cond[0].name].size)])
return all_bits
def _add_op_node(self, op, qargs, cargs, condition=None):
"""Add a new operation node to the graph and assign properties.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list): list of quantum wires to attach to.
cargs (list): list of classical wires to attach to.
condition (tuple or None): optional condition (ClassicalRegister, int)
"""
# Add a new operation node to the graph
self.node_counter += 1
self.multi_graph.add_node(self.node_counter)
# Update the operation itself. TODO: remove after qargs not connected to op
op.qargs = qargs
op.cargs = cargs
# Update that operation node's data
self.multi_graph.node[self.node_counter]["type"] = "op"
self.multi_graph.node[self.node_counter]["op"] = op
self.multi_graph.node[self.node_counter]["name"] = op.name
self.multi_graph.node[self.node_counter]["qargs"] = qargs
self.multi_graph.node[self.node_counter]["cargs"] = cargs
self.multi_graph.node[self.node_counter]["condition"] = condition
def apply_operation_back(self, op, qargs=None, cargs=None, condition=None):
"""Apply an operation to the output of the circuit.
TODO: make `qargs` and `cargs` mandatory, when they are dropped from op.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple]): cbits that op will be applied to
condition (tuple or None): optional condition (ClassicalRegister, int)
Raises:
DAGCircuitError: if a leaf node is connected to multiple outputs
"""
qargs = qargs or op.qargs
cargs = cargs or op.cargs
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(op, qargs, cargs)
self._check_condition(op.name, condition)
self._check_bits(qargs, self.output_map)
self._check_bits(all_cbits, self.output_map)
self._add_op_node(op, qargs, cargs, condition)
# Add new in-edges from predecessors of the output nodes to the
# operation node while deleting the old in-edges of the output nodes
# and adding new edges from the operation node to each output node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.predecessors(self.output_map[q]))
if len(ie) != 1:
raise DAGCircuitError("output node has multiple in-edges")
self.multi_graph.add_edge(ie[0], self.node_counter,
name="%s[%s]" % (q[0].name, q[1]), wire=q)
self.multi_graph.remove_edge(ie[0], self.output_map[q])
self.multi_graph.add_edge(self.node_counter, self.output_map[q],
name="%s[%s]" % (q[0].name, q[1]), wire=q)
def apply_operation_front(self, op, qargs=None, cargs=None, condition=None):
"""Apply an operation to the input of the circuit.
TODO: make `qargs` and `cargs` mandatory, when they are dropped from op.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple]): cbits that op will be applied to
condition (tuple or None): optional condition (ClassicalRegister, value)
Raises:
DAGCircuitError: if initial nodes connected to multiple out edges
"""
qargs = qargs or op.qargs
cargs = cargs or op.cargs
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(op, qargs, cargs)
self._check_condition(op.name, condition)
self._check_bits(qargs, self.input_map)
self._check_bits(all_cbits, self.input_map)
self._add_op_node(op, qargs, cargs, condition)
# Add new out-edges to successors of the input nodes from the
# operation node while deleting the old out-edges of the input nodes
# and adding new edges to the operation node from each input node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.successors(self.input_map[q]))
if len(ie) != 1:
raise DAGCircuitError("input node has multiple out-edges")
self.multi_graph.add_edge(self.node_counter, ie[0],
name="%s[%s]" % (q[0].name, q[1]), wire=q)
self.multi_graph.remove_edge(self.input_map[q], ie[0])
self.multi_graph.add_edge(self.input_map[q], self.node_counter,
name="%s[%s]" % (q[0].name, q[1]), wire=q)
def _make_union_basis(self, input_circuit):
"""Return a new basis map.
The new basis is a copy of self.basis with
new elements of input_circuit.basis added.
input_circuit is a DAGCircuit
"""
union_basis = self.basis.copy()
for g in input_circuit.basis:
if g not in union_basis:
union_basis[g] = input_circuit.basis[g]
if union_basis[g] != input_circuit.basis[g]:
raise DAGCircuitError("incompatible basis")
return union_basis
def _make_union_gates(self, input_circuit):
"""Return a new gates map.
The new gates are a copy of self.gates with
new elements of input_circuit.gates added.
input_circuit is a DAGCircuit
NOTE: gates in input_circuit that are also in self must
be *identical* to the gates in self
"""
union_gates = {}
for k, v in self.gates.items():
union_gates[k] = v
for k, v in input_circuit.gates.items():
if k not in union_gates:
union_gates[k] = v
if union_gates[k]["opaque"] != input_circuit.gates[k]["opaque"] or \
union_gates[k]["n_args"] != input_circuit.gates[k]["n_args"] or \
union_gates[k]["n_bits"] != input_circuit.gates[k]["n_bits"] or \
union_gates[k]["args"] != input_circuit.gates[k]["args"] or \
union_gates[k]["bits"] != input_circuit.gates[k]["bits"]:
raise DAGCircuitError("inequivalent gate definitions for %s"
% k)
return union_gates
def _check_edgemap_registers(self, edge_map, keyregs, valregs, valreg=True):
"""Check that wiremap neither fragments nor leaves duplicate registers.
1. There are no fragmented registers. A register in keyregs
is fragmented if not all of its (qu)bits are renamed by edge_map.
2. There are no duplicate registers. A register is duplicate if
it appears in both self and keyregs but not in edge_map.
Args:
edge_map (dict): map from (reg,idx) in keyregs to (reg,idx) in valregs
keyregs (dict): a map from register names to Register objects
valregs (dict): a map from register names to Register objects
valreg (bool): if False the method ignores valregs and does not
add regs for bits in the edge_map image that don't appear in valregs
Returns:
set(Register): the set of regs to add to self
Raises:
DAGCircuitError: if the wiremap fragments, or duplicates exist
"""
# FIXME: some mixing of objects and strings here are awkward (due to
# self.qregs/self.cregs still keying on string.
add_regs = set()
reg_frag_chk = {}
for v in keyregs.values():
reg_frag_chk[v] = {j: False for j in range(len(v))}
for k in edge_map.keys():
if k[0].name in keyregs:
reg_frag_chk[k[0]][k[1]] = True
for k, v in reg_frag_chk.items():
s = set(v.values())
if len(s) == 2:
raise DAGCircuitError("edge_map fragments reg %s" % k)
elif s == set([False]):
if k in self.qregs.values() or k in self.cregs.values():
raise DAGCircuitError("unmapped duplicate reg %s" % k)
else:
# Add registers that appear only in keyregs
add_regs.add(k)
else:
if valreg:
# If mapping to a register not in valregs, add it.
# (k,0) exists in edge_map because edge_map doesn't
# fragment k
if not edge_map[(k, 0)][0].name in valregs:
size = max(map(lambda x: x[1],
filter(lambda x: x[0] == edge_map[(k, 0)][0],
edge_map.values())))
qreg = QuantumRegister(size + 1, edge_map[(k, 0)][0].name)
add_regs.add(qreg)
return add_regs
def _check_wiremap_validity(self, wire_map, keymap, valmap):
"""Check that the wiremap is consistent.
Check that the wiremap refers to valid wires and that
those wires have consistent types.
Args:
wire_map (dict): map from (register,idx) in keymap to
(register,idx) in valmap
keymap (dict): a map whose keys are wire_map keys
valmap (dict): a map whose keys are wire_map values
Raises:
DAGCircuitError: if wire_map not valid
"""
for k, v in wire_map.items():
kname = "%s[%d]" % (k[0].name, k[1])
vname = "%s[%d]" % (v[0].name, v[1])
if k not in keymap:
raise DAGCircuitError("invalid wire mapping key %s" % kname)
if v not in valmap:
raise DAGCircuitError("invalid wire mapping value %s" % vname)
if type(k) is not type(v):
raise DAGCircuitError("inconsistent wire_map at (%s,%s)" %
(kname, vname))
def _map_condition(self, wire_map, condition):
"""Use the wire_map dict to change the condition tuple's creg name.
Args:
wire_map (dict): a map from wires to wires
condition (tuple): (ClassicalRegister,int)
Returns:
tuple(ClassicalRegister,int): new condition
"""
if condition is None:
new_condition = None
else:
# Map the register name, using fact that registers must not be
# fragmented by the wire_map (this must have been checked
# elsewhere)
bit0 = (condition[0], 0)
new_condition = (wire_map.get(bit0, bit0)[0], condition[1])
return new_condition
def extend_back(self, dag, edge_map=None):
"""Add `dag` at the end of `self`, using `edge_map`.
"""
edge_map = edge_map or {}
for qreg in dag.qregs.values():
if qreg.name not in self.qregs:
self.add_qreg(QuantumRegister(qreg.size, qreg.name))
edge_map.update([(qbit, qbit) for qbit in qreg if qbit not in edge_map])
for creg in dag.cregs.values():
if creg.name not in self.cregs:
self.add_creg(ClassicalRegister(creg.size, creg.name))
edge_map.update([(cbit, cbit) for cbit in creg if cbit not in edge_map])
self.compose_back(dag, edge_map)
def compose_back(self, input_circuit, edge_map=None):
"""Apply the input circuit to the output of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of input qubits of the input circuit are mapped
to a subset of output qubits of this circuit.
Args:
input_circuit (DAGCircuit): circuit to append
edge_map (dict): map {(Register, int): (Register, int)}
from the output wires of input_circuit to input wires
of self.
Raises:
DAGCircuitError: if missing, duplicate or incosistent wire
"""
edge_map = edge_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map for duplicate values
if len(set(edge_map.values())) != len(edge_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_edgemap_registers(edge_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(edge_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(edge_map, input_circuit.input_map,
self.output_map)
# Compose
self.basis = union_basis
self.gates = union_gates
for node in nx.topological_sort(input_circuit.multi_graph):
nd = input_circuit.multi_graph.node[node]
if nd["type"] == "in":
# if in wire_map, get new name, else use existing name
m_wire = edge_map.get(nd["wire"], nd["wire"])
# the mapped wire should already exist
if m_wire not in self.output_map:
raise DAGCircuitError("wire %s[%d] not in self" % (m_wire[0].name, m_wire[1]))
if nd["wire"] not in input_circuit.wires:
raise DAGCircuitError("inconsistent wire type for %s[%d] in input_circuit"
% (nd["wire"][0].name, nd["wire"][1]))
elif nd["type"] == "out":
# ignore output nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(edge_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: edge_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: edge_map.get(x, x), nd["cargs"]))
self.apply_operation_back(nd["op"], m_qargs, m_cargs, condition)
else:
raise DAGCircuitError("bad node type %s" % nd["type"])
# FIXME: this does not work as expected. it is also not used anywhere
def compose_front(self, input_circuit, wire_map=None):
"""Apply the input circuit to the input of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of output qubits of the input circuit are mapped
to a subset of input qubits of this circuit.
Args:
input_circuit (DAGCircuit): circuit to append
wire_map (dict): map {(Register, int): (Register, int)}
from the output wires of input_circuit to input wires
of self.
Raises:
DAGCircuitError: missing, duplicate or inconsistent wire
"""
wire_map = wire_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_edgemap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.output_map,
self.input_map)
# Compose
self.basis = union_basis
self.gates = union_gates
for n in reversed(list(nx.topological_sort(input_circuit.multi_graph))):
nd = input_circuit.multi_graph.node[n]
if nd["type"] == "out":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["wire"], nd["wire"])
# the mapped wire should already exist
if m_name not in self.input_map:
raise DAGCircuitError("wire %s[%d] not in self" % (m_name[0].name, m_name[1]))
if nd["wire"] not in input_circuit.wires:
raise DAGCircuitError(
"inconsistent wire for %s[%d] in input_circuit"
% (nd["wire"][0].name, nd["wire"][1]))
elif nd["type"] == "in":
# ignore input nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
self.apply_operation_front(nd["op"], condition)
else:
raise DAGCircuitError("bad node type %s" % nd["type"])
def size(self):
"""Return the number of operations."""
return self.multi_graph.order() - 2 * len(self.wires)
def depth(self):
"""Return the circuit depth.
Returns:
int: the circuit depth
Raises:
DAGCircuitError: if not a directed acyclic graph
"""
if not nx.is_directed_acyclic_graph(self.multi_graph):
raise DAGCircuitError("not a DAG")
return nx.dag_longest_path_length(self.multi_graph) - 1
def width(self):
"""Return the total number of qubits used by the circuit."""
return len(self.wires) - self.num_cbits()
def num_cbits(self):
"""Return the total number of bits used by the circuit."""
return sum(creg.size for creg in self.cregs.values())
def num_tensor_factors(self):
"""Compute how many components the circuit can decompose into."""
return nx.number_weakly_connected_components(self.multi_graph)
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.gates[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.gates[name]["n_args"] > 0:
out += "(" + ",".join(self.gates[name]["args"]) + ")"
out += " " + ",".join(self.gates[name]["bits"])
if self.gates[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.gates[name]["body"].qasm() + "}"
return out
def qasm(self, no_decls=False, qeflag=False, aliases=None, eval_symbols=False):
"""Return a string containing QASM for this circuit.
Args:
qeflag (bool): if True, add a line to include "qelib1.inc"
and only generate gate code for gates not in qelib1.
eval_symbols (bool): if True, evaluate all symbolic
expressions to their floating point representation.
no_decls (bool): if True, only print the instructions.
aliases (dict): if not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
Returns:
str: OpenQASM representation of the DAG
Raises:
DAGCircuitError: if dag nodes not in expected format
"""
# TODO: some of the input flags are not needed anymore
# Rename qregs if necessary
if aliases:
qregdata = OrderedDict()
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
# Write top matter
if no_decls:
out = ""
else:
printed_gates = []
out = "OPENQASM 2.0;\n"
if qeflag:
out += "include \"qelib1.inc\";\n"
for k, v in qregdata.items():
out += "qreg %s[%d];\n" % (k, v.size)
for k, v in self.cregs.items():
out += "creg %s[%d];\n" % (k, v.size)
omit = ["U", "CX", "measure", "reset", "barrier"]
# TODO: dagcircuit shouldn't know about extensions
if qeflag:
qelib = ["u3", "u2", "u1", "cx", "id", "x", "y", "z", "h",
"s", "sdg", "t", "tdg", "cz", "cy", "ccx", "cu1",
"cu3", "swap", "cswap", "u0", "rx", "ry", "rz",
"ch", "crz", "rzz"]
omit.extend(qelib)
printed_gates.extend(qelib)
simulator_instructions = ["snapshot", "save", "load", "noise", "wait"]
omit.extend(simulator_instructions)
for k in self.basis.keys():
if k not in omit:
if not self.gates[k]["opaque"]:
calls = self.gates[k]["body"].calls()
for c in calls:
if c not in printed_gates:
out += self._gate_string(c) + "\n"
printed_gates.append(c)
if k not in printed_gates:
out += self._gate_string(k) + "\n"
printed_gates.append(k)
# Write the instructions
for n in nx.lexicographical_topological_sort(
self.multi_graph, key=lambda x: (self.multi_graph.nodes[x]["type"],
self.multi_graph.nodes[x]["name"])):
nd = self.multi_graph.node[n]
if nd["type"] == "op":
if nd["condition"] is not None:
out += "if(%s==%d) " \
% (nd["condition"][0], nd["condition"][1])
if not nd["cargs"]:
nm = nd["op"].name
if aliases:
qarglist = map(lambda x: aliases[x], nd["qargs"])
else:
qarglist = nd["qargs"]
qarg = ",".join(map(lambda x: "%s[%d]" % (x[0].name, x[1]),
qarglist))
if nd["op"].params:
if eval_symbols:
param = ",".join(map(lambda x: str(x.evalf()),
nd["op"].params))
else:
param = ",".join(map(lambda x: x.replace("**", "^"),
map(str, nd["op"].params)))
out += "%s(%s) %s;\n" % (nm, param, qarg)
else:
out += "%s %s;\n" % (nm, qarg)
else:
if nd["op"].name == "measure":
if len(nd["cargs"]) != 1 or len(nd["qargs"]) != 1 \
or nd["op"].param:
raise DAGCircuitError("bad node data")
qname = nd["qargs"][0][0].name
qindex = nd["qargs"][0][1]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
out += "measure %s[%d] -> %s[%d];\n" \
% (qname,
qindex,
nd["cargs"][0][0].name,
nd["cargs"][0][1])
else:
raise DAGCircuitError("bad node data")
return out
def _check_wires_list(self, wires, op, input_circuit, condition=None):
"""Check that a list of wires satisfies some conditions.
- no duplicate names
- correct length for operation
- elements are wires of input_circuit
Raise an exception otherwise.
Args:
wires (list[register, index]): gives an order for (qu)bits
in the input_circuit that is replacing the operation.
op (Instruction): operation
input_circuit (DAGCircuit): replacement circuit for operation
condition (tuple or None): if this instance of the
operation is classically controlled by a (ClassicalRegister, int)
Raises:
DAGCircuitError: if check doesn't pass.
"""
if len(set(wires)) != len(wires):
raise DAGCircuitError("duplicate wires")
wire_tot = len(op.qargs) + len(op.cargs)
if condition is not None:
wire_tot += condition[0].size
if len(wires) != wire_tot:
raise DAGCircuitError("expected %d wires, got %d"
% (wire_tot, len(wires)))
for w in wires:
if w not in input_circuit.wires:
raise DAGCircuitError("wire (%s,%d) not in input circuit"
% (w[0], w[1]))
def _make_pred_succ_maps(self, n):
"""Return predecessor and successor dictionaries.
Args:
n (int): reference to self.multi_graph node id
Returns:
tuple(dict): tuple(predecessor_map, successor_map)
These map from wire (Register, int) to predecessor (successor)
nodes of n.
"""
pred_map = {e[2]['wire']: e[0] for e in
self.multi_graph.in_edges(nbunch=n, data=True)}
succ_map = {e[2]['wire']: e[1] for e in
self.multi_graph.out_edges(nbunch=n, data=True)}
return pred_map, succ_map
def _full_pred_succ_maps(self, pred_map, succ_map, input_circuit,
wire_map):
"""Map all wires of the input circuit.
Map all wires of the input circuit to predecessor and
successor nodes in self, keyed on wires in self.
Args:
pred_map (dict): comes from _make_pred_succ_maps
succ_map (dict): comes from _make_pred_succ_maps
input_circuit (DAGCircuit): the input circuit
wire_map (dict): the map from wires of input_circuit to wires of self
Returns:
tuple: full_pred_map, full_succ_map (dict, dict)
Raises:
DAGCircuitError: if more than one predecessor for output nodes
"""
full_pred_map = {}
full_succ_map = {}
for w in input_circuit.input_map:
# If w is wire mapped, find the corresponding predecessor
# of the node
if w in wire_map:
full_pred_map[wire_map[w]] = pred_map[wire_map[w]]
full_succ_map[wire_map[w]] = succ_map[wire_map[w]]
else:
# Otherwise, use the corresponding output nodes of self
# and compute the predecessor.
full_succ_map[w] = self.output_map[w]
full_pred_map[w] = self.multi_graph.predecessors(
self.output_map[w])[0]
if len(list(self.multi_graph.predecessors(self.output_map[w]))) != 1:
raise DAGCircuitError("too many predecessors for %s[%d] "
"output node" % (w[0], w[1]))
return full_pred_map, full_succ_map
@staticmethod
def _match_dag_nodes(node1, node2):
"""
Check if DAG nodes are considered equivalent, e.g. as a node_match for nx.is_isomorphic.
Args:
node1 (dict): A node to compare.
node2 (dict): The other node to compare.
Returns:
Bool: If node1 == node2
"""
copy_node1 = {k: v for (k, v) in node1.items()}
copy_node2 = {k: v for (k, v) in node2.items()}
# For barriers, qarg order is not significant so compare as sets
if 'barrier' == copy_node1['name'] == copy_node2['name']:
node1_qargs = set(copy_node1.pop('qargs', []))
node2_qargs = set(copy_node2.pop('qargs', []))
if node1_qargs != node2_qargs:
return False
return copy_node1 == copy_node2
def __eq__(self, other):
return nx.is_isomorphic(self.multi_graph, other.multi_graph,
node_match=DAGCircuit._match_dag_nodes)
def node_nums_in_topological_order(self):
"""
Returns the nodes (their ids) in topological order.
Returns:
list: The list of node numbers in topological order
"""
return nx.topological_sort(self.multi_graph)
def substitute_circuit_all(self, op, input_circuit, wires=None):
"""Replace every occurrence of operation op with input_circuit.
Args:
op (Instruction): operation type to substitute across the dag.
input_circuit (DAGCircuit): what to replace with
wires (list[register, index]): gives an order for (qu)bits
in the input_circuit that is replacing the operation.
Raises:
DAGCircuitError: if met with unexpected predecessor/successors
"""
# TODO: rewrite this method to call substitute_node_with_dag
wires = wires or []
if op.name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% op.name)
self._check_wires_list(wires, op, input_circuit)
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: (QuantumRegister(1, 'proxy'), 0) for w in wires}
add_qregs = self._check_edgemap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Iterate through the nodes of self and replace the selected nodes
# by iterating through the input_circuit, constructing and
# checking the validity of the wire_map for each replacement
# NOTE: We do not replace conditioned gates. One way to implement
# this later is to add or update the conditions of each gate
# that we add from the input_circuit.
self.basis = union_basis
self.gates = union_gates
for n in self.node_nums_in_topological_order():
nd = self.multi_graph.node[n]
if nd["type"] == "op" and nd["op"] == op:
if nd["condition"] is None:
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"], nd["cargs"]]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map)
pred_map, succ_map = self._make_pred_succ_maps(n)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(n)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map,
md["condition"])
m_qargs = [wire_map.get(x, x) for x in md["qargs0"]]
m_cargs = [wire_map.get(x, x) for x in md["cargs0"]]
self._add_op_node(md["op"], m_qargs, m_cargs, condition)
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter,
name="%s[%s]" % (q[0].name, q[1]),
wire=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w],
full_succ_map[w],
name="%s[%s]" % (w[0].name, w[1]),
wire=w)
o_pred = list(self.multi_graph.predecessors(
self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise DAGCircuitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise DAGCircuitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(
p[0], self.output_map[w])
def substitute_node_with_dag(self, node, input_dag, wires=None):
"""Replace one node with dag.
Args:
node (int): node of self.multi_graph (of type "op") to substitute
input_dag (DAGCircuit): circuit that will substitute the node
wires (list[(Register, index)]): gives an order for (qu)bits
in the input circuit. This order gets matched to the node wires
by qargs first, then cargs, then conditions.
Raises:
DAGCircuitError: if met with unexpected predecessor/successors
"""
nd = self.multi_graph.node[node]
condition = nd["condition"]
# the decomposition rule must be amended if used in a
# conditional context. delete the op nodes and replay
# them with the condition.
if condition:
input_dag.add_creg(condition[0])
to_replay = []
for n_it in nx.topological_sort(input_dag.multi_graph):
n = input_dag.multi_graph.nodes[n_it]
if n["type"] == "op":
n["op"].control = condition
to_replay.append(n)
for n in input_dag.get_op_nodes():
input_dag._remove_op_node(n)
for n in to_replay:
input_dag.apply_operation_back(n["op"], condition=condition)
if wires is None:
qwires = [w for w in input_dag.wires if isinstance(w[0], QuantumRegister)]
cwires = [w for w in input_dag.wires if isinstance(w[0], ClassicalRegister)]
wires = qwires + cwires
self._check_wires_list(wires, nd["op"], input_dag, nd["condition"])
union_basis = self._make_union_basis(input_dag)
union_gates = self._make_union_gates(input_dag)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: QuantumRegister(1, 'proxy') for w in wires}
add_qregs = self._check_edgemap_registers(proxy_map,
input_dag.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(proxy_map,
input_dag.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Replace the node by iterating through the input_circuit.
# Constructing and checking the validity of the wire_map.
# If a gate is conditioned, we expect the replacement subcircuit
# to depend on those control bits as well.
self.basis = union_basis
self.gates = union_gates
if nd["type"] != "op":
raise DAGCircuitError("expected node type \"op\", got %s"
% nd["type"])
condition_bit_list = self._bits_in_condition(nd["condition"])
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"],
nd["cargs"],
condition_bit_list]
for i in s])}
self._check_wiremap_validity(wire_map, wires, self.input_map)
pred_map, succ_map = self._make_pred_succ_maps(node)
full_pred_map, full_succ_map = self._full_pred_succ_maps(pred_map, succ_map,
input_dag, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(node)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_dag.multi_graph):
md = input_dag.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map, md["condition"])
m_qargs = list(map(lambda x: wire_map.get(x, x),
md["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x),
md["cargs"]))
self._add_op_node(md["op"], m_qargs, m_cargs, condition)
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter,
name="%s[%s]" % (q[0].name, q[1]),
wire=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w],
full_succ_map[w],
name="%s[%s]" % (w[0].name, w[1]),
wire=w)
o_pred = list(self.multi_graph.predecessors(self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise DAGCircuitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise DAGCircuitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(p[0], self.output_map[w])
def get_op_nodes(self, op=None, data=False):
"""Get the list of "op" nodes in the dag.
Args:
op (Type): Instruction subclass op nodes to return. if op=None, return
all op nodes.
data (bool): Default: False. If True, return a list of tuple
(node_id, node_data). If False, return a list of int (node_id)
Returns:
list: the list of node ids containing the given op.
"""
nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data["type"] == "op":
if op is None or isinstance(node_data["op"], op):
nodes.append((node_id, node_data))
if not data:
nodes = [n[0] for n in nodes]
return nodes
def get_gate_nodes(self, data=False):
"""Get the list of gate nodes in the dag.
Args:
data (bool): Default: False. If True, return a list of tuple
(node_id, node_data). If False, return a list of int (node_id)
Returns:
list: the list of node ids that represent gates.
"""
nodes = []
for node_id, node_data in self.get_op_nodes(data=True):
if isinstance(node_data['op'], Gate):
nodes.append((node_id, node_data))
if not data:
nodes = [n[0] for n in nodes]
return nodes
def get_named_nodes(self, *names):
"""Get the set of "op" nodes with the given name."""
named_nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data['type'] == 'op' and node_data['op'].name in names:
named_nodes.append(node_id)
return named_nodes
def get_2q_nodes(self):
"""Get list of 2-qubit nodes."""
two_q_nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data['type'] == 'op' and len(node_data['qargs']) == 2:
two_q_nodes.append(self.multi_graph.node[node_id])
return two_q_nodes
def get_3q_or_more_nodes(self):
"""Get list of 3-or-more-qubit nodes: (id, data)."""
three_q_nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data['type'] == 'op' and len(node_data['qargs']) >= 3:
three_q_nodes.append((node_id, self.multi_graph.node[node_id]))
return three_q_nodes
def successors(self, node):
"""Returns the successors of a node."""
return self.multi_graph.successors(node)
def ancestors(self, node):
"""Returns the ancestors of a node."""
return nx.ancestors(self.multi_graph, node)
def descendants(self, node):
"""Returns the descendants of a node."""
return nx.descendants(self.multi_graph, node)
def quantum_successors(self, node):
"""Returns the successors of a node that are connected by a quantum edge"""
successors = []
for successor in self.successors(node):
if isinstance(self.multi_graph.get_edge_data(node, successor, key=0)['wire'][0],
QuantumRegister):
successors.append(successor)
return successors
def _remove_op_node(self, n):
"""Remove an operation node n.
Add edges from predecessors to successors.
"""
pred_map, succ_map = self._make_pred_succ_maps(n)
self.multi_graph.remove_node(n)
for w in pred_map.keys():
self.multi_graph.add_edge(pred_map[w], succ_map[w],
name="%s[%s]" % (w[0].name, w[1]), wire=w)
def remove_ancestors_of(self, node):
"""Remove all of the ancestor operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
# TODO: probably better to do all at once using
# multi_graph.remove_nodes_from; same for related functions ...
for n in anc:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_descendants_of(self, node):
"""Remove all of the descendant operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
for n in dec:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nonancestors_of(self, node):
"""Remove all of the non-ancestors operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(anc))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nondescendants_of(self, node):
"""Remove all of the non-descendants operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(dec))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def layers(self):
"""Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit.
A layer is a circuit whose gates act on disjoint qubits, i.e.
a layer has depth 1. The total number of layers equals the
circuit depth d. The layers are indexed from 0 to d-1 with the
earliest layer at index 0. The layers are constructed using a
greedy algorithm. Each returned layer is a dict containing
{"graph": circuit graph, "partition": list of qubit lists}.
TODO: Gates that use the same cbits will end up in different
layers as this is currently implemented. This may not be
the desired behavior.
"""
graph_layers = self.multigraph_layers()
try:
next(graph_layers) # Remove input nodes
except StopIteration:
return
def nodes_data(nodes):
"""Construct full nodes from just node ids."""
return ((node_id, self.multi_graph.nodes[node_id]) for node_id in nodes)
for graph_layer in graph_layers:
# Get the op nodes from the layer, removing any input and output nodes.
op_nodes = [node for node in nodes_data(graph_layer) if node[1]["type"] == "op"]
# Stop yielding once there are no more op_nodes in a layer.
if not op_nodes:
return
# Construct a shallow copy of self
new_layer = copy.copy(self)
new_layer.multi_graph = nx.MultiDiGraph()
new_layer.multi_graph.add_nodes_from(nodes_data(self.input_map.values()))
new_layer.multi_graph.add_nodes_from(nodes_data(self.output_map.values()))
# The quantum registers that have an operation in this layer.
support_list = [
op_node[1]["qargs"]
for op_node in op_nodes
if op_node[1]["op"].name not in {"barrier", "snapshot", "save", "load", "noise"}
]
new_layer.multi_graph.add_nodes_from(op_nodes)
# Now add the edges to the multi_graph
# By default we just wire inputs to the outputs.
wires = {self.input_map[wire]: self.output_map[wire]
for wire in self.wires}
# Wire inputs to op nodes, and op nodes to outputs.
for op_node in op_nodes:
args = self._bits_in_condition(op_node[1]["condition"]) \
+ op_node[1]["cargs"] + op_node[1]["qargs"]
arg_ids = (self.input_map[(arg[0], arg[1])] for arg in args)
for arg_id in arg_ids:
wires[arg_id], wires[op_node[0]] = op_node[0], wires[arg_id]
# Add wiring to/from the operations and between unused inputs & outputs.
new_layer.multi_graph.add_edges_from(wires.items())
yield {"graph": new_layer, "partition": support_list}
def serial_layers(self):
"""Yield a layer for all gates of this circuit.
A serial layer is a circuit with one gate. The layers have the
same structure as in layers().
"""
for n in self.node_nums_in_topological_order():
nxt_nd = self.multi_graph.node[n]
if nxt_nd["type"] == "op":
new_layer = DAGCircuit()
for qreg in self.qregs.values():
new_layer.add_qreg(qreg)
for creg in self.cregs.values():
new_layer.add_creg(creg)
new_layer.basis = self.basis.copy()
new_layer.gates = self.gates.copy()
# Save the support of the operation we add to the layer
support_list = []
# Operation data
op = copy.copy(nxt_nd["op"])
qa = copy.copy(nxt_nd["qargs"])
ca = copy.copy(nxt_nd["cargs"])
co = copy.copy(nxt_nd["condition"])
_ = self._bits_in_condition(co)
# Add node to new_layer
new_layer.apply_operation_back(op, qa, ca, co)
# Add operation to partition
if nxt_nd["name"] not in ["barrier",
"snapshot", "save", "load", "noise"]:
support_list.append(list(qa))
l_dict = {"graph": new_layer, "partition": support_list}
yield l_dict
def multigraph_layers(self):
"""Yield layers of the multigraph."""
predecessor_count = dict() # Dict[node, predecessors not visited]
cur_layer = [node for node in self.input_map.values()]
yield cur_layer
next_layer = []
while cur_layer:
for node in cur_layer:
# Count multiedges with multiplicity.
for successor in self.multi_graph.successors(node):
multiplicity = self.multi_graph.number_of_edges(node, successor)
if successor in predecessor_count:
predecessor_count[successor] -= multiplicity
else:
predecessor_count[successor] = \
self.multi_graph.in_degree(successor) - multiplicity
if predecessor_count[successor] == 0:
next_layer.append(successor)
del predecessor_count[successor]
yield next_layer
cur_layer = next_layer
next_layer = []
def collect_runs(self, namelist):
"""Return a set of runs of "op" nodes with the given names.
For example, "... h q[0]; cx q[0],q[1]; cx q[0],q[1]; h q[1]; .."
would produce the tuple of cx nodes as an element of the set returned
from a call to collect_runs(["cx"]). If instead the cx nodes were
"cx q[0],q[1]; cx q[1],q[0];", the method would still return the
pair in a tuple. The namelist can contain names that are not
in the circuit's basis.
Nodes must have only one successor to continue the run.
"""
group_list = []
# Iterate through the nodes of self in topological order
# and form tuples containing sequences of gates
# on the same qubit(s).
tops_node = list(self.node_nums_in_topological_order())
nodes_seen = dict(zip(tops_node, [False] * len(tops_node)))
for node in tops_node:
nd = self.multi_graph.node[node]
if nd["type"] == "op" and nd["name"] in namelist \
and not nodes_seen[node]:
group = [node]
nodes_seen[node] = True
s = list(self.multi_graph.successors(node))
while len(s) == 1 and \
self.multi_graph.node[s[0]]["type"] == "op" and \
self.multi_graph.node[s[0]]["name"] in namelist:
group.append(s[0])
nodes_seen[s[0]] = True
s = list(self.multi_graph.successors(s[0]))
if len(group) > 1:
group_list.append(tuple(group))
return set(group_list)
def count_ops(self):
"""Count the occurrences of operation names.
Returns a dictionary of counts keyed on the operation name.
"""
op_dict = {}
for node in self.node_nums_in_topological_order():
nd = self.multi_graph.node[node]
name = nd["name"]
if nd["type"] == "op":
if name not in op_dict:
op_dict[name] = 1
else:
op_dict[name] += 1
return op_dict
def properties(self):
"""Return a dictionary of circuit properties."""
summary = {"size": self.size(),
"depth": self.depth(),
"width": self.width(),
"bits": self.num_cbits(),
"factors": self.num_tensor_factors(),
"operations": self.count_ops()}
return summary
<|code_end|>
|
qiskit/converters/circuit_to_dag.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Helper function for converting a circuit to a dag"""
from qiskit.circuit.compositegate import CompositeGate
from qiskit.dagcircuit._dagcircuit import DAGCircuit
def circuit_to_dag(circuit):
"""Build a ``DAGCircuit`` object from a ``QuantumCircuit``.
Args:
circuit (QuantumCircuit): the input circuit.
Return:
DAGCircuit: the DAG representing the input circuit.
"""
dagcircuit = DAGCircuit()
dagcircuit.name = circuit.name
for register in circuit.qregs:
dagcircuit.add_qreg(register)
for register in circuit.cregs:
dagcircuit.add_creg(register)
# Add user gate definitions
for name, data in circuit.definitions.items():
dagcircuit.add_basis_element(name, data["n_bits"], 0, data["n_args"])
dagcircuit.add_gate_data(name, data)
# Add instructions
builtins = {
"U": ["U", 1, 0, 3],
"CX": ["CX", 2, 0, 0],
"measure": ["measure", 1, 1, 0],
"reset": ["reset", 1, 0, 0],
"barrier": ["barrier", -1, 0, 0]
}
# Add simulator instructions
simulator_instructions = {
"snapshot": ["snapshot", -1, 0, 1],
"save": ["save", -1, 0, 1],
"load": ["load", -1, 0, 1],
"noise": ["noise", -1, 0, 1]
}
for main_instruction in circuit.data:
# TODO: generate definitions and nodes for CompositeGates,
# for now simply drop their instructions into the DAG
instruction_list = []
is_composite = isinstance(main_instruction, CompositeGate)
if is_composite:
instruction_list = main_instruction.instruction_list()
else:
instruction_list.append(main_instruction)
for instruction in instruction_list:
# Add OpenQASM built-in gates on demand
if instruction.name in builtins:
dagcircuit.add_basis_element(*builtins[instruction.name])
# Add simulator extension instructions
if instruction.name in simulator_instructions:
dagcircuit.add_basis_element(*simulator_instructions[instruction.name])
# Get arguments for classical control (if any)
if instruction.control is None:
control = None
else:
control = (instruction.control[0], instruction.control[1])
def duplicate_instruction(inst):
"""Create a fresh instruction from an input instruction."""
if inst.name == 'barrier':
params = [inst.qargs]
elif inst.name in simulator_instructions.keys():
params = inst.params + [inst.qargs] + [inst.circuit]
else:
params = inst.params + inst.qargs + inst.cargs
new_inst = inst.__class__(*params)
return new_inst
inst = duplicate_instruction(instruction)
dagcircuit.apply_operation_back(inst, inst.qargs,
inst.cargs, control)
return dagcircuit
<|code_end|>
qiskit/dagcircuit/_dagcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Object to represent a quantum circuit as a directed acyclic graph.
The nodes in the graph are either input/output nodes or operation nodes.
The operation nodes are elements of a basis that is part of the circuit.
The QASM definitions of the basis elements are carried with the circuit.
The edges correspond to qubits or bits in the circuit. A directed edge
from node A to node B means that the (qu)bit passes from the output of A
to the input of B. The object's methods allow circuits to be constructed,
composed, and modified. Some natural properties like depth can be computed
directly from the graph.
"""
import re
from collections import OrderedDict
import copy
import itertools
import networkx as nx
from qiskit.circuit.quantumregister import QuantumRegister
from qiskit.circuit.classicalregister import ClassicalRegister
from qiskit.circuit.gate import Gate
from .exceptions import DAGCircuitError
class DAGCircuit:
"""
Quantum circuit as a directed acyclic graph.
There are 3 types of nodes in the graph: inputs, outputs, and operations.
The nodes are connected by directed edges that correspond to qubits and
bits.
"""
# pylint: disable=invalid-name
def __init__(self):
"""Create an empty circuit."""
# Circuit name. Generally, this corresponds to the name
# of the QuantumCircuit from which the DAG was generated.
self.name = None
# Set of wires (Register,idx) in the dag
self.wires = []
# Map from wire (Register,idx) to input nodes of the graph
self.input_map = OrderedDict()
# Map from wire (Register,idx) to output nodes of the graph
self.output_map = OrderedDict()
# Running count of the total number of nodes
self.node_counter = 0
# Map of user defined gates to ast nodes defining them
self.gates = OrderedDict()
# Map of named operations in this circuit and their signatures.
# The signature is an integer tuple (nq,nc,np) specifying the
# number of input qubits, input bits, and real parameters.
# The definition is external to the circuit object.
self.basis = OrderedDict()
self.add_basis_element(name="U", number_qubits=1,
number_classical=0, number_parameters=3)
self.add_basis_element("CX", 2, 0, 0)
self.add_basis_element("measure", 1, 1, 0)
self.add_basis_element("reset", 1, 0, 0)
self.add_basis_element("barrier", -1)
# Directed multigraph whose nodes are inputs, outputs, or operations.
# Operation nodes have equal in- and out-degrees and carry
# additional data about the operation, including the argument order
# and parameter values.
# Input nodes have out-degree 1 and output nodes have in-degree 1.
# Edges carry wire labels (reg,idx) and each operation has
# corresponding in- and out-edges with the same wire labels.
self.multi_graph = nx.MultiDiGraph()
# Map of qreg name to QuantumRegister object
self.qregs = OrderedDict()
# Map of creg name to ClassicalRegister object
self.cregs = OrderedDict()
def get_qubits(self):
"""Return a list of qubits as (QuantumRegister, index) pairs."""
return [(v, i) for k, v in self.qregs.items() for i in range(v.size)]
def get_bits(self):
"""Return a list of bits as (ClassicalRegister, index) pairs."""
return [(v, i) for k, v in self.cregs.items() for i in range(v.size)]
# TODO: unused function. is it needed?
def rename_register(self, regname, newname):
"""Rename a classical or quantum register throughout the circuit.
regname = existing register name string
newname = replacement register name string
"""
if regname == newname:
return
if newname in self.qregs or newname in self.cregs:
raise DAGCircuitError("duplicate register name %s" % newname)
if regname not in self.qregs and regname not in self.cregs:
raise DAGCircuitError("no register named %s" % regname)
if regname in self.qregs:
reg = self.qregs[regname]
reg.name = newname
self.qregs[newname] = reg
self.qregs.pop(regname, None)
if regname in self.cregs:
reg = self.cregs[regname]
reg.name = newname
self.qregs[newname] = reg
self.qregs.pop(regname, None)
# n node d = data
for _, d in self.multi_graph.nodes(data=True):
if d["type"] == "in" or d["type"] == "out":
if regname in d["name"]:
d["name"] = re.sub(regname, newname, d["name"])
elif d["type"] == "op":
qa = []
for a in d["qargs"]:
if a[0] == regname:
a = (newname, a[1])
qa.append(a)
d["qargs"] = qa
ca = []
for a in d["cargs"]:
if a[0] == regname:
a = (newname, a[1])
ca.append(a)
d["cargs"] = ca
if d["condition"] is not None:
if d["condition"][0] == regname:
d["condition"] = (newname, d["condition"][1])
# eX = edge, d= data
for _, _, d in self.multi_graph.edges(data=True):
if regname in d["name"]:
d["name"] = re.sub(regname, newname, d["name"])
def remove_all_ops_named(self, opname):
"""Remove all operation nodes with the given name."""
for n in self.get_named_nodes(opname):
self._remove_op_node(n)
def add_qreg(self, qreg):
"""Add all wires in a quantum register."""
if not isinstance(qreg, QuantumRegister):
raise DAGCircuitError("not a QuantumRegister instance.")
if qreg.name in self.qregs:
raise DAGCircuitError("duplicate register %s" % qreg.name)
self.qregs[qreg.name] = qreg
for j in range(qreg.size):
self._add_wire((qreg, j))
def add_creg(self, creg):
"""Add all wires in a classical register."""
if not isinstance(creg, ClassicalRegister):
raise DAGCircuitError("not a ClassicalRegister instance.")
if creg.name in self.cregs:
raise DAGCircuitError("duplicate register %s" % creg.name)
self.cregs[creg.name] = creg
for j in range(creg.size):
self._add_wire((creg, j))
def _add_wire(self, wire):
"""Add a qubit or bit to the circuit.
Args:
wire (tuple): (Register,int) containing a register instance and index
This adds a pair of in and out nodes connected by an edge.
Raises:
DAGCircuitError: if trying to add duplicate wire
"""
if wire not in self.wires:
self.wires.append(wire)
self.node_counter += 1
self.input_map[wire] = self.node_counter
self.node_counter += 1
self.output_map[wire] = self.node_counter
in_node = self.input_map[wire]
out_node = self.output_map[wire]
self.multi_graph.add_edge(in_node, out_node)
self.multi_graph.node[in_node]["type"] = "in"
self.multi_graph.node[out_node]["type"] = "out"
self.multi_graph.node[in_node]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.node[out_node]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.node[in_node]["wire"] = wire
self.multi_graph.node[out_node]["wire"] = wire
self.multi_graph.adj[in_node][out_node][0]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.adj[in_node][out_node][0]["wire"] = wire
else:
raise DAGCircuitError("duplicate wire %s" % (wire,))
def add_basis_element(self, name, number_qubits,
number_classical=0, number_parameters=0):
"""Add an operation to the basis.
name is string label for operation
number_qubits is number of qubit arguments
number_classical is number of bit arguments
number_parameters is number of real parameters
The parameters (nq,nc,np) are ignored for the special case
when name = "barrier". The barrier instruction has a variable
number of qubit arguments.
"""
if name not in self.basis:
self.basis[name] = (
number_qubits,
number_classical,
number_parameters)
if name in self.gates:
if self.gates[name]["n_args"] != number_parameters or \
self.gates[name]["n_bits"] != number_qubits or number_classical != 0:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def add_gate_data(self, name, gatedata):
"""Add the definition of a gate.
gatedata is dict with fields:
"print" = True or False
"opaque" = True or False
"n_args" = number of real parameters
"n_bits" = number of qubits
"args" = list of parameter names
"bits" = list of qubit names
"body" = GateBody AST node
"""
if name not in self.gates:
self.gates[name] = gatedata
if name in self.basis:
if self.basis[name][0] != self.gates[name]["n_bits"] or \
self.basis[name][1] != 0 or \
self.basis[name][2] != self.gates[name]["n_args"]:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def _check_basis_data(self, op, qargs, cargs):
"""Check the arguments against the data for this operation.
Args:
op (Instruction): a quantum operation
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple]): cbits that op will be applied to
Raises:
DAGCircuitError: If the check fails.
"""
# Check that we have this operation
if op.name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations" % op.name)
# Check the number of arguments matches the signature
if op.name in ["barrier"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s" % op.name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s" % op.name)
elif op.name in ["snapshot", "noise", "save", "load"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s" % op.name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s" % op.name)
else:
if len(qargs) != self.basis[op.name][0]:
raise DAGCircuitError("incorrect number of qubits for %s" % op.name)
if len(cargs) != self.basis[op.name][1]:
raise DAGCircuitError("incorrect number of bits for %s" % op.name)
def _check_condition(self, name, condition):
"""Verify that the condition is valid.
Args:
name (string): used for error reporting
condition (tuple or None): a condition tuple (ClassicalRegister,int)
Raises:
DAGCircuitError: if conditioning on an invalid register
"""
# Verify creg exists
if condition is not None and condition[0].name not in self.cregs:
raise DAGCircuitError("invalid creg in condition for %s" % name)
def _check_bits(self, args, amap):
"""Check the values of a list of (qu)bit arguments.
For each element of args, check that amap contains it.
Args:
args (list): (register,idx) tuples
amap (dict): a dictionary keyed on (register,idx) tuples
Raises:
DAGCircuitError: if a qubit is not contained in amap
"""
# Check for each wire
for wire in args:
if wire not in amap:
raise DAGCircuitError("(qu)bit %s[%d] not found" % (wire[0].name, wire[1]))
def _bits_in_condition(self, cond):
"""Return a list of bits in the given condition.
Args:
cond (tuple or None): optional condition (ClassicalRegister, int)
Returns:
list[(ClassicalRegister, idx)]: list of bits
"""
all_bits = []
if cond is not None:
all_bits.extend([(cond[0], j) for j in range(self.cregs[cond[0].name].size)])
return all_bits
def _add_op_node(self, op, qargs, cargs, condition=None):
"""Add a new operation node to the graph and assign properties.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list): list of quantum wires to attach to.
cargs (list): list of classical wires to attach to.
condition (tuple or None): optional condition (ClassicalRegister, int)
"""
# Add a new operation node to the graph
self.node_counter += 1
self.multi_graph.add_node(self.node_counter)
# Update the operation itself. TODO: remove after qargs not connected to op
op.qargs = qargs
op.cargs = cargs
# Update that operation node's data
self.multi_graph.node[self.node_counter]["type"] = "op"
self.multi_graph.node[self.node_counter]["op"] = op
self.multi_graph.node[self.node_counter]["name"] = op.name
self.multi_graph.node[self.node_counter]["qargs"] = qargs
self.multi_graph.node[self.node_counter]["cargs"] = cargs
self.multi_graph.node[self.node_counter]["condition"] = condition
def apply_operation_back(self, op, qargs=None, cargs=None, condition=None):
"""Apply an operation to the output of the circuit.
TODO: make `qargs` and `cargs` mandatory, when they are dropped from op.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple]): cbits that op will be applied to
condition (tuple or None): optional condition (ClassicalRegister, int)
Raises:
DAGCircuitError: if a leaf node is connected to multiple outputs
"""
qargs = qargs or op.qargs
cargs = cargs or op.cargs
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(op, qargs, cargs)
self._check_condition(op.name, condition)
self._check_bits(qargs, self.output_map)
self._check_bits(all_cbits, self.output_map)
self._add_op_node(op, qargs, cargs, condition)
# Add new in-edges from predecessors of the output nodes to the
# operation node while deleting the old in-edges of the output nodes
# and adding new edges from the operation node to each output node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.predecessors(self.output_map[q]))
if len(ie) != 1:
raise DAGCircuitError("output node has multiple in-edges")
self.multi_graph.add_edge(ie[0], self.node_counter,
name="%s[%s]" % (q[0].name, q[1]), wire=q)
self.multi_graph.remove_edge(ie[0], self.output_map[q])
self.multi_graph.add_edge(self.node_counter, self.output_map[q],
name="%s[%s]" % (q[0].name, q[1]), wire=q)
def apply_operation_front(self, op, qargs=None, cargs=None, condition=None):
"""Apply an operation to the input of the circuit.
TODO: make `qargs` and `cargs` mandatory, when they are dropped from op.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple]): cbits that op will be applied to
condition (tuple or None): optional condition (ClassicalRegister, value)
Raises:
DAGCircuitError: if initial nodes connected to multiple out edges
"""
qargs = qargs or op.qargs
cargs = cargs or op.cargs
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(op, qargs, cargs)
self._check_condition(op.name, condition)
self._check_bits(qargs, self.input_map)
self._check_bits(all_cbits, self.input_map)
self._add_op_node(op, qargs, cargs, condition)
# Add new out-edges to successors of the input nodes from the
# operation node while deleting the old out-edges of the input nodes
# and adding new edges to the operation node from each input node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.successors(self.input_map[q]))
if len(ie) != 1:
raise DAGCircuitError("input node has multiple out-edges")
self.multi_graph.add_edge(self.node_counter, ie[0],
name="%s[%s]" % (q[0].name, q[1]), wire=q)
self.multi_graph.remove_edge(self.input_map[q], ie[0])
self.multi_graph.add_edge(self.input_map[q], self.node_counter,
name="%s[%s]" % (q[0].name, q[1]), wire=q)
def _make_union_basis(self, input_circuit):
"""Return a new basis map.
The new basis is a copy of self.basis with
new elements of input_circuit.basis added.
input_circuit is a DAGCircuit
"""
union_basis = self.basis.copy()
for g in input_circuit.basis:
if g not in union_basis:
union_basis[g] = input_circuit.basis[g]
if union_basis[g] != input_circuit.basis[g]:
raise DAGCircuitError("incompatible basis")
return union_basis
def _make_union_gates(self, input_circuit):
"""Return a new gates map.
The new gates are a copy of self.gates with
new elements of input_circuit.gates added.
input_circuit is a DAGCircuit
NOTE: gates in input_circuit that are also in self must
be *identical* to the gates in self
"""
union_gates = {}
for k, v in self.gates.items():
union_gates[k] = v
for k, v in input_circuit.gates.items():
if k not in union_gates:
union_gates[k] = v
if union_gates[k]["opaque"] != input_circuit.gates[k]["opaque"] or \
union_gates[k]["n_args"] != input_circuit.gates[k]["n_args"] or \
union_gates[k]["n_bits"] != input_circuit.gates[k]["n_bits"] or \
union_gates[k]["args"] != input_circuit.gates[k]["args"] or \
union_gates[k]["bits"] != input_circuit.gates[k]["bits"]:
raise DAGCircuitError("inequivalent gate definitions for %s"
% k)
return union_gates
def _check_edgemap_registers(self, edge_map, keyregs, valregs, valreg=True):
"""Check that wiremap neither fragments nor leaves duplicate registers.
1. There are no fragmented registers. A register in keyregs
is fragmented if not all of its (qu)bits are renamed by edge_map.
2. There are no duplicate registers. A register is duplicate if
it appears in both self and keyregs but not in edge_map.
Args:
edge_map (dict): map from (reg,idx) in keyregs to (reg,idx) in valregs
keyregs (dict): a map from register names to Register objects
valregs (dict): a map from register names to Register objects
valreg (bool): if False the method ignores valregs and does not
add regs for bits in the edge_map image that don't appear in valregs
Returns:
set(Register): the set of regs to add to self
Raises:
DAGCircuitError: if the wiremap fragments, or duplicates exist
"""
# FIXME: some mixing of objects and strings here are awkward (due to
# self.qregs/self.cregs still keying on string.
add_regs = set()
reg_frag_chk = {}
for v in keyregs.values():
reg_frag_chk[v] = {j: False for j in range(len(v))}
for k in edge_map.keys():
if k[0].name in keyregs:
reg_frag_chk[k[0]][k[1]] = True
for k, v in reg_frag_chk.items():
s = set(v.values())
if len(s) == 2:
raise DAGCircuitError("edge_map fragments reg %s" % k)
elif s == set([False]):
if k in self.qregs.values() or k in self.cregs.values():
raise DAGCircuitError("unmapped duplicate reg %s" % k)
else:
# Add registers that appear only in keyregs
add_regs.add(k)
else:
if valreg:
# If mapping to a register not in valregs, add it.
# (k,0) exists in edge_map because edge_map doesn't
# fragment k
if not edge_map[(k, 0)][0].name in valregs:
size = max(map(lambda x: x[1],
filter(lambda x: x[0] == edge_map[(k, 0)][0],
edge_map.values())))
qreg = QuantumRegister(size + 1, edge_map[(k, 0)][0].name)
add_regs.add(qreg)
return add_regs
def _check_wiremap_validity(self, wire_map, keymap, valmap):
"""Check that the wiremap is consistent.
Check that the wiremap refers to valid wires and that
those wires have consistent types.
Args:
wire_map (dict): map from (register,idx) in keymap to
(register,idx) in valmap
keymap (dict): a map whose keys are wire_map keys
valmap (dict): a map whose keys are wire_map values
Raises:
DAGCircuitError: if wire_map not valid
"""
for k, v in wire_map.items():
kname = "%s[%d]" % (k[0].name, k[1])
vname = "%s[%d]" % (v[0].name, v[1])
if k not in keymap:
raise DAGCircuitError("invalid wire mapping key %s" % kname)
if v not in valmap:
raise DAGCircuitError("invalid wire mapping value %s" % vname)
if type(k) is not type(v):
raise DAGCircuitError("inconsistent wire_map at (%s,%s)" %
(kname, vname))
def _map_condition(self, wire_map, condition):
"""Use the wire_map dict to change the condition tuple's creg name.
Args:
wire_map (dict): a map from wires to wires
condition (tuple): (ClassicalRegister,int)
Returns:
tuple(ClassicalRegister,int): new condition
"""
if condition is None:
new_condition = None
else:
# Map the register name, using fact that registers must not be
# fragmented by the wire_map (this must have been checked
# elsewhere)
bit0 = (condition[0], 0)
new_condition = (wire_map.get(bit0, bit0)[0], condition[1])
return new_condition
def extend_back(self, dag, edge_map=None):
"""Add `dag` at the end of `self`, using `edge_map`.
"""
edge_map = edge_map or {}
for qreg in dag.qregs.values():
if qreg.name not in self.qregs:
self.add_qreg(QuantumRegister(qreg.size, qreg.name))
edge_map.update([(qbit, qbit) for qbit in qreg if qbit not in edge_map])
for creg in dag.cregs.values():
if creg.name not in self.cregs:
self.add_creg(ClassicalRegister(creg.size, creg.name))
edge_map.update([(cbit, cbit) for cbit in creg if cbit not in edge_map])
self.compose_back(dag, edge_map)
def compose_back(self, input_circuit, edge_map=None):
"""Apply the input circuit to the output of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of input qubits of the input circuit are mapped
to a subset of output qubits of this circuit.
Args:
input_circuit (DAGCircuit): circuit to append
edge_map (dict): map {(Register, int): (Register, int)}
from the output wires of input_circuit to input wires
of self.
Raises:
DAGCircuitError: if missing, duplicate or incosistent wire
"""
edge_map = edge_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map for duplicate values
if len(set(edge_map.values())) != len(edge_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_edgemap_registers(edge_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(edge_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(edge_map, input_circuit.input_map,
self.output_map)
# Compose
self.basis = union_basis
self.gates = union_gates
for node in nx.topological_sort(input_circuit.multi_graph):
nd = input_circuit.multi_graph.node[node]
if nd["type"] == "in":
# if in wire_map, get new name, else use existing name
m_wire = edge_map.get(nd["wire"], nd["wire"])
# the mapped wire should already exist
if m_wire not in self.output_map:
raise DAGCircuitError("wire %s[%d] not in self" % (m_wire[0].name, m_wire[1]))
if nd["wire"] not in input_circuit.wires:
raise DAGCircuitError("inconsistent wire type for %s[%d] in input_circuit"
% (nd["wire"][0].name, nd["wire"][1]))
elif nd["type"] == "out":
# ignore output nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(edge_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: edge_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: edge_map.get(x, x), nd["cargs"]))
self.apply_operation_back(nd["op"], m_qargs, m_cargs, condition)
else:
raise DAGCircuitError("bad node type %s" % nd["type"])
# FIXME: this does not work as expected. it is also not used anywhere
def compose_front(self, input_circuit, wire_map=None):
"""Apply the input circuit to the input of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of output qubits of the input circuit are mapped
to a subset of input qubits of this circuit.
Args:
input_circuit (DAGCircuit): circuit to append
wire_map (dict): map {(Register, int): (Register, int)}
from the output wires of input_circuit to input wires
of self.
Raises:
DAGCircuitError: missing, duplicate or inconsistent wire
"""
wire_map = wire_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_edgemap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.output_map,
self.input_map)
# Compose
self.basis = union_basis
self.gates = union_gates
for n in reversed(list(nx.topological_sort(input_circuit.multi_graph))):
nd = input_circuit.multi_graph.node[n]
if nd["type"] == "out":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["wire"], nd["wire"])
# the mapped wire should already exist
if m_name not in self.input_map:
raise DAGCircuitError("wire %s[%d] not in self" % (m_name[0].name, m_name[1]))
if nd["wire"] not in input_circuit.wires:
raise DAGCircuitError(
"inconsistent wire for %s[%d] in input_circuit"
% (nd["wire"][0].name, nd["wire"][1]))
elif nd["type"] == "in":
# ignore input nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
self.apply_operation_front(nd["op"], condition)
else:
raise DAGCircuitError("bad node type %s" % nd["type"])
def size(self):
"""Return the number of operations."""
return self.multi_graph.order() - 2 * len(self.wires)
def depth(self):
"""Return the circuit depth.
Returns:
int: the circuit depth
Raises:
DAGCircuitError: if not a directed acyclic graph
"""
if not nx.is_directed_acyclic_graph(self.multi_graph):
raise DAGCircuitError("not a DAG")
return nx.dag_longest_path_length(self.multi_graph) - 1
def width(self):
"""Return the total number of qubits used by the circuit."""
return len(self.wires) - self.num_cbits()
def num_cbits(self):
"""Return the total number of bits used by the circuit."""
return sum(creg.size for creg in self.cregs.values())
def num_tensor_factors(self):
"""Compute how many components the circuit can decompose into."""
return nx.number_weakly_connected_components(self.multi_graph)
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.gates[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.gates[name]["n_args"] > 0:
out += "(" + ",".join(self.gates[name]["args"]) + ")"
out += " " + ",".join(self.gates[name]["bits"])
if self.gates[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.gates[name]["body"].qasm() + "}"
return out
def qasm(self, no_decls=False, qeflag=False, aliases=None, eval_symbols=False):
"""Return a string containing QASM for this circuit.
Args:
qeflag (bool): if True, add a line to include "qelib1.inc"
and only generate gate code for gates not in qelib1.
eval_symbols (bool): if True, evaluate all symbolic
expressions to their floating point representation.
no_decls (bool): if True, only print the instructions.
aliases (dict): if not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
Returns:
str: OpenQASM representation of the DAG
Raises:
DAGCircuitError: if dag nodes not in expected format
"""
# TODO: some of the input flags are not needed anymore
# Rename qregs if necessary
if aliases:
qregdata = OrderedDict()
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
# Write top matter
if no_decls:
out = ""
else:
printed_gates = []
out = "OPENQASM 2.0;\n"
if qeflag:
out += "include \"qelib1.inc\";\n"
for k, v in qregdata.items():
out += "qreg %s[%d];\n" % (k, v.size)
for k, v in self.cregs.items():
out += "creg %s[%d];\n" % (k, v.size)
omit = ["U", "CX", "measure", "reset", "barrier"]
# TODO: dagcircuit shouldn't know about extensions
if qeflag:
qelib = ["u3", "u2", "u1", "cx", "id", "x", "y", "z", "h",
"s", "sdg", "t", "tdg", "cz", "cy", "ccx", "cu1",
"cu3", "swap", "cswap", "u0", "rx", "ry", "rz",
"ch", "crz", "rzz"]
omit.extend(qelib)
printed_gates.extend(qelib)
simulator_instructions = ["snapshot", "save", "load", "noise", "wait"]
omit.extend(simulator_instructions)
for k in self.basis.keys():
if k not in omit:
if not self.gates[k]["opaque"]:
calls = self.gates[k]["body"].calls()
for c in calls:
if c not in printed_gates:
out += self._gate_string(c) + "\n"
printed_gates.append(c)
if k not in printed_gates:
out += self._gate_string(k) + "\n"
printed_gates.append(k)
# Write the instructions
for n in nx.lexicographical_topological_sort(
self.multi_graph, key=lambda x: (self.multi_graph.nodes[x]["type"],
self.multi_graph.nodes[x]["name"])):
nd = self.multi_graph.node[n]
if nd["type"] == "op":
if nd["condition"] is not None:
out += "if(%s==%d) " \
% (nd["condition"][0], nd["condition"][1])
if not nd["cargs"]:
nm = nd["op"].name
if aliases:
qarglist = map(lambda x: aliases[x], nd["qargs"])
else:
qarglist = nd["qargs"]
qarg = ",".join(map(lambda x: "%s[%d]" % (x[0].name, x[1]),
qarglist))
if nd["op"].params:
if eval_symbols:
param = ",".join(map(lambda x: str(x.evalf()),
nd["op"].params))
else:
param = ",".join(map(lambda x: x.replace("**", "^"),
map(str, nd["op"].params)))
out += "%s(%s) %s;\n" % (nm, param, qarg)
else:
out += "%s %s;\n" % (nm, qarg)
else:
if nd["op"].name == "measure":
if len(nd["cargs"]) != 1 or len(nd["qargs"]) != 1 \
or nd["op"].param:
raise DAGCircuitError("bad node data")
qname = nd["qargs"][0][0].name
qindex = nd["qargs"][0][1]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
out += "measure %s[%d] -> %s[%d];\n" \
% (qname,
qindex,
nd["cargs"][0][0].name,
nd["cargs"][0][1])
else:
raise DAGCircuitError("bad node data")
return out
def _check_wires_list(self, wires, op, input_circuit, condition=None):
"""Check that a list of wires satisfies some conditions.
- no duplicate names
- correct length for operation
- elements are wires of input_circuit
Raise an exception otherwise.
Args:
wires (list[register, index]): gives an order for (qu)bits
in the input_circuit that is replacing the operation.
op (Instruction): operation
input_circuit (DAGCircuit): replacement circuit for operation
condition (tuple or None): if this instance of the
operation is classically controlled by a (ClassicalRegister, int)
Raises:
DAGCircuitError: if check doesn't pass.
"""
if len(set(wires)) != len(wires):
raise DAGCircuitError("duplicate wires")
wire_tot = len(op.qargs) + len(op.cargs)
if condition is not None:
wire_tot += condition[0].size
if len(wires) != wire_tot:
raise DAGCircuitError("expected %d wires, got %d"
% (wire_tot, len(wires)))
for w in wires:
if w not in input_circuit.wires:
raise DAGCircuitError("wire (%s,%d) not in input circuit"
% (w[0], w[1]))
def _make_pred_succ_maps(self, n):
"""Return predecessor and successor dictionaries.
Args:
n (int): reference to self.multi_graph node id
Returns:
tuple(dict): tuple(predecessor_map, successor_map)
These map from wire (Register, int) to predecessor (successor)
nodes of n.
"""
pred_map = {e[2]['wire']: e[0] for e in
self.multi_graph.in_edges(nbunch=n, data=True)}
succ_map = {e[2]['wire']: e[1] for e in
self.multi_graph.out_edges(nbunch=n, data=True)}
return pred_map, succ_map
def _full_pred_succ_maps(self, pred_map, succ_map, input_circuit,
wire_map):
"""Map all wires of the input circuit.
Map all wires of the input circuit to predecessor and
successor nodes in self, keyed on wires in self.
Args:
pred_map (dict): comes from _make_pred_succ_maps
succ_map (dict): comes from _make_pred_succ_maps
input_circuit (DAGCircuit): the input circuit
wire_map (dict): the map from wires of input_circuit to wires of self
Returns:
tuple: full_pred_map, full_succ_map (dict, dict)
Raises:
DAGCircuitError: if more than one predecessor for output nodes
"""
full_pred_map = {}
full_succ_map = {}
for w in input_circuit.input_map:
# If w is wire mapped, find the corresponding predecessor
# of the node
if w in wire_map:
full_pred_map[wire_map[w]] = pred_map[wire_map[w]]
full_succ_map[wire_map[w]] = succ_map[wire_map[w]]
else:
# Otherwise, use the corresponding output nodes of self
# and compute the predecessor.
full_succ_map[w] = self.output_map[w]
full_pred_map[w] = self.multi_graph.predecessors(
self.output_map[w])[0]
if len(list(self.multi_graph.predecessors(self.output_map[w]))) != 1:
raise DAGCircuitError("too many predecessors for %s[%d] "
"output node" % (w[0], w[1]))
return full_pred_map, full_succ_map
@staticmethod
def _match_dag_nodes(node1, node2):
"""
Check if DAG nodes are considered equivalent, e.g. as a node_match for nx.is_isomorphic.
Args:
node1 (dict): A node to compare.
node2 (dict): The other node to compare.
Returns:
Bool: If node1 == node2
"""
copy_node1 = {k: v for (k, v) in node1.items()}
copy_node2 = {k: v for (k, v) in node2.items()}
# For barriers, qarg order is not significant so compare as sets
if 'barrier' == copy_node1['name'] == copy_node2['name']:
node1_qargs = set(copy_node1.pop('qargs', []))
node2_qargs = set(copy_node2.pop('qargs', []))
if node1_qargs != node2_qargs:
return False
return copy_node1 == copy_node2
def __eq__(self, other):
return nx.is_isomorphic(self.multi_graph, other.multi_graph,
node_match=DAGCircuit._match_dag_nodes)
def node_nums_in_topological_order(self):
"""
Returns the nodes (their ids) in topological order.
Returns:
list: The list of node numbers in topological order
"""
return nx.lexicographical_topological_sort(self.multi_graph)
def substitute_circuit_all(self, op, input_circuit, wires=None):
"""Replace every occurrence of operation op with input_circuit.
Args:
op (Instruction): operation type to substitute across the dag.
input_circuit (DAGCircuit): what to replace with
wires (list[register, index]): gives an order for (qu)bits
in the input_circuit that is replacing the operation.
Raises:
DAGCircuitError: if met with unexpected predecessor/successors
"""
# TODO: rewrite this method to call substitute_node_with_dag
wires = wires or []
if op.name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% op.name)
self._check_wires_list(wires, op, input_circuit)
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: (QuantumRegister(1, 'proxy'), 0) for w in wires}
add_qregs = self._check_edgemap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Iterate through the nodes of self and replace the selected nodes
# by iterating through the input_circuit, constructing and
# checking the validity of the wire_map for each replacement
# NOTE: We do not replace conditioned gates. One way to implement
# this later is to add or update the conditions of each gate
# that we add from the input_circuit.
self.basis = union_basis
self.gates = union_gates
for n in self.node_nums_in_topological_order():
nd = self.multi_graph.node[n]
if nd["type"] == "op" and nd["op"] == op:
if nd["condition"] is None:
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"], nd["cargs"]]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map)
pred_map, succ_map = self._make_pred_succ_maps(n)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(n)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map,
md["condition"])
m_qargs = [wire_map.get(x, x) for x in md["qargs0"]]
m_cargs = [wire_map.get(x, x) for x in md["cargs0"]]
self._add_op_node(md["op"], m_qargs, m_cargs, condition)
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter,
name="%s[%s]" % (q[0].name, q[1]),
wire=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w],
full_succ_map[w],
name="%s[%s]" % (w[0].name, w[1]),
wire=w)
o_pred = list(self.multi_graph.predecessors(
self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise DAGCircuitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise DAGCircuitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(
p[0], self.output_map[w])
def substitute_node_with_dag(self, node, input_dag, wires=None):
"""Replace one node with dag.
Args:
node (int): node of self.multi_graph (of type "op") to substitute
input_dag (DAGCircuit): circuit that will substitute the node
wires (list[(Register, index)]): gives an order for (qu)bits
in the input circuit. This order gets matched to the node wires
by qargs first, then cargs, then conditions.
Raises:
DAGCircuitError: if met with unexpected predecessor/successors
"""
nd = self.multi_graph.node[node]
condition = nd["condition"]
# the decomposition rule must be amended if used in a
# conditional context. delete the op nodes and replay
# them with the condition.
if condition:
input_dag.add_creg(condition[0])
to_replay = []
for n_it in nx.topological_sort(input_dag.multi_graph):
n = input_dag.multi_graph.nodes[n_it]
if n["type"] == "op":
n["op"].control = condition
to_replay.append(n)
for n in input_dag.get_op_nodes():
input_dag._remove_op_node(n)
for n in to_replay:
input_dag.apply_operation_back(n["op"], condition=condition)
if wires is None:
qwires = [w for w in input_dag.wires if isinstance(w[0], QuantumRegister)]
cwires = [w for w in input_dag.wires if isinstance(w[0], ClassicalRegister)]
wires = qwires + cwires
self._check_wires_list(wires, nd["op"], input_dag, nd["condition"])
union_basis = self._make_union_basis(input_dag)
union_gates = self._make_union_gates(input_dag)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: QuantumRegister(1, 'proxy') for w in wires}
add_qregs = self._check_edgemap_registers(proxy_map,
input_dag.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(proxy_map,
input_dag.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Replace the node by iterating through the input_circuit.
# Constructing and checking the validity of the wire_map.
# If a gate is conditioned, we expect the replacement subcircuit
# to depend on those control bits as well.
self.basis = union_basis
self.gates = union_gates
if nd["type"] != "op":
raise DAGCircuitError("expected node type \"op\", got %s"
% nd["type"])
condition_bit_list = self._bits_in_condition(nd["condition"])
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"],
nd["cargs"],
condition_bit_list]
for i in s])}
self._check_wiremap_validity(wire_map, wires, self.input_map)
pred_map, succ_map = self._make_pred_succ_maps(node)
full_pred_map, full_succ_map = self._full_pred_succ_maps(pred_map, succ_map,
input_dag, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(node)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_dag.multi_graph):
md = input_dag.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map, md["condition"])
m_qargs = list(map(lambda x: wire_map.get(x, x),
md["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x),
md["cargs"]))
self._add_op_node(md["op"], m_qargs, m_cargs, condition)
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter,
name="%s[%s]" % (q[0].name, q[1]),
wire=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w],
full_succ_map[w],
name="%s[%s]" % (w[0].name, w[1]),
wire=w)
o_pred = list(self.multi_graph.predecessors(self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise DAGCircuitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise DAGCircuitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(p[0], self.output_map[w])
def get_op_nodes(self, op=None, data=False):
"""Get the list of "op" nodes in the dag.
Args:
op (Type): Instruction subclass op nodes to return. if op=None, return
all op nodes.
data (bool): Default: False. If True, return a list of tuple
(node_id, node_data). If False, return a list of int (node_id)
Returns:
list: the list of node ids containing the given op.
"""
nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data["type"] == "op":
if op is None or isinstance(node_data["op"], op):
nodes.append((node_id, node_data))
if not data:
nodes = [n[0] for n in nodes]
return nodes
def get_gate_nodes(self, data=False):
"""Get the list of gate nodes in the dag.
Args:
data (bool): Default: False. If True, return a list of tuple
(node_id, node_data). If False, return a list of int (node_id)
Returns:
list: the list of node ids that represent gates.
"""
nodes = []
for node_id, node_data in self.get_op_nodes(data=True):
if isinstance(node_data['op'], Gate):
nodes.append((node_id, node_data))
if not data:
nodes = [n[0] for n in nodes]
return nodes
def get_named_nodes(self, *names):
"""Get the set of "op" nodes with the given name."""
named_nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data['type'] == 'op' and node_data['op'].name in names:
named_nodes.append(node_id)
return named_nodes
def get_2q_nodes(self):
"""Get list of 2-qubit nodes."""
two_q_nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data['type'] == 'op' and len(node_data['qargs']) == 2:
two_q_nodes.append(self.multi_graph.node[node_id])
return two_q_nodes
def get_3q_or_more_nodes(self):
"""Get list of 3-or-more-qubit nodes: (id, data)."""
three_q_nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data['type'] == 'op' and len(node_data['qargs']) >= 3:
three_q_nodes.append((node_id, self.multi_graph.node[node_id]))
return three_q_nodes
def successors(self, node):
"""Returns the successors of a node."""
return self.multi_graph.successors(node)
def ancestors(self, node):
"""Returns the ancestors of a node."""
return nx.ancestors(self.multi_graph, node)
def descendants(self, node):
"""Returns the descendants of a node."""
return nx.descendants(self.multi_graph, node)
def quantum_successors(self, node):
"""Returns the successors of a node that are connected by a quantum edge"""
successors = []
for successor in self.successors(node):
if isinstance(self.multi_graph.get_edge_data(node, successor, key=0)['wire'][0],
QuantumRegister):
successors.append(successor)
return successors
def _remove_op_node(self, n):
"""Remove an operation node n.
Add edges from predecessors to successors.
"""
pred_map, succ_map = self._make_pred_succ_maps(n)
self.multi_graph.remove_node(n)
for w in pred_map.keys():
self.multi_graph.add_edge(pred_map[w], succ_map[w],
name="%s[%s]" % (w[0].name, w[1]), wire=w)
def remove_ancestors_of(self, node):
"""Remove all of the ancestor operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
# TODO: probably better to do all at once using
# multi_graph.remove_nodes_from; same for related functions ...
for n in anc:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_descendants_of(self, node):
"""Remove all of the descendant operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
for n in dec:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nonancestors_of(self, node):
"""Remove all of the non-ancestors operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(anc))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nondescendants_of(self, node):
"""Remove all of the non-descendants operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(dec))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def layers(self):
"""Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit.
A layer is a circuit whose gates act on disjoint qubits, i.e.
a layer has depth 1. The total number of layers equals the
circuit depth d. The layers are indexed from 0 to d-1 with the
earliest layer at index 0. The layers are constructed using a
greedy algorithm. Each returned layer is a dict containing
{"graph": circuit graph, "partition": list of qubit lists}.
TODO: Gates that use the same cbits will end up in different
layers as this is currently implemented. This may not be
the desired behavior.
"""
graph_layers = self.multigraph_layers()
try:
next(graph_layers) # Remove input nodes
except StopIteration:
return
def nodes_data(nodes):
"""Construct full nodes from just node ids."""
return ((node_id, self.multi_graph.nodes[node_id]) for node_id in nodes)
for graph_layer in graph_layers:
# Get the op nodes from the layer, removing any input and output nodes.
op_nodes = [node for node in nodes_data(graph_layer) if node[1]["type"] == "op"]
# Stop yielding once there are no more op_nodes in a layer.
if not op_nodes:
return
# Construct a shallow copy of self
new_layer = copy.copy(self)
new_layer.multi_graph = nx.MultiDiGraph()
new_layer.multi_graph.add_nodes_from(nodes_data(self.input_map.values()))
new_layer.multi_graph.add_nodes_from(nodes_data(self.output_map.values()))
# The quantum registers that have an operation in this layer.
support_list = [
op_node[1]["qargs"]
for op_node in op_nodes
if op_node[1]["op"].name not in {"barrier", "snapshot", "save", "load", "noise"}
]
new_layer.multi_graph.add_nodes_from(op_nodes)
# Now add the edges to the multi_graph
# By default we just wire inputs to the outputs.
wires = {self.input_map[wire]: self.output_map[wire]
for wire in self.wires}
# Wire inputs to op nodes, and op nodes to outputs.
for op_node in op_nodes:
args = self._bits_in_condition(op_node[1]["condition"]) \
+ op_node[1]["cargs"] + op_node[1]["qargs"]
arg_ids = (self.input_map[(arg[0], arg[1])] for arg in args)
for arg_id in arg_ids:
wires[arg_id], wires[op_node[0]] = op_node[0], wires[arg_id]
# Add wiring to/from the operations and between unused inputs & outputs.
new_layer.multi_graph.add_edges_from(wires.items())
yield {"graph": new_layer, "partition": support_list}
def serial_layers(self):
"""Yield a layer for all gates of this circuit.
A serial layer is a circuit with one gate. The layers have the
same structure as in layers().
"""
for n in self.node_nums_in_topological_order():
nxt_nd = self.multi_graph.node[n]
if nxt_nd["type"] == "op":
new_layer = DAGCircuit()
for qreg in self.qregs.values():
new_layer.add_qreg(qreg)
for creg in self.cregs.values():
new_layer.add_creg(creg)
new_layer.basis = self.basis.copy()
new_layer.gates = self.gates.copy()
# Save the support of the operation we add to the layer
support_list = []
# Operation data
op = copy.copy(nxt_nd["op"])
qa = copy.copy(nxt_nd["qargs"])
ca = copy.copy(nxt_nd["cargs"])
co = copy.copy(nxt_nd["condition"])
_ = self._bits_in_condition(co)
# Add node to new_layer
new_layer.apply_operation_back(op, qa, ca, co)
# Add operation to partition
if nxt_nd["name"] not in ["barrier",
"snapshot", "save", "load", "noise"]:
support_list.append(list(qa))
l_dict = {"graph": new_layer, "partition": support_list}
yield l_dict
def multigraph_layers(self):
"""Yield layers of the multigraph."""
predecessor_count = dict() # Dict[node, predecessors not visited]
cur_layer = [node for node in self.input_map.values()]
yield cur_layer
next_layer = []
while cur_layer:
for node in cur_layer:
# Count multiedges with multiplicity.
for successor in self.multi_graph.successors(node):
multiplicity = self.multi_graph.number_of_edges(node, successor)
if successor in predecessor_count:
predecessor_count[successor] -= multiplicity
else:
predecessor_count[successor] = \
self.multi_graph.in_degree(successor) - multiplicity
if predecessor_count[successor] == 0:
next_layer.append(successor)
del predecessor_count[successor]
yield next_layer
cur_layer = next_layer
next_layer = []
def collect_runs(self, namelist):
"""Return a set of runs of "op" nodes with the given names.
For example, "... h q[0]; cx q[0],q[1]; cx q[0],q[1]; h q[1]; .."
would produce the tuple of cx nodes as an element of the set returned
from a call to collect_runs(["cx"]). If instead the cx nodes were
"cx q[0],q[1]; cx q[1],q[0];", the method would still return the
pair in a tuple. The namelist can contain names that are not
in the circuit's basis.
Nodes must have only one successor to continue the run.
"""
group_list = []
# Iterate through the nodes of self in topological order
# and form tuples containing sequences of gates
# on the same qubit(s).
tops_node = list(self.node_nums_in_topological_order())
nodes_seen = dict(zip(tops_node, [False] * len(tops_node)))
for node in tops_node:
nd = self.multi_graph.node[node]
if nd["type"] == "op" and nd["name"] in namelist \
and not nodes_seen[node]:
group = [node]
nodes_seen[node] = True
s = list(self.multi_graph.successors(node))
while len(s) == 1 and \
self.multi_graph.node[s[0]]["type"] == "op" and \
self.multi_graph.node[s[0]]["name"] in namelist:
group.append(s[0])
nodes_seen[s[0]] = True
s = list(self.multi_graph.successors(s[0]))
if len(group) > 1:
group_list.append(tuple(group))
return set(group_list)
def count_ops(self):
"""Count the occurrences of operation names.
Returns a dictionary of counts keyed on the operation name.
"""
op_dict = {}
for node in self.node_nums_in_topological_order():
nd = self.multi_graph.node[node]
name = nd["name"]
if nd["type"] == "op":
if name not in op_dict:
op_dict[name] = 1
else:
op_dict[name] += 1
return op_dict
def properties(self):
"""Return a dictionary of circuit properties."""
summary = {"size": self.size(),
"depth": self.depth(),
"width": self.width(),
"bits": self.num_cbits(),
"factors": self.num_tensor_factors(),
"operations": self.count_ops()}
return summary
<|code_end|>
|
BasicAer qasm_simulator not detecting that sample measurement can be used
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: 0.7.0
- **Python version**: 3.6.6
- **Operating system**: Ubuntu
### What is the current behavior?
Currently, it can detect that it can sample if there is only measurments at the end, but sometimes the measurment instruction is put further up, and it's not detected even when there is no more operations applied to the qubit.
### Steps to reproduce the problem
If you look at what gets called with the following:
```python
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, BasicAer
qubit_reg = QuantumRegister(4)
clbit_reg = ClassicalRegister(4)
qc1 = QuantumCircuit(qubit_reg, clbit_reg)
qc1.h(qubit_reg[0])
qc1.cx(qubit_reg[0], qubit_reg[1])
qc1.measure(qubit_reg, clbit_reg)
job_sim = execute(qc1, BasicAer.get_backend('qasm_simulator'))
sim_result = job_sim.result()
```
The function `_add_sample_measure` is never called.
### What is the expected behavior?
It should just sample measure, which would be quicker.
### Suggested solutions
Change the `_validate_measure_sampling` function in `qiskit/providers/builtinsimulators/qasm_simulator.py` to be something like:
```python
def _validate_measure_sampling(self, experiment):
"""Determine if sampling can be used for an experiment
Args:
experiment (QobjExperiment): a qobj experiment
"""
measure_flags = {}
if hasattr(experiment.config, 'allows_measure_sampling'):
self._sample_measure = experiment.config.allows_measure_sampling
else:
for instruction in experiment.instructions:
if instruction.name == "reset":
measure_flags[instruction.qubits[0]] = False
self._sample_measure = False
return
if measure_flags.get(instruction.qubits[0], False):
if instruction.name not in ["measure", "barrier", "id", "u0"]:
for qubit in instruction.qubits:
measure_flags[qubit] = False
return
elif instruction.name == "measure":
for qubit in instruction.qubits:
measure_flags[qubit] = True
self._sample_measure = True
for key, value in measure_flags.items():
if value == False:
self._sample_measure = False
return
```
|
qiskit/transpiler/_transpiler.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Tools for compiling a batch of quantum circuits."""
import logging
from qiskit.circuit import QuantumCircuit
from qiskit.mapper import CouplingMap, swap_mapper
from qiskit.tools.parallel import parallel_map
from qiskit.converters import circuit_to_dag
from qiskit.converters import dag_to_circuit
from qiskit.extensions.standard import SwapGate
from .passes.cx_cancellation import CXCancellation
from .passes.decompose import Decompose
from .passes.optimize_1q_gates import Optimize1qGates
from .passes.mapping.barrier_before_final_measurements import BarrierBeforeFinalMeasurements
from .passes.mapping.check_map import CheckMap
from .passes.mapping.cx_direction import CXDirection
from .passes.mapping.dense_layout import DenseLayout
from .passes.mapping.trivial_layout import TrivialLayout
from .passes.mapping.unroller import Unroller
from .exceptions import TranspilerError
logger = logging.getLogger(__name__)
def transpile(circuits, backend=None, basis_gates=None, coupling_map=None,
initial_layout=None, seed_mapper=None, pass_manager=None):
"""transpile one or more circuits.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend): a backend to compile for
basis_gates (str): comma-separated basis gate set to compile to
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
seed_mapper (int): random seed for the swap_mapper
pass_manager (PassManager): a pass_manager for the transpiler stages
Returns:
QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s).
Raises:
TranspilerError: if args are not complete for the transpiler to function
"""
return_form_is_single = False
if isinstance(circuits, QuantumCircuit):
circuits = [circuits]
return_form_is_single = True
# Check for valid parameters for the experiments.
basis_gates = basis_gates or ','.join(backend.configuration().basis_gates)
coupling_map = coupling_map or getattr(backend.configuration(),
'coupling_map', None)
if not basis_gates:
raise TranspilerError('no basis_gates or backend to compile to')
circuits = parallel_map(_transpilation, circuits,
task_kwargs={'basis_gates': basis_gates,
'coupling_map': coupling_map,
'initial_layout': initial_layout,
'seed_mapper': seed_mapper,
'pass_manager': pass_manager})
if return_form_is_single:
return circuits[0]
return circuits
def _transpilation(circuit, basis_gates=None, coupling_map=None,
initial_layout=None, seed_mapper=None,
pass_manager=None):
"""Perform transpilation of a single circuit.
Args:
circuit (QuantumCircuit): A circuit to transpile.
basis_gates (str): comma-separated basis gate set to compile to
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
seed_mapper (int): random seed for the swap_mapper
pass_manager (PassManager): a pass_manager for the transpiler stage
Returns:
QuantumCircuit: A transpiled circuit.
Raises:
TranspilerError: if args are not complete for transpiler to function.
"""
if pass_manager and not pass_manager.working_list:
return circuit
dag = circuit_to_dag(circuit)
# pick a trivial layout if the circuit already satisfies the coupling constraints
# else layout on the most densely connected physical qubit subset
# FIXME: this should be simplified once it is ported to a PassManager
if coupling_map:
check_map = CheckMap(CouplingMap(coupling_map))
check_map.run(dag)
if check_map.property_set['is_direction_mapped']:
trivial_layout = TrivialLayout(CouplingMap(coupling_map))
trivial_layout.run(dag)
initial_layout = trivial_layout.property_set['layout']
else:
dense_layout = DenseLayout(CouplingMap(coupling_map))
dense_layout.run(dag)
initial_layout = dense_layout.property_set['layout']
# temporarily build old-style layout dict
# (FIXME: remove after transition to StochasticSwap pass)
layout = initial_layout.copy()
virtual_qubits = layout.get_virtual_bits()
initial_layout = {(v[0].name, v[1]): ('q', layout[v]) for v in virtual_qubits}
final_dag = transpile_dag(dag, basis_gates=basis_gates,
coupling_map=coupling_map,
initial_layout=initial_layout,
seed_mapper=seed_mapper,
pass_manager=pass_manager)
out_circuit = dag_to_circuit(final_dag)
return out_circuit
# pylint: disable=redefined-builtin
def transpile_dag(dag, basis_gates='u1,u2,u3,cx,id', coupling_map=None,
initial_layout=None, seed_mapper=None, pass_manager=None):
"""Transform a dag circuit into another dag circuit (transpile), through
consecutive passes on the dag.
Args:
dag (DAGCircuit): dag circuit to transform via transpilation
basis_gates (str): a comma separated string for the target basis gates
coupling_map (list): A graph of coupling::
[
[control0(int), target0(int)],
[control1(int), target1(int)],
]
eg. [[0, 2], [1, 2], [1, 3], [3, 4]}
initial_layout (dict): A mapping of qubit to qubit::
{
("q", start(int)): ("q", final(int)),
...
}
eg.
{
("q", 0): ("q", 0),
("q", 1): ("q", 1),
("q", 2): ("q", 2),
("q", 3): ("q", 3)
}
seed_mapper (int): random seed_mapper for the swap mapper
pass_manager (PassManager): pass manager instance for the transpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
DAGCircuit: transformed dag
"""
# TODO: `basis_gates` will be removed after we have the unroller pass.
# TODO: `coupling_map`, `initial_layout`, `seed_mapper` removed after mapper pass.
# TODO: move this to the mapper pass
num_qubits = sum([qreg.size for qreg in dag.qregs.values()])
if num_qubits == 1 or coupling_map == "all-to-all":
coupling_map = None
final_layout = None
if pass_manager:
# run the passes specified by the pass manager
# TODO return the property set too. See #1086
dag = pass_manager.run_passes(dag)
else:
# default set of passes
# TODO: move each step here to a pass, and use a default passmanager below
basis = basis_gates.split(',') if basis_gates else []
dag = Unroller(basis).run(dag)
name = dag.name
# if a coupling map is given compile to the map
if coupling_map:
logger.info("pre-mapping properties: %s",
dag.properties())
# Insert swap gates
coupling = CouplingMap(coupling_map)
logger.info("initial layout: %s", initial_layout)
dag = BarrierBeforeFinalMeasurements().run(dag)
dag, final_layout = swap_mapper(
dag, coupling, initial_layout, trials=20, seed=seed_mapper)
logger.info("final layout: %s", final_layout)
# Expand swaps
dag = Decompose(SwapGate).run(dag)
# Change cx directions
dag = CXDirection(coupling).run(dag)
# Simplify cx gates
dag = CXCancellation().run(dag)
# Unroll to the basis
dag = Unroller(['u1', 'u2', 'u3', 'id', 'cx']).run(dag)
# Simplify single qubit gates
dag = Optimize1qGates().run(dag)
logger.info("post-mapping properties: %s",
dag.properties())
dag.name = name
return dag
<|code_end|>
qiskit/transpiler/passes/mapping/barrier_before_final_measurements.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
This pass adds a barrier before the final measurements.
"""
from qiskit.extensions.standard.barrier import Barrier
from qiskit.transpiler._basepasses import TransformationPass
from qiskit.dagcircuit import DAGCircuit
class BarrierBeforeFinalMeasurements(TransformationPass):
"""Adds a barrier before final measurements."""
def run(self, dag):
"""Return a circuit with a barrier before last measurments."""
last_measures = []
for measure in dag.get_named_nodes('measure'):
is_last_measurement = all([after_measure in dag.output_map.values() for after_measure in
dag.quantum_successors(measure)])
if is_last_measurement:
last_measures.append(measure)
if not last_measures:
return dag
# create a laywer with the barrier and the measurements in last_measures operation
dag.add_basis_element('barrier', len(last_measures), 0, 0)
barried_layer = DAGCircuit()
last_measures_nodes = [dag.multi_graph.node[node] for node in last_measures]
last_measures_qubits = [node['qargs'][0] for node in last_measures_nodes]
# Add registers from the original dag.
for qreg in dag.qregs.values():
barried_layer.add_qreg(qreg)
for creg in dag.cregs.values():
barried_layer.add_creg(creg)
# Add the barrier operation
barried_layer.apply_operation_back(Barrier(qubits=last_measures_qubits))
# Add the measurements to the behind the barrier
for last_measures_node in last_measures_nodes:
barried_layer.apply_operation_back(last_measures_node['op'])
# Remove barriers in front the measurements in the original dag
for last_measure in last_measures:
for predecesor in dag.multi_graph.predecessors(last_measure):
if dag.multi_graph.nodes[predecesor]['type'] == 'op' and \
isinstance(dag.multi_graph.nodes[predecesor]['op'], Barrier):
dag._remove_op_node(predecesor)
# Remove the measurements from the original dag
for last_measure in last_measures:
dag._remove_op_node(last_measure)
# Extend the original dag with the barried layer
dag.extend_back(barried_layer)
return dag
<|code_end|>
|
qiskit/transpiler/_transpiler.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Tools for compiling a batch of quantum circuits."""
import logging
from qiskit.circuit import QuantumCircuit
from qiskit.mapper import CouplingMap, swap_mapper
from qiskit.tools.parallel import parallel_map
from qiskit.converters import circuit_to_dag
from qiskit.converters import dag_to_circuit
from qiskit.extensions.standard import SwapGate
from .passes.cx_cancellation import CXCancellation
from .passes.decompose import Decompose
from .passes.optimize_1q_gates import Optimize1qGates
from .passes.mapping.barrier_before_final_measurements import BarrierBeforeFinalMeasurements
from .passes.mapping.check_map import CheckMap
from .passes.mapping.cx_direction import CXDirection
from .passes.mapping.dense_layout import DenseLayout
from .passes.mapping.trivial_layout import TrivialLayout
from .passes.mapping.unroller import Unroller
from .exceptions import TranspilerError
logger = logging.getLogger(__name__)
def transpile(circuits, backend=None, basis_gates=None, coupling_map=None,
initial_layout=None, seed_mapper=None, pass_manager=None):
"""transpile one or more circuits.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend): a backend to compile for
basis_gates (str): comma-separated basis gate set to compile to
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
seed_mapper (int): random seed for the swap_mapper
pass_manager (PassManager): a pass_manager for the transpiler stages
Returns:
QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s).
Raises:
TranspilerError: if args are not complete for the transpiler to function
"""
return_form_is_single = False
if isinstance(circuits, QuantumCircuit):
circuits = [circuits]
return_form_is_single = True
# Check for valid parameters for the experiments.
basis_gates = basis_gates or ','.join(backend.configuration().basis_gates)
coupling_map = coupling_map or getattr(backend.configuration(),
'coupling_map', None)
if not basis_gates:
raise TranspilerError('no basis_gates or backend to compile to')
circuits = parallel_map(_transpilation, circuits,
task_kwargs={'basis_gates': basis_gates,
'coupling_map': coupling_map,
'initial_layout': initial_layout,
'seed_mapper': seed_mapper,
'pass_manager': pass_manager})
if return_form_is_single:
return circuits[0]
return circuits
def _transpilation(circuit, basis_gates=None, coupling_map=None,
initial_layout=None, seed_mapper=None,
pass_manager=None):
"""Perform transpilation of a single circuit.
Args:
circuit (QuantumCircuit): A circuit to transpile.
basis_gates (str): comma-separated basis gate set to compile to
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
seed_mapper (int): random seed for the swap_mapper
pass_manager (PassManager): a pass_manager for the transpiler stage
Returns:
QuantumCircuit: A transpiled circuit.
Raises:
TranspilerError: if args are not complete for transpiler to function.
"""
if pass_manager and not pass_manager.working_list:
return circuit
dag = circuit_to_dag(circuit)
# pick a trivial layout if the circuit already satisfies the coupling constraints
# else layout on the most densely connected physical qubit subset
# FIXME: this should be simplified once it is ported to a PassManager
if coupling_map:
check_map = CheckMap(CouplingMap(coupling_map))
check_map.run(dag)
if check_map.property_set['is_direction_mapped']:
trivial_layout = TrivialLayout(CouplingMap(coupling_map))
trivial_layout.run(dag)
initial_layout = trivial_layout.property_set['layout']
else:
dense_layout = DenseLayout(CouplingMap(coupling_map))
dense_layout.run(dag)
initial_layout = dense_layout.property_set['layout']
# temporarily build old-style layout dict
# (FIXME: remove after transition to StochasticSwap pass)
layout = initial_layout.copy()
virtual_qubits = layout.get_virtual_bits()
initial_layout = {(v[0].name, v[1]): ('q', layout[v]) for v in virtual_qubits}
final_dag = transpile_dag(dag, basis_gates=basis_gates,
coupling_map=coupling_map,
initial_layout=initial_layout,
seed_mapper=seed_mapper,
pass_manager=pass_manager)
out_circuit = dag_to_circuit(final_dag)
return out_circuit
# pylint: disable=redefined-builtin
def transpile_dag(dag, basis_gates='u1,u2,u3,cx,id', coupling_map=None,
initial_layout=None, seed_mapper=None, pass_manager=None):
"""Transform a dag circuit into another dag circuit (transpile), through
consecutive passes on the dag.
Args:
dag (DAGCircuit): dag circuit to transform via transpilation
basis_gates (str): a comma separated string for the target basis gates
coupling_map (list): A graph of coupling::
[
[control0(int), target0(int)],
[control1(int), target1(int)],
]
eg. [[0, 2], [1, 2], [1, 3], [3, 4]}
initial_layout (dict): A mapping of qubit to qubit::
{
("q", start(int)): ("q", final(int)),
...
}
eg.
{
("q", 0): ("q", 0),
("q", 1): ("q", 1),
("q", 2): ("q", 2),
("q", 3): ("q", 3)
}
seed_mapper (int): random seed_mapper for the swap mapper
pass_manager (PassManager): pass manager instance for the transpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
DAGCircuit: transformed dag
"""
# TODO: `basis_gates` will be removed after we have the unroller pass.
# TODO: `coupling_map`, `initial_layout`, `seed_mapper` removed after mapper pass.
# TODO: move this to the mapper pass
num_qubits = sum([qreg.size for qreg in dag.qregs.values()])
if num_qubits == 1 or coupling_map == "all-to-all":
coupling_map = None
final_layout = None
if pass_manager:
# run the passes specified by the pass manager
# TODO return the property set too. See #1086
dag = pass_manager.run_passes(dag)
else:
# default set of passes
# TODO: move each step here to a pass, and use a default passmanager below
basis = basis_gates.split(',') if basis_gates else []
name = dag.name
dag = Unroller(basis).run(dag)
dag = BarrierBeforeFinalMeasurements().run(dag)
# if a coupling map is given compile to the map
if coupling_map:
logger.info("pre-mapping properties: %s",
dag.properties())
# Insert swap gates
coupling = CouplingMap(coupling_map)
logger.info("initial layout: %s", initial_layout)
dag, final_layout = swap_mapper(
dag, coupling, initial_layout, trials=20, seed=seed_mapper)
logger.info("final layout: %s", final_layout)
# Expand swaps
dag = Decompose(SwapGate).run(dag)
# Change cx directions
dag = CXDirection(coupling).run(dag)
# Simplify cx gates
dag = CXCancellation().run(dag)
# Unroll to the basis
dag = Unroller(['u1', 'u2', 'u3', 'id', 'cx']).run(dag)
# Simplify single qubit gates
dag = Optimize1qGates().run(dag)
logger.info("post-mapping properties: %s",
dag.properties())
dag.name = name
return dag
<|code_end|>
qiskit/transpiler/passes/mapping/barrier_before_final_measurements.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
This pass adds a barrier before the final measurements.
"""
from qiskit.extensions.standard.barrier import Barrier
from qiskit.transpiler._basepasses import TransformationPass
from qiskit.dagcircuit import DAGCircuit
class BarrierBeforeFinalMeasurements(TransformationPass):
"""Adds a barrier before final measurements."""
def run(self, dag):
"""Return a circuit with a barrier before last measurments."""
last_measures = []
for measure in dag.get_named_nodes('measure'):
is_last_measurement = all([after_measure in dag.output_map.values() for after_measure in
dag.successors(measure)])
if is_last_measurement:
last_measures.append(measure)
if not last_measures:
return dag
# create a laywer with the barrier and the measurements in last_measures operation
dag.add_basis_element('barrier', len(last_measures), 0, 0)
barried_layer = DAGCircuit()
last_measures_nodes = [dag.multi_graph.node[node] for node in last_measures]
last_measures_qubits = [node['qargs'][0] for node in last_measures_nodes]
# Add registers from the original dag.
for qreg in dag.qregs.values():
barried_layer.add_qreg(qreg)
for creg in dag.cregs.values():
barried_layer.add_creg(creg)
# Add the barrier operation
barried_layer.apply_operation_back(Barrier(qubits=last_measures_qubits))
# Add the measurements to the behind the barrier
for last_measures_node in last_measures_nodes:
barried_layer.apply_operation_back(last_measures_node['op'])
# Remove barriers in front the measurements in the original dag
for last_measure in last_measures:
for predecesor in dag.multi_graph.predecessors(last_measure):
if dag.multi_graph.nodes[predecesor]['type'] == 'op' and \
isinstance(dag.multi_graph.nodes[predecesor]['op'], Barrier):
dag._remove_op_node(predecesor)
# Remove the measurements from the original dag
for last_measure in last_measures:
dag._remove_op_node(last_measure)
# Extend the original dag with the barried layer
dag.extend_back(barried_layer)
return dag
<|code_end|>
|
Removed compiled_circuit_qasm from QobjExperimentalHeader
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected behavior?
After #1629 when all the backends are Qobj 1.0 compatible we need to remove compiled_circuit_qasm from the header.
|
qiskit/converters/circuits_to_qobj.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Compile function for converting a list of circuits to the qobj"""
import uuid
import warnings
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.qobj import Qobj, QobjConfig, QobjExperiment, QobjInstruction, QobjHeader
from qiskit.qobj import QobjExperimentConfig, QobjExperimentHeader, QobjConditional
from qiskit.qobj.run_config import RunConfig
def circuits_to_qobj(circuits, user_qobj_header=None, run_config=None,
qobj_id=None, backend_name=None,
config=None, shots=None, max_credits=None,
basis_gates=None,
coupling_map=None, seed=None, memory=None):
"""Convert a list of circuits into a qobj.
Args:
circuits (list[QuantumCircuits] or QuantumCircuit): circuits to compile
user_qobj_header (QobjHeader): header to pass to the results
run_config (RunConfig): RunConfig object
qobj_id (int): identifier for the generated qobj
backend_name (str): TODO: delete after qiskit-terra 0.8
config (dict): TODO: delete after qiskit-terra 0.8
shots (int): TODO: delete after qiskit-terra 0.8
max_credits (int): TODO: delete after qiskit-terra 0.8
basis_gates (str): TODO: delete after qiskit-terra 0.8
coupling_map (list): TODO: delete after qiskit-terra 0.8
seed (int): TODO: delete after qiskit-terra 0.8
memory (bool): TODO: delete after qiskit-terra 0.8
Returns:
Qobj: the Qobj to be run on the backends
"""
user_qobj_header = user_qobj_header or QobjHeader()
run_config = run_config or RunConfig()
if isinstance(circuits, QuantumCircuit):
circuits = [circuits]
if backend_name:
warnings.warn('backend_name is not required anymore', DeprecationWarning)
user_qobj_header.backend_name = backend_name
if config:
warnings.warn('config is not used anymore. Set all configs in '
'run_config.', DeprecationWarning)
if shots:
warnings.warn('shots is not used anymore. Set it via run_config.', DeprecationWarning)
run_config.shots = shots
if basis_gates:
warnings.warn('basis_gates was unused and will be removed.', DeprecationWarning)
if coupling_map:
warnings.warn('coupling_map was unused and will be removed.', DeprecationWarning)
if seed:
warnings.warn('seed is not used anymore. Set it via run_config', DeprecationWarning)
run_config.seed = seed
if memory:
warnings.warn('memory is not used anymore. Set it via run_config', DeprecationWarning)
run_config.memory = memory
if max_credits:
warnings.warn('max_credits is not used anymore. Set it via run_config', DeprecationWarning)
run_config.max_credits = max_credits
userconfig = QobjConfig(**run_config.to_dict())
experiments = []
max_n_qubits = 0
max_memory_slots = 0
for circuit in circuits:
# header stuff
n_qubits = 0
memory_slots = 0
qubit_labels = []
clbit_labels = []
qreg_sizes = []
creg_sizes = []
for qreg in circuit.qregs:
qreg_sizes.append([qreg.name, qreg.size])
for j in range(qreg.size):
qubit_labels.append([qreg.name, j])
n_qubits += qreg.size
for creg in circuit.cregs:
creg_sizes.append([creg.name, creg.size])
for j in range(creg.size):
clbit_labels.append([creg.name, j])
memory_slots += creg.size
# TODO: why do we need creq_sizes and qreg_sizes in header
# TODO: we need to rethink memory_slots as they are tied to classical bit
# TODO: when no more backends use the compiled_circuit_qasm lets delete it form header
experimentheader = QobjExperimentHeader(qubit_labels=qubit_labels,
n_qubits=n_qubits,
qreg_sizes=qreg_sizes,
clbit_labels=clbit_labels,
memory_slots=memory_slots,
creg_sizes=creg_sizes,
name=circuit.name,
compiled_circuit_qasm=circuit.qasm())
# TODO: why do we need n_qubits and memory_slots in both the header and the config
experimentconfig = QobjExperimentConfig(n_qubits=n_qubits, memory_slots=memory_slots)
instructions = []
for opt in circuit.data:
current_instruction = QobjInstruction(name=opt.name)
if opt.qargs:
qubit_indices = [qubit_labels.index([qubit[0].name, qubit[1]])
for qubit in opt.qargs]
current_instruction.qubits = qubit_indices
if opt.cargs:
clbit_indices = [clbit_labels.index([clbit[0].name, clbit[1]])
for clbit in opt.cargs]
current_instruction.memory = clbit_indices
if opt.params:
params = list(map(lambda x: x.evalf(), opt.params))
current_instruction.params = params
# TODO: I really dont like this for snapshot. I also think we should change
# type to snap_type
if opt.name == "snapshot":
current_instruction.label = str(opt.params[0])
current_instruction.type = str(opt.params[1])
if opt.control:
mask = 0
for clbit in clbit_labels:
if clbit[0] == opt.control[0].name:
mask |= (1 << clbit_labels.index(clbit))
current_instruction.conditional = QobjConditional(mask="0x%X" % mask,
type='equals',
val="0x%X" % opt.control[1])
instructions.append(current_instruction)
experiments.append(QobjExperiment(instructions=instructions, header=experimentheader,
config=experimentconfig))
if n_qubits > max_n_qubits:
max_n_qubits = n_qubits
if memory_slots > max_memory_slots:
max_memory_slots = memory_slots
userconfig.memory_slots = max_memory_slots
userconfig.n_qubits = max_n_qubits
return Qobj(qobj_id=qobj_id or str(uuid.uuid4()), config=userconfig,
experiments=experiments, header=user_qobj_header)
<|code_end|>
qiskit/qobj/_converter.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Qobj conversion helpers."""
import logging
from qiskit.exceptions import QiskitError
from .qobj import QOBJ_VERSION
from .qobj import QobjItem
logger = logging.getLogger(__name__)
def qobj_to_dict(qobj, version=QOBJ_VERSION):
"""Convert a Qobj to another version of the schema.
Convert all types to native python types.
Args:
qobj (Qobj): input Qobj.
version (string): target version for conversion.
Returns:
dict: dictionary representing the qobj for the specified schema version.
Raises:
QiskitError: if the target version is not supported.
"""
if version == QOBJ_VERSION:
return qobj_to_dict_current_version(qobj)
elif version == '0.0.1':
return_dict = qobj_to_dict_previous_version(qobj)
return {key: QobjItem._expand_item(value) for key, value
in return_dict.items()}
else:
raise QiskitError('Invalid target version for conversion.')
def qobj_to_dict_current_version(qobj):
"""
Return a dictionary representation of the QobjItem, recursively converting
its public attributes.
Args:
qobj (Qobj): input Qobj.
Returns:
dict: dictionary representing the qobj.
"""
return qobj.as_dict()
def qobj_to_dict_previous_version(qobj):
"""Convert a Qobj to the 0.0.1 version of the schema.
Args:
qobj (Qobj): input Qobj.
Returns:
dict: dictionary representing the qobj for the specified schema version.
"""
# Build the top Qobj element.
converted = {
'id': qobj.qobj_id,
'config': {
'shots': qobj.config.shots,
'backend_name': getattr(qobj.header, 'backend_name', None),
'max_credits': getattr(qobj.config, 'max_credits', None)
},
'circuits': []
}
# Update configuration: qobj.config might have extra items.
for key, value in qobj.config.__dict__.items():
if key not in ('shots', 'memory_slots', 'max_credits', 'seed'):
converted['config'][key] = value
# Add circuits.
for experiment in qobj.experiments:
circuit_config = getattr(experiment, 'config', {})
if circuit_config:
circuit_config = circuit_config.as_dict()
circuit_config['seed'] = getattr(qobj.config, 'seed', None)
circuit = {
'name': getattr(experiment.header, 'name', None),
'config': circuit_config,
'compiled_circuit': {
'header': experiment.header.as_dict(),
'operations': [instruction.as_dict() for instruction in
experiment.instructions]
},
'compiled_circuit_qasm': getattr(experiment.header,
'compiled_circuit_qasm', None)
}
converted['circuits'].append(circuit)
return converted
<|code_end|>
|
qiskit/converters/circuits_to_qobj.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Compile function for converting a list of circuits to the qobj"""
import uuid
import warnings
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.qobj import Qobj, QobjConfig, QobjExperiment, QobjInstruction, QobjHeader
from qiskit.qobj import QobjExperimentConfig, QobjExperimentHeader, QobjConditional
from qiskit.qobj.run_config import RunConfig
def circuits_to_qobj(circuits, user_qobj_header=None, run_config=None,
qobj_id=None, backend_name=None,
config=None, shots=None, max_credits=None,
basis_gates=None,
coupling_map=None, seed=None, memory=None):
"""Convert a list of circuits into a qobj.
Args:
circuits (list[QuantumCircuits] or QuantumCircuit): circuits to compile
user_qobj_header (QobjHeader): header to pass to the results
run_config (RunConfig): RunConfig object
qobj_id (int): identifier for the generated qobj
backend_name (str): TODO: delete after qiskit-terra 0.8
config (dict): TODO: delete after qiskit-terra 0.8
shots (int): TODO: delete after qiskit-terra 0.8
max_credits (int): TODO: delete after qiskit-terra 0.8
basis_gates (str): TODO: delete after qiskit-terra 0.8
coupling_map (list): TODO: delete after qiskit-terra 0.8
seed (int): TODO: delete after qiskit-terra 0.8
memory (bool): TODO: delete after qiskit-terra 0.8
Returns:
Qobj: the Qobj to be run on the backends
"""
user_qobj_header = user_qobj_header or QobjHeader()
run_config = run_config or RunConfig()
if isinstance(circuits, QuantumCircuit):
circuits = [circuits]
if backend_name:
warnings.warn('backend_name is not required anymore', DeprecationWarning)
user_qobj_header.backend_name = backend_name
if config:
warnings.warn('config is not used anymore. Set all configs in '
'run_config.', DeprecationWarning)
if shots:
warnings.warn('shots is not used anymore. Set it via run_config.', DeprecationWarning)
run_config.shots = shots
if basis_gates:
warnings.warn('basis_gates was unused and will be removed.', DeprecationWarning)
if coupling_map:
warnings.warn('coupling_map was unused and will be removed.', DeprecationWarning)
if seed:
warnings.warn('seed is not used anymore. Set it via run_config', DeprecationWarning)
run_config.seed = seed
if memory:
warnings.warn('memory is not used anymore. Set it via run_config', DeprecationWarning)
run_config.memory = memory
if max_credits:
warnings.warn('max_credits is not used anymore. Set it via run_config', DeprecationWarning)
run_config.max_credits = max_credits
userconfig = QobjConfig(**run_config.to_dict())
experiments = []
max_n_qubits = 0
max_memory_slots = 0
for circuit in circuits:
# header stuff
n_qubits = 0
memory_slots = 0
qubit_labels = []
clbit_labels = []
qreg_sizes = []
creg_sizes = []
for qreg in circuit.qregs:
qreg_sizes.append([qreg.name, qreg.size])
for j in range(qreg.size):
qubit_labels.append([qreg.name, j])
n_qubits += qreg.size
for creg in circuit.cregs:
creg_sizes.append([creg.name, creg.size])
for j in range(creg.size):
clbit_labels.append([creg.name, j])
memory_slots += creg.size
# TODO: why do we need creq_sizes and qreg_sizes in header
# TODO: we need to rethink memory_slots as they are tied to classical bit
experimentheader = QobjExperimentHeader(qubit_labels=qubit_labels,
n_qubits=n_qubits,
qreg_sizes=qreg_sizes,
clbit_labels=clbit_labels,
memory_slots=memory_slots,
creg_sizes=creg_sizes,
name=circuit.name)
# TODO: why do we need n_qubits and memory_slots in both the header and the config
experimentconfig = QobjExperimentConfig(n_qubits=n_qubits, memory_slots=memory_slots)
instructions = []
for opt in circuit.data:
current_instruction = QobjInstruction(name=opt.name)
if opt.qargs:
qubit_indices = [qubit_labels.index([qubit[0].name, qubit[1]])
for qubit in opt.qargs]
current_instruction.qubits = qubit_indices
if opt.cargs:
clbit_indices = [clbit_labels.index([clbit[0].name, clbit[1]])
for clbit in opt.cargs]
current_instruction.memory = clbit_indices
if opt.params:
params = list(map(lambda x: x.evalf(), opt.params))
current_instruction.params = params
# TODO: I really dont like this for snapshot. I also think we should change
# type to snap_type
if opt.name == "snapshot":
current_instruction.label = str(opt.params[0])
current_instruction.type = str(opt.params[1])
if opt.control:
mask = 0
for clbit in clbit_labels:
if clbit[0] == opt.control[0].name:
mask |= (1 << clbit_labels.index(clbit))
current_instruction.conditional = QobjConditional(mask="0x%X" % mask,
type='equals',
val="0x%X" % opt.control[1])
instructions.append(current_instruction)
experiments.append(QobjExperiment(instructions=instructions, header=experimentheader,
config=experimentconfig))
if n_qubits > max_n_qubits:
max_n_qubits = n_qubits
if memory_slots > max_memory_slots:
max_memory_slots = memory_slots
userconfig.memory_slots = max_memory_slots
userconfig.n_qubits = max_n_qubits
return Qobj(qobj_id=qobj_id or str(uuid.uuid4()), config=userconfig,
experiments=experiments, header=user_qobj_header)
<|code_end|>
qiskit/qobj/_converter.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Qobj conversion helpers."""
import logging
from qiskit.exceptions import QiskitError
from .qobj import QOBJ_VERSION
from .qobj import QobjItem
logger = logging.getLogger(__name__)
def qobj_to_dict(qobj, version=QOBJ_VERSION):
"""Convert a Qobj to another version of the schema.
Convert all types to native python types.
Args:
qobj (Qobj): input Qobj.
version (string): target version for conversion.
Returns:
dict: dictionary representing the qobj for the specified schema version.
Raises:
QiskitError: if the target version is not supported.
"""
if version == QOBJ_VERSION:
return qobj_to_dict_current_version(qobj)
elif version == '0.0.1':
return_dict = qobj_to_dict_previous_version(qobj)
return {key: QobjItem._expand_item(value) for key, value
in return_dict.items()}
else:
raise QiskitError('Invalid target version for conversion.')
def qobj_to_dict_current_version(qobj):
"""
Return a dictionary representation of the QobjItem, recursively converting
its public attributes.
Args:
qobj (Qobj): input Qobj.
Returns:
dict: dictionary representing the qobj.
"""
return qobj.as_dict()
def qobj_to_dict_previous_version(qobj):
"""Convert a Qobj to the 0.0.1 version of the schema.
Args:
qobj (Qobj): input Qobj.
Returns:
dict: dictionary representing the qobj for the specified schema version.
"""
# Build the top Qobj element.
converted = {
'id': qobj.qobj_id,
'config': {
'shots': qobj.config.shots,
'backend_name': getattr(qobj.header, 'backend_name', None),
'max_credits': getattr(qobj.config, 'max_credits', None)
},
'circuits': []
}
# Update configuration: qobj.config might have extra items.
for key, value in qobj.config.__dict__.items():
if key not in ('shots', 'memory_slots', 'max_credits', 'seed'):
converted['config'][key] = value
# Add circuits.
for experiment in qobj.experiments:
circuit_config = getattr(experiment, 'config', {})
if circuit_config:
circuit_config = circuit_config.as_dict()
circuit_config['seed'] = getattr(qobj.config, 'seed', None)
circuit = {
'name': getattr(experiment.header, 'name', None),
'config': circuit_config,
'compiled_circuit': {
'header': experiment.header.as_dict(),
'operations': [instruction.as_dict() for instruction in
experiment.instructions]
},
}
converted['circuits'].append(circuit)
return converted
<|code_end|>
|
Transpiler reorders measure through barriers
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: master
- **Python version**: 3.6
- **Operating system**: MacOS
### What is the current behavior?
A recent merge into master (I think probably #1705) is `qiskit-aer` master to fail because it reorders measurements past barriers.
### Steps to reproduce the problem
One of the Aer tests is a non-local measure noise: if I measure qubit 0, apply a noise operator on qubit 1. To test this the circuit has to ensure measure of qubit 0 happens before measure of qubit 1 and looks like
```
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circ = QuantumCircuit(qr, cr)
circ.measure(qr[0], cr[0])
circ.barrier(qr)
circ.measure(qr[1], cr[1])
```
Before this would ensure the output qobj had instructions:
```
[QobjInstruction(memory=[0], name='measure', qubits=[0]),
QobjInstruction(memory=[1], name='measure', qubits=[1])]
```
But now it reorders the measures past the barrier returning:
```
[QobjInstruction(memory=[1], name='measure', qubits=[1]),
QobjInstruction(memory=[0], name='measure', qubits=[0])]
```
### What is the expected behavior?
Measure instructions should respect barrier placement
### Suggested solutions
|
qiskit/dagcircuit/_dagcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Object to represent a quantum circuit as a directed acyclic graph.
The nodes in the graph are either input/output nodes or operation nodes.
The operation nodes are elements of a basis that is part of the circuit.
The QASM definitions of the basis elements are carried with the circuit.
The edges correspond to qubits or bits in the circuit. A directed edge
from node A to node B means that the (qu)bit passes from the output of A
to the input of B. The object's methods allow circuits to be constructed,
composed, and modified. Some natural properties like depth can be computed
directly from the graph.
"""
import re
from collections import OrderedDict
import copy
import itertools
import networkx as nx
from qiskit.circuit.quantumregister import QuantumRegister
from qiskit.circuit.classicalregister import ClassicalRegister
from qiskit.circuit.gate import Gate
from .exceptions import DAGCircuitError
class DAGCircuit:
"""
Quantum circuit as a directed acyclic graph.
There are 3 types of nodes in the graph: inputs, outputs, and operations.
The nodes are connected by directed edges that correspond to qubits and
bits.
"""
# pylint: disable=invalid-name
def __init__(self):
"""Create an empty circuit."""
# Circuit name. Generally, this corresponds to the name
# of the QuantumCircuit from which the DAG was generated.
self.name = None
# Set of wires (Register,idx) in the dag
self.wires = []
# Map from wire (Register,idx) to input nodes of the graph
self.input_map = OrderedDict()
# Map from wire (Register,idx) to output nodes of the graph
self.output_map = OrderedDict()
# Running count of the total number of nodes
self.node_counter = 0
# Map of user defined gates to ast nodes defining them
self.gates = OrderedDict()
# Map of named operations in this circuit and their signatures.
# The signature is an integer tuple (nq,nc,np) specifying the
# number of input qubits, input bits, and real parameters.
# The definition is external to the circuit object.
self.basis = OrderedDict()
self.add_basis_element(name="U", number_qubits=1,
number_classical=0, number_parameters=3)
self.add_basis_element("CX", 2, 0, 0)
self.add_basis_element("measure", 1, 1, 0)
self.add_basis_element("reset", 1, 0, 0)
self.add_basis_element("barrier", -1)
# Directed multigraph whose nodes are inputs, outputs, or operations.
# Operation nodes have equal in- and out-degrees and carry
# additional data about the operation, including the argument order
# and parameter values.
# Input nodes have out-degree 1 and output nodes have in-degree 1.
# Edges carry wire labels (reg,idx) and each operation has
# corresponding in- and out-edges with the same wire labels.
self.multi_graph = nx.MultiDiGraph()
# Map of qreg name to QuantumRegister object
self.qregs = OrderedDict()
# Map of creg name to ClassicalRegister object
self.cregs = OrderedDict()
def get_qubits(self):
"""Return a list of qubits as (QuantumRegister, index) pairs."""
return [(v, i) for k, v in self.qregs.items() for i in range(v.size)]
def get_bits(self):
"""Return a list of bits as (ClassicalRegister, index) pairs."""
return [(v, i) for k, v in self.cregs.items() for i in range(v.size)]
# TODO: unused function. is it needed?
def rename_register(self, regname, newname):
"""Rename a classical or quantum register throughout the circuit.
regname = existing register name string
newname = replacement register name string
"""
if regname == newname:
return
if newname in self.qregs or newname in self.cregs:
raise DAGCircuitError("duplicate register name %s" % newname)
if regname not in self.qregs and regname not in self.cregs:
raise DAGCircuitError("no register named %s" % regname)
if regname in self.qregs:
reg = self.qregs[regname]
reg.name = newname
self.qregs[newname] = reg
self.qregs.pop(regname, None)
if regname in self.cregs:
reg = self.cregs[regname]
reg.name = newname
self.qregs[newname] = reg
self.qregs.pop(regname, None)
# n node d = data
for _, d in self.multi_graph.nodes(data=True):
if d["type"] == "in" or d["type"] == "out":
if regname in d["name"]:
d["name"] = re.sub(regname, newname, d["name"])
elif d["type"] == "op":
qa = []
for a in d["qargs"]:
if a[0] == regname:
a = (newname, a[1])
qa.append(a)
d["qargs"] = qa
ca = []
for a in d["cargs"]:
if a[0] == regname:
a = (newname, a[1])
ca.append(a)
d["cargs"] = ca
if d["condition"] is not None:
if d["condition"][0] == regname:
d["condition"] = (newname, d["condition"][1])
# eX = edge, d= data
for _, _, d in self.multi_graph.edges(data=True):
if regname in d["name"]:
d["name"] = re.sub(regname, newname, d["name"])
def remove_all_ops_named(self, opname):
"""Remove all operation nodes with the given name."""
for n in self.get_named_nodes(opname):
self._remove_op_node(n)
def add_qreg(self, qreg):
"""Add all wires in a quantum register."""
if not isinstance(qreg, QuantumRegister):
raise DAGCircuitError("not a QuantumRegister instance.")
if qreg.name in self.qregs:
raise DAGCircuitError("duplicate register %s" % qreg.name)
self.qregs[qreg.name] = qreg
for j in range(qreg.size):
self._add_wire((qreg, j))
def add_creg(self, creg):
"""Add all wires in a classical register."""
if not isinstance(creg, ClassicalRegister):
raise DAGCircuitError("not a ClassicalRegister instance.")
if creg.name in self.cregs:
raise DAGCircuitError("duplicate register %s" % creg.name)
self.cregs[creg.name] = creg
for j in range(creg.size):
self._add_wire((creg, j))
def _add_wire(self, wire):
"""Add a qubit or bit to the circuit.
Args:
wire (tuple): (Register,int) containing a register instance and index
This adds a pair of in and out nodes connected by an edge.
Raises:
DAGCircuitError: if trying to add duplicate wire
"""
if wire not in self.wires:
self.wires.append(wire)
self.node_counter += 1
self.input_map[wire] = self.node_counter
self.node_counter += 1
self.output_map[wire] = self.node_counter
in_node = self.input_map[wire]
out_node = self.output_map[wire]
self.multi_graph.add_edge(in_node, out_node)
self.multi_graph.node[in_node]["type"] = "in"
self.multi_graph.node[out_node]["type"] = "out"
self.multi_graph.node[in_node]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.node[out_node]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.node[in_node]["wire"] = wire
self.multi_graph.node[out_node]["wire"] = wire
self.multi_graph.adj[in_node][out_node][0]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.adj[in_node][out_node][0]["wire"] = wire
else:
raise DAGCircuitError("duplicate wire %s" % (wire,))
def add_basis_element(self, name, number_qubits,
number_classical=0, number_parameters=0):
"""Add an operation to the basis.
name is string label for operation
number_qubits is number of qubit arguments
number_classical is number of bit arguments
number_parameters is number of real parameters
The parameters (nq,nc,np) are ignored for the special case
when name = "barrier". The barrier instruction has a variable
number of qubit arguments.
"""
if name not in self.basis:
self.basis[name] = (
number_qubits,
number_classical,
number_parameters)
if name in self.gates:
if self.gates[name]["n_args"] != number_parameters or \
self.gates[name]["n_bits"] != number_qubits or number_classical != 0:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def add_gate_data(self, name, gatedata):
"""Add the definition of a gate.
gatedata is dict with fields:
"print" = True or False
"opaque" = True or False
"n_args" = number of real parameters
"n_bits" = number of qubits
"args" = list of parameter names
"bits" = list of qubit names
"body" = GateBody AST node
"""
if name not in self.gates:
self.gates[name] = gatedata
if name in self.basis:
if self.basis[name][0] != self.gates[name]["n_bits"] or \
self.basis[name][1] != 0 or \
self.basis[name][2] != self.gates[name]["n_args"]:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def _check_basis_data(self, op, qargs, cargs):
"""Check the arguments against the data for this operation.
Args:
op (Instruction): a quantum operation
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple]): cbits that op will be applied to
Raises:
DAGCircuitError: If the check fails.
"""
# Check that we have this operation
if op.name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations" % op.name)
# Check the number of arguments matches the signature
if op.name in ["barrier"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s" % op.name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s" % op.name)
elif op.name in ["snapshot", "noise", "save", "load"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s" % op.name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s" % op.name)
else:
if len(qargs) != self.basis[op.name][0]:
raise DAGCircuitError("incorrect number of qubits for %s" % op.name)
if len(cargs) != self.basis[op.name][1]:
raise DAGCircuitError("incorrect number of bits for %s" % op.name)
def _check_condition(self, name, condition):
"""Verify that the condition is valid.
Args:
name (string): used for error reporting
condition (tuple or None): a condition tuple (ClassicalRegister,int)
Raises:
DAGCircuitError: if conditioning on an invalid register
"""
# Verify creg exists
if condition is not None and condition[0].name not in self.cregs:
raise DAGCircuitError("invalid creg in condition for %s" % name)
def _check_bits(self, args, amap):
"""Check the values of a list of (qu)bit arguments.
For each element of args, check that amap contains it.
Args:
args (list): (register,idx) tuples
amap (dict): a dictionary keyed on (register,idx) tuples
Raises:
DAGCircuitError: if a qubit is not contained in amap
"""
# Check for each wire
for wire in args:
if wire not in amap:
raise DAGCircuitError("(qu)bit %s[%d] not found" % (wire[0].name, wire[1]))
def _bits_in_condition(self, cond):
"""Return a list of bits in the given condition.
Args:
cond (tuple or None): optional condition (ClassicalRegister, int)
Returns:
list[(ClassicalRegister, idx)]: list of bits
"""
all_bits = []
if cond is not None:
all_bits.extend([(cond[0], j) for j in range(self.cregs[cond[0].name].size)])
return all_bits
def _add_op_node(self, op, qargs, cargs, condition=None):
"""Add a new operation node to the graph and assign properties.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list): list of quantum wires to attach to.
cargs (list): list of classical wires to attach to.
condition (tuple or None): optional condition (ClassicalRegister, int)
"""
# Add a new operation node to the graph
self.node_counter += 1
self.multi_graph.add_node(self.node_counter)
# Update the operation itself. TODO: remove after qargs not connected to op
op.qargs = qargs
op.cargs = cargs
# Update that operation node's data
self.multi_graph.node[self.node_counter]["type"] = "op"
self.multi_graph.node[self.node_counter]["op"] = op
self.multi_graph.node[self.node_counter]["name"] = op.name
self.multi_graph.node[self.node_counter]["qargs"] = qargs
self.multi_graph.node[self.node_counter]["cargs"] = cargs
self.multi_graph.node[self.node_counter]["condition"] = condition
def apply_operation_back(self, op, qargs=None, cargs=None, condition=None):
"""Apply an operation to the output of the circuit.
TODO: make `qargs` and `cargs` mandatory, when they are dropped from op.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple]): cbits that op will be applied to
condition (tuple or None): optional condition (ClassicalRegister, int)
Raises:
DAGCircuitError: if a leaf node is connected to multiple outputs
"""
qargs = qargs or op.qargs
cargs = cargs or op.cargs
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(op, qargs, cargs)
self._check_condition(op.name, condition)
self._check_bits(qargs, self.output_map)
self._check_bits(all_cbits, self.output_map)
self._add_op_node(op, qargs, cargs, condition)
# Add new in-edges from predecessors of the output nodes to the
# operation node while deleting the old in-edges of the output nodes
# and adding new edges from the operation node to each output node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.predecessors(self.output_map[q]))
if len(ie) != 1:
raise DAGCircuitError("output node has multiple in-edges")
self.multi_graph.add_edge(ie[0], self.node_counter,
name="%s[%s]" % (q[0].name, q[1]), wire=q)
self.multi_graph.remove_edge(ie[0], self.output_map[q])
self.multi_graph.add_edge(self.node_counter, self.output_map[q],
name="%s[%s]" % (q[0].name, q[1]), wire=q)
def apply_operation_front(self, op, qargs=None, cargs=None, condition=None):
"""Apply an operation to the input of the circuit.
TODO: make `qargs` and `cargs` mandatory, when they are dropped from op.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple]): cbits that op will be applied to
condition (tuple or None): optional condition (ClassicalRegister, value)
Raises:
DAGCircuitError: if initial nodes connected to multiple out edges
"""
qargs = qargs or op.qargs
cargs = cargs or op.cargs
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(op, qargs, cargs)
self._check_condition(op.name, condition)
self._check_bits(qargs, self.input_map)
self._check_bits(all_cbits, self.input_map)
self._add_op_node(op, qargs, cargs, condition)
# Add new out-edges to successors of the input nodes from the
# operation node while deleting the old out-edges of the input nodes
# and adding new edges to the operation node from each input node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.successors(self.input_map[q]))
if len(ie) != 1:
raise DAGCircuitError("input node has multiple out-edges")
self.multi_graph.add_edge(self.node_counter, ie[0],
name="%s[%s]" % (q[0].name, q[1]), wire=q)
self.multi_graph.remove_edge(self.input_map[q], ie[0])
self.multi_graph.add_edge(self.input_map[q], self.node_counter,
name="%s[%s]" % (q[0].name, q[1]), wire=q)
def _make_union_basis(self, input_circuit):
"""Return a new basis map.
The new basis is a copy of self.basis with
new elements of input_circuit.basis added.
input_circuit is a DAGCircuit
"""
union_basis = self.basis.copy()
for g in input_circuit.basis:
if g not in union_basis:
union_basis[g] = input_circuit.basis[g]
if union_basis[g] != input_circuit.basis[g]:
raise DAGCircuitError("incompatible basis")
return union_basis
def _make_union_gates(self, input_circuit):
"""Return a new gates map.
The new gates are a copy of self.gates with
new elements of input_circuit.gates added.
input_circuit is a DAGCircuit
NOTE: gates in input_circuit that are also in self must
be *identical* to the gates in self
"""
union_gates = {}
for k, v in self.gates.items():
union_gates[k] = v
for k, v in input_circuit.gates.items():
if k not in union_gates:
union_gates[k] = v
if union_gates[k]["opaque"] != input_circuit.gates[k]["opaque"] or \
union_gates[k]["n_args"] != input_circuit.gates[k]["n_args"] or \
union_gates[k]["n_bits"] != input_circuit.gates[k]["n_bits"] or \
union_gates[k]["args"] != input_circuit.gates[k]["args"] or \
union_gates[k]["bits"] != input_circuit.gates[k]["bits"]:
raise DAGCircuitError("inequivalent gate definitions for %s"
% k)
return union_gates
def _check_edgemap_registers(self, edge_map, keyregs, valregs, valreg=True):
"""Check that wiremap neither fragments nor leaves duplicate registers.
1. There are no fragmented registers. A register in keyregs
is fragmented if not all of its (qu)bits are renamed by edge_map.
2. There are no duplicate registers. A register is duplicate if
it appears in both self and keyregs but not in edge_map.
Args:
edge_map (dict): map from (reg,idx) in keyregs to (reg,idx) in valregs
keyregs (dict): a map from register names to Register objects
valregs (dict): a map from register names to Register objects
valreg (bool): if False the method ignores valregs and does not
add regs for bits in the edge_map image that don't appear in valregs
Returns:
set(Register): the set of regs to add to self
Raises:
DAGCircuitError: if the wiremap fragments, or duplicates exist
"""
# FIXME: some mixing of objects and strings here are awkward (due to
# self.qregs/self.cregs still keying on string.
add_regs = set()
reg_frag_chk = {}
for v in keyregs.values():
reg_frag_chk[v] = {j: False for j in range(len(v))}
for k in edge_map.keys():
if k[0].name in keyregs:
reg_frag_chk[k[0]][k[1]] = True
for k, v in reg_frag_chk.items():
s = set(v.values())
if len(s) == 2:
raise DAGCircuitError("edge_map fragments reg %s" % k)
elif s == set([False]):
if k in self.qregs.values() or k in self.cregs.values():
raise DAGCircuitError("unmapped duplicate reg %s" % k)
else:
# Add registers that appear only in keyregs
add_regs.add(k)
else:
if valreg:
# If mapping to a register not in valregs, add it.
# (k,0) exists in edge_map because edge_map doesn't
# fragment k
if not edge_map[(k, 0)][0].name in valregs:
size = max(map(lambda x: x[1],
filter(lambda x: x[0] == edge_map[(k, 0)][0],
edge_map.values())))
qreg = QuantumRegister(size + 1, edge_map[(k, 0)][0].name)
add_regs.add(qreg)
return add_regs
def _check_wiremap_validity(self, wire_map, keymap, valmap):
"""Check that the wiremap is consistent.
Check that the wiremap refers to valid wires and that
those wires have consistent types.
Args:
wire_map (dict): map from (register,idx) in keymap to
(register,idx) in valmap
keymap (dict): a map whose keys are wire_map keys
valmap (dict): a map whose keys are wire_map values
Raises:
DAGCircuitError: if wire_map not valid
"""
for k, v in wire_map.items():
kname = "%s[%d]" % (k[0].name, k[1])
vname = "%s[%d]" % (v[0].name, v[1])
if k not in keymap:
raise DAGCircuitError("invalid wire mapping key %s" % kname)
if v not in valmap:
raise DAGCircuitError("invalid wire mapping value %s" % vname)
if type(k) is not type(v):
raise DAGCircuitError("inconsistent wire_map at (%s,%s)" %
(kname, vname))
def _map_condition(self, wire_map, condition):
"""Use the wire_map dict to change the condition tuple's creg name.
Args:
wire_map (dict): a map from wires to wires
condition (tuple): (ClassicalRegister,int)
Returns:
tuple(ClassicalRegister,int): new condition
"""
if condition is None:
new_condition = None
else:
# Map the register name, using fact that registers must not be
# fragmented by the wire_map (this must have been checked
# elsewhere)
bit0 = (condition[0], 0)
new_condition = (wire_map.get(bit0, bit0)[0], condition[1])
return new_condition
def extend_back(self, dag, edge_map=None):
"""Add `dag` at the end of `self`, using `edge_map`.
"""
edge_map = edge_map or {}
for qreg in dag.qregs.values():
if qreg.name not in self.qregs:
self.add_qreg(QuantumRegister(qreg.size, qreg.name))
edge_map.update([(qbit, qbit) for qbit in qreg if qbit not in edge_map])
for creg in dag.cregs.values():
if creg.name not in self.cregs:
self.add_creg(ClassicalRegister(creg.size, creg.name))
edge_map.update([(cbit, cbit) for cbit in creg if cbit not in edge_map])
self.compose_back(dag, edge_map)
def compose_back(self, input_circuit, edge_map=None):
"""Apply the input circuit to the output of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of input qubits of the input circuit are mapped
to a subset of output qubits of this circuit.
Args:
input_circuit (DAGCircuit): circuit to append
edge_map (dict): map {(Register, int): (Register, int)}
from the output wires of input_circuit to input wires
of self.
Raises:
DAGCircuitError: if missing, duplicate or incosistent wire
"""
edge_map = edge_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map for duplicate values
if len(set(edge_map.values())) != len(edge_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_edgemap_registers(edge_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(edge_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(edge_map, input_circuit.input_map,
self.output_map)
# Compose
self.basis = union_basis
self.gates = union_gates
for node in nx.topological_sort(input_circuit.multi_graph):
nd = input_circuit.multi_graph.node[node]
if nd["type"] == "in":
# if in wire_map, get new name, else use existing name
m_wire = edge_map.get(nd["wire"], nd["wire"])
# the mapped wire should already exist
if m_wire not in self.output_map:
raise DAGCircuitError("wire %s[%d] not in self" % (m_wire[0].name, m_wire[1]))
if nd["wire"] not in input_circuit.wires:
raise DAGCircuitError("inconsistent wire type for %s[%d] in input_circuit"
% (nd["wire"][0].name, nd["wire"][1]))
elif nd["type"] == "out":
# ignore output nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(edge_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: edge_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: edge_map.get(x, x), nd["cargs"]))
self.apply_operation_back(nd["op"], m_qargs, m_cargs, condition)
else:
raise DAGCircuitError("bad node type %s" % nd["type"])
# FIXME: this does not work as expected. it is also not used anywhere
def compose_front(self, input_circuit, wire_map=None):
"""Apply the input circuit to the input of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of output qubits of the input circuit are mapped
to a subset of input qubits of this circuit.
Args:
input_circuit (DAGCircuit): circuit to append
wire_map (dict): map {(Register, int): (Register, int)}
from the output wires of input_circuit to input wires
of self.
Raises:
DAGCircuitError: missing, duplicate or inconsistent wire
"""
wire_map = wire_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_edgemap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.output_map,
self.input_map)
# Compose
self.basis = union_basis
self.gates = union_gates
for n in reversed(list(nx.topological_sort(input_circuit.multi_graph))):
nd = input_circuit.multi_graph.node[n]
if nd["type"] == "out":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["wire"], nd["wire"])
# the mapped wire should already exist
if m_name not in self.input_map:
raise DAGCircuitError("wire %s[%d] not in self" % (m_name[0].name, m_name[1]))
if nd["wire"] not in input_circuit.wires:
raise DAGCircuitError(
"inconsistent wire for %s[%d] in input_circuit"
% (nd["wire"][0].name, nd["wire"][1]))
elif nd["type"] == "in":
# ignore input nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
self.apply_operation_front(nd["op"], condition)
else:
raise DAGCircuitError("bad node type %s" % nd["type"])
def size(self):
"""Return the number of operations."""
return self.multi_graph.order() - 2 * len(self.wires)
def depth(self):
"""Return the circuit depth.
Returns:
int: the circuit depth
Raises:
DAGCircuitError: if not a directed acyclic graph
"""
if not nx.is_directed_acyclic_graph(self.multi_graph):
raise DAGCircuitError("not a DAG")
return nx.dag_longest_path_length(self.multi_graph) - 1
def width(self):
"""Return the total number of qubits used by the circuit."""
return len(self.wires) - self.num_cbits()
def num_cbits(self):
"""Return the total number of bits used by the circuit."""
return sum(creg.size for creg in self.cregs.values())
def num_tensor_factors(self):
"""Compute how many components the circuit can decompose into."""
return nx.number_weakly_connected_components(self.multi_graph)
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.gates[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.gates[name]["n_args"] > 0:
out += "(" + ",".join(self.gates[name]["args"]) + ")"
out += " " + ",".join(self.gates[name]["bits"])
if self.gates[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.gates[name]["body"].qasm() + "}"
return out
def qasm(self, no_decls=False, qeflag=False, aliases=None, eval_symbols=False):
"""Return a string containing QASM for this circuit.
Args:
qeflag (bool): if True, add a line to include "qelib1.inc"
and only generate gate code for gates not in qelib1.
eval_symbols (bool): if True, evaluate all symbolic
expressions to their floating point representation.
no_decls (bool): if True, only print the instructions.
aliases (dict): if not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
Returns:
str: OpenQASM representation of the DAG
Raises:
DAGCircuitError: if dag nodes not in expected format
"""
# TODO: some of the input flags are not needed anymore
# Rename qregs if necessary
if aliases:
qregdata = OrderedDict()
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
# Write top matter
if no_decls:
out = ""
else:
printed_gates = []
out = "OPENQASM 2.0;\n"
if qeflag:
out += "include \"qelib1.inc\";\n"
for k, v in qregdata.items():
out += "qreg %s[%d];\n" % (k, v.size)
for k, v in self.cregs.items():
out += "creg %s[%d];\n" % (k, v.size)
omit = ["U", "CX", "measure", "reset", "barrier"]
# TODO: dagcircuit shouldn't know about extensions
if qeflag:
qelib = ["u3", "u2", "u1", "cx", "id", "x", "y", "z", "h",
"s", "sdg", "t", "tdg", "cz", "cy", "ccx", "cu1",
"cu3", "swap", "cswap", "u0", "rx", "ry", "rz",
"ch", "crz", "rzz"]
omit.extend(qelib)
printed_gates.extend(qelib)
simulator_instructions = ["snapshot", "save", "load", "noise", "wait"]
omit.extend(simulator_instructions)
for k in self.basis.keys():
if k not in omit:
if not self.gates[k]["opaque"]:
calls = self.gates[k]["body"].calls()
for c in calls:
if c not in printed_gates:
out += self._gate_string(c) + "\n"
printed_gates.append(c)
if k not in printed_gates:
out += self._gate_string(k) + "\n"
printed_gates.append(k)
# Write the instructions
for n in nx.lexicographical_topological_sort(
self.multi_graph, key=lambda x: (self.multi_graph.nodes[x]["type"],
self.multi_graph.nodes[x]["name"])):
nd = self.multi_graph.node[n]
if nd["type"] == "op":
if nd["condition"] is not None:
out += "if(%s==%d) " \
% (nd["condition"][0], nd["condition"][1])
if not nd["cargs"]:
nm = nd["op"].name
if aliases:
qarglist = map(lambda x: aliases[x], nd["qargs"])
else:
qarglist = nd["qargs"]
qarg = ",".join(map(lambda x: "%s[%d]" % (x[0].name, x[1]),
qarglist))
if nd["op"].params:
if eval_symbols:
param = ",".join(map(lambda x: str(x.evalf()),
nd["op"].params))
else:
param = ",".join(map(lambda x: x.replace("**", "^"),
map(str, nd["op"].params)))
out += "%s(%s) %s;\n" % (nm, param, qarg)
else:
out += "%s %s;\n" % (nm, qarg)
else:
if nd["op"].name == "measure":
if len(nd["cargs"]) != 1 or len(nd["qargs"]) != 1 \
or nd["op"].param:
raise DAGCircuitError("bad node data")
qname = nd["qargs"][0][0].name
qindex = nd["qargs"][0][1]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
out += "measure %s[%d] -> %s[%d];\n" \
% (qname,
qindex,
nd["cargs"][0][0].name,
nd["cargs"][0][1])
else:
raise DAGCircuitError("bad node data")
return out
def _check_wires_list(self, wires, op, input_circuit, condition=None):
"""Check that a list of wires satisfies some conditions.
- no duplicate names
- correct length for operation
- elements are wires of input_circuit
Raise an exception otherwise.
Args:
wires (list[register, index]): gives an order for (qu)bits
in the input_circuit that is replacing the operation.
op (Instruction): operation
input_circuit (DAGCircuit): replacement circuit for operation
condition (tuple or None): if this instance of the
operation is classically controlled by a (ClassicalRegister, int)
Raises:
DAGCircuitError: if check doesn't pass.
"""
if len(set(wires)) != len(wires):
raise DAGCircuitError("duplicate wires")
wire_tot = len(op.qargs) + len(op.cargs)
if condition is not None:
wire_tot += condition[0].size
if len(wires) != wire_tot:
raise DAGCircuitError("expected %d wires, got %d"
% (wire_tot, len(wires)))
for w in wires:
if w not in input_circuit.wires:
raise DAGCircuitError("wire (%s,%d) not in input circuit"
% (w[0], w[1]))
def _make_pred_succ_maps(self, n):
"""Return predecessor and successor dictionaries.
Args:
n (int): reference to self.multi_graph node id
Returns:
set(dict): set({predecessor_map, successor_map})
These map from wire (Register, int) to predecessor (successor)
nodes of n.
"""
pred_map = {e[2]['wire']: e[0] for e in
self.multi_graph.in_edges(nbunch=n, data=True)}
succ_map = {e[2]['wire']: e[1] for e in
self.multi_graph.out_edges(nbunch=n, data=True)}
return pred_map, succ_map
def _full_pred_succ_maps(self, pred_map, succ_map, input_circuit,
wire_map):
"""Map all wires of the input circuit.
Map all wires of the input circuit to predecessor and
successor nodes in self, keyed on wires in self.
Args:
pred_map (dict): comes from _make_pred_succ_maps
succ_map (dict): comes from _make_pred_succ_maps
input_circuit (DAGCircuit): the input circuit
wire_map (dict): the map from wires of input_circuit to wires of self
Returns:
tuple: full_pred_map, full_succ_map (dict, dict)
Raises:
DAGCircuitError: if more than one predecessor for output nodes
"""
full_pred_map = {}
full_succ_map = {}
for w in input_circuit.input_map:
# If w is wire mapped, find the corresponding predecessor
# of the node
if w in wire_map:
full_pred_map[wire_map[w]] = pred_map[wire_map[w]]
full_succ_map[wire_map[w]] = succ_map[wire_map[w]]
else:
# Otherwise, use the corresponding output nodes of self
# and compute the predecessor.
full_succ_map[w] = self.output_map[w]
full_pred_map[w] = self.multi_graph.predecessors(
self.output_map[w])[0]
if len(list(self.multi_graph.predecessors(self.output_map[w]))) != 1:
raise DAGCircuitError("too many predecessors for %s[%d] "
"output node" % (w[0], w[1]))
return full_pred_map, full_succ_map
@staticmethod
def _match_dag_nodes(node1, node2):
"""
Check if DAG nodes are considered equivalent, e.g. as a node_match for nx.is_isomorphic.
Args:
node1 (dict): A node to compare.
node2 (dict): The other node to compare.
Returns:
Bool: If node1 == node2
"""
copy_node1 = {k: v for (k, v) in node1.items()}
copy_node2 = {k: v for (k, v) in node2.items()}
return copy_node1 == copy_node2
def __eq__(self, other):
return nx.is_isomorphic(self.multi_graph, other.multi_graph,
node_match=DAGCircuit._match_dag_nodes)
def node_nums_in_topological_order(self):
"""
Returns the nodes (their ids) in topological order.
Returns:
list: The list of node numbers in topological order
"""
return nx.topological_sort(self.multi_graph)
def substitute_circuit_all(self, op, input_circuit, wires=None):
"""Replace every occurrence of operation op with input_circuit.
Args:
op (Instruction): operation type to substitute across the dag.
input_circuit (DAGCircuit): what to replace with
wires (list[register, index]): gives an order for (qu)bits
in the input_circuit that is replacing the operation.
Raises:
DAGCircuitError: if met with unexpected predecessor/successors
"""
# TODO: rewrite this method to call substitute_node_with_dag
wires = wires or []
if op.name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% op.name)
self._check_wires_list(wires, op, input_circuit)
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: (QuantumRegister(1, 'proxy'), 0) for w in wires}
add_qregs = self._check_edgemap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Iterate through the nodes of self and replace the selected nodes
# by iterating through the input_circuit, constructing and
# checking the validity of the wire_map for each replacement
# NOTE: We do not replace conditioned gates. One way to implement
# this later is to add or update the conditions of each gate
# that we add from the input_circuit.
self.basis = union_basis
self.gates = union_gates
for n in self.node_nums_in_topological_order():
nd = self.multi_graph.node[n]
if nd["type"] == "op" and nd["op"] == op:
if nd["condition"] is None:
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"], nd["cargs"]]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map)
pred_map, succ_map = self._make_pred_succ_maps(n)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(n)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map,
md["condition"])
m_qargs = [wire_map.get(x, x) for x in md["qargs0"]]
m_cargs = [wire_map.get(x, x) for x in md["cargs0"]]
self._add_op_node(md["op"], m_qargs, m_cargs, condition)
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter,
name="%s[%s]" % (q[0].name, q[1]),
wire=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w],
full_succ_map[w],
name="%s[%s]" % (w[0].name, w[1]),
wire=w)
o_pred = list(self.multi_graph.predecessors(
self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise DAGCircuitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise DAGCircuitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(
p[0], self.output_map[w])
def substitute_node_with_dag(self, node, input_dag, wires=None):
"""Replace one node with dag.
Args:
node (int): node of self.multi_graph (of type "op") to substitute
input_dag (DAGCircuit): circuit that will substitute the node
wires (list[(Register, index)]): gives an order for (qu)bits
in the input circuit. This order gets matched to the node wires
by qargs first, then cargs, then conditions.
Raises:
DAGCircuitError: if met with unexpected predecessor/successors
"""
nd = self.multi_graph.node[node]
condition = nd["condition"]
# the decomposition rule must be amended if used in a
# conditional context. delete the op nodes and replay
# them with the condition.
if condition:
input_dag.add_creg(condition[0])
to_replay = []
for n_it in nx.topological_sort(input_dag.multi_graph):
n = input_dag.multi_graph.nodes[n_it]
if n["type"] == "op":
n["op"].control = condition
to_replay.append(n)
for n in input_dag.get_op_nodes():
input_dag._remove_op_node(n)
for n in to_replay:
input_dag.apply_operation_back(n["op"], condition=condition)
if wires is None:
qwires = [w for w in input_dag.wires if isinstance(w[0], QuantumRegister)]
cwires = [w for w in input_dag.wires if isinstance(w[0], ClassicalRegister)]
wires = qwires + cwires
self._check_wires_list(wires, nd["op"], input_dag, nd["condition"])
union_basis = self._make_union_basis(input_dag)
union_gates = self._make_union_gates(input_dag)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: QuantumRegister(1, 'proxy') for w in wires}
add_qregs = self._check_edgemap_registers(proxy_map,
input_dag.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(proxy_map,
input_dag.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Replace the node by iterating through the input_circuit.
# Constructing and checking the validity of the wire_map.
# If a gate is conditioned, we expect the replacement subcircuit
# to depend on those control bits as well.
self.basis = union_basis
self.gates = union_gates
if nd["type"] != "op":
raise DAGCircuitError("expected node type \"op\", got %s"
% nd["type"])
condition_bit_list = self._bits_in_condition(nd["condition"])
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"],
nd["cargs"],
condition_bit_list]
for i in s])}
self._check_wiremap_validity(wire_map, wires, self.input_map)
pred_map, succ_map = self._make_pred_succ_maps(node)
full_pred_map, full_succ_map = self._full_pred_succ_maps(pred_map, succ_map,
input_dag, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(node)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_dag.multi_graph):
md = input_dag.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map, md["condition"])
m_qargs = list(map(lambda x: wire_map.get(x, x),
md["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x),
md["cargs"]))
self._add_op_node(md["op"], m_qargs, m_cargs, condition)
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter,
name="%s[%s]" % (q[0].name, q[1]),
wire=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w],
full_succ_map[w],
name="%s[%s]" % (w[0].name, w[1]),
wire=w)
o_pred = list(self.multi_graph.predecessors(self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise DAGCircuitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise DAGCircuitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(p[0], self.output_map[w])
def get_op_nodes(self, op=None, data=False):
"""Get the list of "op" nodes in the dag.
Args:
op (Type): Instruction subclass op nodes to return. if op=None, return
all op nodes.
data (bool): Default: False. If True, return a list of tuple
(node_id, node_data). If False, return a list of int (node_id)
Returns:
list: the list of node ids containing the given op.
"""
nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data["type"] == "op":
if op is None or isinstance(node_data["op"], op):
nodes.append((node_id, node_data))
if not data:
nodes = [n[0] for n in nodes]
return nodes
def get_gate_nodes(self, data=False):
"""Get the list of gate nodes in the dag.
Args:
data (bool): Default: False. If True, return a list of tuple
(node_id, node_data). If False, return a list of int (node_id)
Returns:
list: the list of node ids that represent gates.
"""
nodes = []
for node_id, node_data in self.get_op_nodes(data=True):
if isinstance(node_data['op'], Gate):
nodes.append((node_id, node_data))
if not data:
nodes = [n[0] for n in nodes]
return nodes
def get_named_nodes(self, *names):
"""Get the set of "op" nodes with the given name."""
named_nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data['type'] == 'op' and node_data['op'].name in names:
named_nodes.append(node_id)
return named_nodes
def get_2q_nodes(self):
"""Get list of 2-qubit nodes."""
two_q_nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data['type'] == 'op' and len(node_data['qargs']) == 2:
two_q_nodes.append(self.multi_graph.node[node_id])
return two_q_nodes
def get_3q_or_more_nodes(self):
"""Get list of 3-or-more-qubit nodes: (id, data)."""
three_q_nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data['type'] == 'op' and len(node_data['qargs']) >= 3:
three_q_nodes.append((node_id, self.multi_graph.node[node_id]))
return three_q_nodes
def successors(self, node):
"""Returns the successors of a node."""
return self.multi_graph.successors(node)
def quantum_successors(self, node):
"""Returns the successors of a node that are connected by a quantum edge"""
successors = []
for successor in self.successors(node):
if isinstance(self.multi_graph.get_edge_data(node, successor, key=0)['wire'][0],
QuantumRegister):
successors.append(successor)
return successors
def _remove_op_node(self, n):
"""Remove an operation node n.
Add edges from predecessors to successors.
"""
pred_map, succ_map = self._make_pred_succ_maps(n)
self.multi_graph.remove_node(n)
for w in pred_map.keys():
self.multi_graph.add_edge(pred_map[w], succ_map[w],
name="%s[%s]" % (w[0].name, w[1]), wire=w)
def remove_ancestors_of(self, node):
"""Remove all of the ancestor operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
# TODO: probably better to do all at once using
# multi_graph.remove_nodes_from; same for related functions ...
for n in anc:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_descendants_of(self, node):
"""Remove all of the descendant operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
for n in dec:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nonancestors_of(self, node):
"""Remove all of the non-ancestors operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(anc))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nondescendants_of(self, node):
"""Remove all of the non-descendants operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(dec))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def layers(self):
"""Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit.
A layer is a circuit whose gates act on disjoint qubits, i.e.
a layer has depth 1. The total number of layers equals the
circuit depth d. The layers are indexed from 0 to d-1 with the
earliest layer at index 0. The layers are constructed using a
greedy algorithm. Each returned layer is a dict containing
{"graph": circuit graph, "partition": list of qubit lists}.
TODO: Gates that use the same cbits will end up in different
layers as this is currently implemented. This may not be
the desired behavior.
"""
graph_layers = self.multigraph_layers()
try:
next(graph_layers) # Remove input nodes
except StopIteration:
return
def nodes_data(nodes):
"""Construct full nodes from just node ids."""
return ((node_id, self.multi_graph.nodes[node_id]) for node_id in nodes)
for graph_layer in graph_layers:
# Get the op nodes from the layer, removing any input and output nodes.
op_nodes = [node for node in nodes_data(graph_layer) if node[1]["type"] == "op"]
# Stop yielding once there are no more op_nodes in a layer.
if not op_nodes:
return
# Construct a shallow copy of self
new_layer = copy.copy(self)
new_layer.multi_graph = nx.MultiDiGraph()
new_layer.multi_graph.add_nodes_from(nodes_data(self.input_map.values()))
new_layer.multi_graph.add_nodes_from(nodes_data(self.output_map.values()))
# The quantum registers that have an operation in this layer.
support_list = [
op_node[1]["qargs"]
for op_node in op_nodes
if op_node[1]["op"].name not in {"barrier", "snapshot", "save", "load", "noise"}
]
new_layer.multi_graph.add_nodes_from(op_nodes)
# Now add the edges to the multi_graph
# By default we just wire inputs to the outputs.
wires = {self.input_map[wire]: self.output_map[wire]
for wire in self.wires}
# Wire inputs to op nodes, and op nodes to outputs.
for op_node in op_nodes:
args = self._bits_in_condition(op_node[1]["condition"]) \
+ op_node[1]["cargs"] + op_node[1]["qargs"]
arg_ids = (self.input_map[(arg[0], arg[1])] for arg in args)
for arg_id in arg_ids:
wires[arg_id], wires[op_node[0]] = op_node[0], wires[arg_id]
# Add wiring to/from the operations and between unused inputs & outputs.
new_layer.multi_graph.add_edges_from(wires.items())
yield {"graph": new_layer, "partition": support_list}
def serial_layers(self):
"""Yield a layer for all gates of this circuit.
A serial layer is a circuit with one gate. The layers have the
same structure as in layers().
"""
for n in self.node_nums_in_topological_order():
nxt_nd = self.multi_graph.node[n]
if nxt_nd["type"] == "op":
new_layer = DAGCircuit()
for qreg in self.qregs.values():
new_layer.add_qreg(qreg)
for creg in self.cregs.values():
new_layer.add_creg(creg)
new_layer.basis = self.basis.copy()
new_layer.gates = self.gates.copy()
# Save the support of the operation we add to the layer
support_list = []
# Operation data
op = copy.copy(nxt_nd["op"])
qa = copy.copy(nxt_nd["qargs"])
ca = copy.copy(nxt_nd["cargs"])
co = copy.copy(nxt_nd["condition"])
_ = self._bits_in_condition(co)
# Add node to new_layer
new_layer.apply_operation_back(op, qa, ca, co)
# Add operation to partition
if nxt_nd["name"] not in ["barrier",
"snapshot", "save", "load", "noise"]:
support_list.append(list(qa))
l_dict = {"graph": new_layer, "partition": support_list}
yield l_dict
def multigraph_layers(self):
"""Yield layers of the multigraph."""
predecessor_count = dict() # Dict[node, predecessors not visited]
cur_layer = [node for node in self.input_map.values()]
yield cur_layer
next_layer = []
while cur_layer:
for node in cur_layer:
# Count multiedges with multiplicity.
for successor in self.multi_graph.successors(node):
multiplicity = self.multi_graph.number_of_edges(node, successor)
if successor in predecessor_count:
predecessor_count[successor] -= multiplicity
else:
predecessor_count[successor] = \
self.multi_graph.in_degree(successor) - multiplicity
if predecessor_count[successor] == 0:
next_layer.append(successor)
del predecessor_count[successor]
yield next_layer
cur_layer = next_layer
next_layer = []
def collect_runs(self, namelist):
"""Return a set of runs of "op" nodes with the given names.
For example, "... h q[0]; cx q[0],q[1]; cx q[0],q[1]; h q[1]; .."
would produce the tuple of cx nodes as an element of the set returned
from a call to collect_runs(["cx"]). If instead the cx nodes were
"cx q[0],q[1]; cx q[1],q[0];", the method would still return the
pair in a tuple. The namelist can contain names that are not
in the circuit's basis.
Nodes must have only one successor to continue the run.
"""
group_list = []
# Iterate through the nodes of self in topological order
# and form tuples containing sequences of gates
# on the same qubit(s).
tops_node = list(self.node_nums_in_topological_order())
nodes_seen = dict(zip(tops_node, [False] * len(tops_node)))
for node in tops_node:
nd = self.multi_graph.node[node]
if nd["type"] == "op" and nd["name"] in namelist \
and not nodes_seen[node]:
group = [node]
nodes_seen[node] = True
s = list(self.multi_graph.successors(node))
while len(s) == 1 and \
self.multi_graph.node[s[0]]["type"] == "op" and \
self.multi_graph.node[s[0]]["name"] in namelist:
group.append(s[0])
nodes_seen[s[0]] = True
s = list(self.multi_graph.successors(s[0]))
if len(group) > 1:
group_list.append(tuple(group))
return set(group_list)
def count_ops(self):
"""Count the occurrences of operation names.
Returns a dictionary of counts keyed on the operation name.
"""
op_dict = {}
for node in self.node_nums_in_topological_order():
nd = self.multi_graph.node[node]
name = nd["name"]
if nd["type"] == "op":
if name not in op_dict:
op_dict[name] = 1
else:
op_dict[name] += 1
return op_dict
def properties(self):
"""Return a dictionary of circuit properties."""
summary = {"size": self.size(),
"depth": self.depth(),
"width": self.width(),
"bits": self.num_cbits(),
"factors": self.num_tensor_factors(),
"operations": self.count_ops()}
return summary
<|code_end|>
qiskit/transpiler/passes/mapping/barrier_before_final_measurements.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
This pass adds a barrier before the final measurements.
"""
from qiskit.extensions.standard.barrier import Barrier
from qiskit.transpiler._basepasses import TransformationPass
from qiskit.dagcircuit import DAGCircuit
class BarrierBeforeFinalMeasurements(TransformationPass):
"""Adds a barrier before final measurements."""
def run(self, dag):
"""Return a circuit with a barrier before last measurments."""
last_measures = []
for measure in dag.get_named_nodes('measure'):
is_last_measurement = all([after_measure in dag.output_map.values() for after_measure in
dag.successors(measure)])
if is_last_measurement:
last_measures.append(measure)
if not last_measures:
return dag
# create a laywer with the barrier and the measurements in last_measures operation
dag.add_basis_element('barrier', len(last_measures), 0, 0)
barried_layer = DAGCircuit()
last_measures_nodes = [dag.multi_graph.node[node] for node in last_measures]
last_measures_qubits = [node['qargs'][0] for node in last_measures_nodes]
# Add registers from the original dag.
for qreg in dag.qregs.values():
barried_layer.add_qreg(qreg)
for creg in dag.cregs.values():
barried_layer.add_creg(creg)
# Add the barrier operation
barried_layer.apply_operation_back(Barrier(qubits=last_measures_qubits))
# Add the measurements to the behind the barrier
for last_measures_node in last_measures_nodes:
barried_layer.apply_operation_back(last_measures_node['op'])
# Remove barriers in front the measurements in the original dag
for last_measure in last_measures:
for predecesor in dag.multi_graph.predecessors(last_measure):
if dag.multi_graph.nodes[predecesor]['type'] == 'op' and \
isinstance(dag.multi_graph.nodes[predecesor]['op'], Barrier):
dag._remove_op_node(predecesor)
# Remove the measurements from the original dag
for last_measure in last_measures:
dag._remove_op_node(last_measure)
# Extend the original dag with the barried layer
dag.extend_back(barried_layer)
return dag
<|code_end|>
|
qiskit/dagcircuit/_dagcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Object to represent a quantum circuit as a directed acyclic graph.
The nodes in the graph are either input/output nodes or operation nodes.
The operation nodes are elements of a basis that is part of the circuit.
The QASM definitions of the basis elements are carried with the circuit.
The edges correspond to qubits or bits in the circuit. A directed edge
from node A to node B means that the (qu)bit passes from the output of A
to the input of B. The object's methods allow circuits to be constructed,
composed, and modified. Some natural properties like depth can be computed
directly from the graph.
"""
import re
from collections import OrderedDict
import copy
import itertools
import networkx as nx
from qiskit.circuit.quantumregister import QuantumRegister
from qiskit.circuit.classicalregister import ClassicalRegister
from qiskit.circuit.gate import Gate
from .exceptions import DAGCircuitError
class DAGCircuit:
"""
Quantum circuit as a directed acyclic graph.
There are 3 types of nodes in the graph: inputs, outputs, and operations.
The nodes are connected by directed edges that correspond to qubits and
bits.
"""
# pylint: disable=invalid-name
def __init__(self):
"""Create an empty circuit."""
# Circuit name. Generally, this corresponds to the name
# of the QuantumCircuit from which the DAG was generated.
self.name = None
# Set of wires (Register,idx) in the dag
self.wires = []
# Map from wire (Register,idx) to input nodes of the graph
self.input_map = OrderedDict()
# Map from wire (Register,idx) to output nodes of the graph
self.output_map = OrderedDict()
# Running count of the total number of nodes
self.node_counter = 0
# Map of user defined gates to ast nodes defining them
self.gates = OrderedDict()
# Map of named operations in this circuit and their signatures.
# The signature is an integer tuple (nq,nc,np) specifying the
# number of input qubits, input bits, and real parameters.
# The definition is external to the circuit object.
self.basis = OrderedDict()
self.add_basis_element(name="U", number_qubits=1,
number_classical=0, number_parameters=3)
self.add_basis_element("CX", 2, 0, 0)
self.add_basis_element("measure", 1, 1, 0)
self.add_basis_element("reset", 1, 0, 0)
self.add_basis_element("barrier", -1)
# Directed multigraph whose nodes are inputs, outputs, or operations.
# Operation nodes have equal in- and out-degrees and carry
# additional data about the operation, including the argument order
# and parameter values.
# Input nodes have out-degree 1 and output nodes have in-degree 1.
# Edges carry wire labels (reg,idx) and each operation has
# corresponding in- and out-edges with the same wire labels.
self.multi_graph = nx.MultiDiGraph()
# Map of qreg name to QuantumRegister object
self.qregs = OrderedDict()
# Map of creg name to ClassicalRegister object
self.cregs = OrderedDict()
def get_qubits(self):
"""Return a list of qubits as (QuantumRegister, index) pairs."""
return [(v, i) for k, v in self.qregs.items() for i in range(v.size)]
def get_bits(self):
"""Return a list of bits as (ClassicalRegister, index) pairs."""
return [(v, i) for k, v in self.cregs.items() for i in range(v.size)]
# TODO: unused function. is it needed?
def rename_register(self, regname, newname):
"""Rename a classical or quantum register throughout the circuit.
regname = existing register name string
newname = replacement register name string
"""
if regname == newname:
return
if newname in self.qregs or newname in self.cregs:
raise DAGCircuitError("duplicate register name %s" % newname)
if regname not in self.qregs and regname not in self.cregs:
raise DAGCircuitError("no register named %s" % regname)
if regname in self.qregs:
reg = self.qregs[regname]
reg.name = newname
self.qregs[newname] = reg
self.qregs.pop(regname, None)
if regname in self.cregs:
reg = self.cregs[regname]
reg.name = newname
self.qregs[newname] = reg
self.qregs.pop(regname, None)
# n node d = data
for _, d in self.multi_graph.nodes(data=True):
if d["type"] == "in" or d["type"] == "out":
if regname in d["name"]:
d["name"] = re.sub(regname, newname, d["name"])
elif d["type"] == "op":
qa = []
for a in d["qargs"]:
if a[0] == regname:
a = (newname, a[1])
qa.append(a)
d["qargs"] = qa
ca = []
for a in d["cargs"]:
if a[0] == regname:
a = (newname, a[1])
ca.append(a)
d["cargs"] = ca
if d["condition"] is not None:
if d["condition"][0] == regname:
d["condition"] = (newname, d["condition"][1])
# eX = edge, d= data
for _, _, d in self.multi_graph.edges(data=True):
if regname in d["name"]:
d["name"] = re.sub(regname, newname, d["name"])
def remove_all_ops_named(self, opname):
"""Remove all operation nodes with the given name."""
for n in self.get_named_nodes(opname):
self._remove_op_node(n)
def add_qreg(self, qreg):
"""Add all wires in a quantum register."""
if not isinstance(qreg, QuantumRegister):
raise DAGCircuitError("not a QuantumRegister instance.")
if qreg.name in self.qregs:
raise DAGCircuitError("duplicate register %s" % qreg.name)
self.qregs[qreg.name] = qreg
for j in range(qreg.size):
self._add_wire((qreg, j))
def add_creg(self, creg):
"""Add all wires in a classical register."""
if not isinstance(creg, ClassicalRegister):
raise DAGCircuitError("not a ClassicalRegister instance.")
if creg.name in self.cregs:
raise DAGCircuitError("duplicate register %s" % creg.name)
self.cregs[creg.name] = creg
for j in range(creg.size):
self._add_wire((creg, j))
def _add_wire(self, wire):
"""Add a qubit or bit to the circuit.
Args:
wire (tuple): (Register,int) containing a register instance and index
This adds a pair of in and out nodes connected by an edge.
Raises:
DAGCircuitError: if trying to add duplicate wire
"""
if wire not in self.wires:
self.wires.append(wire)
self.node_counter += 1
self.input_map[wire] = self.node_counter
self.node_counter += 1
self.output_map[wire] = self.node_counter
in_node = self.input_map[wire]
out_node = self.output_map[wire]
self.multi_graph.add_edge(in_node, out_node)
self.multi_graph.node[in_node]["type"] = "in"
self.multi_graph.node[out_node]["type"] = "out"
self.multi_graph.node[in_node]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.node[out_node]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.node[in_node]["wire"] = wire
self.multi_graph.node[out_node]["wire"] = wire
self.multi_graph.adj[in_node][out_node][0]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.adj[in_node][out_node][0]["wire"] = wire
else:
raise DAGCircuitError("duplicate wire %s" % (wire,))
def add_basis_element(self, name, number_qubits,
number_classical=0, number_parameters=0):
"""Add an operation to the basis.
name is string label for operation
number_qubits is number of qubit arguments
number_classical is number of bit arguments
number_parameters is number of real parameters
The parameters (nq,nc,np) are ignored for the special case
when name = "barrier". The barrier instruction has a variable
number of qubit arguments.
"""
if name not in self.basis:
self.basis[name] = (
number_qubits,
number_classical,
number_parameters)
if name in self.gates:
if self.gates[name]["n_args"] != number_parameters or \
self.gates[name]["n_bits"] != number_qubits or number_classical != 0:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def add_gate_data(self, name, gatedata):
"""Add the definition of a gate.
gatedata is dict with fields:
"print" = True or False
"opaque" = True or False
"n_args" = number of real parameters
"n_bits" = number of qubits
"args" = list of parameter names
"bits" = list of qubit names
"body" = GateBody AST node
"""
if name not in self.gates:
self.gates[name] = gatedata
if name in self.basis:
if self.basis[name][0] != self.gates[name]["n_bits"] or \
self.basis[name][1] != 0 or \
self.basis[name][2] != self.gates[name]["n_args"]:
raise DAGCircuitError("gate data does not match "
+ "basis element specification")
def _check_basis_data(self, op, qargs, cargs):
"""Check the arguments against the data for this operation.
Args:
op (Instruction): a quantum operation
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple]): cbits that op will be applied to
Raises:
DAGCircuitError: If the check fails.
"""
# Check that we have this operation
if op.name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations" % op.name)
# Check the number of arguments matches the signature
if op.name in ["barrier"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s" % op.name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s" % op.name)
elif op.name in ["snapshot", "noise", "save", "load"]:
if not qargs:
raise DAGCircuitError("incorrect number of qubits for %s" % op.name)
if cargs:
raise DAGCircuitError("incorrect number of bits for %s" % op.name)
else:
if len(qargs) != self.basis[op.name][0]:
raise DAGCircuitError("incorrect number of qubits for %s" % op.name)
if len(cargs) != self.basis[op.name][1]:
raise DAGCircuitError("incorrect number of bits for %s" % op.name)
def _check_condition(self, name, condition):
"""Verify that the condition is valid.
Args:
name (string): used for error reporting
condition (tuple or None): a condition tuple (ClassicalRegister,int)
Raises:
DAGCircuitError: if conditioning on an invalid register
"""
# Verify creg exists
if condition is not None and condition[0].name not in self.cregs:
raise DAGCircuitError("invalid creg in condition for %s" % name)
def _check_bits(self, args, amap):
"""Check the values of a list of (qu)bit arguments.
For each element of args, check that amap contains it.
Args:
args (list): (register,idx) tuples
amap (dict): a dictionary keyed on (register,idx) tuples
Raises:
DAGCircuitError: if a qubit is not contained in amap
"""
# Check for each wire
for wire in args:
if wire not in amap:
raise DAGCircuitError("(qu)bit %s[%d] not found" % (wire[0].name, wire[1]))
def _bits_in_condition(self, cond):
"""Return a list of bits in the given condition.
Args:
cond (tuple or None): optional condition (ClassicalRegister, int)
Returns:
list[(ClassicalRegister, idx)]: list of bits
"""
all_bits = []
if cond is not None:
all_bits.extend([(cond[0], j) for j in range(self.cregs[cond[0].name].size)])
return all_bits
def _add_op_node(self, op, qargs, cargs, condition=None):
"""Add a new operation node to the graph and assign properties.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list): list of quantum wires to attach to.
cargs (list): list of classical wires to attach to.
condition (tuple or None): optional condition (ClassicalRegister, int)
"""
# Add a new operation node to the graph
self.node_counter += 1
self.multi_graph.add_node(self.node_counter)
# Update the operation itself. TODO: remove after qargs not connected to op
op.qargs = qargs
op.cargs = cargs
# Update that operation node's data
self.multi_graph.node[self.node_counter]["type"] = "op"
self.multi_graph.node[self.node_counter]["op"] = op
self.multi_graph.node[self.node_counter]["name"] = op.name
self.multi_graph.node[self.node_counter]["qargs"] = qargs
self.multi_graph.node[self.node_counter]["cargs"] = cargs
self.multi_graph.node[self.node_counter]["condition"] = condition
def apply_operation_back(self, op, qargs=None, cargs=None, condition=None):
"""Apply an operation to the output of the circuit.
TODO: make `qargs` and `cargs` mandatory, when they are dropped from op.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple]): cbits that op will be applied to
condition (tuple or None): optional condition (ClassicalRegister, int)
Raises:
DAGCircuitError: if a leaf node is connected to multiple outputs
"""
qargs = qargs or op.qargs
cargs = cargs or op.cargs
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(op, qargs, cargs)
self._check_condition(op.name, condition)
self._check_bits(qargs, self.output_map)
self._check_bits(all_cbits, self.output_map)
self._add_op_node(op, qargs, cargs, condition)
# Add new in-edges from predecessors of the output nodes to the
# operation node while deleting the old in-edges of the output nodes
# and adding new edges from the operation node to each output node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.predecessors(self.output_map[q]))
if len(ie) != 1:
raise DAGCircuitError("output node has multiple in-edges")
self.multi_graph.add_edge(ie[0], self.node_counter,
name="%s[%s]" % (q[0].name, q[1]), wire=q)
self.multi_graph.remove_edge(ie[0], self.output_map[q])
self.multi_graph.add_edge(self.node_counter, self.output_map[q],
name="%s[%s]" % (q[0].name, q[1]), wire=q)
def apply_operation_front(self, op, qargs=None, cargs=None, condition=None):
"""Apply an operation to the input of the circuit.
TODO: make `qargs` and `cargs` mandatory, when they are dropped from op.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple]): cbits that op will be applied to
condition (tuple or None): optional condition (ClassicalRegister, value)
Raises:
DAGCircuitError: if initial nodes connected to multiple out edges
"""
qargs = qargs or op.qargs
cargs = cargs or op.cargs
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_basis_data(op, qargs, cargs)
self._check_condition(op.name, condition)
self._check_bits(qargs, self.input_map)
self._check_bits(all_cbits, self.input_map)
self._add_op_node(op, qargs, cargs, condition)
# Add new out-edges to successors of the input nodes from the
# operation node while deleting the old out-edges of the input nodes
# and adding new edges to the operation node from each input node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.successors(self.input_map[q]))
if len(ie) != 1:
raise DAGCircuitError("input node has multiple out-edges")
self.multi_graph.add_edge(self.node_counter, ie[0],
name="%s[%s]" % (q[0].name, q[1]), wire=q)
self.multi_graph.remove_edge(self.input_map[q], ie[0])
self.multi_graph.add_edge(self.input_map[q], self.node_counter,
name="%s[%s]" % (q[0].name, q[1]), wire=q)
def _make_union_basis(self, input_circuit):
"""Return a new basis map.
The new basis is a copy of self.basis with
new elements of input_circuit.basis added.
input_circuit is a DAGCircuit
"""
union_basis = self.basis.copy()
for g in input_circuit.basis:
if g not in union_basis:
union_basis[g] = input_circuit.basis[g]
if union_basis[g] != input_circuit.basis[g]:
raise DAGCircuitError("incompatible basis")
return union_basis
def _make_union_gates(self, input_circuit):
"""Return a new gates map.
The new gates are a copy of self.gates with
new elements of input_circuit.gates added.
input_circuit is a DAGCircuit
NOTE: gates in input_circuit that are also in self must
be *identical* to the gates in self
"""
union_gates = {}
for k, v in self.gates.items():
union_gates[k] = v
for k, v in input_circuit.gates.items():
if k not in union_gates:
union_gates[k] = v
if union_gates[k]["opaque"] != input_circuit.gates[k]["opaque"] or \
union_gates[k]["n_args"] != input_circuit.gates[k]["n_args"] or \
union_gates[k]["n_bits"] != input_circuit.gates[k]["n_bits"] or \
union_gates[k]["args"] != input_circuit.gates[k]["args"] or \
union_gates[k]["bits"] != input_circuit.gates[k]["bits"]:
raise DAGCircuitError("inequivalent gate definitions for %s"
% k)
return union_gates
def _check_edgemap_registers(self, edge_map, keyregs, valregs, valreg=True):
"""Check that wiremap neither fragments nor leaves duplicate registers.
1. There are no fragmented registers. A register in keyregs
is fragmented if not all of its (qu)bits are renamed by edge_map.
2. There are no duplicate registers. A register is duplicate if
it appears in both self and keyregs but not in edge_map.
Args:
edge_map (dict): map from (reg,idx) in keyregs to (reg,idx) in valregs
keyregs (dict): a map from register names to Register objects
valregs (dict): a map from register names to Register objects
valreg (bool): if False the method ignores valregs and does not
add regs for bits in the edge_map image that don't appear in valregs
Returns:
set(Register): the set of regs to add to self
Raises:
DAGCircuitError: if the wiremap fragments, or duplicates exist
"""
# FIXME: some mixing of objects and strings here are awkward (due to
# self.qregs/self.cregs still keying on string.
add_regs = set()
reg_frag_chk = {}
for v in keyregs.values():
reg_frag_chk[v] = {j: False for j in range(len(v))}
for k in edge_map.keys():
if k[0].name in keyregs:
reg_frag_chk[k[0]][k[1]] = True
for k, v in reg_frag_chk.items():
s = set(v.values())
if len(s) == 2:
raise DAGCircuitError("edge_map fragments reg %s" % k)
elif s == set([False]):
if k in self.qregs.values() or k in self.cregs.values():
raise DAGCircuitError("unmapped duplicate reg %s" % k)
else:
# Add registers that appear only in keyregs
add_regs.add(k)
else:
if valreg:
# If mapping to a register not in valregs, add it.
# (k,0) exists in edge_map because edge_map doesn't
# fragment k
if not edge_map[(k, 0)][0].name in valregs:
size = max(map(lambda x: x[1],
filter(lambda x: x[0] == edge_map[(k, 0)][0],
edge_map.values())))
qreg = QuantumRegister(size + 1, edge_map[(k, 0)][0].name)
add_regs.add(qreg)
return add_regs
def _check_wiremap_validity(self, wire_map, keymap, valmap):
"""Check that the wiremap is consistent.
Check that the wiremap refers to valid wires and that
those wires have consistent types.
Args:
wire_map (dict): map from (register,idx) in keymap to
(register,idx) in valmap
keymap (dict): a map whose keys are wire_map keys
valmap (dict): a map whose keys are wire_map values
Raises:
DAGCircuitError: if wire_map not valid
"""
for k, v in wire_map.items():
kname = "%s[%d]" % (k[0].name, k[1])
vname = "%s[%d]" % (v[0].name, v[1])
if k not in keymap:
raise DAGCircuitError("invalid wire mapping key %s" % kname)
if v not in valmap:
raise DAGCircuitError("invalid wire mapping value %s" % vname)
if type(k) is not type(v):
raise DAGCircuitError("inconsistent wire_map at (%s,%s)" %
(kname, vname))
def _map_condition(self, wire_map, condition):
"""Use the wire_map dict to change the condition tuple's creg name.
Args:
wire_map (dict): a map from wires to wires
condition (tuple): (ClassicalRegister,int)
Returns:
tuple(ClassicalRegister,int): new condition
"""
if condition is None:
new_condition = None
else:
# Map the register name, using fact that registers must not be
# fragmented by the wire_map (this must have been checked
# elsewhere)
bit0 = (condition[0], 0)
new_condition = (wire_map.get(bit0, bit0)[0], condition[1])
return new_condition
def extend_back(self, dag, edge_map=None):
"""Add `dag` at the end of `self`, using `edge_map`.
"""
edge_map = edge_map or {}
for qreg in dag.qregs.values():
if qreg.name not in self.qregs:
self.add_qreg(QuantumRegister(qreg.size, qreg.name))
edge_map.update([(qbit, qbit) for qbit in qreg if qbit not in edge_map])
for creg in dag.cregs.values():
if creg.name not in self.cregs:
self.add_creg(ClassicalRegister(creg.size, creg.name))
edge_map.update([(cbit, cbit) for cbit in creg if cbit not in edge_map])
self.compose_back(dag, edge_map)
def compose_back(self, input_circuit, edge_map=None):
"""Apply the input circuit to the output of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of input qubits of the input circuit are mapped
to a subset of output qubits of this circuit.
Args:
input_circuit (DAGCircuit): circuit to append
edge_map (dict): map {(Register, int): (Register, int)}
from the output wires of input_circuit to input wires
of self.
Raises:
DAGCircuitError: if missing, duplicate or incosistent wire
"""
edge_map = edge_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map for duplicate values
if len(set(edge_map.values())) != len(edge_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_edgemap_registers(edge_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(edge_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(edge_map, input_circuit.input_map,
self.output_map)
# Compose
self.basis = union_basis
self.gates = union_gates
for node in nx.topological_sort(input_circuit.multi_graph):
nd = input_circuit.multi_graph.node[node]
if nd["type"] == "in":
# if in wire_map, get new name, else use existing name
m_wire = edge_map.get(nd["wire"], nd["wire"])
# the mapped wire should already exist
if m_wire not in self.output_map:
raise DAGCircuitError("wire %s[%d] not in self" % (m_wire[0].name, m_wire[1]))
if nd["wire"] not in input_circuit.wires:
raise DAGCircuitError("inconsistent wire type for %s[%d] in input_circuit"
% (nd["wire"][0].name, nd["wire"][1]))
elif nd["type"] == "out":
# ignore output nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(edge_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: edge_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: edge_map.get(x, x), nd["cargs"]))
self.apply_operation_back(nd["op"], m_qargs, m_cargs, condition)
else:
raise DAGCircuitError("bad node type %s" % nd["type"])
# FIXME: this does not work as expected. it is also not used anywhere
def compose_front(self, input_circuit, wire_map=None):
"""Apply the input circuit to the input of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of output qubits of the input circuit are mapped
to a subset of input qubits of this circuit.
Args:
input_circuit (DAGCircuit): circuit to append
wire_map (dict): map {(Register, int): (Register, int)}
from the output wires of input_circuit to input wires
of self.
Raises:
DAGCircuitError: missing, duplicate or inconsistent wire
"""
wire_map = wire_map or {}
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Check the wire map
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_edgemap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.output_map,
self.input_map)
# Compose
self.basis = union_basis
self.gates = union_gates
for n in reversed(list(nx.topological_sort(input_circuit.multi_graph))):
nd = input_circuit.multi_graph.node[n]
if nd["type"] == "out":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["wire"], nd["wire"])
# the mapped wire should already exist
if m_name not in self.input_map:
raise DAGCircuitError("wire %s[%d] not in self" % (m_name[0].name, m_name[1]))
if nd["wire"] not in input_circuit.wires:
raise DAGCircuitError(
"inconsistent wire for %s[%d] in input_circuit"
% (nd["wire"][0].name, nd["wire"][1]))
elif nd["type"] == "in":
# ignore input nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
self.apply_operation_front(nd["op"], condition)
else:
raise DAGCircuitError("bad node type %s" % nd["type"])
def size(self):
"""Return the number of operations."""
return self.multi_graph.order() - 2 * len(self.wires)
def depth(self):
"""Return the circuit depth.
Returns:
int: the circuit depth
Raises:
DAGCircuitError: if not a directed acyclic graph
"""
if not nx.is_directed_acyclic_graph(self.multi_graph):
raise DAGCircuitError("not a DAG")
return nx.dag_longest_path_length(self.multi_graph) - 1
def width(self):
"""Return the total number of qubits used by the circuit."""
return len(self.wires) - self.num_cbits()
def num_cbits(self):
"""Return the total number of bits used by the circuit."""
return sum(creg.size for creg in self.cregs.values())
def num_tensor_factors(self):
"""Compute how many components the circuit can decompose into."""
return nx.number_weakly_connected_components(self.multi_graph)
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.gates[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.gates[name]["n_args"] > 0:
out += "(" + ",".join(self.gates[name]["args"]) + ")"
out += " " + ",".join(self.gates[name]["bits"])
if self.gates[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.gates[name]["body"].qasm() + "}"
return out
def qasm(self, no_decls=False, qeflag=False, aliases=None, eval_symbols=False):
"""Return a string containing QASM for this circuit.
Args:
qeflag (bool): if True, add a line to include "qelib1.inc"
and only generate gate code for gates not in qelib1.
eval_symbols (bool): if True, evaluate all symbolic
expressions to their floating point representation.
no_decls (bool): if True, only print the instructions.
aliases (dict): if not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
Returns:
str: OpenQASM representation of the DAG
Raises:
DAGCircuitError: if dag nodes not in expected format
"""
# TODO: some of the input flags are not needed anymore
# Rename qregs if necessary
if aliases:
qregdata = OrderedDict()
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
# Write top matter
if no_decls:
out = ""
else:
printed_gates = []
out = "OPENQASM 2.0;\n"
if qeflag:
out += "include \"qelib1.inc\";\n"
for k, v in qregdata.items():
out += "qreg %s[%d];\n" % (k, v.size)
for k, v in self.cregs.items():
out += "creg %s[%d];\n" % (k, v.size)
omit = ["U", "CX", "measure", "reset", "barrier"]
# TODO: dagcircuit shouldn't know about extensions
if qeflag:
qelib = ["u3", "u2", "u1", "cx", "id", "x", "y", "z", "h",
"s", "sdg", "t", "tdg", "cz", "cy", "ccx", "cu1",
"cu3", "swap", "cswap", "u0", "rx", "ry", "rz",
"ch", "crz", "rzz"]
omit.extend(qelib)
printed_gates.extend(qelib)
simulator_instructions = ["snapshot", "save", "load", "noise", "wait"]
omit.extend(simulator_instructions)
for k in self.basis.keys():
if k not in omit:
if not self.gates[k]["opaque"]:
calls = self.gates[k]["body"].calls()
for c in calls:
if c not in printed_gates:
out += self._gate_string(c) + "\n"
printed_gates.append(c)
if k not in printed_gates:
out += self._gate_string(k) + "\n"
printed_gates.append(k)
# Write the instructions
for n in nx.lexicographical_topological_sort(
self.multi_graph, key=lambda x: (self.multi_graph.nodes[x]["type"],
self.multi_graph.nodes[x]["name"])):
nd = self.multi_graph.node[n]
if nd["type"] == "op":
if nd["condition"] is not None:
out += "if(%s==%d) " \
% (nd["condition"][0], nd["condition"][1])
if not nd["cargs"]:
nm = nd["op"].name
if aliases:
qarglist = map(lambda x: aliases[x], nd["qargs"])
else:
qarglist = nd["qargs"]
qarg = ",".join(map(lambda x: "%s[%d]" % (x[0].name, x[1]),
qarglist))
if nd["op"].params:
if eval_symbols:
param = ",".join(map(lambda x: str(x.evalf()),
nd["op"].params))
else:
param = ",".join(map(lambda x: x.replace("**", "^"),
map(str, nd["op"].params)))
out += "%s(%s) %s;\n" % (nm, param, qarg)
else:
out += "%s %s;\n" % (nm, qarg)
else:
if nd["op"].name == "measure":
if len(nd["cargs"]) != 1 or len(nd["qargs"]) != 1 \
or nd["op"].param:
raise DAGCircuitError("bad node data")
qname = nd["qargs"][0][0].name
qindex = nd["qargs"][0][1]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
out += "measure %s[%d] -> %s[%d];\n" \
% (qname,
qindex,
nd["cargs"][0][0].name,
nd["cargs"][0][1])
else:
raise DAGCircuitError("bad node data")
return out
def _check_wires_list(self, wires, op, input_circuit, condition=None):
"""Check that a list of wires satisfies some conditions.
- no duplicate names
- correct length for operation
- elements are wires of input_circuit
Raise an exception otherwise.
Args:
wires (list[register, index]): gives an order for (qu)bits
in the input_circuit that is replacing the operation.
op (Instruction): operation
input_circuit (DAGCircuit): replacement circuit for operation
condition (tuple or None): if this instance of the
operation is classically controlled by a (ClassicalRegister, int)
Raises:
DAGCircuitError: if check doesn't pass.
"""
if len(set(wires)) != len(wires):
raise DAGCircuitError("duplicate wires")
wire_tot = len(op.qargs) + len(op.cargs)
if condition is not None:
wire_tot += condition[0].size
if len(wires) != wire_tot:
raise DAGCircuitError("expected %d wires, got %d"
% (wire_tot, len(wires)))
for w in wires:
if w not in input_circuit.wires:
raise DAGCircuitError("wire (%s,%d) not in input circuit"
% (w[0], w[1]))
def _make_pred_succ_maps(self, n):
"""Return predecessor and successor dictionaries.
Args:
n (int): reference to self.multi_graph node id
Returns:
tuple(dict): tuple(predecessor_map, successor_map)
These map from wire (Register, int) to predecessor (successor)
nodes of n.
"""
pred_map = {e[2]['wire']: e[0] for e in
self.multi_graph.in_edges(nbunch=n, data=True)}
succ_map = {e[2]['wire']: e[1] for e in
self.multi_graph.out_edges(nbunch=n, data=True)}
return pred_map, succ_map
def _full_pred_succ_maps(self, pred_map, succ_map, input_circuit,
wire_map):
"""Map all wires of the input circuit.
Map all wires of the input circuit to predecessor and
successor nodes in self, keyed on wires in self.
Args:
pred_map (dict): comes from _make_pred_succ_maps
succ_map (dict): comes from _make_pred_succ_maps
input_circuit (DAGCircuit): the input circuit
wire_map (dict): the map from wires of input_circuit to wires of self
Returns:
tuple: full_pred_map, full_succ_map (dict, dict)
Raises:
DAGCircuitError: if more than one predecessor for output nodes
"""
full_pred_map = {}
full_succ_map = {}
for w in input_circuit.input_map:
# If w is wire mapped, find the corresponding predecessor
# of the node
if w in wire_map:
full_pred_map[wire_map[w]] = pred_map[wire_map[w]]
full_succ_map[wire_map[w]] = succ_map[wire_map[w]]
else:
# Otherwise, use the corresponding output nodes of self
# and compute the predecessor.
full_succ_map[w] = self.output_map[w]
full_pred_map[w] = self.multi_graph.predecessors(
self.output_map[w])[0]
if len(list(self.multi_graph.predecessors(self.output_map[w]))) != 1:
raise DAGCircuitError("too many predecessors for %s[%d] "
"output node" % (w[0], w[1]))
return full_pred_map, full_succ_map
@staticmethod
def _match_dag_nodes(node1, node2):
"""
Check if DAG nodes are considered equivalent, e.g. as a node_match for nx.is_isomorphic.
Args:
node1 (dict): A node to compare.
node2 (dict): The other node to compare.
Returns:
Bool: If node1 == node2
"""
copy_node1 = {k: v for (k, v) in node1.items()}
copy_node2 = {k: v for (k, v) in node2.items()}
# For barriers, qarg order is not significant so compare as sets
if 'barrier' == copy_node1['name'] == copy_node2['name']:
node1_qargs = set(copy_node1.pop('qargs', []))
node2_qargs = set(copy_node2.pop('qargs', []))
if node1_qargs != node2_qargs:
return False
return copy_node1 == copy_node2
def __eq__(self, other):
return nx.is_isomorphic(self.multi_graph, other.multi_graph,
node_match=DAGCircuit._match_dag_nodes)
def node_nums_in_topological_order(self):
"""
Returns the nodes (their ids) in topological order.
Returns:
list: The list of node numbers in topological order
"""
return nx.topological_sort(self.multi_graph)
def substitute_circuit_all(self, op, input_circuit, wires=None):
"""Replace every occurrence of operation op with input_circuit.
Args:
op (Instruction): operation type to substitute across the dag.
input_circuit (DAGCircuit): what to replace with
wires (list[register, index]): gives an order for (qu)bits
in the input_circuit that is replacing the operation.
Raises:
DAGCircuitError: if met with unexpected predecessor/successors
"""
# TODO: rewrite this method to call substitute_node_with_dag
wires = wires or []
if op.name not in self.basis:
raise DAGCircuitError("%s is not in the list of basis operations"
% op.name)
self._check_wires_list(wires, op, input_circuit)
union_basis = self._make_union_basis(input_circuit)
union_gates = self._make_union_gates(input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: (QuantumRegister(1, 'proxy'), 0) for w in wires}
add_qregs = self._check_edgemap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Iterate through the nodes of self and replace the selected nodes
# by iterating through the input_circuit, constructing and
# checking the validity of the wire_map for each replacement
# NOTE: We do not replace conditioned gates. One way to implement
# this later is to add or update the conditions of each gate
# that we add from the input_circuit.
self.basis = union_basis
self.gates = union_gates
for n in self.node_nums_in_topological_order():
nd = self.multi_graph.node[n]
if nd["type"] == "op" and nd["op"] == op:
if nd["condition"] is None:
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"], nd["cargs"]]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map)
pred_map, succ_map = self._make_pred_succ_maps(n)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(n)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map,
md["condition"])
m_qargs = [wire_map.get(x, x) for x in md["qargs0"]]
m_cargs = [wire_map.get(x, x) for x in md["cargs0"]]
self._add_op_node(md["op"], m_qargs, m_cargs, condition)
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter,
name="%s[%s]" % (q[0].name, q[1]),
wire=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w],
full_succ_map[w],
name="%s[%s]" % (w[0].name, w[1]),
wire=w)
o_pred = list(self.multi_graph.predecessors(
self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise DAGCircuitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise DAGCircuitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(
p[0], self.output_map[w])
def substitute_node_with_dag(self, node, input_dag, wires=None):
"""Replace one node with dag.
Args:
node (int): node of self.multi_graph (of type "op") to substitute
input_dag (DAGCircuit): circuit that will substitute the node
wires (list[(Register, index)]): gives an order for (qu)bits
in the input circuit. This order gets matched to the node wires
by qargs first, then cargs, then conditions.
Raises:
DAGCircuitError: if met with unexpected predecessor/successors
"""
nd = self.multi_graph.node[node]
condition = nd["condition"]
# the decomposition rule must be amended if used in a
# conditional context. delete the op nodes and replay
# them with the condition.
if condition:
input_dag.add_creg(condition[0])
to_replay = []
for n_it in nx.topological_sort(input_dag.multi_graph):
n = input_dag.multi_graph.nodes[n_it]
if n["type"] == "op":
n["op"].control = condition
to_replay.append(n)
for n in input_dag.get_op_nodes():
input_dag._remove_op_node(n)
for n in to_replay:
input_dag.apply_operation_back(n["op"], condition=condition)
if wires is None:
qwires = [w for w in input_dag.wires if isinstance(w[0], QuantumRegister)]
cwires = [w for w in input_dag.wires if isinstance(w[0], ClassicalRegister)]
wires = qwires + cwires
self._check_wires_list(wires, nd["op"], input_dag, nd["condition"])
union_basis = self._make_union_basis(input_dag)
union_gates = self._make_union_gates(input_dag)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: QuantumRegister(1, 'proxy') for w in wires}
add_qregs = self._check_edgemap_registers(proxy_map,
input_dag.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(proxy_map,
input_dag.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Replace the node by iterating through the input_circuit.
# Constructing and checking the validity of the wire_map.
# If a gate is conditioned, we expect the replacement subcircuit
# to depend on those control bits as well.
self.basis = union_basis
self.gates = union_gates
if nd["type"] != "op":
raise DAGCircuitError("expected node type \"op\", got %s"
% nd["type"])
condition_bit_list = self._bits_in_condition(nd["condition"])
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"],
nd["cargs"],
condition_bit_list]
for i in s])}
self._check_wiremap_validity(wire_map, wires, self.input_map)
pred_map, succ_map = self._make_pred_succ_maps(node)
full_pred_map, full_succ_map = self._full_pred_succ_maps(pred_map, succ_map,
input_dag, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(node)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_dag.multi_graph):
md = input_dag.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map, md["condition"])
m_qargs = list(map(lambda x: wire_map.get(x, x),
md["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x),
md["cargs"]))
self._add_op_node(md["op"], m_qargs, m_cargs, condition)
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter,
name="%s[%s]" % (q[0].name, q[1]),
wire=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w],
full_succ_map[w],
name="%s[%s]" % (w[0].name, w[1]),
wire=w)
o_pred = list(self.multi_graph.predecessors(self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise DAGCircuitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise DAGCircuitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(p[0], self.output_map[w])
def get_op_nodes(self, op=None, data=False):
"""Get the list of "op" nodes in the dag.
Args:
op (Type): Instruction subclass op nodes to return. if op=None, return
all op nodes.
data (bool): Default: False. If True, return a list of tuple
(node_id, node_data). If False, return a list of int (node_id)
Returns:
list: the list of node ids containing the given op.
"""
nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data["type"] == "op":
if op is None or isinstance(node_data["op"], op):
nodes.append((node_id, node_data))
if not data:
nodes = [n[0] for n in nodes]
return nodes
def get_gate_nodes(self, data=False):
"""Get the list of gate nodes in the dag.
Args:
data (bool): Default: False. If True, return a list of tuple
(node_id, node_data). If False, return a list of int (node_id)
Returns:
list: the list of node ids that represent gates.
"""
nodes = []
for node_id, node_data in self.get_op_nodes(data=True):
if isinstance(node_data['op'], Gate):
nodes.append((node_id, node_data))
if not data:
nodes = [n[0] for n in nodes]
return nodes
def get_named_nodes(self, *names):
"""Get the set of "op" nodes with the given name."""
named_nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data['type'] == 'op' and node_data['op'].name in names:
named_nodes.append(node_id)
return named_nodes
def get_2q_nodes(self):
"""Get list of 2-qubit nodes."""
two_q_nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data['type'] == 'op' and len(node_data['qargs']) == 2:
two_q_nodes.append(self.multi_graph.node[node_id])
return two_q_nodes
def get_3q_or_more_nodes(self):
"""Get list of 3-or-more-qubit nodes: (id, data)."""
three_q_nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data['type'] == 'op' and len(node_data['qargs']) >= 3:
three_q_nodes.append((node_id, self.multi_graph.node[node_id]))
return three_q_nodes
def successors(self, node):
"""Returns the successors of a node."""
return self.multi_graph.successors(node)
def ancestors(self, node):
"""Returns the ancestors of a node."""
return nx.ancestors(self.multi_graph, node)
def descendants(self, node):
"""Returns the descendants of a node."""
return nx.descendants(self.multi_graph, node)
def quantum_successors(self, node):
"""Returns the successors of a node that are connected by a quantum edge"""
successors = []
for successor in self.successors(node):
if isinstance(self.multi_graph.get_edge_data(node, successor, key=0)['wire'][0],
QuantumRegister):
successors.append(successor)
return successors
def _remove_op_node(self, n):
"""Remove an operation node n.
Add edges from predecessors to successors.
"""
pred_map, succ_map = self._make_pred_succ_maps(n)
self.multi_graph.remove_node(n)
for w in pred_map.keys():
self.multi_graph.add_edge(pred_map[w], succ_map[w],
name="%s[%s]" % (w[0].name, w[1]), wire=w)
def remove_ancestors_of(self, node):
"""Remove all of the ancestor operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
# TODO: probably better to do all at once using
# multi_graph.remove_nodes_from; same for related functions ...
for n in anc:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_descendants_of(self, node):
"""Remove all of the descendant operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
for n in dec:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nonancestors_of(self, node):
"""Remove all of the non-ancestors operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(anc))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nondescendants_of(self, node):
"""Remove all of the non-descendants operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(dec))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def layers(self):
"""Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit.
A layer is a circuit whose gates act on disjoint qubits, i.e.
a layer has depth 1. The total number of layers equals the
circuit depth d. The layers are indexed from 0 to d-1 with the
earliest layer at index 0. The layers are constructed using a
greedy algorithm. Each returned layer is a dict containing
{"graph": circuit graph, "partition": list of qubit lists}.
TODO: Gates that use the same cbits will end up in different
layers as this is currently implemented. This may not be
the desired behavior.
"""
graph_layers = self.multigraph_layers()
try:
next(graph_layers) # Remove input nodes
except StopIteration:
return
def nodes_data(nodes):
"""Construct full nodes from just node ids."""
return ((node_id, self.multi_graph.nodes[node_id]) for node_id in nodes)
for graph_layer in graph_layers:
# Get the op nodes from the layer, removing any input and output nodes.
op_nodes = [node for node in nodes_data(graph_layer) if node[1]["type"] == "op"]
# Stop yielding once there are no more op_nodes in a layer.
if not op_nodes:
return
# Construct a shallow copy of self
new_layer = copy.copy(self)
new_layer.multi_graph = nx.MultiDiGraph()
new_layer.multi_graph.add_nodes_from(nodes_data(self.input_map.values()))
new_layer.multi_graph.add_nodes_from(nodes_data(self.output_map.values()))
# The quantum registers that have an operation in this layer.
support_list = [
op_node[1]["qargs"]
for op_node in op_nodes
if op_node[1]["op"].name not in {"barrier", "snapshot", "save", "load", "noise"}
]
new_layer.multi_graph.add_nodes_from(op_nodes)
# Now add the edges to the multi_graph
# By default we just wire inputs to the outputs.
wires = {self.input_map[wire]: self.output_map[wire]
for wire in self.wires}
# Wire inputs to op nodes, and op nodes to outputs.
for op_node in op_nodes:
args = self._bits_in_condition(op_node[1]["condition"]) \
+ op_node[1]["cargs"] + op_node[1]["qargs"]
arg_ids = (self.input_map[(arg[0], arg[1])] for arg in args)
for arg_id in arg_ids:
wires[arg_id], wires[op_node[0]] = op_node[0], wires[arg_id]
# Add wiring to/from the operations and between unused inputs & outputs.
new_layer.multi_graph.add_edges_from(wires.items())
yield {"graph": new_layer, "partition": support_list}
def serial_layers(self):
"""Yield a layer for all gates of this circuit.
A serial layer is a circuit with one gate. The layers have the
same structure as in layers().
"""
for n in self.node_nums_in_topological_order():
nxt_nd = self.multi_graph.node[n]
if nxt_nd["type"] == "op":
new_layer = DAGCircuit()
for qreg in self.qregs.values():
new_layer.add_qreg(qreg)
for creg in self.cregs.values():
new_layer.add_creg(creg)
new_layer.basis = self.basis.copy()
new_layer.gates = self.gates.copy()
# Save the support of the operation we add to the layer
support_list = []
# Operation data
op = copy.copy(nxt_nd["op"])
qa = copy.copy(nxt_nd["qargs"])
ca = copy.copy(nxt_nd["cargs"])
co = copy.copy(nxt_nd["condition"])
_ = self._bits_in_condition(co)
# Add node to new_layer
new_layer.apply_operation_back(op, qa, ca, co)
# Add operation to partition
if nxt_nd["name"] not in ["barrier",
"snapshot", "save", "load", "noise"]:
support_list.append(list(qa))
l_dict = {"graph": new_layer, "partition": support_list}
yield l_dict
def multigraph_layers(self):
"""Yield layers of the multigraph."""
predecessor_count = dict() # Dict[node, predecessors not visited]
cur_layer = [node for node in self.input_map.values()]
yield cur_layer
next_layer = []
while cur_layer:
for node in cur_layer:
# Count multiedges with multiplicity.
for successor in self.multi_graph.successors(node):
multiplicity = self.multi_graph.number_of_edges(node, successor)
if successor in predecessor_count:
predecessor_count[successor] -= multiplicity
else:
predecessor_count[successor] = \
self.multi_graph.in_degree(successor) - multiplicity
if predecessor_count[successor] == 0:
next_layer.append(successor)
del predecessor_count[successor]
yield next_layer
cur_layer = next_layer
next_layer = []
def collect_runs(self, namelist):
"""Return a set of runs of "op" nodes with the given names.
For example, "... h q[0]; cx q[0],q[1]; cx q[0],q[1]; h q[1]; .."
would produce the tuple of cx nodes as an element of the set returned
from a call to collect_runs(["cx"]). If instead the cx nodes were
"cx q[0],q[1]; cx q[1],q[0];", the method would still return the
pair in a tuple. The namelist can contain names that are not
in the circuit's basis.
Nodes must have only one successor to continue the run.
"""
group_list = []
# Iterate through the nodes of self in topological order
# and form tuples containing sequences of gates
# on the same qubit(s).
tops_node = list(self.node_nums_in_topological_order())
nodes_seen = dict(zip(tops_node, [False] * len(tops_node)))
for node in tops_node:
nd = self.multi_graph.node[node]
if nd["type"] == "op" and nd["name"] in namelist \
and not nodes_seen[node]:
group = [node]
nodes_seen[node] = True
s = list(self.multi_graph.successors(node))
while len(s) == 1 and \
self.multi_graph.node[s[0]]["type"] == "op" and \
self.multi_graph.node[s[0]]["name"] in namelist:
group.append(s[0])
nodes_seen[s[0]] = True
s = list(self.multi_graph.successors(s[0]))
if len(group) > 1:
group_list.append(tuple(group))
return set(group_list)
def count_ops(self):
"""Count the occurrences of operation names.
Returns a dictionary of counts keyed on the operation name.
"""
op_dict = {}
for node in self.node_nums_in_topological_order():
nd = self.multi_graph.node[node]
name = nd["name"]
if nd["type"] == "op":
if name not in op_dict:
op_dict[name] = 1
else:
op_dict[name] += 1
return op_dict
def properties(self):
"""Return a dictionary of circuit properties."""
summary = {"size": self.size(),
"depth": self.depth(),
"width": self.width(),
"bits": self.num_cbits(),
"factors": self.num_tensor_factors(),
"operations": self.count_ops()}
return summary
<|code_end|>
qiskit/transpiler/passes/mapping/barrier_before_final_measurements.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
This pass adds a barrier before the set of final measurements. Measurements
are considered final if they are followed by no other operations (aside from
other measurements or barriers.)
A new barrier will not be added if an equivalent barrier is already present.
"""
from qiskit.extensions.standard.barrier import Barrier
from qiskit.transpiler._basepasses import TransformationPass
from qiskit.dagcircuit import DAGCircuit
class BarrierBeforeFinalMeasurements(TransformationPass):
"""Adds a barrier before final measurements."""
def run(self, dag):
"""Return a circuit with a barrier before last measurments."""
# Collect DAG nodes which are followed only by barriers or other measures.
final_op_types = ['measure', 'barrier']
final_ops = []
for candidate_op in dag.get_named_nodes(*final_op_types):
nodes_after_candidate = [dag.multi_graph.nodes[node_id]
for node_id in dag.descendants(candidate_op)]
is_final_op = all([node['type'] == 'out'
or (node['type'] == 'op' and node['op'].name in final_op_types)
for node in nodes_after_candidate])
if is_final_op:
final_ops.append(candidate_op)
if not final_ops:
return dag
# Create a layer with the barrier and add registers from the original dag.
barrier_layer = DAGCircuit()
for qreg in dag.qregs.values():
barrier_layer.add_qreg(qreg)
for creg in dag.cregs.values():
barrier_layer.add_creg(creg)
final_qubits = set(dag.multi_graph.node[final_op]['qargs'][0]
for final_op in final_ops)
barrier_layer.apply_operation_back(Barrier(qubits=final_qubits))
new_barrier_id = barrier_layer.node_counter
# Preserve order of final ops collected earlier from the original DAG.
ordered_node_ids = [node_id for node_id in dag.node_nums_in_topological_order()
if node_id in set(final_ops)]
ordered_final_nodes = [dag.multi_graph.node[node] for node in ordered_node_ids]
# Move final ops to the new layer and append the new layer to the DAG.
for final_node in ordered_final_nodes:
barrier_layer.apply_operation_back(final_node['op'])
for final_op in final_ops:
dag._remove_op_node(final_op)
# Check to see if the new barrier added to the DAG is equivalent to any
# existing barriers, and if so, consolidate the two.
our_ancestors = barrier_layer.ancestors(new_barrier_id)
our_descendants = barrier_layer.descendants(new_barrier_id)
our_qubits = final_qubits
existing_barriers = barrier_layer.get_named_nodes('barrier')
existing_barriers.remove(new_barrier_id)
for candidate_barrier in existing_barriers:
their_ancestors = barrier_layer.ancestors(candidate_barrier)
their_descendants = barrier_layer.descendants(candidate_barrier)
their_qubits = set(barrier_layer.multi_graph.nodes[candidate_barrier]['op'].qargs)
if (
not our_qubits.isdisjoint(their_qubits)
and our_ancestors.isdisjoint(their_descendants)
and our_descendants.isdisjoint(their_ancestors)
):
merge_barrier = Barrier(qubits=(our_qubits | their_qubits))
barrier_layer.apply_operation_front(merge_barrier)
merge_barrier_id = barrier_layer.node_counter
our_ancestors = our_ancestors | their_ancestors
our_descendants = our_descendants | their_descendants
barrier_layer._remove_op_node(candidate_barrier)
barrier_layer._remove_op_node(new_barrier_id)
new_barrier_id = merge_barrier_id
dag.extend_back(barrier_layer)
return dag
<|code_end|>
|
Bug in drawing barriers in matplotlib circuit drawer
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: master
- **Python version**: 3.6
- **Operating system**: mac
### What is the current behavior?
Drawing barriers (or barrier like instructions such as snapshot) sometimes fails in matplotlib drawer.
### Steps to reproduce the problem
```python
from qiskit import QuantumCircuit
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
qreg r[1];
creg c[1];
cz q, r;
barrier q, r;
x q;
y q;
measure q -> c;
z q;
if (c==1) z r;
"""
circ = QuantumCircuit.from_qasm_str(qasm)
circ.draw(output='mpl')
```

### What is the expected behavior?
Barrier should extend across all qubits.
|
qiskit/tools/visualization/_matplotlib.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""mpl circuit visualization backend."""
import collections
import fractions
import itertools
import json
import logging
import math
import numpy as np
try:
from matplotlib import patches
from matplotlib import pyplot as plt
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
from qiskit.tools.visualization import exceptions
from qiskit.tools.visualization import _qcstyle
from qiskit.tools.visualization import _utils
logger = logging.getLogger(__name__)
Register = collections.namedtuple('Register', 'reg index')
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
scale=1.0, style=None, plot_barriers=True,
reverse_bits=False):
if not HAS_MATPLOTLIB:
raise ImportError('The class MatplotlibDrawer needs matplotlib. '
'Run "pip install matplotlib" before.')
self._ast = None
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = collections.OrderedDict()
self._creg_dict = collections.OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = _qcstyle.QCStyle()
self.plot_barriers = plot_barriers
self.reverse_bits = reverse_bits
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False,
labelleft=False, labelright=False)
def parse_circuit(self, circuit):
qregs, cregs, ops = _utils._get_instructions(
circuit, reversebits=self.reverse_bits)
self._registers(cregs, qregs)
self._ops = ops
def _registers(self, creg, qreg):
self._creg = []
for e in creg:
self._creg.append(Register(reg=e[0], index=e[1]))
self._qreg = []
for e in qreg:
self._qreg.append(Register(reg=e[0], index=e[1]))
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(
xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center',
va='center', fontsize=self._style.fs,
color=self._style.gt, clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.sc, clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7,
height=HIG * 0.7, theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID],
[qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy + 0.35 * WID], lc=self._style.cc,
ls=self._style.cline)
arrowhead = patches.Polygon(((cx - 0.20 * WID, cy + 0.35 * WID),
(cx + 0.20 * WID, cy + 0.35 * WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'],
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
plt.close(self.figure)
return self.figure
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.reg.name, reg.index)
else:
label = '${}$'.format(reg.reg.name)
pos = -ii
self._qreg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.reg
}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(itertools.zip_longest(
self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.reg.name)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.reg
}
if not (not nreg or reg.reg != nreg.reg):
continue
else:
label = '${}_{{{}}}$'.format(reg.reg.name, reg.index)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.reg
}
self._cond['n_lines'] += 1
idx += 1
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left',
va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc,
ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(
itertools.zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qargs' in op.keys():
q_idxs = []
for qarg in op['qargs']:
for index, reg in self._qreg_dict.items():
if (reg['group'] == qarg[0] and
reg['index'] == qarg[1]):
q_idxs.append(index)
break
else:
q_idxs = []
# get creg index
if 'cargs' in op.keys():
c_idxs = []
for carg in op['cargs']:
for index, reg in self._creg_dict.items():
if (reg['group'] == carg[0] and
reg['index'] == carg[1]):
c_idxs.append(index)
break
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or (
'condition' in op.keys() and op['condition']) or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied),
max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(
this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] in [
'barrier', 'snapshot', 'load', 'save',
'noise'] and not self.plot_barriers:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg coordinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'op' in op.keys() and hasattr(op['op'], 'param'):
param = self.param_parse(op['op'].params, self._style.pimode)
else:
param = None
# conditional gate
if 'condition' in op.keys() and op['condition']:
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for
ii in self._creg_dict]
mask = 0
for index, cbit in enumerate(self._creg):
if cbit.reg == op['condition'][0]:
mask |= (1 << index)
val = op['condition'][1]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, hex(val))
self._line(qreg_t, creg_b, lc=self._style.cc,
ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] in ['barrier', 'snapshot', 'load', 'save',
'noise']:
q_group = self._qreg_dict[q_idxs[0]]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[0])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self.plot_barriers:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise exceptions.VisualizationError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (
self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.tc, clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if math.isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if math.isclose(math.fmod(abs_val, 1.0),
0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
if 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if math.isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return fractions.Fraction(i, j)
return None
<|code_end|>
|
qiskit/tools/visualization/_matplotlib.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""mpl circuit visualization backend."""
import collections
import fractions
import itertools
import json
import logging
import math
import numpy as np
try:
from matplotlib import patches
from matplotlib import pyplot as plt
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
from qiskit.tools.visualization import exceptions
from qiskit.tools.visualization import _qcstyle
from qiskit.tools.visualization import _utils
logger = logging.getLogger(__name__)
Register = collections.namedtuple('Register', 'reg index')
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self,
scale=1.0, style=None, plot_barriers=True,
reverse_bits=False):
if not HAS_MATPLOTLIB:
raise ImportError('The class MatplotlibDrawer needs matplotlib. '
'Run "pip install matplotlib" before.')
self._ast = None
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._ops = []
self._qreg_dict = collections.OrderedDict()
self._creg_dict = collections.OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
self._style = _qcstyle.QCStyle()
self.plot_barriers = plot_barriers
self.reverse_bits = reverse_bits
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False,
labelleft=False, labelright=False)
def parse_circuit(self, circuit):
qregs, cregs, ops = _utils._get_instructions(
circuit, reversebits=self.reverse_bits)
self._registers(cregs, qregs)
self._ops = ops
def _registers(self, creg, qreg):
self._creg = []
for e in creg:
self._creg.append(Register(reg=e[0], index=e[1]))
self._qreg = []
for e in qreg:
self._qreg.append(Register(reg=e[0], index=e[1]))
@property
def ast(self):
return self._ast
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
wid = WID * 2.8
else:
wid = WID
if fc:
_fc = fc
elif text:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(
xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
disp_text = "${}$".format(self._style.disptex[text])
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center',
va='center', fontsize=self._style.fs,
color=self._style.gt, clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.sc, clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7,
height=HIG * 0.7, theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID],
[qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy + 0.35 * WID], lc=self._style.cc,
ls=self._style.cline)
arrowhead = patches.Polygon(((cx - 0.20 * WID, cy + 0.35 * WID),
(cx + 0.20 * WID, cy + 0.35 * WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'],
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (
self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
plt.close(self.figure)
return self.figure
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.reg.name, reg.index)
else:
label = '${}$'.format(reg.reg.name)
pos = -ii
self._qreg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.reg
}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(itertools.zip_longest(
self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.reg.name)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.reg
}
if not (not nreg or reg.reg != nreg.reg):
continue
else:
label = '${}_{{{}}}$'.format(reg.reg.name, reg.index)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.reg
}
self._cond['n_lines'] += 1
idx += 1
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left',
va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc,
ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_force_next = 'measure barrier'.split()
_wide_gate = 'u2 u3 cu2 cu3'.split()
_barriers = {'coord': [], 'group': []}
next_ops = self._ops.copy()
next_ops.pop(0)
this_anc = 0
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
for i, (op, op_next) in enumerate(
itertools.zip_longest(self._ops, next_ops)):
# wide gate
if op['name'] in _wide_gate:
_iswide = True
gw = 2
else:
_iswide = False
gw = 1
# get qreg index
if 'qargs' in op.keys():
q_idxs = []
for qarg in op['qargs']:
for index, reg in self._qreg_dict.items():
if (reg['group'] == qarg[0] and
reg['index'] == qarg[1]):
q_idxs.append(index)
break
else:
q_idxs = []
# get creg index
if 'cargs' in op.keys():
c_idxs = []
for carg in op['cargs']:
for index, reg in self._creg_dict.items():
if (reg['group'] == carg[0] and
reg['index'] == carg[1]):
c_idxs.append(index)
break
else:
c_idxs = []
# find empty space to place gate
if not _barriers['group']:
this_anc = max([q_anchors[ii].get_index() for ii in q_idxs])
while True:
if op['name'] in _force_next or (
'condition' in op.keys() and op['condition']) or \
not self._style.compress:
occupied = self._qreg_dict.keys()
else:
occupied = q_idxs
q_list = [ii for ii in range(min(occupied),
max(occupied) + 1)]
locs = [q_anchors[jj].is_locatable(
this_anc, gw) for jj in q_list]
if all(locs):
for ii in q_list:
if op['name'] in [
'barrier', 'snapshot', 'load', 'save',
'noise'] and not self.plot_barriers:
q_anchors[ii].set_index(this_anc - 1, gw)
else:
q_anchors[ii].set_index(this_anc, gw)
break
else:
this_anc += 1
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, gw) for ii in q_idxs]
# creg coordinate
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
if verbose:
print(i, op)
# rotation parameter
if 'op' in op.keys() and hasattr(op['op'], 'param'):
param = self.param_parse(op['op'].params, self._style.pimode)
else:
param = None
# conditional gate
if 'condition' in op.keys() and op['condition']:
c_xy = [c_anchors[ii].plot_coord(this_anc, gw) for
ii in self._creg_dict]
mask = 0
for index, cbit in enumerate(self._creg):
if cbit.reg == op['condition'][0]:
mask |= (1 << index)
val = op['condition'][1]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, hex(val))
self._line(qreg_t, creg_b, lc=self._style.cc,
ls=self._style.cline)
#
# draw special gates
#
if op['name'] == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op['name'] in ['barrier', 'snapshot', 'load', 'save',
'noise']:
# Go over all indices to add barriers across
for index, qbit in enumerate(q_idxs):
q_group = self._qreg_dict[qbit]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[index])
if op_next and op_next['name'] == 'barrier':
continue
else:
if self.plot_barriers:
self._barrier(_barriers, this_anc)
_barriers['group'].clear()
_barriers['coord'].clear()
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op['name']
if param:
self._gate(q_xy[0], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op['name'] in ['cx']:
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# cz for latexmode
elif op['name'] == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# control gate
elif op['name'] in ['cy', 'ch', 'cu3', 'crz']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# cu1 for latexmode
elif op['name'] in ['cu1']:
disp = op['name'].replace('c', '')
self._ctrl_qubit(q_xy[0])
if self._style.latexmode:
self._ctrl_qubit(q_xy[1])
self._subtext(qreg_b, param)
else:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
# swap gate
elif op['name'] == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op['name'] == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# ccx gate
elif op['name'] == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
else:
logger.critical('Invalid gate %s', op)
raise exceptions.VisualizationError('invalid gate {}'.format(op))
#
# adjust window size and draw horizontal lines
#
max_anc = max([q_anchors[ii].get_index() for ii in self._qreg_dict])
n_fold = (max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (
self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.tc, clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
for i, e in enumerate(v):
if pimode:
v[i] = MatplotlibDrawer.format_pi(e)
else:
v[i] = MatplotlibDrawer.format_numeric(e)
if v[i].startswith('-'):
v[i] = '$-$' + v[i][1:]
param = ', '.join(v)
return param
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
abs_val = abs(val)
if math.isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if math.isclose(math.fmod(abs_val, 1.0),
0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
if 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if math.isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return fractions.Fraction(i, j)
return None
<|code_end|>
|
BackendConfiguration fails validation if backend supports pulse
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**:0.8.0
- **Python version**3.6.6
- **Operating system**:OSX
### What is the current behavior?
If a backend sets `open_pulse=true` in its configuration Qiskit will raise a validation error when creating a `BackendConfigurationSchema`
### Steps to reproduce the problem
Create a backend with `open_pulse=true` set in its configuration.
### What is the expected behavior?
Should not fail.
### Suggested solutions
Allow `open_pulse=true` to be valid.
|
qiskit/providers/models/backendconfiguration.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Model and schema for backend configuration."""
from marshmallow.validate import Equal, Length, OneOf, Range, Regexp
from qiskit.validation import BaseModel, BaseSchema, bind_schema
from qiskit.validation.fields import Boolean, DateTime, Integer, List, Nested, String
class GateConfigSchema(BaseSchema):
"""Schema for GateConfig."""
# Required properties.
name = String(required=True)
parameters = List(String(), required=True)
qasm_def = String(required=True)
# Optional properties.
coupling_map = List(List(Integer(),
validate=Length(min=1)),
validate=Length(min=1))
latency_map = List(List(Integer(validate=OneOf([0, 1])),
validate=Length(min=1)),
validate=Length(min=1))
conditional = Boolean()
description = String()
class BackendConfigurationSchema(BaseSchema):
"""Schema for BackendConfiguration."""
# Required properties.
backend_name = String(required=True)
backend_version = String(required=True,
validate=Regexp("[0-9]+.[0-9]+.[0-9]+$"))
n_qubits = Integer(required=True, validate=Range(min=1))
basis_gates = List(String(), required=True,
validate=Length(min=1))
gates = Nested(GateConfigSchema, required=True, many=True,
validate=Length(min=1))
local = Boolean(required=True)
simulator = Boolean(required=True)
conditional = Boolean(required=True)
open_pulse = Boolean(required=True, validate=Equal(False))
memory = Boolean(required=True)
max_shots = Integer(required=True, validate=Range(min=1))
# Optional properties.
max_experiments = Integer(validate=Range(min=1))
sample_name = String()
coupling_map = List(List(Integer(),
validate=Length(min=1)),
validate=Length(min=1))
n_registers = Integer(validate=Range(min=1))
register_map = List(List(Integer(validate=OneOf([0, 1])),
validate=Length(min=1)),
validate=Length(min=1))
configurable = Boolean()
credits_required = Boolean()
online_date = DateTime()
display_name = String()
description = String()
tags = List(String())
@bind_schema(GateConfigSchema)
class GateConfig(BaseModel):
"""Model for GateConfig.
Please note that this class only describes the required fields. For the
full description of the model, please check ``GateConfigSchema``.
Attributes:
name (str): the gate name as it will be referred to in QASM.
parameters (list[str]): variable names for the gate parameters (if any).
qasm_def (str): definition of this gate in terms of QASM primitives U
and CX.
"""
def __init__(self, name, parameters, qasm_def, **kwargs):
self.name = name
self.parameters = parameters
self.qasm_def = qasm_def
super().__init__(**kwargs)
@bind_schema(BackendConfigurationSchema)
class BackendConfiguration(BaseModel):
"""Model for BackendConfiguration.
Please note that this class only describes the required fields. For the
full description of the model, please check ``BackendConfigurationSchema``.
Attributes:
backend_name (str): backend name.
backend_version (str): backend version in the form X.Y.Z.
n_qubits (int): number of qubits.
basis_gates (list[str]): list of basis gates names on the backend.
gates (GateConfig): list of basis gates on the backend.
local (bool): backend is local or remote.
simulator (bool): backend is a simulator.
conditional (bool): backend supports conditional operations.
open_pulse (bool): backend supports open pulse.
memory (bool): backend supports memory.
max_shots (int): maximum number of shots supported.
"""
def __init__(self, backend_name, backend_version, n_qubits, basis_gates,
gates, local, simulator, conditional, open_pulse, memory,
max_shots, **kwargs):
self.backend_name = backend_name
self.backend_version = backend_version
self.n_qubits = n_qubits
self.basis_gates = basis_gates
self.gates = gates
self.local = local
self.simulator = simulator
self.conditional = conditional
self.open_pulse = open_pulse
self.memory = memory
self.max_shots = max_shots
super().__init__(**kwargs)
<|code_end|>
|
qiskit/providers/models/backendconfiguration.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Model and schema for backend configuration."""
from marshmallow.validate import Length, OneOf, Range, Regexp
from qiskit.validation import BaseModel, BaseSchema, bind_schema
from qiskit.validation.fields import Boolean, DateTime, Integer, List, Nested, String
class GateConfigSchema(BaseSchema):
"""Schema for GateConfig."""
# Required properties.
name = String(required=True)
parameters = List(String(), required=True)
qasm_def = String(required=True)
# Optional properties.
coupling_map = List(List(Integer(),
validate=Length(min=1)),
validate=Length(min=1))
latency_map = List(List(Integer(validate=OneOf([0, 1])),
validate=Length(min=1)),
validate=Length(min=1))
conditional = Boolean()
description = String()
class BackendConfigurationSchema(BaseSchema):
"""Schema for BackendConfiguration."""
# Required properties.
backend_name = String(required=True)
backend_version = String(required=True,
validate=Regexp("[0-9]+.[0-9]+.[0-9]+$"))
n_qubits = Integer(required=True, validate=Range(min=1))
basis_gates = List(String(), required=True,
validate=Length(min=1))
gates = Nested(GateConfigSchema, required=True, many=True,
validate=Length(min=1))
local = Boolean(required=True)
simulator = Boolean(required=True)
conditional = Boolean(required=True)
open_pulse = Boolean(required=True)
memory = Boolean(required=True)
max_shots = Integer(required=True, validate=Range(min=1))
# Optional properties.
max_experiments = Integer(validate=Range(min=1))
sample_name = String()
coupling_map = List(List(Integer(),
validate=Length(min=1)),
validate=Length(min=1))
n_registers = Integer(validate=Range(min=1))
register_map = List(List(Integer(validate=OneOf([0, 1])),
validate=Length(min=1)),
validate=Length(min=1))
configurable = Boolean()
credits_required = Boolean()
online_date = DateTime()
display_name = String()
description = String()
tags = List(String())
@bind_schema(GateConfigSchema)
class GateConfig(BaseModel):
"""Model for GateConfig.
Please note that this class only describes the required fields. For the
full description of the model, please check ``GateConfigSchema``.
Attributes:
name (str): the gate name as it will be referred to in QASM.
parameters (list[str]): variable names for the gate parameters (if any).
qasm_def (str): definition of this gate in terms of QASM primitives U
and CX.
"""
def __init__(self, name, parameters, qasm_def, **kwargs):
self.name = name
self.parameters = parameters
self.qasm_def = qasm_def
super().__init__(**kwargs)
@bind_schema(BackendConfigurationSchema)
class BackendConfiguration(BaseModel):
"""Model for BackendConfiguration.
Please note that this class only describes the required fields. For the
full description of the model, please check ``BackendConfigurationSchema``.
Attributes:
backend_name (str): backend name.
backend_version (str): backend version in the form X.Y.Z.
n_qubits (int): number of qubits.
basis_gates (list[str]): list of basis gates names on the backend.
gates (GateConfig): list of basis gates on the backend.
local (bool): backend is local or remote.
simulator (bool): backend is a simulator.
conditional (bool): backend supports conditional operations.
open_pulse (bool): backend supports open pulse.
memory (bool): backend supports memory.
max_shots (int): maximum number of shots supported.
"""
def __init__(self, backend_name, backend_version, n_qubits, basis_gates,
gates, local, simulator, conditional, open_pulse, memory,
max_shots, **kwargs):
self.backend_name = backend_name
self.backend_version = backend_version
self.n_qubits = n_qubits
self.basis_gates = basis_gates
self.gates = gates
self.local = local
self.simulator = simulator
self.conditional = conditional
self.open_pulse = open_pulse
self.memory = memory
self.max_shots = max_shots
super().__init__(**kwargs)
<|code_end|>
|
StochasticSwap bug
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**:
- **Python version**: 0.7.0
- **Operating system**:
### What is the current behavior?
The stochastic swap mapper seems to create a non-equivalent circuit for the following case:
```python
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import BasicAer, execute
from qiskit.transpiler import PassManager, transpile
from qiskit.transpiler.passes import StochasticSwap
from qiskit.mapper import CouplingMap
coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
qr = QuantumRegister(7, 'q')
cr = ClassicalRegister(7, 'c')
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[3])
circuit.cx(qr[0], qr[6])
circuit.cx(qr[6], qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[3], qr[1])
circuit.cx(qr[3], qr[0])
circuit.measure(qr, cr)
simulator = BasicAer.get_backend('qasm_simulator')
coupling_map = CouplingMap(couplinglist=coupling)
pass_manager = PassManager(StochasticSwap(coupling_map=coupling_map))
stochastic_circ = transpile(circuit, simulator, pass_manager=pass_manager)
print(execute(circuit, simulator).result().get_counts())
print(execute(stochastic_circ, simulator).result().get_counts())
```
```
{'0000000': 488, '0001011': 536}
{'0000000': 499, '0001001': 525}
```
|
qiskit/transpiler/passes/mapping/stochastic_swap.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A pass implementing the default Qiskit stochastic mapper.
"""
from logging import getLogger
from pprint import pformat
from math import inf
import numpy as np
from qiskit.transpiler._basepasses import TransformationPass
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.dagcircuit import DAGCircuit
from qiskit.extensions.standard import SwapGate
from qiskit.mapper import Layout
from .barrier_before_final_measurements import BarrierBeforeFinalMeasurements
logger = getLogger(__name__)
# Notes:
# 1. Measurements may occur and be followed by swaps that result in repeated
# measurement of the same qubit. Near-term experiments cannot implement
# these circuits, so some care is required when using this mapper
# with experimental backend targets.
# 2. We do not use the fact that the input state is zero to simplify
# the circuit.
class StochasticSwap(TransformationPass):
"""
Maps a DAGCircuit onto a `coupling_map` adding swap gates.
Uses a randomized algorithm.
"""
def __init__(self, coupling_map, initial_layout=None,
trials=20, seed=None):
"""
Map a DAGCircuit onto a `coupling_map` using swap gates.
If initial_layout is not None, we assume the input circuit
has been layed out before running this pass, and that
the layout process yields a DAG, coupling map, and layout
with the following properties:
1. All three have the same number of qubits
2. The layout a bijection from the DAG qubits to the coupling map
For this mapping pass, it may also be necessary that
3. The coupling map is a connected graph
If these are not satisfied, the behavior is undefined.
Args:
coupling_map (CouplingMap): Directed graph representing a coupling
map.
initial_layout (Layout): initial layout of qubits in mapping
trials (int): maximum number of iterations to attempt
seed (int): seed for random number generator
"""
super().__init__()
self.coupling_map = coupling_map
self.initial_layout = initial_layout
self.input_layout = None
self.trials = trials
self.seed = seed
self.requires.append(BarrierBeforeFinalMeasurements())
def run(self, dag):
"""
Run the StochasticSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
"""
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
self.input_layout = self.initial_layout.copy()
new_dag = self._mapper(dag, self.coupling_map, trials=self.trials, seed=self.seed)
# self.property_set["layout"] = self.initial_layout
return new_dag
def _layer_permutation(self, layer_partition, layout, qubit_subset,
coupling, trials, seed=None):
"""Find a swap circuit that implements a permutation for this layer.
The goal is to swap qubits such that qubits in the same two-qubit gates
are adjacent.
Based on S. Bravyi's algorithm.
layer_partition (list): The layer_partition is a list of (qu)bit
lists and each qubit is a tuple (qreg, index).
layout (Layout): The layout is a Layout object mapping virtual
qubits in the input circuit to physical qubits in the coupling
graph. It reflects the current positions of the data.
qubit_subset (list): The qubit_subset is the set of qubits in
the coupling graph that we have chosen to map into, as tuples
(Register, index).
coupling (CouplingMap): Directed graph representing a coupling map.
This coupling map should be one that was provided to the
stochastic mapper.
trials (int): Number of attempts the randomized algorithm makes.
seed (int): Optional seed for the random number generator. If it is
None we do not reseed.
Returns:
Tuple: success_flag, best_circuit, best_depth, best_layout, trivial_flag
If success_flag is True, then best_circuit contains a DAGCircuit with
the swap circuit, best_depth contains the depth of the swap circuit,
and best_layout contains the new positions of the data qubits after the
swap circuit has been applied. The trivial_flag is set if the layer
has no multi-qubit gates.
Raises:
TranspilerError: if anything went wrong.
"""
if seed is not None:
np.random.seed(seed)
logger.debug("layer_permutation: layer_partition = %s",
pformat(layer_partition))
logger.debug("layer_permutation: layout = %s",
pformat(layout.get_virtual_bits()))
logger.debug("layer_permutation: qubit_subset = %s",
pformat(qubit_subset))
logger.debug("layer_permutation: trials = %s", trials)
gates = [] # list of lists of tuples [[(register, index), ...], ...]
for gate_args in layer_partition:
if len(gate_args) > 2:
raise TranspilerError("Layer contains > 2-qubit gates")
elif len(gate_args) == 2:
gates.append(tuple(gate_args))
logger.debug("layer_permutation: gates = %s", pformat(gates))
# Can we already apply the gates? If so, there is no work to do.
dist = sum([coupling.distance(layout[g[0]], layout[g[1]])
for g in gates])
logger.debug("layer_permutation: distance = %s", dist)
if dist == len(gates):
logger.debug("layer_permutation: nothing to do")
circ = DAGCircuit()
for register in layout.get_virtual_bits().keys():
if register[0] not in circ.qregs.values():
circ.add_qreg(register[0])
circ.add_basis_element("swap", 2)
return True, circ, 0, layout, (not bool(gates))
# Begin loop over trials of randomized algorithm
num_qubits = len(layout)
best_depth = inf # initialize best depth
best_circuit = None # initialize best swap circuit
best_layout = None # initialize best final layout
for trial in range(trials):
logger.debug("layer_permutation: trial %s", trial)
trial_layout = layout.copy()
trial_circuit = DAGCircuit() # SWAP circuit for this trial
for register in trial_layout.get_virtual_bits().keys():
if register[0] not in trial_circuit.qregs.values():
trial_circuit.add_qreg(register[0])
# Compute randomized distance
xi = {} # pylint: disable=invalid-name
for i in range(num_qubits):
xi[i] = {}
for i in range(num_qubits):
for j in range(i, num_qubits):
scale = 1 + np.random.normal(0, 1 / num_qubits)
xi[i][j] = scale * coupling.distance(i, j) ** 2
xi[j][i] = xi[i][j]
slice_circuit = DAGCircuit() # circuit for this swap slice
for register in trial_layout.get_virtual_bits().keys():
if register[0] not in slice_circuit.qregs.values():
slice_circuit.add_qreg(register[0])
slice_circuit.add_basis_element("swap", 2)
# Loop over depths from 1 up to a maximum depth
depth_step = 1
depth_max = 2 * num_qubits + 1
while depth_step < depth_max:
qubit_set = set(qubit_subset)
# While there are still qubits available
while qubit_set:
# Compute the objective function
min_cost = sum([xi[trial_layout[g[0]]][trial_layout[g[1]]] for g in gates])
# Try to decrease objective function
cost_reduced = False
# Loop over edges of coupling graph
for edge in coupling.get_edges():
qubits = [trial_layout[e] for e in edge]
# Are the qubits available?
if qubits[0] in qubit_set and qubits[1] in qubit_set:
# Try this edge to reduce the cost
new_layout = trial_layout.copy()
new_layout.swap(edge[0], edge[1])
# Compute the objective function
new_cost = sum([xi[new_layout[g[0]]][new_layout[g[1]]] for g in gates])
# Record progress if we succceed
if new_cost < min_cost:
logger.debug("layer_permutation: min_cost "
"improved to %s", min_cost)
cost_reduced = True
min_cost = new_cost
optimal_layout = new_layout
optimal_edge = qubits
# Were there any good swap choices?
if cost_reduced:
qubit_set.remove(optimal_edge[0])
qubit_set.remove(optimal_edge[1])
trial_layout = optimal_layout
slice_circuit.apply_operation_back(
SwapGate(optimal_edge[0],
optimal_edge[1]))
logger.debug("layer_permutation: swap the pair %s",
pformat(optimal_edge))
else:
break
# We have either run out of swap pairs to try or
# failed to improve the cost.
# Compute the coupling graph distance
dist = sum([coupling.distance(trial_layout[g[0]],
trial_layout[g[1]])
for g in gates])
logger.debug("layer_permutation: new swap distance = %s", dist)
# If all gates can be applied now, we are finished.
# Otherwise we need to consider a deeper swap circuit
if dist == len(gates):
logger.debug("layer_permutation: all gates can be "
"applied now in this layer")
trial_circuit.extend_back(slice_circuit)
break
# Increment the depth
depth_step += 1
logger.debug("layer_permutation: increment depth to %s", depth_step)
# Either we have succeeded at some depth d < dmax or failed
dist = sum([coupling.distance(trial_layout[g[0]],
trial_layout[g[1]])
for g in gates])
logger.debug("layer_permutation: final distance for this trial = %s", dist)
if dist == len(gates):
if depth_step < best_depth:
logger.debug("layer_permutation: got circuit with improved depth %s",
depth_step)
best_circuit = trial_circuit
best_layout = trial_layout
best_depth = min(best_depth, depth_step)
# Break out of trial loop if we found a depth 1 circuit
# since we can't improve it further
if best_depth == 1:
break
# If we have no best circuit for this layer, all of the
# trials have failed
if best_circuit is None:
logger.debug("layer_permutation: failed!")
return False, None, None, None, False
# Otherwise, we return our result for this layer
logger.debug("layer_permutation: success!")
return True, best_circuit, best_depth, best_layout, False
def _layer_update(self, i, first_layer, best_layout, best_depth,
best_circuit, layer_list):
"""Provide a DAGCircuit for a new mapped layer.
i (int) = layer number
first_layer (bool) = True if this is the first layer in the
circuit with any multi-qubit gates
best_layout (Layout) = layout returned from _layer_permutation
best_depth (int) = depth returned from _layer_permutation
best_circuit (DAGCircuit) = swap circuit returned
from _layer_permutation
layer_list (list) = list of DAGCircuit objects for each layer,
output of DAGCircuit layers() method
Return a DAGCircuit object to append to the output DAGCircuit
that the _mapper method is building.
"""
layout = best_layout
logger.debug("layer_update: layout = %s", pformat(layout))
logger.debug("layer_update: self.initial_layout = %s", pformat(self.initial_layout))
dagcircuit_output = DAGCircuit()
for register in layout.get_virtual_bits().keys():
if register[0] not in dagcircuit_output.qregs.values():
dagcircuit_output.add_qreg(register[0])
# If this is the first layer with multi-qubit gates,
# output all layers up to this point and ignore any
# swap gates. Set the initial layout.
if first_layer:
logger.debug("layer_update: first multi-qubit gate layer")
# Output all layers up to this point
for j in range(i + 1):
# Make qubit edge map and extend by classical bits
edge_map = layout.combine_into_edge_map(self.initial_layout)
for bit in dagcircuit_output.get_bits():
edge_map[bit] = bit
dagcircuit_output.compose_back(layer_list[j]["graph"], edge_map)
# Otherwise, we output the current layer and the associated swap gates.
else:
# Output any swaps
if best_depth > 0:
logger.debug("layer_update: there are swaps in this layer, "
"depth %d", best_depth)
dagcircuit_output.extend_back(best_circuit)
else:
logger.debug("layer_update: there are no swaps in this layer")
# Make qubit edge map and extend by classical bits
edge_map = layout.combine_into_edge_map(self.initial_layout)
for bit in dagcircuit_output.get_bits():
edge_map[bit] = bit
# Output this layer
dagcircuit_output.compose_back(layer_list[i]["graph"], edge_map)
return dagcircuit_output
def _mapper(self, circuit_graph, coupling_graph,
trials=20, seed=None):
"""Map a DAGCircuit onto a CouplingMap using swap gates.
Use self.initial_layout for the initial layout.
Args:
circuit_graph (DAGCircuit): input DAG circuit
coupling_graph (CouplingMap): coupling graph to map onto
trials (int): number of trials.
seed (int): initial seed.
Returns:
DAGCircuit: object containing a circuit equivalent to
circuit_graph that respects couplings in coupling_graph
Layout: a layout object mapping qubits of circuit_graph into
qubits of coupling_graph. The layout may differ from the
initial_layout if the first layer of gates cannot be
executed on the initial_layout, since in this case
it is more efficient to modify the layout instead of swapping
Dict: a final-layer qubit permutation
Raises:
TranspilerError: if there was any error during the mapping
or with the parameters.
"""
# Schedule the input circuit by calling layers()
layerlist = list(circuit_graph.layers())
logger.debug("schedule:")
for i, v in enumerate(layerlist):
logger.debug(" %d: %s", i, v["partition"])
if self.initial_layout is not None:
qubit_subset = self.initial_layout.get_virtual_bits().keys()
else:
# Supply a default layout for this dag
self.initial_layout = Layout()
physical_qubit = 0
for qreg in circuit_graph.qregs.values():
for index in range(qreg.size):
self.initial_layout[(qreg, index)] = physical_qubit
physical_qubit += 1
qubit_subset = self.initial_layout.get_virtual_bits().keys()
# Restrict the coupling map to the image of the layout
coupling_graph = coupling_graph.subgraph(
self.initial_layout.get_physical_bits().keys())
if coupling_graph.size() < len(self.initial_layout):
raise TranspilerError("Coupling map too small for default layout")
self.input_layout = self.initial_layout.copy()
# Find swap circuit to preceed to each layer of input circuit
layout = self.initial_layout.copy()
# Construct an empty DAGCircuit with the same set of
# qregs and cregs as the input circuit
dagcircuit_output = DAGCircuit()
dagcircuit_output.name = circuit_graph.name
for qreg in circuit_graph.qregs.values():
dagcircuit_output.add_qreg(qreg)
for creg in circuit_graph.cregs.values():
dagcircuit_output.add_creg(creg)
# Make a trivial wire mapping between the subcircuits
# returned by _layer_update and the circuit we build
identity_wire_map = {}
for qubit in circuit_graph.get_qubits():
identity_wire_map[qubit] = qubit
for bit in circuit_graph.get_bits():
identity_wire_map[bit] = bit
first_layer = True # True until first layer is output
logger.debug("initial_layout = %s", layout)
# Iterate over layers
for i, layer in enumerate(layerlist):
# Attempt to find a permutation for this layer
success_flag, best_circuit, best_depth, best_layout, trivial_flag \
= self._layer_permutation(layer["partition"], layout,
qubit_subset, coupling_graph,
trials, seed)
logger.debug("mapper: layer %d", i)
logger.debug("mapper: success_flag=%s,best_depth=%s,trivial_flag=%s",
success_flag, str(best_depth), trivial_flag)
# If this fails, try one gate at a time in this layer
if not success_flag:
logger.debug("mapper: failed, layer %d, "
"retrying sequentially", i)
serial_layerlist = list(layer["graph"].serial_layers())
# Go through each gate in the layer
for j, serial_layer in enumerate(serial_layerlist):
success_flag, best_circuit, best_depth, best_layout, trivial_flag = \
self._layer_permutation(
serial_layer["partition"],
layout, qubit_subset,
coupling_graph,
trials, seed)
logger.debug("mapper: layer %d, sublayer %d", i, j)
logger.debug("mapper: success_flag=%s,best_depth=%s,"
"trivial_flag=%s",
success_flag, str(best_depth), trivial_flag)
# Give up if we fail again
if not success_flag:
raise TranspilerError("mapper failed: " +
"layer %d, sublayer %d" %
(i, j) + ", \"%s\"" %
serial_layer["graph"].qasm(
no_decls=True,
aliases=layout))
# If this layer is only single-qubit gates,
# and we have yet to see multi-qubit gates,
# continue to the next inner iteration
if trivial_flag and first_layer:
logger.debug("mapper: skip to next sublayer")
continue
if first_layer:
self.initial_layout = layout
# Update the record of qubit positions
# for each inner iteration
layout = best_layout
# Update the DAG
dagcircuit_output.extend_back(
self._layer_update(j,
first_layer,
best_layout,
best_depth,
best_circuit,
serial_layerlist),
identity_wire_map)
if first_layer:
first_layer = False
else:
# Update the record of qubit positions for each iteration
layout = best_layout
if first_layer:
self.initial_layout = layout
# Update the DAG
dagcircuit_output.extend_back(
self._layer_update(i,
first_layer,
best_layout,
best_depth,
best_circuit,
layerlist),
identity_wire_map)
if first_layer:
first_layer = False
# This is the final edgemap. We might use it to correctly replace
# any measurements that needed to be removed earlier.
logger.debug("mapper: self.initial_layout = %s", pformat(self.initial_layout))
logger.debug("mapper: layout = %s", pformat(layout))
last_edgemap = layout.combine_into_edge_map(self.initial_layout)
logger.debug("mapper: last_edgemap = %s", pformat(last_edgemap))
# If first_layer is still set, the circuit only has single-qubit gates
# so we can use the initial layout to output the entire circuit
# This code is dead due to changes to first_layer above.
if first_layer:
logger.debug("mapper: first_layer flag still set")
layout = self.initial_layout
for i, layer in enumerate(layerlist):
edge_map = layout.combine_into_edge_map(self.initial_layout)
dagcircuit_output.compose_back(layer["graph"], edge_map)
return dagcircuit_output
<|code_end|>
|
qiskit/transpiler/passes/mapping/stochastic_swap.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A pass implementing the default Qiskit stochastic mapper.
"""
from logging import getLogger
from pprint import pformat
from math import inf
import numpy as np
from qiskit.transpiler._basepasses import TransformationPass
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.dagcircuit import DAGCircuit
from qiskit.extensions.standard import SwapGate
from qiskit.mapper import Layout
from .barrier_before_final_measurements import BarrierBeforeFinalMeasurements
logger = getLogger(__name__)
# Notes:
# 1. Measurements may occur and be followed by swaps that result in repeated
# measurement of the same qubit. Near-term experiments cannot implement
# these circuits, so some care is required when using this mapper
# with experimental backend targets.
# 2. We do not use the fact that the input state is zero to simplify
# the circuit.
class StochasticSwap(TransformationPass):
"""
Maps a DAGCircuit onto a `coupling_map` adding swap gates.
Uses a randomized algorithm.
"""
def __init__(self, coupling_map, initial_layout=None,
trials=20, seed=None):
"""
Map a DAGCircuit onto a `coupling_map` using swap gates.
If initial_layout is not None, we assume the input circuit
has been layed out before running this pass, and that
the layout process yields a DAG, coupling map, and layout
with the following properties:
1. All three have the same number of qubits
2. The layout a bijection from the DAG qubits to the coupling map
For this mapping pass, it may also be necessary that
3. The coupling map is a connected graph
If these are not satisfied, the behavior is undefined.
Args:
coupling_map (CouplingMap): Directed graph representing a coupling
map.
initial_layout (Layout): initial layout of qubits in mapping
trials (int): maximum number of iterations to attempt
seed (int): seed for random number generator
"""
super().__init__()
self.coupling_map = coupling_map
self.initial_layout = initial_layout
self.input_layout = None
self.trials = trials
self.seed = seed
self.requires.append(BarrierBeforeFinalMeasurements())
def run(self, dag):
"""
Run the StochasticSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
"""
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
self.input_layout = self.initial_layout.copy()
new_dag = self._mapper(dag, self.coupling_map, trials=self.trials, seed=self.seed)
# self.property_set["layout"] = self.initial_layout
return new_dag
def _layer_permutation(self, layer_partition, layout, qubit_subset,
coupling, trials, seed=None):
"""Find a swap circuit that implements a permutation for this layer.
The goal is to swap qubits such that qubits in the same two-qubit gates
are adjacent.
Based on S. Bravyi's algorithm.
layer_partition (list): The layer_partition is a list of (qu)bit
lists and each qubit is a tuple (qreg, index).
layout (Layout): The layout is a Layout object mapping virtual
qubits in the input circuit to physical qubits in the coupling
graph. It reflects the current positions of the data.
qubit_subset (list): The qubit_subset is the set of qubits in
the coupling graph that we have chosen to map into, as tuples
(Register, index).
coupling (CouplingMap): Directed graph representing a coupling map.
This coupling map should be one that was provided to the
stochastic mapper.
trials (int): Number of attempts the randomized algorithm makes.
seed (int): Optional seed for the random number generator. If it is
None we do not reseed.
Returns:
Tuple: success_flag, best_circuit, best_depth, best_layout, trivial_flag
If success_flag is True, then best_circuit contains a DAGCircuit with
the swap circuit, best_depth contains the depth of the swap circuit,
and best_layout contains the new positions of the data qubits after the
swap circuit has been applied. The trivial_flag is set if the layer
has no multi-qubit gates.
Raises:
TranspilerError: if anything went wrong.
"""
if seed is not None:
np.random.seed(seed)
logger.debug("layer_permutation: layer_partition = %s",
pformat(layer_partition))
logger.debug("layer_permutation: layout = %s",
pformat(layout.get_virtual_bits()))
logger.debug("layer_permutation: qubit_subset = %s",
pformat(qubit_subset))
logger.debug("layer_permutation: trials = %s", trials)
gates = [] # list of lists of tuples [[(register, index), ...], ...]
for gate_args in layer_partition:
if len(gate_args) > 2:
raise TranspilerError("Layer contains > 2-qubit gates")
elif len(gate_args) == 2:
gates.append(tuple(gate_args))
logger.debug("layer_permutation: gates = %s", pformat(gates))
# Can we already apply the gates? If so, there is no work to do.
dist = sum([coupling.distance(layout[g[0]], layout[g[1]])
for g in gates])
logger.debug("layer_permutation: distance = %s", dist)
if dist == len(gates):
logger.debug("layer_permutation: nothing to do")
circ = DAGCircuit()
for register in layout.get_virtual_bits().keys():
if register[0] not in circ.qregs.values():
circ.add_qreg(register[0])
circ.add_basis_element("swap", 2)
return True, circ, 0, layout, (not bool(gates))
# Begin loop over trials of randomized algorithm
num_qubits = len(layout)
best_depth = inf # initialize best depth
best_circuit = None # initialize best swap circuit
best_layout = None # initialize best final layout
for trial in range(trials):
logger.debug("layer_permutation: trial %s", trial)
trial_layout = layout.copy()
trial_circuit = DAGCircuit() # SWAP circuit for this trial
for register in trial_layout.get_virtual_bits().keys():
if register[0] not in trial_circuit.qregs.values():
trial_circuit.add_qreg(register[0])
# Compute randomized distance
xi = {} # pylint: disable=invalid-name
for i in range(num_qubits):
xi[i] = {}
for i in range(num_qubits):
for j in range(i, num_qubits):
scale = 1 + np.random.normal(0, 1 / num_qubits)
xi[i][j] = scale * coupling.distance(i, j) ** 2
xi[j][i] = xi[i][j]
slice_circuit = DAGCircuit() # circuit for this swap slice
for register in trial_layout.get_virtual_bits().keys():
if register[0] not in slice_circuit.qregs.values():
slice_circuit.add_qreg(register[0])
slice_circuit.add_basis_element("swap", 2)
# Loop over depths from 1 up to a maximum depth
depth_step = 1
depth_max = 2 * num_qubits + 1
while depth_step < depth_max:
qubit_set = set(qubit_subset)
# While there are still qubits available
while qubit_set:
# Compute the objective function
min_cost = sum([xi[trial_layout[g[0]]][trial_layout[g[1]]] for g in gates])
# Try to decrease objective function
cost_reduced = False
# Loop over edges of coupling graph
for edge in coupling.get_edges():
qubits = [trial_layout[e] for e in edge]
# Are the qubits available?
if qubits[0] in qubit_set and qubits[1] in qubit_set:
# Try this edge to reduce the cost
new_layout = trial_layout.copy()
new_layout.swap(edge[0], edge[1])
# Compute the objective function
new_cost = sum([xi[new_layout[g[0]]][new_layout[g[1]]] for g in gates])
# Record progress if we succceed
if new_cost < min_cost:
logger.debug("layer_permutation: min_cost "
"improved to %s", min_cost)
cost_reduced = True
min_cost = new_cost
optimal_layout = new_layout
optimal_edge = [self.initial_layout[q] for q in edge]
optimal_qubits = qubits
# Were there any good swap choices?
if cost_reduced:
qubit_set.remove(optimal_qubits[0])
qubit_set.remove(optimal_qubits[1])
trial_layout = optimal_layout
slice_circuit.apply_operation_back(
SwapGate(optimal_edge[0],
optimal_edge[1]))
logger.debug("layer_permutation: swap the pair %s",
pformat(optimal_edge))
else:
break
# We have either run out of swap pairs to try or
# failed to improve the cost.
# Compute the coupling graph distance
dist = sum([coupling.distance(trial_layout[g[0]],
trial_layout[g[1]])
for g in gates])
logger.debug("layer_permutation: new swap distance = %s", dist)
# If all gates can be applied now, we are finished.
# Otherwise we need to consider a deeper swap circuit
if dist == len(gates):
logger.debug("layer_permutation: all gates can be "
"applied now in this layer")
trial_circuit.extend_back(slice_circuit)
break
# Increment the depth
depth_step += 1
logger.debug("layer_permutation: increment depth to %s", depth_step)
# Either we have succeeded at some depth d < dmax or failed
dist = sum([coupling.distance(trial_layout[g[0]],
trial_layout[g[1]])
for g in gates])
logger.debug("layer_permutation: final distance for this trial = %s", dist)
if dist == len(gates):
if depth_step < best_depth:
logger.debug("layer_permutation: got circuit with improved depth %s",
depth_step)
best_circuit = trial_circuit
best_layout = trial_layout
best_depth = min(best_depth, depth_step)
# Break out of trial loop if we found a depth 1 circuit
# since we can't improve it further
if best_depth == 1:
break
# If we have no best circuit for this layer, all of the
# trials have failed
if best_circuit is None:
logger.debug("layer_permutation: failed!")
return False, None, None, None, False
# Otherwise, we return our result for this layer
logger.debug("layer_permutation: success!")
return True, best_circuit, best_depth, best_layout, False
def _layer_update(self, i, first_layer, best_layout, best_depth,
best_circuit, layer_list):
"""Provide a DAGCircuit for a new mapped layer.
i (int) = layer number
first_layer (bool) = True if this is the first layer in the
circuit with any multi-qubit gates
best_layout (Layout) = layout returned from _layer_permutation
best_depth (int) = depth returned from _layer_permutation
best_circuit (DAGCircuit) = swap circuit returned
from _layer_permutation
layer_list (list) = list of DAGCircuit objects for each layer,
output of DAGCircuit layers() method
Return a DAGCircuit object to append to the output DAGCircuit
that the _mapper method is building.
"""
layout = best_layout
logger.debug("layer_update: layout = %s", pformat(layout))
logger.debug("layer_update: self.initial_layout = %s", pformat(self.initial_layout))
dagcircuit_output = DAGCircuit()
for register in layout.get_virtual_bits().keys():
if register[0] not in dagcircuit_output.qregs.values():
dagcircuit_output.add_qreg(register[0])
# If this is the first layer with multi-qubit gates,
# output all layers up to this point and ignore any
# swap gates. Set the initial layout.
if first_layer:
logger.debug("layer_update: first multi-qubit gate layer")
# Output all layers up to this point
for j in range(i + 1):
# Make qubit edge map and extend by classical bits
edge_map = layout.combine_into_edge_map(self.initial_layout)
for bit in dagcircuit_output.get_bits():
edge_map[bit] = bit
dagcircuit_output.compose_back(layer_list[j]["graph"], edge_map)
# Otherwise, we output the current layer and the associated swap gates.
else:
# Output any swaps
if best_depth > 0:
logger.debug("layer_update: there are swaps in this layer, "
"depth %d", best_depth)
dagcircuit_output.extend_back(best_circuit)
else:
logger.debug("layer_update: there are no swaps in this layer")
# Make qubit edge map and extend by classical bits
edge_map = layout.combine_into_edge_map(self.initial_layout)
for bit in dagcircuit_output.get_bits():
edge_map[bit] = bit
# Output this layer
dagcircuit_output.compose_back(layer_list[i]["graph"], edge_map)
return dagcircuit_output
def _mapper(self, circuit_graph, coupling_graph,
trials=20, seed=None):
"""Map a DAGCircuit onto a CouplingMap using swap gates.
Use self.initial_layout for the initial layout.
Args:
circuit_graph (DAGCircuit): input DAG circuit
coupling_graph (CouplingMap): coupling graph to map onto
trials (int): number of trials.
seed (int): initial seed.
Returns:
DAGCircuit: object containing a circuit equivalent to
circuit_graph that respects couplings in coupling_graph
Layout: a layout object mapping qubits of circuit_graph into
qubits of coupling_graph. The layout may differ from the
initial_layout if the first layer of gates cannot be
executed on the initial_layout, since in this case
it is more efficient to modify the layout instead of swapping
Dict: a final-layer qubit permutation
Raises:
TranspilerError: if there was any error during the mapping
or with the parameters.
"""
# Schedule the input circuit by calling layers()
layerlist = list(circuit_graph.layers())
logger.debug("schedule:")
for i, v in enumerate(layerlist):
logger.debug(" %d: %s", i, v["partition"])
if self.initial_layout is not None:
qubit_subset = self.initial_layout.get_virtual_bits().keys()
else:
# Supply a default layout for this dag
self.initial_layout = Layout()
physical_qubit = 0
for qreg in circuit_graph.qregs.values():
for index in range(qreg.size):
self.initial_layout[(qreg, index)] = physical_qubit
physical_qubit += 1
qubit_subset = self.initial_layout.get_virtual_bits().keys()
# Restrict the coupling map to the image of the layout
coupling_graph = coupling_graph.subgraph(
self.initial_layout.get_physical_bits().keys())
if coupling_graph.size() < len(self.initial_layout):
raise TranspilerError("Coupling map too small for default layout")
self.input_layout = self.initial_layout.copy()
# Find swap circuit to preceed to each layer of input circuit
layout = self.initial_layout.copy()
# Construct an empty DAGCircuit with the same set of
# qregs and cregs as the input circuit
dagcircuit_output = DAGCircuit()
dagcircuit_output.name = circuit_graph.name
for qreg in circuit_graph.qregs.values():
dagcircuit_output.add_qreg(qreg)
for creg in circuit_graph.cregs.values():
dagcircuit_output.add_creg(creg)
# Make a trivial wire mapping between the subcircuits
# returned by _layer_update and the circuit we build
identity_wire_map = {}
for qubit in circuit_graph.get_qubits():
identity_wire_map[qubit] = qubit
for bit in circuit_graph.get_bits():
identity_wire_map[bit] = bit
first_layer = True # True until first layer is output
logger.debug("initial_layout = %s", layout)
# Iterate over layers
for i, layer in enumerate(layerlist):
# Attempt to find a permutation for this layer
success_flag, best_circuit, best_depth, best_layout, trivial_flag \
= self._layer_permutation(layer["partition"], layout,
qubit_subset, coupling_graph,
trials, seed)
logger.debug("mapper: layer %d", i)
logger.debug("mapper: success_flag=%s,best_depth=%s,trivial_flag=%s",
success_flag, str(best_depth), trivial_flag)
# If this fails, try one gate at a time in this layer
if not success_flag:
logger.debug("mapper: failed, layer %d, "
"retrying sequentially", i)
serial_layerlist = list(layer["graph"].serial_layers())
# Go through each gate in the layer
for j, serial_layer in enumerate(serial_layerlist):
success_flag, best_circuit, best_depth, best_layout, trivial_flag = \
self._layer_permutation(
serial_layer["partition"],
layout, qubit_subset,
coupling_graph,
trials, seed)
logger.debug("mapper: layer %d, sublayer %d", i, j)
logger.debug("mapper: success_flag=%s,best_depth=%s,"
"trivial_flag=%s",
success_flag, str(best_depth), trivial_flag)
# Give up if we fail again
if not success_flag:
raise TranspilerError("mapper failed: " +
"layer %d, sublayer %d" %
(i, j) + ", \"%s\"" %
serial_layer["graph"].qasm(
no_decls=True,
aliases=layout))
# If this layer is only single-qubit gates,
# and we have yet to see multi-qubit gates,
# continue to the next inner iteration
if trivial_flag and first_layer:
logger.debug("mapper: skip to next sublayer")
continue
if first_layer:
self.initial_layout = layout
# Update the record of qubit positions
# for each inner iteration
layout = best_layout
# Update the DAG
dagcircuit_output.extend_back(
self._layer_update(j,
first_layer,
best_layout,
best_depth,
best_circuit,
serial_layerlist),
identity_wire_map)
if first_layer:
first_layer = False
else:
# Update the record of qubit positions for each iteration
layout = best_layout
if first_layer:
self.initial_layout = layout
# Update the DAG
dagcircuit_output.extend_back(
self._layer_update(i,
first_layer,
best_layout,
best_depth,
best_circuit,
layerlist),
identity_wire_map)
if first_layer:
first_layer = False
# This is the final edgemap. We might use it to correctly replace
# any measurements that needed to be removed earlier.
logger.debug("mapper: self.initial_layout = %s", pformat(self.initial_layout))
logger.debug("mapper: layout = %s", pformat(layout))
last_edgemap = layout.combine_into_edge_map(self.initial_layout)
logger.debug("mapper: last_edgemap = %s", pformat(last_edgemap))
# If first_layer is still set, the circuit only has single-qubit gates
# so we can use the initial layout to output the entire circuit
# This code is dead due to changes to first_layer above.
if first_layer:
logger.debug("mapper: first_layer flag still set")
layout = self.initial_layout
for i, layer in enumerate(layerlist):
edge_map = layout.combine_into_edge_map(self.initial_layout)
dagcircuit_output.compose_back(layer["graph"], edge_map)
return dagcircuit_output
<|code_end|>
|
Left justify the circuit in text visualizer
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
Currently when a circuit is displayed using the text drawer each gate in a circuit sits in its own column, as shown in the following circuit.
```
┌───┐
q1_0: |0>┤ H ├──────────
└───┘┌───┐
q1_1: |0>─────┤ H ├─────
└───┘
```
It would be better if the circuits could be left justified, so the above circuit would appear as below.
```
┌───┐
q1_0: |0>┤ H ├───────
└───┘
┌───┐
q1_1: |0>┤ H ├───────
└───┘
```
It appears that circuits are already justified like this in the matplotlib drawer.
Consistent gates order in visualizations (and DAG?)
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
As a spin-off from #1617 (thanks @Exferro!) , during that PR it was detected that the same `QuantumCircuit` produces different visualizations between Python [3.5](https://github.com/Qiskit/qiskit-terra/blob/73d47fd924edd948aee51b648b15d06211a17a20/test/python/tools/visualization/references/3.5/deep/mpl.png) and [3.6/3.7](https://github.com/Qiskit/qiskit-terra/blob/73d47fd924edd948aee51b648b15d06211a17a20/test/python/tools/visualization/references/3.6/deep/mpl.png) - the order in which `measure`s are drawn is different.
Digging a bit deeper, it seems it might be a mixture of two issues:
* the order of the instructions in the circuit (`circuit.data`) is not preserved in the final visualization
* potentially, there might be some `dict` vs `OrderedDict` issue involved (based on the example at #1617 producing the _same_ result in 3.6/3.7, and a different one in 3.5) - this is not confirmed.
### Desired behaviour
Ideally, we should be able to at least guarantee a "consistent" order (same visualization is produced regardless of Python version), and hopefully one that respects the original instruction order.
### Proposed solution
The main flow when producing a visualization is through [`_get_instructions()`](
https://github.com/Qiskit/qiskit-terra/blob/179290f082a9c4b905402db8a60fe7bb899f79e8/qiskit/tools/visualization/_utils.py#L68), which in turn ends up invoking [`node_nums_in_topological_order()`](https://github.com/Qiskit/qiskit-terra/blob/179290f082a9c4b905402db8a60fe7bb899f79e8/qiskit/dagcircuit/_dagcircuit.py#L984). A possible solution might involve ensuring that the topological sorting always return the same solution, for example "tagging" or adding extra information to the DAG for allowing it to restore the order in which gates were added to the circuit (@ajavadia can ellaborate into the idea).
## Good first contribution!
I am actually tagging this as `good first contribution`, as I believe is an interesting change to explore both the circuits/dags and the visualization sides of Terra - and with a cool end result! If somebody is interested, please ping us by replying to this issue :tada:
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# TODO: Remove after 0.7 and the deprecated methods are removed
# pylint: disable=unused-argument
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import errno
import logging
import os
import subprocess
import tempfile
from PIL import Image
from qiskit.tools.visualization import exceptions
from qiskit.tools.visualization import _latex
from qiskit.tools.visualization import _text
from qiskit.tools.visualization import _utils
from qiskit.tools.visualization import _matplotlib
logger = logging.getLogger(__name__)
def circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
output='text',
interactive=False,
line_length=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art TextDrawing that can be printed in the console.
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Args:
circuit (QuantumCircuit): the quantum circuit to draw
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (TextDrawing): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if
one is not specified it will use latex and if that fails fallback
to mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(for `mpl` this depends on the matplotlib backend being used
supporting this). Note when used with either the `text` or the
`latex_source` output type this has no effect and will be silently
ignored.
line_length (int): Sets the length of the lines generated by `text`
output type. This useful when the drawing does not fit in the
console. If None (default), it will try to guess the console width
using shutil.get_terminal_size(). However, if you're running in
jupyter the default line length is set to 80 characters. If you
don't want pagination at all, set `line_length=-1`.
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: (output `latex`) an in-memory representation of the image
of the circuit diagram.
matplotlib.figure: (output `mpl`) a matplotlib figure object for the
circuit diagram.
String: (output `latex_source`). The LaTeX source code.
TextDrawing: (output `text`). A drawing that can be printed as ascii art
Raises:
VisualizationError: when an invalid output method is selected
ImportError: when the output methods requieres non-installed libraries.
.. _style-dict-doc:
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defaults to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'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'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
"""
image = None
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename,
line_length=line_length,
reversebits=reverse_bits,
plotbarriers=plot_barriers)
elif output == 'latex':
image = _latex_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'latex_source':
return _generate_latex_source(circuit,
filename=filename, scale=scale,
style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'mpl':
image = _matplotlib_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
else:
raise exceptions.VisualizationError(
'Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if image and interactive:
image.show()
return image
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
"""Return default style for matplotlib_circuit_drawer (IBM QX style)."""
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None, line_length=None, reversebits=False,
plotbarriers=True):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
reversebits (bool): Rearrange the bits in reverse order.
plotbarriers (bool): Draws the barriers when they are there.
Returns:
TextDrawing: An instances that, when printed, draws the circuit in ascii art.
"""
qregs, cregs, ops = _utils._get_instructions(circuit, reversebits=reversebits)
text_drawing = _text.TextDrawing(qregs, cregs, ops)
text_drawing.plotbarriers = plotbarriers
text_drawing.line_length = line_length
if filename:
text_drawing.dump(filename)
return text_drawing
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def _latex_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath,
scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
image = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as ex:
with open('latex_error.log', 'wb') as error_file:
error_file.write(ex.stdout)
logger.warning('WARNING Unable to compile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
image = Image.open(base + '.png')
image = _utils._trim(image)
os.remove(base + '.png')
if filename:
image.save(filename, 'PNG')
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return image
def _generate_latex_source(circuit, filename=None,
scale=0.7, style=None, reverse_bits=False,
plot_barriers=True):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
str: Latex string appropriate for writing to file.
"""
qregs, cregs, ops = _utils._get_instructions(circuit,
reversebits=reverse_bits)
qcimg = _latex.QCircuitImage(qregs, cregs, ops, scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def _matplotlib_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
matplotlib.figure: a matplotlib figure object for the circuit diagram
"""
qcd = _matplotlib.MatplotlibDrawer(scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
<|code_end|>
qiskit/tools/visualization/_text.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A module for drawing circuits in ascii art or some other text representation
"""
from shutil import get_terminal_size
import sys
from .exceptions import VisualizationError
class DrawElement():
""" An element is an instruction or an operation that need to be drawn."""
def __init__(self, label=None):
self._width = None
self.label = self.mid_content = label
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = self.bot_connect = " "
self.top_pad = self._mid_padding = self.bot_pad = " "
self.bot_connector = {}
self.top_connector = {}
self.right_fill = self.left_fill = 0
@property
def top(self):
""" Constructs the top line of the element"""
ret = self.top_format % self.top_connect.center(
self.width - self.left_fill - self.right_fill, self.top_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.top_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.top_pad)
return ret
@property
def mid(self):
""" Constructs the middle line of the element"""
ret = self.mid_format % self.mid_content.center(
self.width - self.left_fill - self.right_fill, self._mid_padding)
if self.right_fill:
ret = ret.ljust(self.right_fill, self._mid_padding)
if self.left_fill:
ret = ret.rjust(self.left_fill, self._mid_padding)
return ret
@property
def bot(self):
""" Constructs the bottom line of the element"""
ret = self.bot_format % self.bot_connect.center(
self.width - self.left_fill - self.right_fill, self.bot_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.bot_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.bot_pad)
return ret
@property
def length(self):
""" Returns the length of the element, including the box around."""
return max(len(self.top), len(self.mid), len(self.bot))
@length.setter
def length(self, value):
""" Adjusts width so the length fits."""
self.width = value - max(
[len(getattr(self, i) % '') for i in ["bot_format", "mid_format", "top_format"]])
@property
def width(self):
""" Returns the width of the label, including padding"""
if self._width:
return self._width
return len(self.mid_content)
@width.setter
def width(self, value):
self._width = value
def connect(self, wire_char, where, label=None):
"""
Connects boxes and elements using wire_char and setting proper connectors.
Args:
wire_char (char): For example '║' or '│'.
where (list["top", "bot"]): Where the connector should be set.
label (string): Some connectors have a label (see cu1, for example).
"""
if 'top' in where and self.top_connector:
self.top_connect = self.top_connector[wire_char]
if 'bot' in where and self.bot_connector:
self.bot_connect = self.bot_connector[wire_char]
if label:
self.top_format = self.top_format[:-1] + (label if label else "")
class BoxOnClWire(DrawElement):
""" Draws a box on the classical wire
top: ┌───┐ ┌───────┐
mid: ╡ A ╞ ╡ A ╞
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "╡ %s ╞"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
class BoxOnQuWire(DrawElement):
""" Draws a box on the quantum wire
top: ┌───┐ ┌───────┐
mid: ┤ A ├ ┤ A ├
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "┤ %s ├"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
self.top_connector = {"│": '┴'}
self.bot_connector = {"│": '┬'}
class MeasureTo(DrawElement):
""" The element on the classic wire to which the measure is performed
top: ║ ║
mid: ═╩═ ═══╩═══
bot:
"""
def __init__(self):
super().__init__()
self.top_connect = " ║ "
self.mid_content = "═╩═"
self.bot_connect = " "
self._mid_padding = "═"
class MeasureFrom(BoxOnQuWire):
""" The element on the quantum wire in which the measure is performed
top: ┌─┐ ┌─┐
mid: ┤M├ ───┤M├───
bot: └╥┘ └╥┘
"""
def __init__(self):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = "┌─┐"
self.mid_content = "┤M├"
self.bot_connect = "└╥┘"
class MultiBox(DrawElement):
"""Elements that is draw on over multiple wires."""
def center_label(self, input_length, order):
"""
In multi-bit elements, the label is centered vertically.
Args:
input_length (int): Rhe amount of wires affected.
order (int): Which middle element is this one?
"""
location_in_the_box = '*'.center(input_length * 2 - 1).index('*') + 1
top_limit = (order - 1) * 2 + 2
bot_limit = top_limit + 2
if top_limit <= location_in_the_box < bot_limit:
if location_in_the_box == top_limit:
self.top_connect = self.label
elif location_in_the_box == top_limit + 1:
self.mid_content = self.label
else:
self.bot_connect = self.label
class BoxOnQuWireTop(MultiBox, BoxOnQuWire):
""" Draws the top part of a box that affects more than one quantum wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnQuWireMid(MultiBox, BoxOnQuWire):
""" Draws the middle part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.center_label(input_length, order)
class BoxOnQuWireBot(MultiBox, BoxOnQuWire):
""" Draws the bottom part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length, bot_connect='─'):
super().__init__(label)
self.top_format = "│ %s │"
self.top_pad = " "
self.bot_connect = bot_connect
self.mid_content = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class BoxOnClWireTop(MultiBox, BoxOnClWire):
""" Draws the top part of a conditional box that affects more than one classical wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnClWireMid(MultiBox, BoxOnClWire):
""" Draws the middle part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.mid_content = label
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.top_pad = self.bot_pad = ' '
self.top_connect = self.bot_connect = self.mid_content = ''
self.center_label(input_length, order)
class BoxOnClWireBot(MultiBox, BoxOnClWire):
""" Draws the bottom part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, bot_connect='─'):
super().__init__(label)
self.top_format = "│ %s │"
self.top_pad = " "
self.bot_connect = bot_connect
self.mid_content = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class DirectOnQuWire(DrawElement):
"""
Element to the wire (without the box).
"""
def __init__(self, label=""):
super().__init__(label)
self.top_format = ' %s '
self.mid_format = '─%s─'
self.bot_format = ' %s '
self._mid_padding = '─'
self.top_connector = {"│": '│'}
self.bot_connector = {"│": '│'}
class Barrier(DirectOnQuWire):
""" Draws a barrier.
top: ░ ░
mid: ─░─ ───░───
bot: ░ ░
"""
def __init__(self, label=""):
super().__init__("░")
self.top_connect = "░"
self.bot_connect = "░"
self.top_connector = {}
self.bot_connector = {}
class Ex(DirectOnQuWire):
""" Draws an X (usually with a connector). E.g. the top part of a swap gate
top:
mid: ─X─ ───X───
bot: │ │
"""
def __init__(self, bot_connect=" ", top_connect=" "):
super().__init__("X")
self.bot_connect = bot_connect
self.top_connect = top_connect
class Reset(DirectOnQuWire):
""" Draws a reset gate"""
def __init__(self):
super().__init__("|0>")
class Bullet(DirectOnQuWire):
""" Draws a bullet (usually with a connector). E.g. the top part of a CX gate.
top:
mid: ─■─ ───■───
bot: │ │
"""
def __init__(self, top_connect=" ", bot_connect=" "):
super().__init__('■')
self.top_connect = top_connect
self.bot_connect = bot_connect
class EmptyWire(DrawElement):
""" This element is just the wire, with no instructions nor operations."""
def __init__(self, wire):
super().__init__(wire)
self._mid_padding = wire
@staticmethod
def fillup_layer(layer, first_clbit):
"""
Given a layer, replace the Nones in it with EmptyWire elements.
Args:
layer (list): The layer that contains Nones.
first_clbit (int): The first wire that is classic.
Returns:
list: The new layer, with no Nones.
"""
for nones in [i for i, x in enumerate(layer) if x is None]:
layer[nones] = EmptyWire('═') if nones >= first_clbit else EmptyWire('─')
return layer
class BreakWire(DrawElement):
""" This element is used to break the drawing in several pages."""
def __init__(self, arrow_char):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = arrow_char
self.mid_content = arrow_char
self.bot_connect = arrow_char
@staticmethod
def fillup_layer(layer_length, arrow_char):
"""
Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer.
"""
breakwire_layer = []
for _ in range(layer_length):
breakwire_layer.append(BreakWire(arrow_char))
return breakwire_layer
class InputWire(DrawElement):
""" This element is the label and the initial value of a wire."""
def __init__(self, label):
super().__init__(label)
@staticmethod
def fillup_layer(names): # pylint: disable=arguments-differ
"""
Creates a layer with InputWire elements.
Args:
names (list): List of names for the wires.
Returns:
list: The new layer
"""
longest = max([len(name) for name in names])
inputs_wires = []
for name in names:
inputs_wires.append(InputWire(name.rjust(longest)))
return inputs_wires
class TextDrawing():
""" The text drawing"""
def __init__(self, qregs, cregs, instructions, plotbarriers=True, line_length=None):
self.qregs = qregs
self.cregs = cregs
self.instructions = instructions
self.plotbarriers = plotbarriers
self.line_length = line_length
def __str__(self):
return self.single_string()
def _repr_html_(self):
return '<pre style="word-wrap: normal;' \
'white-space: pre;' \
'line-height: 15px;">%s</pre>' % self.single_string()
def _get_qubit_labels(self):
qubits = []
for qubit in self.qregs:
qubits.append("%s_%s" % (qubit[0].name, qubit[1]))
return qubits
def _get_clbit_labels(self):
clbits = []
for clbit in self.cregs:
clbits.append("%s_%s" % (clbit[0].name, clbit[1]))
return clbits
def single_string(self):
"""
Creates a loong string with the ascii art
Returns:
str: The lines joined by '\n'
"""
return "\n".join(self.lines())
def dump(self, filename, encoding="utf8"):
"""
Dumps the ascii art in the file.
Args:
filename (str): File to dump the ascii art.
encoding (str): Optional. Default "utf-8".
"""
with open(filename, mode='w', encoding=encoding) as text_file:
text_file.write(self.single_string())
def lines(self, line_length=None):
"""
Generates a list with lines. These lines form the text drawing.
Args:
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
Returns:
list: A list of lines with the text drawing.
"""
if line_length is None:
line_length = self.line_length
if line_length is None:
if ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
line_length = 80
else:
line_length, _ = get_terminal_size()
noqubits = len(self.qregs)
layers = self.build_layers()
# TODO compress layers
# -| H |----------
# --------| H |---
# should be
# -| H |---
# -| H |---
if not line_length:
line_length = self.line_length
layer_groups = [[]]
rest_of_the_line = line_length
for layerno, layer in enumerate(layers):
# Replace the Nones with EmptyWire
layers[layerno] = EmptyWire.fillup_layer(layer, noqubits)
TextDrawing.normalize_width(layer)
if line_length == -1:
# Do not use pagination (aka line breaking. aka ignore line_length).
layer_groups[-1].append(layer)
continue
# chop the layer to the line_length (pager)
layer_length = layers[layerno][0].length
if layer_length < rest_of_the_line:
layer_groups[-1].append(layer)
rest_of_the_line -= layer_length
else:
layer_groups[-1].append(BreakWire.fillup_layer(len(layer), '»'))
# New group
layer_groups.append([BreakWire.fillup_layer(len(layer), '«')])
rest_of_the_line = line_length - layer_groups[-1][-1][0].length
layer_groups[-1].append(
InputWire.fillup_layer(self.wire_names(with_initial_value=False)))
rest_of_the_line -= layer_groups[-1][-1][0].length
layer_groups[-1].append(layer)
rest_of_the_line -= layer_groups[-1][-1][0].length
lines = []
for layer_group in layer_groups:
wires = [i for i in zip(*layer_group)]
lines += TextDrawing.draw_wires(wires)
return lines
def wire_names(self, with_initial_value=True):
"""
Returns a list of names for each wire.
Args:
with_initial_value (bool): Optional (Default: True). If true, adds the initial value to
the name.
Returns:
List: The list of wire names.
"""
qubit_labels = self._get_qubit_labels()
clbit_labels = self._get_clbit_labels()
if with_initial_value:
qubit_labels = ['%s: |0>' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: 0 ' % clbit for clbit in clbit_labels]
else:
qubit_labels = ['%s: ' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: ' % clbit for clbit in clbit_labels]
return qubit_labels + clbit_labels
@staticmethod
def draw_wires(wires):
"""
Given a list of wires, creates a list of lines with the text drawing.
Args:
wires (list): A list of wires with instructions.
Returns:
list: A list of lines with the text drawing.
"""
lines = []
bot_line = None
for wire in wires:
# TOP
top_line = ""
for instruction in wire:
top_line += instruction.top
if bot_line is None:
lines.append(top_line)
else:
lines.append(TextDrawing.merge_lines(lines.pop(), top_line))
# MID
mid_line = ""
for instruction in wire:
mid_line += instruction.mid
lines.append(TextDrawing.merge_lines(lines[-1], mid_line, icod="bot"))
# BOT
bot_line = ""
for instruction in wire:
bot_line += instruction.bot
lines.append(TextDrawing.merge_lines(lines[-1], bot_line, icod="bot"))
return lines
@staticmethod
def label_for_conditional(instruction):
""" Creates the label for a conditional instruction."""
return "%s %s" % ('=', instruction['condition'][1])
@staticmethod
def params_for_label(instruction):
"""Get the params and format them to add them to a label. None if there are no params."""
if 'op' in instruction and hasattr(instruction['op'], 'params'):
return ['%.5g' % i for i in instruction['op'].params]
return None
@staticmethod
def label_for_box(instruction):
""" Creates the label for a box."""
label = instruction['name'].capitalize()
params = TextDrawing.params_for_label(instruction)
if params:
label += "(%s)" % ','.join(params)
return label
@staticmethod
def merge_lines(top, bot, icod="top"):
"""
Merges two lines (top and bot) in the way that the overlapping make senses.
Args:
top (str): the top line
bot (str): the bottom line
icod (top or bot): in case of doubt, which line should have priority? Default: "top".
Returns:
str: The merge of both lines.
"""
ret = ""
for topc, botc in zip(top, bot):
if topc == botc:
ret += topc
elif topc in '┼╪' and botc == " ":
ret += "│"
elif topc == " ":
ret += botc
elif topc in '┬╥' and botc in " ║│":
ret += topc
elif topc in '┬│' and botc == "═":
ret += '╪'
elif topc in '┬│' and botc == "─":
ret += '┼'
elif topc in '└┘║│░' and botc == " ":
ret += topc
elif topc in '─═' and botc == " " and icod == "top":
ret += topc
elif topc in '─═' and botc == " " and icod == "bot":
ret += botc
elif topc in "║╥" and botc in "═":
ret += "╬"
elif topc in "║╥" and botc in "─":
ret += "╫"
elif topc in '╫╬' and botc in " ":
ret += "║"
elif topc == '└' and botc == "┌":
ret += "├"
elif topc == '┘' and botc == "┐":
ret += "┤"
else:
ret += botc
return ret
@staticmethod
def normalize_width(layer):
"""
When the elements of the layer have different widths, sets the width to the max elements.
Args:
layer (list): A list of elements.
"""
instructions = [instruction for instruction in filter(lambda x: x is not None, layer)]
longest = max([instruction.length for instruction in instructions])
for instruction in instructions:
instruction.length = longest
def build_layers(self):
"""
Constructs layers.
Returns:
list: List of DrawElements.
Raises:
VisualizationError: When the drawing is, for some reason, impossible to be drawn.
"""
layers = []
layers.append(InputWire.fillup_layer(self.wire_names(with_initial_value=True)))
for instruction in self.instructions:
layer = Layer(self.qregs, self.cregs)
connector_label = None
if instruction['name'] == 'measure':
layer.set_qubit(instruction['qargs'][0], MeasureFrom())
layer.set_clbit(instruction['cargs'][0], MeasureTo())
elif instruction['name'] in ['barrier', 'snapshot', 'save', 'load',
'noise']:
# barrier
if not self.plotbarriers:
continue
for qubit in instruction['qargs']:
layer.set_qubit(qubit, Barrier())
elif instruction['name'] == 'swap':
# swap
for qubit in instruction['qargs']:
layer.set_qubit(qubit, Ex())
elif instruction['name'] == 'cswap':
# cswap
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], Ex())
layer.set_qubit(instruction['qargs'][2], Ex())
elif instruction['name'] == 'reset':
layer.set_qubit(instruction['qargs'][0], Reset())
elif instruction['condition'] is not None:
# conditional
cllabel = TextDrawing.label_for_conditional(instruction)
qulabel = TextDrawing.label_for_box(instruction)
layer.set_cl_multibox(instruction['condition'][0], cllabel, top_connect='┴')
layer.set_qubit(instruction['qargs'][0], BoxOnQuWire(qulabel, bot_connect='┬'))
elif instruction['name'] in ['cx', 'CX', 'ccx']:
# cx/ccx
for qubit in [qubit for qubit in instruction['qargs'][:-1]]:
layer.set_qubit(qubit, Bullet())
layer.set_qubit(instruction['qargs'][-1], BoxOnQuWire('X'))
elif instruction['name'] == 'cy':
# cy
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], BoxOnQuWire('Y'))
elif instruction['name'] == 'cz':
# cz
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], Bullet())
elif instruction['name'] == 'ch':
# ch
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], BoxOnQuWire('H'))
elif instruction['name'] == 'cu1':
# cu1
connector_label = TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], Bullet())
elif instruction['name'] == 'cu3':
# cu3
params = TextDrawing.params_for_label(instruction)
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1],
BoxOnQuWire("U3(%s)" % ','.join(params)))
elif instruction['name'] == 'crz':
# crz
label = "Rz(%s)" % TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], BoxOnQuWire(label))
elif len(instruction['qargs']) == 1 and not instruction['cargs']:
# unitary gate
layer.set_qubit(instruction['qargs'][0],
BoxOnQuWire(TextDrawing.label_for_box(instruction)))
elif len(instruction['qargs']) >= 2 and not instruction['cargs']:
# multiple qubit gate
layer.set_qu_multibox(instruction['qargs'], TextDrawing.label_for_box(instruction))
else:
raise VisualizationError(
"Text visualizer does not know how to handle this instruction", instruction)
layer.connect_with("│", connector_label)
layers.append(layer.full_layer)
return layers
class Layer:
""" A layer is the "column" of the circuit. """
def __init__(self, qregs, cregs):
self.qregs = qregs
self.cregs = cregs
self.qubit_layer = [None] * len(qregs)
self.clbit_layer = [None] * len(cregs)
@property
def full_layer(self):
"""
Returns the composition of qubits and classic wires.
Returns:
String: self.qubit_layer + self.clbit_layer
"""
return self.qubit_layer + self.clbit_layer
def set_qubit(self, qubit, element):
"""
Sets the qubit to the element
Args:
qubit (qbit): Element of self.qregs.
element (DrawElement): Element to set in the qubit
"""
self.qubit_layer[self.qregs.index(qubit)] = element
def set_clbit(self, clbit, element):
"""
Sets the clbit to the element
Args:
clbit (cbit): Element of self.cregs.
element (DrawElement): Element to set in the clbit
"""
self.clbit_layer[self.cregs.index(clbit)] = element
def _set_multibox(self, wire_type, bits, label, top_connect=None):
# pylint: disable=invalid-name
if wire_type == "cl":
bit_index = sorted([i for i, x in enumerate(self.cregs) if x in bits])
bits.sort(key=self.cregs.index)
set_bit = self.set_clbit
BoxOnWire = BoxOnClWire
BoxOnWireTop = BoxOnClWireTop
BoxOnWireMid = BoxOnClWireMid
BoxOnWireBot = BoxOnClWireBot
elif wire_type == "qu":
bit_index = sorted([i for i, x in enumerate(self.qregs) if x in bits])
bits.sort(key=self.qregs.index)
set_bit = self.set_qubit
BoxOnWire = BoxOnQuWire
BoxOnWireTop = BoxOnQuWireTop
BoxOnWireMid = BoxOnQuWireMid
BoxOnWireBot = BoxOnQuWireBot
else:
raise VisualizationError("_set_multibox only supports 'cl' and 'qu' as wire types.")
# Checks if bits are consecutive
if bit_index != [i for i in range(bit_index[0], bit_index[-1] + 1)]:
raise VisualizationError("Text visualizaer does know how to build a gate with multiple"
"bits when they are not adjacent to each other")
if len(bit_index) == 1:
set_bit(bits[0], BoxOnWire(label, top_connect=top_connect))
else:
set_bit(bits[0], BoxOnWireTop(label, top_connect=top_connect))
for order, bit in enumerate(bits[1:-1], 1):
set_bit(bit, BoxOnWireMid(label, len(bit_index), order))
set_bit(bits[-1], BoxOnWireBot(label, len(bit_index)))
def set_cl_multibox(self, creg, label, top_connect='┴'):
"""
Sets the multi clbit box.
Args:
creg (string): The affected classical register.
label (string): The label for the multi clbit box.
top_connect (char): The char to connect the box on the top.
"""
clbit = [bit for bit in self.cregs if bit[0] == creg]
self._set_multibox("cl", clbit, label, top_connect=top_connect)
def set_qu_multibox(self, bits, label):
"""
Sets the multi qubit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi qubit box.
"""
self._set_multibox("qu", bits, label)
def connect_with(self, wire_char, label=None):
"""
Connects the elements in the layer using wire_char.
Args:
wire_char (char): For example '║' or '│'.
label (string): Some connectors have a label (see cu1, for example).
"""
affected_bits = [bit for bit in self.full_layer if bit is not None]
if len([qbit for qbit in self.qubit_layer if qbit is not None]) == 1:
# Nothing to connect
return
affected_bits[0].connect(wire_char, ['bot'])
for affected_bit in affected_bits[1:-1]:
affected_bit.connect(wire_char, ['bot', 'top'])
if not isinstance(affected_bits[-1], MultiBox):
affected_bits[-1].connect(wire_char, ['top'], label)
if label:
for affected_bit in affected_bits:
affected_bit.right_fill = len(label) + len(affected_bit.mid)
<|code_end|>
qiskit/tools/visualization/_utils.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree
"""Common visualization utilities."""
import PIL
import numpy as np
from qiskit.converters import circuit_to_dag
from qiskit.tools.visualization.exceptions import VisualizationError
def _validate_input_state(quantum_state):
"""Validates the input to state visualization functions.
Args:
quantum_state (ndarray): Input state / density matrix.
Returns:
rho: A 2d numpy array for the density matrix.
Raises:
VisualizationError: Invalid input.
"""
rho = np.asarray(quantum_state)
if rho.ndim == 1:
rho = np.outer(rho, np.conj(rho))
# Check the shape of the input is a square matrix
shape = np.shape(rho)
if len(shape) != 2 or shape[0] != shape[1]:
raise VisualizationError("Input is not a valid quantum state.")
# Check state is an n-qubit state
num = int(np.log2(rho.shape[0]))
if 2 ** num != rho.shape[0]:
raise VisualizationError("Input is not a multi-qubit quantum state.")
return rho
def _trim(image):
"""Trim a PIL image and remove white space."""
background = PIL.Image.new(image.mode, image.size, image.getpixel((0, 0)))
diff = PIL.ImageChops.difference(image, background)
diff = PIL.ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
image = image.crop(bbox)
return image
def _get_instructions(circuit, reversebits=False):
"""
Given a circuit, return a tuple (qregs, cregs, ops) where
qregs and cregs are the quantum and classical registers
in order (based on reversebits) and ops is a list
of DAG nodes which type is "operation".
Args:
circuit (QuantumCircuit): From where the information is extracted.
reversebits (bool): If true the order of the bits in the registers is
reversed.
Returns:
Tuple(list,list,list): To be consumed by the visualizer directly.
"""
dag = circuit_to_dag(circuit)
ops = []
qregs = []
cregs = []
for node_no in dag.node_nums_in_topological_order():
node = dag.multi_graph.node[node_no]
if node['type'] == 'op':
ops.append(node)
for qreg in dag.qregs.values():
qregs += [(qreg, bitno) for bitno in range(qreg.size)]
for creg in dag.cregs.values():
cregs += [(creg, bitno) for bitno in range(creg.size)]
if reversebits:
qregs.reverse()
cregs.reverse()
return qregs, cregs, ops
<|code_end|>
|
qiskit/tools/visualization/_circuit_visualization.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# TODO: Remove after 0.7 and the deprecated methods are removed
# pylint: disable=unused-argument
"""
Two quantum circuit drawers based on:
0. Ascii art
1. LaTeX
2. Matplotlib
"""
import errno
import logging
import os
import subprocess
import tempfile
from PIL import Image
from qiskit.tools.visualization import exceptions
from qiskit.tools.visualization import _latex
from qiskit.tools.visualization import _text
from qiskit.tools.visualization import _utils
from qiskit.tools.visualization import _matplotlib
logger = logging.getLogger(__name__)
def circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
output='text',
interactive=False,
line_length=None,
plot_barriers=True,
reverse_bits=False,
justify=None):
"""Draw a quantum circuit to different formats (set by output parameter):
0. text: ASCII art TextDrawing that can be printed in the console.
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Args:
circuit (QuantumCircuit): the quantum circuit to draw
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file.
This option is only used by the `mpl`, `latex`, and `latex_source`
output types. If a str is passed in that is the path to a json
file which contains that will be open, parsed, and then used just
as the input dict.
output (TextDrawing): Select the output method to use for drawing the circuit.
Valid choices are `text`, `latex`, `latex_source`, `mpl`. Note if
one is not specified it will use latex and if that fails fallback
to mpl. However this behavior is deprecated and in a future release
the default will change.
interactive (bool): when set true show the circuit in a new window
(for `mpl` this depends on the matplotlib backend being used
supporting this). Note when used with either the `text` or the
`latex_source` output type this has no effect and will be silently
ignored.
line_length (int): Sets the length of the lines generated by `text`
output type. This useful when the drawing does not fit in the
console. If None (default), it will try to guess the console width
using shutil.get_terminal_size(). However, if you're running in
jupyter the default line length is set to 80 characters. If you
don't want pagination at all, set `line_length=-1`.
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
justify (string): Options are `left`, `right` or `none`, if anything
else is supplied it defaults to left justified. It refers to where
gates should be placed in the output circuit if there is an option.
`none` results in each gate being placed in its own column. Currently
only supported by text drawer.
Returns:
PIL.Image: (output `latex`) an in-memory representation of the image
of the circuit diagram.
matplotlib.figure: (output `mpl`) a matplotlib figure object for the
circuit diagram.
String: (output `latex_source`). The LaTeX source code.
TextDrawing: (output `text`). A drawing that can be printed as ascii art
Raises:
VisualizationError: when an invalid output method is selected
ImportError: when the output methods requieres non-installed libraries.
.. _style-dict-doc:
The style dict kwarg contains numerous options that define the style of the
output circuit visualization. While the style dict is used by the `mpl`,
`latex`, and `latex_source` outputs some options in that are only used
by the `mpl` output. These options are defined below, if it is only used by
the `mpl` output it is marked as such:
textcolor (str): The color code to use for text. Defaults to
`'#000000'` (`mpl` only)
subtextcolor (str): The color code to use for subtext. Defaults to
`'#000000'` (`mpl` only)
linecolor (str): The color code to use for lines. Defaults to
`'#000000'` (`mpl` only)
creglinecolor (str): The color code to use for classical register lines
`'#778899'`(`mpl` only)
gatetextcolor (str): The color code to use for gate text `'#000000'`
(`mpl` only)
gatefacecolor (str): The color code to use for gates. Defaults to
`'#ffffff'` (`mpl` only)
barrierfacecolor (str): The color code to use for barriers. Defaults to
`'#bdbdbd'` (`mpl` only)
backgroundcolor (str): The color code to use for the background.
Defaults to `'#ffffff'` (`mpl` only)
fontsize (int): The font size to use for text. Defaults to 13 (`mpl`
only)
subfontsize (int): The font size to use for subtext. Defaults to 8
(`mpl` only)
displaytext (dict): A dictionary of the text to use for each element
type in the output visualization. The default values are:
{
'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'
}
You must specify all the necessary values if using this. There is
no provision for passing an incomplete dict in. (`mpl` only)
displaycolor (dict): The color codes to use for each circuit element.
By default all values default to the value of `gatefacecolor` and
the keys are the same as `displaytext`. Also, just like
`displaytext` there is no provision for an incomplete dict passed
in. (`mpl` only)
latexdrawerstyle (bool): When set to True enable latex mode which will
draw gates like the `latex` output modes. (`mpl` only)
usepiformat (bool): When set to True use radians for output (`mpl`
only)
fold (int): The number of circuit elements to fold the circuit at.
Defaults to 20 (`mpl` only)
cregbundle (bool): If set True bundle classical registers (`mpl` only)
showindex (bool): If set True draw an index. (`mpl` only)
compress (bool): If set True draw a compressed circuit (`mpl` only)
figwidth (int): The maximum width (in inches) for the output figure.
(`mpl` only)
dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl`
only)
margin (list): `mpl` only
creglinestyle (str): The style of line to use for classical registers.
Choices are `'solid'`, `'doublet'`, or any valid matplotlib
`linestyle` kwarg value. Defaults to `doublet`(`mpl` only)
"""
image = None
if output == 'text':
return _text_circuit_drawer(circuit, filename=filename,
line_length=line_length,
reversebits=reverse_bits,
plotbarriers=plot_barriers,
justify=justify)
elif output == 'latex':
image = _latex_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'latex_source':
return _generate_latex_source(circuit,
filename=filename, scale=scale,
style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
elif output == 'mpl':
image = _matplotlib_circuit_drawer(circuit, scale=scale,
filename=filename, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
else:
raise exceptions.VisualizationError(
'Invalid output type %s selected. The only valid choices '
'are latex, latex_source, text, and mpl' % output)
if image and interactive:
image.show()
return image
# -----------------------------------------------------------------------------
# Plot style sheet option
# -----------------------------------------------------------------------------
def qx_color_scheme():
"""Return default style for matplotlib_circuit_drawer (IBM QX style)."""
return {
"comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)",
"textcolor": "#000000",
"gatetextcolor": "#000000",
"subtextcolor": "#000000",
"linecolor": "#000000",
"creglinecolor": "#b9b9b9",
"gatefacecolor": "#ffffff",
"barrierfacecolor": "#bdbdbd",
"backgroundcolor": "#ffffff",
"fold": 20,
"fontsize": 13,
"subfontsize": 8,
"figwidth": -1,
"dpi": 150,
"displaytext": {
"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": {
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"
},
"latexdrawerstyle": True,
"usepiformat": False,
"cregbundle": False,
"plotbarrier": False,
"showindex": False,
"compress": True,
"margin": [2.0, 0.0, 0.0, 0.3],
"creglinestyle": "solid",
"reversebits": False
}
# -----------------------------------------------------------------------------
# _text_circuit_drawer
# -----------------------------------------------------------------------------
def _text_circuit_drawer(circuit, filename=None, line_length=None, reversebits=False,
plotbarriers=True, justify=None):
"""
Draws a circuit using ascii art.
Args:
circuit (QuantumCircuit): Input circuit
filename (str): optional filename to write the result
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
reversebits (bool): Rearrange the bits in reverse order.
plotbarriers (bool): Draws the barriers when they are there.
justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
the circuit should be justified.
Returns:
TextDrawing: An instances that, when printed, draws the circuit in ascii art.
"""
qregs, cregs, ops = _utils._get_layered_instructions(circuit,
reversebits=reversebits,
justify=justify)
text_drawing = _text.TextDrawing(qregs, cregs, ops)
text_drawing.plotbarriers = plotbarriers
text_drawing.line_length = line_length
if filename:
text_drawing.dump(filename)
return text_drawing
# -----------------------------------------------------------------------------
# latex_circuit_drawer
# -----------------------------------------------------------------------------
def _latex_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on latex (Qcircuit package)
Requires version >=2.6.0 of the qcircuit LaTeX package.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image: an in-memory representation of the circuit diagram
Raises:
OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is
missing.
CalledProcessError: usually points errors during diagram creation.
"""
tmpfilename = 'circuit'
with tempfile.TemporaryDirectory() as tmpdirname:
tmppath = os.path.join(tmpdirname, tmpfilename + '.tex')
_generate_latex_source(circuit, filename=tmppath,
scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
image = None
try:
subprocess.run(["pdflatex", "-halt-on-error",
"-output-directory={}".format(tmpdirname),
"{}".format(tmpfilename + '.tex')],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True)
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to compile latex. '
'Is `pdflatex` installed? '
'Skipping latex circuit drawing...')
raise
except subprocess.CalledProcessError as ex:
with open('latex_error.log', 'wb') as error_file:
error_file.write(ex.stdout)
logger.warning('WARNING Unable to compile latex. '
'The output from the pdflatex command can '
'be found in latex_error.log')
raise
else:
try:
base = os.path.join(tmpdirname, tmpfilename)
subprocess.run(["pdftocairo", "-singlefile", "-png", "-q",
base + '.pdf', base])
image = Image.open(base + '.png')
image = _utils._trim(image)
os.remove(base + '.png')
if filename:
image.save(filename, 'PNG')
except OSError as ex:
if ex.errno == errno.ENOENT:
logger.warning('WARNING: Unable to convert pdf to image. '
'Is `poppler` installed? '
'Skipping circuit drawing...')
raise
return image
def _generate_latex_source(circuit, filename=None,
scale=0.7, style=None, reverse_bits=False,
plot_barriers=True):
"""Convert QuantumCircuit to LaTeX string.
Args:
circuit (QuantumCircuit): input circuit
scale (float): image scaling
filename (str): optional filename to write latex
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
str: Latex string appropriate for writing to file.
"""
qregs, cregs, ops = _utils._get_instructions(circuit,
reversebits=reverse_bits)
qcimg = _latex.QCircuitImage(qregs, cregs, ops, scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
latex = qcimg.latex()
if filename:
with open(filename, 'w') as latex_file:
latex_file.write(latex)
return latex
# -----------------------------------------------------------------------------
# matplotlib_circuit_drawer
# -----------------------------------------------------------------------------
def _matplotlib_circuit_drawer(circuit,
scale=0.7,
filename=None,
style=None,
plot_barriers=True,
reverse_bits=False):
"""Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.
Args:
circuit (QuantumCircuit): a quantum circuit
scale (float): scaling factor
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
matplotlib.figure: a matplotlib figure object for the circuit diagram
"""
qcd = _matplotlib.MatplotlibDrawer(scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
qcd.parse_circuit(circuit)
return qcd.draw(filename)
<|code_end|>
qiskit/tools/visualization/_text.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A module for drawing circuits in ascii art or some other text representation
"""
from shutil import get_terminal_size
import sys
from .exceptions import VisualizationError
class DrawElement():
""" An element is an instruction or an operation that need to be drawn."""
def __init__(self, label=None):
self._width = None
self.label = self.mid_content = label
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = self.bot_connect = " "
self.top_pad = self._mid_padding = self.bot_pad = " "
self.bot_connector = {}
self.top_connector = {}
self.right_fill = self.left_fill = 0
@property
def top(self):
""" Constructs the top line of the element"""
ret = self.top_format % self.top_connect.center(
self.width - self.left_fill - self.right_fill, self.top_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.top_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.top_pad)
return ret
@property
def mid(self):
""" Constructs the middle line of the element"""
ret = self.mid_format % self.mid_content.center(
self.width - self.left_fill - self.right_fill, self._mid_padding)
if self.right_fill:
ret = ret.ljust(self.right_fill, self._mid_padding)
if self.left_fill:
ret = ret.rjust(self.left_fill, self._mid_padding)
return ret
@property
def bot(self):
""" Constructs the bottom line of the element"""
ret = self.bot_format % self.bot_connect.center(
self.width - self.left_fill - self.right_fill, self.bot_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.bot_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.bot_pad)
return ret
@property
def length(self):
""" Returns the length of the element, including the box around."""
return max(len(self.top), len(self.mid), len(self.bot))
@length.setter
def length(self, value):
""" Adjusts width so the length fits."""
self.width = value - max(
[len(getattr(self, i) % '') for i in ["bot_format", "mid_format", "top_format"]])
@property
def width(self):
""" Returns the width of the label, including padding"""
if self._width:
return self._width
return len(self.mid_content)
@width.setter
def width(self, value):
self._width = value
def connect(self, wire_char, where, label=None):
"""
Connects boxes and elements using wire_char and setting proper connectors.
Args:
wire_char (char): For example '║' or '│'.
where (list["top", "bot"]): Where the connector should be set.
label (string): Some connectors have a label (see cu1, for example).
"""
if 'top' in where and self.top_connector:
self.top_connect = self.top_connector[wire_char]
if 'bot' in where and self.bot_connector:
self.bot_connect = self.bot_connector[wire_char]
if label:
self.top_format = self.top_format[:-1] + (label if label else "")
class BoxOnClWire(DrawElement):
""" Draws a box on the classical wire
top: ┌───┐ ┌───────┐
mid: ╡ A ╞ ╡ A ╞
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "╡ %s ╞"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
class BoxOnQuWire(DrawElement):
""" Draws a box on the quantum wire
top: ┌───┐ ┌───────┐
mid: ┤ A ├ ┤ A ├
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "┤ %s ├"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
self.top_connector = {"│": '┴'}
self.bot_connector = {"│": '┬'}
class MeasureTo(DrawElement):
""" The element on the classic wire to which the measure is performed
top: ║ ║
mid: ═╩═ ═══╩═══
bot:
"""
def __init__(self):
super().__init__()
self.top_connect = " ║ "
self.mid_content = "═╩═"
self.bot_connect = " "
self._mid_padding = "═"
class MeasureFrom(BoxOnQuWire):
""" The element on the quantum wire in which the measure is performed
top: ┌─┐ ┌─┐
mid: ┤M├ ───┤M├───
bot: └╥┘ └╥┘
"""
def __init__(self):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = "┌─┐"
self.mid_content = "┤M├"
self.bot_connect = "└╥┘"
self.top_pad = self.bot_pad = " "
self._mid_padding = '─'
class MultiBox(DrawElement):
"""Elements that is draw on over multiple wires."""
def center_label(self, input_length, order):
"""
In multi-bit elements, the label is centered vertically.
Args:
input_length (int): Rhe amount of wires affected.
order (int): Which middle element is this one?
"""
location_in_the_box = '*'.center(input_length * 2 - 1).index('*') + 1
top_limit = (order - 1) * 2 + 2
bot_limit = top_limit + 2
if top_limit <= location_in_the_box < bot_limit:
if location_in_the_box == top_limit:
self.top_connect = self.label
elif location_in_the_box == top_limit + 1:
self.mid_content = self.label
else:
self.bot_connect = self.label
class BoxOnQuWireTop(MultiBox, BoxOnQuWire):
""" Draws the top part of a box that affects more than one quantum wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnQuWireMid(MultiBox, BoxOnQuWire):
""" Draws the middle part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.center_label(input_length, order)
class BoxOnQuWireBot(MultiBox, BoxOnQuWire):
""" Draws the bottom part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length, bot_connect='─'):
super().__init__(label)
self.top_format = "│ %s │"
self.top_pad = " "
self.bot_connect = bot_connect
self.mid_content = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class BoxOnClWireTop(MultiBox, BoxOnClWire):
""" Draws the top part of a conditional box that affects more than one classical wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnClWireMid(MultiBox, BoxOnClWire):
""" Draws the middle part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.mid_content = label
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.top_pad = self.bot_pad = ' '
self.top_connect = self.bot_connect = self.mid_content = ''
self.center_label(input_length, order)
class BoxOnClWireBot(MultiBox, BoxOnClWire):
""" Draws the bottom part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, bot_connect='─'):
super().__init__(label)
self.top_format = "│ %s │"
self.top_pad = " "
self.bot_connect = bot_connect
self.mid_content = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class DirectOnQuWire(DrawElement):
"""
Element to the wire (without the box).
"""
def __init__(self, label=""):
super().__init__(label)
self.top_format = ' %s '
self.mid_format = '─%s─'
self.bot_format = ' %s '
self._mid_padding = '─'
self.top_connector = {"│": '│'}
self.bot_connector = {"│": '│'}
class Barrier(DirectOnQuWire):
""" Draws a barrier.
top: ░ ░
mid: ─░─ ───░───
bot: ░ ░
"""
def __init__(self, label=""):
super().__init__("░")
self.top_connect = "░"
self.bot_connect = "░"
self.top_connector = {}
self.bot_connector = {}
class Ex(DirectOnQuWire):
""" Draws an X (usually with a connector). E.g. the top part of a swap gate
top:
mid: ─X─ ───X───
bot: │ │
"""
def __init__(self, bot_connect=" ", top_connect=" "):
super().__init__("X")
self.bot_connect = bot_connect
self.top_connect = top_connect
class Reset(DirectOnQuWire):
""" Draws a reset gate"""
def __init__(self):
super().__init__("|0>")
class Bullet(DirectOnQuWire):
""" Draws a bullet (usually with a connector). E.g. the top part of a CX gate.
top:
mid: ─■─ ───■───
bot: │ │
"""
def __init__(self, top_connect="", bot_connect=""):
super().__init__('■')
self.top_connect = top_connect
self.bot_connect = bot_connect
class EmptyWire(DrawElement):
""" This element is just the wire, with no instructions nor operations."""
def __init__(self, wire):
super().__init__(wire)
self._mid_padding = wire
@staticmethod
def fillup_layer(layer, first_clbit):
"""
Given a layer, replace the Nones in it with EmptyWire elements.
Args:
layer (list): The layer that contains Nones.
first_clbit (int): The first wire that is classic.
Returns:
list: The new layer, with no Nones.
"""
for nones in [i for i, x in enumerate(layer) if x is None]:
layer[nones] = EmptyWire('═') if nones >= first_clbit else EmptyWire('─')
return layer
class BreakWire(DrawElement):
""" This element is used to break the drawing in several pages."""
def __init__(self, arrow_char):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = arrow_char
self.mid_content = arrow_char
self.bot_connect = arrow_char
@staticmethod
def fillup_layer(layer_length, arrow_char):
"""
Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer.
"""
breakwire_layer = []
for _ in range(layer_length):
breakwire_layer.append(BreakWire(arrow_char))
return breakwire_layer
class InputWire(DrawElement):
""" This element is the label and the initial value of a wire."""
def __init__(self, label):
super().__init__(label)
@staticmethod
def fillup_layer(names): # pylint: disable=arguments-differ
"""
Creates a layer with InputWire elements.
Args:
names (list): List of names for the wires.
Returns:
list: The new layer
"""
longest = max([len(name) for name in names])
inputs_wires = []
for name in names:
inputs_wires.append(InputWire(name.rjust(longest)))
return inputs_wires
class TextDrawing():
""" The text drawing"""
def __init__(self, qregs, cregs, instructions, plotbarriers=True,
line_length=None):
self.qregs = qregs
self.cregs = cregs
self.instructions = instructions
self.plotbarriers = plotbarriers
self.line_length = line_length
def __str__(self):
return self.single_string()
def _repr_html_(self):
return '<pre style="word-wrap: normal;' \
'white-space: pre;' \
'line-height: 15px;">%s</pre>' % self.single_string()
def _get_qubit_labels(self):
qubits = []
for qubit in self.qregs:
qubits.append("%s_%s" % (qubit[0].name, qubit[1]))
return qubits
def _get_clbit_labels(self):
clbits = []
for clbit in self.cregs:
clbits.append("%s_%s" % (clbit[0].name, clbit[1]))
return clbits
def single_string(self):
"""
Creates a long string with the ascii art
Returns:
str: The lines joined by '\n'
"""
return "\n".join(self.lines())
def dump(self, filename, encoding="utf8"):
"""
Dumps the ascii art in the file.
Args:
filename (str): File to dump the ascii art.
encoding (str): Optional. Default "utf-8".
"""
with open(filename, mode='w', encoding=encoding) as text_file:
text_file.write(self.single_string())
def lines(self, line_length=None):
"""
Generates a list with lines. These lines form the text drawing.
Args:
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
Returns:
list: A list of lines with the text drawing.
"""
if line_length is None:
line_length = self.line_length
if line_length is None:
if ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
line_length = 80
else:
line_length, _ = get_terminal_size()
noqubits = len(self.qregs)
layers = self.build_layers()
if not line_length:
line_length = self.line_length
layer_groups = [[]]
rest_of_the_line = line_length
for layerno, layer in enumerate(layers):
# Replace the Nones with EmptyWire
layers[layerno] = EmptyWire.fillup_layer(layer, noqubits)
TextDrawing.normalize_width(layer)
if line_length == -1:
# Do not use pagination (aka line breaking. aka ignore line_length).
layer_groups[-1].append(layer)
continue
# chop the layer to the line_length (pager)
layer_length = layers[layerno][0].length
if layer_length < rest_of_the_line:
layer_groups[-1].append(layer)
rest_of_the_line -= layer_length
else:
layer_groups[-1].append(BreakWire.fillup_layer(len(layer), '»'))
# New group
layer_groups.append([BreakWire.fillup_layer(len(layer), '«')])
rest_of_the_line = line_length - layer_groups[-1][-1][0].length
layer_groups[-1].append(
InputWire.fillup_layer(self.wire_names(with_initial_value=False)))
rest_of_the_line -= layer_groups[-1][-1][0].length
layer_groups[-1].append(layer)
rest_of_the_line -= layer_groups[-1][-1][0].length
lines = []
for layer_group in layer_groups:
wires = [i for i in zip(*layer_group)]
lines += TextDrawing.draw_wires(wires)
return lines
def wire_names(self, with_initial_value=True):
"""
Returns a list of names for each wire.
Args:
with_initial_value (bool): Optional (Default: True). If true, adds the initial value to
the name.
Returns:
List: The list of wire names.
"""
qubit_labels = self._get_qubit_labels()
clbit_labels = self._get_clbit_labels()
if with_initial_value:
qubit_labels = ['%s: |0>' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: 0 ' % clbit for clbit in clbit_labels]
else:
qubit_labels = ['%s: ' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: ' % clbit for clbit in clbit_labels]
return qubit_labels + clbit_labels
@staticmethod
def draw_wires(wires):
"""
Given a list of wires, creates a list of lines with the text drawing.
Args:
wires (list): A list of wires with instructions.
Returns:
list: A list of lines with the text drawing.
"""
lines = []
bot_line = None
for wire in wires:
# TOP
top_line = ''
for instruction in wire:
top_line += instruction.top
if bot_line is None:
lines.append(top_line)
else:
lines.append(TextDrawing.merge_lines(lines.pop(), top_line))
# MID
mid_line = ""
for instruction in wire:
mid_line += instruction.mid
lines.append(TextDrawing.merge_lines(lines[-1], mid_line, icod="bot"))
# BOT
bot_line = ""
for instruction in wire:
bot_line += instruction.bot
lines.append(TextDrawing.merge_lines(lines[-1], bot_line, icod="bot"))
return lines
@staticmethod
def label_for_conditional(instruction):
""" Creates the label for a conditional instruction."""
return "%s %s" % ('=', instruction['condition'][1])
@staticmethod
def params_for_label(instruction):
"""Get the params and format them to add them to a label. None if there are no params."""
if 'op' in instruction and hasattr(instruction['op'], 'params'):
return ['%.5g' % i for i in instruction['op'].params]
return None
@staticmethod
def label_for_box(instruction):
""" Creates the label for a box."""
label = instruction['name'].capitalize()
params = TextDrawing.params_for_label(instruction)
if params:
label += "(%s)" % ','.join(params)
return label
@staticmethod
def merge_lines(top, bot, icod="top"):
"""
Merges two lines (top and bot) in the way that the overlapping make senses.
Args:
top (str): the top line
bot (str): the bottom line
icod (top or bot): in case of doubt, which line should have priority? Default: "top".
Returns:
str: The merge of both lines.
"""
ret = ""
for topc, botc in zip(top, bot):
if topc == botc:
ret += topc
elif topc in '┼╪' and botc == " ":
ret += "│"
elif topc == " ":
ret += botc
elif topc in '┬╥' and botc in " ║│":
ret += topc
elif topc in '┬│' and botc == "═":
ret += '╪'
elif topc in '┬│' and botc == "─":
ret += '┼'
elif topc in '└┘║│░' and botc == " ":
ret += topc
elif topc in '─═' and botc == " " and icod == "top":
ret += topc
elif topc in '─═' and botc == " " and icod == "bot":
ret += botc
elif topc in "║╥" and botc in "═":
ret += "╬"
elif topc in "║╥" and botc in "─":
ret += "╫"
elif topc in '╫╬' and botc in " ":
ret += "║"
elif topc == '└' and botc == "┌":
ret += "├"
elif topc == '┘' and botc == "┐":
ret += "┤"
elif botc in "┐┌":
ret += "┬"
else:
ret += botc
return ret
@staticmethod
def normalize_width(layer):
"""
When the elements of the layer have different widths, sets the width to the max elements.
Args:
layer (list): A list of elements.
"""
instructions = [instruction for instruction in filter(lambda x: x is not None, layer)]
longest = max([instruction.length for instruction in instructions])
for instruction in instructions:
instruction.length = longest
def _instruction_to_gate(self, instruction, layer):
""" Convert an instruction into its corresponding Gate object, and establish
any connections it introduces between qubits"""
current_cons = []
connection_label = None
# add in a gate that operates over multiple qubits
def add_connected_gate(instruction, gates, layer, current_cons):
for i, gate in enumerate(gates):
layer.set_qubit(instruction['qargs'][i], gate)
actual_index = self.qregs.index(instruction['qargs'][i])
current_cons.append((actual_index, gate))
if instruction['name'] == 'measure':
gate = MeasureFrom()
layer.set_qubit(instruction['qargs'][0], gate)
layer.set_clbit(instruction['cargs'][0], MeasureTo())
elif instruction['name'] in ['barrier', 'snapshot', 'save', 'load',
'noise']:
# barrier
if not self.plotbarriers:
return layer, current_cons, connection_label
for qubit in instruction['qargs']:
layer.set_qubit(qubit, Barrier())
elif instruction['name'] == 'swap':
# swap
gates = [Ex() for _ in range(len(instruction['qargs']))]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction['name'] == 'cswap':
# cswap
gates = [Bullet(), Ex(), Ex()]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction['name'] == 'reset':
layer.set_qubit(instruction['qargs'][0], Reset())
elif instruction['condition'] is not None:
# conditional
cllabel = TextDrawing.label_for_conditional(instruction)
qulabel = TextDrawing.label_for_box(instruction)
layer.set_cl_multibox(instruction['condition'][0], cllabel, top_connect='┴')
layer.set_qubit(instruction['qargs'][0], BoxOnQuWire(qulabel, bot_connect='┬'))
elif instruction['name'] in ['cx', 'CX', 'ccx']:
# cx/ccx
gates = [Bullet() for _ in range(len(instruction['qargs']) - 1)]
gates.append(BoxOnQuWire('X'))
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction['name'] == 'cy':
# cy
gates = [Bullet(), BoxOnQuWire('Y')]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction['name'] == 'cz':
# cz
gates = [Bullet(), Bullet()]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction['name'] == 'ch':
# ch
gates = [Bullet(), BoxOnQuWire('H')]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction['name'] == 'cu1':
# cu1
connection_label = TextDrawing.params_for_label(instruction)[0]
gates = [Bullet(), Bullet()]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction['name'] == 'cu3':
# cu3
params = TextDrawing.params_for_label(instruction)
gates = [Bullet(), BoxOnQuWire("U3(%s)" % ','.join(params))]
add_connected_gate(instruction, gates, layer, current_cons)
elif instruction['name'] == 'crz':
# crz
label = "Rz(%s)" % TextDrawing.params_for_label(instruction)[0]
gates = [Bullet(), BoxOnQuWire(label)]
add_connected_gate(instruction, gates, layer, current_cons)
elif len(instruction['qargs']) == 1 and not instruction['cargs']:
# unitary gate
layer.set_qubit(instruction['qargs'][0],
BoxOnQuWire(TextDrawing.label_for_box(instruction)))
elif len(instruction['qargs']) >= 2 and not instruction['cargs']:
# multiple qubit gate
layer.set_qu_multibox(instruction['qargs'], TextDrawing.label_for_box(instruction))
else:
raise VisualizationError(
"Text visualizer does not know how to handle this instruction", instruction)
# sort into the order they were declared in
# this ensures that connected boxes have lines in the right direction
current_cons.sort(key=lambda tup: tup[0])
current_cons = [g for q, g in current_cons]
return layer, current_cons, connection_label
def build_layers(self):
"""
Constructs layers.
Returns:
list: List of DrawElements.
Raises:
VisualizationError: When the drawing is, for some reason, impossible to be drawn.
"""
layers = [InputWire.fillup_layer(self.wire_names(with_initial_value=True))]
for instruction_layer in self.instructions:
layer = Layer(self.qregs, self.cregs)
for instruction in instruction_layer:
layer, current_connections, connection_label = \
self._instruction_to_gate(instruction, layer)
layer.connections.append((connection_label, current_connections))
layer.connect_with("│")
layers.append(layer.full_layer)
return layers
class Layer:
""" A layer is the "column" of the circuit. """
def __init__(self, qregs, cregs):
self.qregs = qregs
self.cregs = cregs
self.qubit_layer = [None] * len(qregs)
self.connections = []
self.clbit_layer = [None] * len(cregs)
@property
def full_layer(self):
"""
Returns the composition of qubits and classic wires.
Returns:
String: self.qubit_layer + self.clbit_layer
"""
return self.qubit_layer + self.clbit_layer
def set_qubit(self, qubit, element):
"""
Sets the qubit to the element
Args:
qubit (qbit): Element of self.qregs.
element (DrawElement): Element to set in the qubit
"""
self.qubit_layer[self.qregs.index(qubit)] = element
def set_clbit(self, clbit, element):
"""
Sets the clbit to the element
Args:
clbit (cbit): Element of self.cregs.
element (DrawElement): Element to set in the clbit
"""
self.clbit_layer[self.cregs.index(clbit)] = element
def _set_multibox(self, wire_type, bits, label, top_connect=None):
# pylint: disable=invalid-name
if wire_type == "cl":
bit_index = sorted([i for i, x in enumerate(self.cregs) if x in bits])
bits.sort(key=self.cregs.index)
set_bit = self.set_clbit
BoxOnWire = BoxOnClWire
BoxOnWireTop = BoxOnClWireTop
BoxOnWireMid = BoxOnClWireMid
BoxOnWireBot = BoxOnClWireBot
elif wire_type == "qu":
bit_index = sorted([i for i, x in enumerate(self.qregs) if x in bits])
bits.sort(key=self.qregs.index)
set_bit = self.set_qubit
BoxOnWire = BoxOnQuWire
BoxOnWireTop = BoxOnQuWireTop
BoxOnWireMid = BoxOnQuWireMid
BoxOnWireBot = BoxOnQuWireBot
else:
raise VisualizationError("_set_multibox only supports 'cl' and 'qu' as wire types.")
# Checks if bits are consecutive
if bit_index != [i for i in range(bit_index[0], bit_index[-1] + 1)]:
raise VisualizationError("Text visualizaer does know how to build a gate with multiple"
"bits when they are not adjacent to each other")
if len(bit_index) == 1:
set_bit(bits[0], BoxOnWire(label, top_connect=top_connect))
else:
set_bit(bits[0], BoxOnWireTop(label, top_connect=top_connect))
for order, bit in enumerate(bits[1:-1], 1):
set_bit(bit, BoxOnWireMid(label, len(bit_index), order))
set_bit(bits[-1], BoxOnWireBot(label, len(bit_index)))
def set_cl_multibox(self, creg, label, top_connect='┴'):
"""
Sets the multi clbit box.
Args:
creg (string): The affected classical register.
label (string): The label for the multi clbit box.
top_connect (char): The char to connect the box on the top.
"""
clbit = [bit for bit in self.cregs if bit[0] == creg]
self._set_multibox("cl", clbit, label, top_connect=top_connect)
def set_qu_multibox(self, bits, label):
"""
Sets the multi qubit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi qubit box.
"""
self._set_multibox("qu", bits, label)
def connect_with(self, wire_char):
"""
Connects the elements in the layer using wire_char.
Args:
wire_char (char): For example '║' or '│'.
"""
if len([qbit for qbit in self.qubit_layer if qbit is not None]) == 1:
# Nothing to connect
return
for label, affected_bits in self.connections:
if not affected_bits:
continue
affected_bits[0].connect(wire_char, ['bot'])
for affected_bit in affected_bits[1:-1]:
affected_bit.connect(wire_char, ['bot', 'top'])
affected_bits[-1].connect(wire_char, ['top'], label)
if label:
for affected_bit in affected_bits:
affected_bit.right_fill = len(label) + len(affected_bit.mid)
<|code_end|>
qiskit/tools/visualization/_utils.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree
"""Common visualization utilities."""
import PIL
import numpy as np
from qiskit.converters import circuit_to_dag
from qiskit.tools.visualization.exceptions import VisualizationError
def _validate_input_state(quantum_state):
"""Validates the input to state visualization functions.
Args:
quantum_state (ndarray): Input state / density matrix.
Returns:
rho: A 2d numpy array for the density matrix.
Raises:
VisualizationError: Invalid input.
"""
rho = np.asarray(quantum_state)
if rho.ndim == 1:
rho = np.outer(rho, np.conj(rho))
# Check the shape of the input is a square matrix
shape = np.shape(rho)
if len(shape) != 2 or shape[0] != shape[1]:
raise VisualizationError("Input is not a valid quantum state.")
# Check state is an n-qubit state
num = int(np.log2(rho.shape[0]))
if 2 ** num != rho.shape[0]:
raise VisualizationError("Input is not a multi-qubit quantum state.")
return rho
def _trim(image):
"""Trim a PIL image and remove white space."""
background = PIL.Image.new(image.mode, image.size, image.getpixel((0, 0)))
diff = PIL.ImageChops.difference(image, background)
diff = PIL.ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
image = image.crop(bbox)
return image
def _get_layered_instructions(circuit, reversebits=False, justify=None):
"""
Given a circuit, return a tuple (qregs, cregs, ops) where
qregs and cregs are the quantum and classical registers
in order (based on reversebits) and ops is a list
of DAG nodes which type is "operation".
Args:
circuit (QuantumCircuit): From where the information is extracted.
reversebits (bool): If true the order of the bits in the registers is
reversed.
justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
the circuit should be justified.
Returns:
Tuple(list,list,list): To be consumed by the visualizer directly.
"""
if justify:
justify.lower()
# default to left
justify = justify if justify in ('right', 'none') else 'left'
dag = circuit_to_dag(circuit)
ops = []
qregs = []
cregs = []
for qreg in dag.qregs.values():
qregs += [(qreg, bitno) for bitno in range(qreg.size)]
for creg in dag.cregs.values():
cregs += [(creg, bitno) for bitno in range(creg.size)]
if justify == 'none':
for node_no in dag.node_nums_in_topological_order():
node = dag.multi_graph.node[node_no]
if node['type'] == 'op':
ops.append([node])
if justify == 'left':
for dag_layer in dag.layers():
layers = []
current_layer = []
dag_nodes = dag_layer['graph'].op_nodes(data=True)
dag_nodes.sort(key=lambda tup: tup[0])
dag_nodes = [v for k, v in dag_nodes]
for node in dag_nodes:
multibit_gate = len(node['qargs']) + len(node['cargs']) > 1
if multibit_gate:
# need to see if it crosses over any other nodes
gate_span = _get_gate_span(qregs, node)
all_indices = []
for ins in dag_nodes:
if ins != node:
all_indices += _get_gate_span(qregs, ins)
if any(i in gate_span for i in all_indices):
# needs to be a new layer
layers.append([node])
else:
# can be added
current_layer.append(node)
else:
current_layer.append(node)
layers.append(current_layer)
ops += layers
if justify == 'right':
dag_layers = []
for dag_layer in dag.layers():
dag_layers.append(dag_layer)
# Have to work from the end of the circuit
dag_layers.reverse()
# Dict per layer, keys are qubits and values are the gate
layer_dicts = [{}]
for dag_layer in dag_layers:
dag_instructions = dag_layer['graph'].get_op_nodes(data=True)
# sort into the order they were input
dag_instructions.sort(key=lambda tup: tup[0])
for (_, instruction) in dag_instructions:
gate_span = _get_gate_span(qregs, instruction)
added = False
for i in range(len(layer_dicts)):
# iterate from the end
curr_dict = layer_dicts[-1 - i]
if any(index in curr_dict for index in gate_span):
added = True
if i == 0:
new_dict = {}
for index in gate_span:
new_dict[index] = instruction
layer_dicts.append(new_dict)
else:
curr_dict = layer_dicts[-i]
for index in gate_span:
curr_dict[index] = instruction
break
if not added:
for index in gate_span:
layer_dicts[0][index] = instruction
# need to convert from dict format to layers
layer_dicts.reverse()
ops = [list(layer.values()) for layer in layer_dicts]
if reversebits:
qregs.reverse()
cregs.reverse()
return qregs, cregs, ops
def _get_instructions(circuit, reversebits=False):
"""
Given a circuit, return a tuple (qregs, cregs, ops) where
qregs and cregs are the quantum and classical registers
in order (based on reversebits) and ops is a list
of DAG nodes which type is "operation".
Args:
circuit (QuantumCircuit): From where the information is extracted.
reversebits (bool): If true the order of the bits in the registers is
reversed.
Returns:
Tuple(list,list,list): To be consumed by the visualizer directly.
"""
dag = circuit_to_dag(circuit)
ops = []
qregs = []
cregs = []
for node_no in dag.node_nums_in_topological_order():
node = dag.multi_graph.node[node_no]
if node['type'] == 'op':
ops.append(node)
for qreg in dag.qregs.values():
qregs += [(qreg, bitno) for bitno in range(qreg.size)]
for creg in dag.cregs.values():
cregs += [(creg, bitno) for bitno in range(creg.size)]
if reversebits:
qregs.reverse()
cregs.reverse()
return qregs, cregs, ops
def _get_gate_span(qregs, instruction):
"""Get the list of qubits drawing this gate would cover"""
min_index = len(qregs)
max_index = 0
for qreg in instruction['qargs']:
index = qregs.index(qreg)
if index < min_index:
min_index = index
if index > max_index:
max_index = index
if instruction['cargs']:
return qregs[min_index:]
return qregs[min_index:max_index + 1]
<|code_end|>
|
circuit.draw(output = 'latex') truncates circuit unexpectedly
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: 0.7.0
- **Python version**: 3.6.5
- **Operating system**: Windows 10
### What is the current behavior?
test.draw(output = 'latex')

### Steps to reproduce the problem
```
numq = 6
q = QuantumRegister(numq, name='qn')
c = ClassicalRegister(numq, name='cn')
test = QuantumCircuit(q,c)
for i in range(numq):
test.h(q[i])
test.barrier(q[i])
for i in range(numq-1):
test.h(q[i+1])
test.cx(q[i],q[i+1])
test.h(q[i+1])
test.barrier(q[i+1])
```
### What is the expected behavior?
test.draw(output = 'mpl')

### Suggested solutions
possibly a issue with latex or windows, might not be terra related
|
qiskit/tools/visualization/_latex.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""latex circuit visualization backends."""
import collections
import io
import itertools
import json
import math
import operator
import re
import numpy as np
from qiskit.tools.visualization import exceptions
from qiskit.tools.visualization import _qcstyle
class QCircuitImage:
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for Qiskit.
"""
def __init__(self, qregs, cregs, ops, scale, style=None,
plot_barriers=True, reverse_bits=False):
"""
Args:
qregs (list): A list of tuples for the quantum registers
cregs (list): A list of tuples for the classical registers
ops (list): A list of dicts where each entry is a operation from
the circuit.
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
"""
# style sheet
self._style = _qcstyle.QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.ops = ops
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
self.reverse_bits = reverse_bits
self.plot_barriers = plot_barriers
#################################
self.qregs = collections.OrderedDict(_get_register_specs(qregs))
self.qubit_list = qregs
self.ordered_regs = qregs + cregs
self.cregs = collections.OrderedDict(_get_register_specs(cregs))
self.clbit_list = cregs
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = io.StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\' + '\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0].name + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0].name + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
VisualizationError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.ops:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's',
'sdg', 't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy',
'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image
# scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['op'].params:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float, str(arg))
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
if len(op['cargs']) != 1 or len(op['qargs']) != 1:
raise exceptions.VisualizationError("bad operation record")
if 'condition' in op and op['condition']:
raise exceptions.VisualizationError(
'conditional measures currently not supported.')
qname, qindex = op['qargs'][0]
cname, cindex = op['cargs'][0]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op and op['condition']:
raise exceptions.VisualizationError(
'conditional reset currently not supported.')
qname, qindex = op['qargs'][0]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] in ["barrier", 'snapshot', 'load', 'save',
'noise']:
if self.plot_barriers:
qarglist = op['qargs']
indexes = [self._get_qubit_index(x) for x in qarglist]
start_bit = self.qubit_list[min(indexes)]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[start_bit]
span = len(op['qargs']) - 1
for i in range(start, span + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(start, span + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
else:
raise exceptions.VisualizationError("bad node data")
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns + 1, math.ceil(sum_column_widths) + 4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet
# (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def _get_mask(self, creg_name):
mask = 0
for index, cbit in enumerate(self.clbit_list):
if creg_name == cbit[0]:
mask |= (1 << index)
return mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.ops):
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(op['condition'][1],
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier', 'snapshot', 'load',
'save', 'noise']:
nm = op['name']
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["op"].params[0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["op"].params[0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["op"].params[0], op["op"].params[1])
elif nm == "u3":
self._latex[pos_1][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["op"].params[0],
op["op"].params[1],
op["op"].params[2]))
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["op"].params[0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["op"].params[0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["op"].params[0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["op"].params[0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["op"].params[0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["op"].params[0], op["op"].params[1])
elif nm == "u3":
self._latex[pos_1][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["op"].params[0],
op["op"].params[1],
op["op"].params[2]))
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["op"].params[0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["op"].params[0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["op"].params[0])
elif nm == "reset":
self._latex[pos_1][columns] = (
"\\push{\\rule{.6em}{0em}\\ket{0}\\"
"rule{.2em}{0em}} \\qw")
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'condition' in op and op['condition']:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["op"].params[0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["op"].params[0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["op"].params[0],
op["op"].params[1],
op["op"].params[2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["op"].params[0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["op"].params[0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["op"].params[0],
op["op"].params[1],
op["op"].params[2]))
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'condition' in op and op['condition']:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-0.65em]{')
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(
pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-0.65em]{')
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(
pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
if (len(op['cargs']) != 1
or len(op['qargs']) != 1
or op['op'].params):
raise exceptions.VisualizationError("bad operation record")
if 'condition' in op and op['condition']:
raise exceptions.VisualizationError(
"If controlled measures currently not supported.")
qname, qindex = op['qargs'][0]
cname, cindex = op['cargs'][0]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise exceptions.VisualizationError(
'Error during Latex building: %s' % str(e))
elif op['name'] in ["barrier", 'snapshot', 'load', 'save',
'noise']:
if self.plot_barriers:
qarglist = op['qargs']
indexes = [self._get_qubit_index(x) for x in qarglist]
start_bit = self.qubit_list[min(indexes)]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[start_bit]
span = len(op['qargs']) - 1
for i in range(start, span + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(start, span + 1):
is_occupied[j] = True
break
self._latex[start][columns] = "\\qw \\barrier{" + str(
span) + "}"
else:
raise exceptions.VisualizationError("bad node data")
def _get_qubit_index(self, qubit):
"""Get the index number for a quantum bit
Args:
qubit (tuple): The tuple of the bit of the form
(register_name, bit_number)
Returns:
int: The index in the bit list
Raises:
VisualizationError: If the bit isn't found
"""
for i, bit in enumerate(self.qubit_list):
if qubit == bit:
qindex = i
break
else:
raise exceptions.VisualizationError(
"unable to find bit for operation")
return qindex
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
return origin - 1
def _get_register_specs(bit_labels):
"""Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = itertools.groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
<|code_end|>
|
qiskit/tools/visualization/_latex.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring
"""latex circuit visualization backends."""
import collections
import io
import itertools
import json
import math
import operator
import re
import numpy as np
from qiskit.tools.visualization import exceptions
from qiskit.tools.visualization import _qcstyle
class QCircuitImage:
"""This class contains methods to create \\LaTeX circuit images.
The class targets the \\LaTeX package Q-circuit
(https://arxiv.org/pdf/quant-ph/0406003).
Thanks to Eric Sabo for the initial implementation for Qiskit.
"""
def __init__(self, qregs, cregs, ops, scale, style=None,
plot_barriers=True, reverse_bits=False):
"""
Args:
qregs (list): A list of tuples for the quantum registers
cregs (list): A list of tuples for the classical registers
ops (list): A list of dicts where each entry is a operation from
the circuit.
scale (float): image scaling
style (dict or str): dictionary of style or file name of style file
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
"""
# style sheet
self._style = _qcstyle.QCStyle()
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
# compiled qobj circuit
self.ops = ops
# image scaling
self.scale = scale
# Map of qregs to sizes
self.qregs = {}
# Map of cregs to sizes
self.cregs = {}
# List of qregs and cregs in order of appearance in code and image
self.ordered_regs = []
# Map from registers to the list they appear in the image
self.img_regs = {}
# Array to hold the \\LaTeX commands to generate a circuit image.
self._latex = []
# Variable to hold image depth (width)
self.img_depth = 0
# Variable to hold image width (height)
self.img_width = 0
# Variable to hold total circuit depth
self.sum_column_widths = 0
# Variable to hold total circuit width
self.sum_row_heights = 0
# em points of separation between circuit columns
self.column_separation = 0.5
# em points of separation between circuit row
self.row_separation = 0.0
# presence of "box" or "target" determines row spacing
self.has_box = False
self.has_target = False
self.reverse_bits = reverse_bits
self.plot_barriers = plot_barriers
#################################
self.qregs = collections.OrderedDict(_get_register_specs(qregs))
self.qubit_list = qregs
self.ordered_regs = qregs + cregs
self.cregs = collections.OrderedDict(_get_register_specs(cregs))
self.clbit_list = cregs
self.img_regs = {bit: ind for ind, bit in
enumerate(self.ordered_regs)}
self.img_width = len(self.img_regs)
self.wire_type = {}
for key, value in self.ordered_regs:
self.wire_type[(key, value)] = key in self.cregs.keys()
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(aliases)
self._build_latex_array(aliases)
header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
qcircuit_line = r"""
\Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
output = io.StringIO()
output.write(header_1)
output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
output.write(beamer_line % self._get_beamer_page())
output.write(header_2)
output.write(qcircuit_line %
(self.column_separation, self.row_separation))
for i in range(self.img_width):
output.write("\t \t")
for j in range(self.img_depth + 1):
cell_str = self._latex[i][j]
# Don't truncate offset float if drawing a barrier
if 'barrier' in cell_str:
output.write(cell_str)
else:
# floats can cause "Dimension too large" latex error in
# xymatrix this truncates floats to avoid issue.
cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float,
cell_str)
output.write(cell_str)
if j != self.img_depth:
output.write(" & ")
else:
output.write(r'\\' + '\n')
output.write('\t }\n')
output.write('\\end{equation*}\n\n')
output.write('\\end{document}')
contents = output.getvalue()
output.close()
return contents
def _initialize_latex_array(self, aliases=None):
# pylint: disable=unused-argument
self.img_depth, self.sum_column_widths = self._get_image_depth(aliases)
self.sum_row_heights = self.img_width
# choose the most compact row spacing, while not squashing them
if self.has_box:
self.row_separation = 0.0
elif self.has_target:
self.row_separation = 0.2
else:
self.row_separation = 1.0
self._latex = [
["\\cw" if self.wire_type[self.ordered_regs[j]]
else "\\qw" for i in range(self.img_depth + 1)]
for j in range(self.img_width)]
self._latex.append([" "] * (self.img_depth + 1))
for i in range(self.img_width):
if self.wire_type[self.ordered_regs[i]]:
self._latex[i][0] = "\\lstick{" + self.ordered_regs[i][0].name + \
"_{" + str(self.ordered_regs[i][1]) + "}" + \
": 0}"
else:
self._latex[i][0] = "\\lstick{" + \
self.ordered_regs[i][0].name + "_{" + \
str(self.ordered_regs[i][1]) + "}" + \
": \\ket{0}}"
def _get_image_depth(self, aliases=None):
"""Get depth information for the circuit.
Args:
aliases (dict): dict mapping the current qubits in the circuit to
new qubit names.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
Raises:
VisualizationError: if trying to draw unsupported gates
"""
columns = 2 # wires in the beginning and end
is_occupied = [False] * self.img_width
max_column_width = {}
for op in self.ops:
# useful information for determining row spacing
boxed_gates = ['u0', 'u1', 'u2', 'u3', 'x', 'y', 'z', 'h', 's',
'sdg', 't', 'tdg', 'rx', 'ry', 'rz', 'ch', 'cy',
'crz', 'cu3']
target_gates = ['cx', 'ccx']
if op['name'] in boxed_gates:
self.has_box = True
if op['name'] in target_gates:
self.has_target = True
# useful information for determining column widths and final image
# scaling
if op['name'] not in ['measure', 'reset', 'barrier']:
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
else:
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_3 = self.img_regs[(if_reg, 0)]
if pos_1 > pos_2:
for i in range(pos_2, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_2, pos_3 + 1):
is_occupied[j] = True
break
else:
for i in range(pos_1, pos_3 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[max(pos_1, pos_2)] = True
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# update current column width
arg_str_len = 0
for arg in op['op'].params:
arg_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
_truncate_float, str(arg))
arg_str_len += len(arg_str)
if columns not in max_column_width:
max_column_width[columns] = 0
max_column_width[columns] = max(arg_str_len,
max_column_width[columns])
elif op['name'] == "measure":
if len(op['cargs']) != 1 or len(op['qargs']) != 1:
raise exceptions.VisualizationError("bad operation record")
if 'condition' in op and op['condition']:
raise exceptions.VisualizationError(
'conditional measures currently not supported.')
qname, qindex = op['qargs'][0]
cname, cindex = op['cargs'][0]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
temp = [pos_1, pos_2]
temp.sort(key=int)
[pos_1, pos_2] = temp
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
elif op['name'] == "reset":
if 'conditional' in op and op['condition']:
raise exceptions.VisualizationError(
'conditional reset currently not supported.')
qname, qindex = op['qargs'][0]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
if is_occupied[pos_1] is False:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
elif op['name'] in ["barrier", 'snapshot', 'load', 'save',
'noise']:
if self.plot_barriers:
qarglist = op['qargs']
indexes = [self._get_qubit_index(x) for x in qarglist]
start_bit = self.qubit_list[min(indexes)]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[start_bit]
span = len(op['qargs']) - 1
for i in range(start, start + span + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(start, start + span + 1):
is_occupied[j] = True
break
# update current column width
if columns not in max_column_width:
max_column_width[columns] = 0
else:
raise exceptions.VisualizationError("bad node data")
# every 3 characters is roughly one extra 'unit' of width in the cell
# the gate name is 1 extra 'unit'
# the qubit/cbit labels plus initial states is 2 more
# the wires poking out at the ends is 2 more
sum_column_widths = sum(1 + v / 3 for v in max_column_width.values())
return columns + 1, math.ceil(sum_column_widths) + 4
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be limited to < 50000
# if you want to avoid a "warning" too, set it to < 25000
PIL_limit = 40000
# the beamer latex template limits each dimension to < 19 feet
# (i.e. 575cm)
beamer_limit = 550
# columns are roughly twice as big as rows
aspect_ratio = self.sum_row_heights / self.sum_column_widths
# choose a page margin so circuit is not cropped
margin_factor = 1.5
height = min(self.sum_row_heights * margin_factor, beamer_limit)
width = min(self.sum_column_widths * margin_factor, beamer_limit)
# if too large, make it fit
if height * width > PIL_limit:
height = min(np.sqrt(PIL_limit * aspect_ratio), beamer_limit)
width = min(np.sqrt(PIL_limit / aspect_ratio), beamer_limit)
# if too small, give it a minimum size
height = max(height, 10)
width = max(width, 10)
return (height, width, self.scale)
def _get_mask(self, creg_name):
mask = 0
for index, cbit in enumerate(self.clbit_list):
if creg_name == cbit[0]:
mask |= (1 << index)
return mask
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
"""
columns = 1
is_occupied = [False] * self.img_width
# Rename qregs if necessary
if aliases:
qregdata = {}
for q in aliases.values():
if q[0] not in qregdata:
qregdata[q[0]] = q[1] + 1
elif qregdata[q[0]] < q[1] + 1:
qregdata[q[0]] = q[1] + 1
else:
qregdata = self.qregs
for _, op in enumerate(self.ops):
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
if_value = format(op['condition'][1],
'b').zfill(self.cregs[if_reg])[::-1]
if op['name'] not in ['measure', 'barrier', 'snapshot', 'load',
'save', 'noise']:
nm = op['name']
qarglist = op['qargs']
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
if len(qarglist) == 1:
pos_1 = self.img_regs[(qarglist[0][0],
qarglist[0][1])]
if 'condition' in op and op['condition']:
mask = self._get_mask(op['condition'][0])
cl_reg = self.clbit_list[self._ffs(mask)]
if_reg = cl_reg[0]
pos_2 = self.img_regs[cl_reg]
for i in range(pos_1, pos_2 + self.cregs[if_reg]):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["op"].params[0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["op"].params[0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["op"].params[0], op["op"].params[1])
elif nm == "u3":
self._latex[pos_1][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["op"].params[0],
op["op"].params[1],
op["op"].params[2]))
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["op"].params[0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["op"].params[0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["op"].params[0])
gap = pos_2 - pos_1
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_2 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_2 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
if not is_occupied[pos_1]:
is_occupied[pos_1] = True
else:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[pos_1] = True
if nm == "x":
self._latex[pos_1][columns] = "\\gate{X}"
elif nm == "y":
self._latex[pos_1][columns] = "\\gate{Y}"
elif nm == "z":
self._latex[pos_1][columns] = "\\gate{Z}"
elif nm == "h":
self._latex[pos_1][columns] = "\\gate{H}"
elif nm == "s":
self._latex[pos_1][columns] = "\\gate{S}"
elif nm == "sdg":
self._latex[pos_1][columns] = "\\gate{S^\\dag}"
elif nm == "t":
self._latex[pos_1][columns] = "\\gate{T}"
elif nm == "tdg":
self._latex[pos_1][columns] = "\\gate{T^\\dag}"
elif nm == "u0":
self._latex[pos_1][columns] = "\\gate{U_0(%s)}" % (
op["op"].params[0])
elif nm == "u1":
self._latex[pos_1][columns] = "\\gate{U_1(%s)}" % (
op["op"].params[0])
elif nm == "u2":
self._latex[pos_1][columns] = \
"\\gate{U_2\\left(%s,%s\\right)}" % (
op["op"].params[0], op["op"].params[1])
elif nm == "u3":
self._latex[pos_1][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["op"].params[0],
op["op"].params[1],
op["op"].params[2]))
elif nm == "rx":
self._latex[pos_1][columns] = "\\gate{R_x(%s)}" % (
op["op"].params[0])
elif nm == "ry":
self._latex[pos_1][columns] = "\\gate{R_y(%s)}" % (
op["op"].params[0])
elif nm == "rz":
self._latex[pos_1][columns] = "\\gate{R_z(%s)}" % (
op["op"].params[0])
elif nm == "reset":
self._latex[pos_1][columns] = (
"\\push{\\rule{.6em}{0em}\\ket{0}\\"
"rule{.2em}{0em}} \\qw")
elif len(qarglist) == 2:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
if 'condition' in op and op['condition']:
pos_3 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, pos_3 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_3 + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
gap = pos_3 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_3 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_3 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "cx":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["op"].params[0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["op"].params[0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = \
"\\ctrl{" + str(pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{U_3(%s,%s,%s)}" % (op["op"].params[0],
op["op"].params[1],
op["op"].params[2])
else:
temp = [pos_1, pos_2]
temp.sort(key=int)
top = temp[0]
bottom = temp[1]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
# symetric gates have angle labels
if op['name'] in ['cu1']:
columns += 1
is_occupied = [False] * self.img_width
is_occupied[top] = True
if nm == "cx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\targ"
elif nm == "cz":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\control\\qw"
elif nm == "cy":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{Y}"
elif nm == "ch":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\gate{H}"
elif nm == "swap":
self._latex[pos_1][columns] = "\\qswap"
self._latex[pos_2][columns] = \
"\\qswap \\qwx[" + str(pos_1 - pos_2) + "]"
elif nm == "crz":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = \
"\\gate{R_z(%s)}" % (op["op"].params[0])
elif nm == "cu1":
self._latex[pos_1][columns - 1] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns - 1] = "\\control\\qw"
self._latex[min(pos_1, pos_2)][columns] = \
"\\dstick{%s}\\qw" % (op["op"].params[0])
self._latex[max(pos_1, pos_2)][columns] = "\\qw"
elif nm == "cu3":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = ("\\gate{U_3(%s,%s,%s)}" % (
op["op"].params[0],
op["op"].params[1],
op["op"].params[2]))
elif len(qarglist) == 3:
pos_1 = self.img_regs[(qarglist[0][0], qarglist[0][1])]
pos_2 = self.img_regs[(qarglist[1][0], qarglist[1][1])]
pos_3 = self.img_regs[(qarglist[2][0], qarglist[2][1])]
if 'condition' in op and op['condition']:
pos_4 = self.img_regs[(if_reg, 0)]
temp = [pos_1, pos_2, pos_3, pos_4]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, pos_4 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, pos_4 + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-0.65em]{')
gap = pos_4 - bottom
for i in range(self.cregs[if_reg]):
if if_value[i] == '1':
self._latex[pos_4 + i][columns] = \
"\\control \\cw \\cwx[-" + str(gap) + "]"
gap = 1
else:
self._latex[pos_4 + i][columns] = \
"\\controlo \\cw \\cwx[-" + str(gap) + "]"
gap = 1
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(
pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
else:
temp = [pos_1, pos_2, pos_3]
temp.sort(key=int)
top = temp[0]
bottom = temp[2]
for i in range(top, bottom + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(top, bottom + 1):
is_occupied[j] = True
break
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and any(i in temp for i in range(
item, int(span.group(1)))):
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-0.65em]{')
if nm == "ccx":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\ctrl{" + str(
pos_3 - pos_2) + "}"
self._latex[pos_3][columns] = "\\targ"
if nm == "cswap":
self._latex[pos_1][columns] = "\\ctrl{" + str(
pos_2 - pos_1) + "}"
self._latex[pos_2][columns] = "\\qswap"
self._latex[pos_3][columns] = \
"\\qswap \\qwx[" + str(pos_2 - pos_3) + "]"
elif op["name"] == "measure":
if (len(op['cargs']) != 1
or len(op['qargs']) != 1
or op['op'].params):
raise exceptions.VisualizationError("bad operation record")
if 'condition' in op and op['condition']:
raise exceptions.VisualizationError(
"If controlled measures currently not supported.")
qname, qindex = op['qargs'][0]
cname, cindex = op['cargs'][0]
if aliases:
newq = aliases[(qname, qindex)]
qname = newq[0]
qindex = newq[1]
pos_1 = self.img_regs[(qname, qindex)]
pos_2 = self.img_regs[(cname, cindex)]
for i in range(pos_1, pos_2 + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(pos_1, pos_2 + 1):
is_occupied[j] = True
break
try:
self._latex[pos_1][columns] = "\\meter"
prev_column = [x[columns - 1] for x in self._latex]
for item, prev_entry in enumerate(prev_column):
if 'barrier' in prev_entry:
span = re.search('barrier{(.*)}', prev_entry)
if span and (
item + int(span.group(1))) - pos_1 >= 0:
self._latex[item][columns - 1] = \
prev_entry.replace(
'\\barrier{',
'\\barrier[-1.15em]{')
self._latex[pos_2][columns] = \
"\\cw \\cwx[-" + str(pos_2 - pos_1) + "]"
except Exception as e:
raise exceptions.VisualizationError(
'Error during Latex building: %s' % str(e))
elif op['name'] in ["barrier", 'snapshot', 'load', 'save',
'noise']:
if self.plot_barriers:
qarglist = op['qargs']
indexes = [self._get_qubit_index(x) for x in qarglist]
start_bit = self.qubit_list[min(indexes)]
if aliases is not None:
qarglist = map(lambda x: aliases[x], qarglist)
start = self.img_regs[start_bit]
span = len(op['qargs']) - 1
for i in range(start, start + span + 1):
if is_occupied[i] is False:
is_occupied[i] = True
else:
columns += 1
is_occupied = [False] * self.img_width
for j in range(start, start + span + 1):
is_occupied[j] = True
break
self._latex[start][columns] = "\\qw \\barrier{" + str(
span) + "}"
else:
raise exceptions.VisualizationError("bad node data")
def _get_qubit_index(self, qubit):
"""Get the index number for a quantum bit
Args:
qubit (tuple): The tuple of the bit of the form
(register_name, bit_number)
Returns:
int: The index in the bit list
Raises:
VisualizationError: If the bit isn't found
"""
for i, bit in enumerate(self.qubit_list):
if qubit == bit:
qindex = i
break
else:
raise exceptions.VisualizationError(
"unable to find bit for operation")
return qindex
def _ffs(self, mask):
"""Find index of first set bit.
Args:
mask (int): integer to search
Returns:
int: index of the first set bit.
"""
origin = (mask & (-mask)).bit_length()
return origin - 1
def _get_register_specs(bit_labels):
"""Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register named "reg2" of size 1. This is the
format of classic and quantum bit labels in qobj
header.
Yields:
tuple: iterator of register_name:size pairs.
"""
it = itertools.groupby(bit_labels, operator.itemgetter(0))
for register_name, sub_it in it:
yield register_name, max(ind[1] for ind in sub_it) + 1
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), format_str)
return ''
<|code_end|>
|
StochasticSwap mapper fails when given no initial_layout if qreg does not use all qubits in coupling_map
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: master
- **Python version**: 3.7
- **Operating system**: OSX
### What is the current behavior?
I created a pass manager as follows:
```
pm = qiskit.transpiler.PassManager()
pm.append(Unroller(basis))
pm.append(BarrierBeforeFinalMeasurements())
pm.append(StochasticSwap(coupling, seed=123456))
pm.append(Decompose(SwapGate))
pm.append(CXDirection(coupling))
pm.append(CXCancellation())
pm.append(Unroller(['u1', 'u2', 'u3', 'id', 'cx']))
pm.append(Optimize1qGates())
```
to mimic the default set of passes. However, when running a circuit through it I get the following error (for a width 5 circuit) in the StochasticSwap:
```
~/Desktop/Github_repos/qiskit-terra/qiskit/transpiler/passes/mapping/stochastic_swap.py in <listcomp>(.0)
210 # Loop over edges of coupling graph
211 for edge in coupling.get_edges():
--> 212 qubits = [trial_layout[e] for e in edge]
213 # Are the qubits available?
214 if qubits[0] in qubit_set and qubits[1] in qubit_set:
~/Desktop/Github_repos/qiskit-terra/qiskit/mapper/_layout.py in __getitem__(self, item)
55 if isinstance(item, int) and item < len(self) and item not in self:
56 return None
---> 57 return dict.__getitem__(self, item)
58
59 def __setitem__(self, key, value):
KeyError: 5
```
It seems that this is because the coupling map (in this case a 20q machine) has edges that are outside of the default initial_layout that is generated if no layout is given to the mapper. This is leading to a KeyError because the register is smaller than the full number of qubits. Indeed, if I run a width 20 circuit, it works without error.
### Steps to reproduce the problem
### What is the expected behavior?
### Suggested solutions
|
qiskit/transpiler/passes/mapping/basic_swap.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A pass implementing a basic mapper.
The basic mapper is a minimum effort to insert swap gates to map the DAG into a coupling map. When
a cx is not in the coupling map possibilities, it inserts one or more swaps in front to make it
compatible.
"""
from copy import copy
from qiskit.transpiler._basepasses import TransformationPass
from qiskit.dagcircuit import DAGCircuit
from qiskit.mapper import Layout
from qiskit.extensions.standard import SwapGate
from .barrier_before_final_measurements import BarrierBeforeFinalMeasurements
class BasicSwap(TransformationPass):
"""
Maps (with minimum effort) a DAGCircuit onto a `coupling_map` adding swap gates.
"""
def __init__(self,
coupling_map,
initial_layout=None):
"""
Maps a DAGCircuit onto a `coupling_map` using swap gates.
Args:
coupling_map (CouplingMap): Directed graph represented a coupling map.
initial_layout (Layout): initial layout of qubits in mapping
"""
super().__init__()
self.coupling_map = coupling_map
self.initial_layout = initial_layout
self.swap_gate = SwapGate
self.requires.append(BarrierBeforeFinalMeasurements())
def run(self, dag):
"""
Runs the BasicSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
"""
new_dag = DAGCircuit()
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
current_layout = copy(self.initial_layout)
for layer in dag.serial_layers():
subdag = layer['graph']
for gate in subdag.get_2q_nodes():
physical_q0 = current_layout[gate['qargs'][0]]
physical_q1 = current_layout[gate['qargs'][1]]
if self.coupling_map.distance(physical_q0, physical_q1) != 1:
# Insert a new layer with the SWAP(s).
swap_layer = DAGCircuit()
path = self.coupling_map.shortest_undirected_path(physical_q0, physical_q1)
for swap in range(len(path) - 2):
connected_wire_1 = path[swap]
connected_wire_2 = path[swap + 1]
qubit_1 = current_layout[connected_wire_1]
qubit_2 = current_layout[connected_wire_2]
# create qregs
for qreg in current_layout.get_registers():
if qreg[0] not in swap_layer.qregs.values():
swap_layer.add_qreg(qreg[0])
# create the swap operation
swap_layer.add_basis_element('swap', 2, 0, 0)
swap_layer.apply_operation_back(self.swap_gate(qubit_1, qubit_2),
qargs=[qubit_1, qubit_2])
# layer insertion
edge_map = current_layout.combine_into_edge_map(self.initial_layout)
new_dag.compose_back(swap_layer, edge_map)
# update current_layout
for swap in range(len(path) - 2):
current_layout.swap(path[swap], path[swap + 1])
edge_map = current_layout.combine_into_edge_map(self.initial_layout)
new_dag.extend_back(subdag, edge_map)
return new_dag
<|code_end|>
qiskit/transpiler/passes/mapping/lookahead_swap.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Implementation of Sven Jandura's swap mapper submission for the 2018 QISKit
Developer Challenge, adapted to integrate into the transpiler architecture.
The role of the mapper pass is to modify the starting circuit to be compatible
with the target device's topology (the set of two-qubit gates available on the
hardware.) To do this, the mapper will insert SWAP gates to relocate the virtual
qubits for each upcoming gate onto a set of coupled physical qubits. However, as
SWAP gates are particularly lossy, the goal is to accomplish this remapping while
introducing the fewest possible additional SWAPs.
This algorithm searches through the available combinations of SWAP gates by means
of a narrowed best first/beam search, described as follows:
- Start with a layout of virtual qubits onto physical qubits.
- Find any gates in the input circuit which can be performed with the current
layout and mark them as mapped.
- For all possible SWAP gates, calculate the layout that would result from their
application and rank them according to the distance of the resulting layout
over upcoming gates (see _calc_layout_distance.)
- For the four (SEARCH_WIDTH) highest-ranking SWAPs, repeat the above process on
the layout that would be generated if they were applied.
- Repeat this process down to a depth of four (SEARCH_DEPTH) SWAPs away from the
initial layout, for a total of 256 (SEARCH_WIDTH^SEARCH_DEPTH) prospective
layouts.
- Choose the layout which maximizes the number of two-qubit which could be
performed. Add its mapped gates, including the SWAPs generated, to the
output circuit.
- Repeat the above until all gates from the initial circuit are mapped.
For more details on the algorithm, see Sven's blog post:
https://medium.com/qiskit/improving-a-quantum-compiler-48410d7a7084
"""
from copy import deepcopy
from qiskit import QuantumRegister
from qiskit.dagcircuit import DAGCircuit
from qiskit.extensions.standard import SwapGate
from qiskit.transpiler._basepasses import TransformationPass
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.mapper import Layout
from .barrier_before_final_measurements import BarrierBeforeFinalMeasurements
SEARCH_DEPTH = 4
SEARCH_WIDTH = 4
class LookaheadSwap(TransformationPass):
"""Map input circuit onto a backend topology via insertion of SWAPs."""
def __init__(self, coupling_map, initial_layout=None):
"""Initialize a LookaheadSwap instance.
Arguments:
coupling_map (CouplingMap): CouplingMap of the target backend.
initial_layout (Layout): The initial layout of the DAG to analyze.
"""
super().__init__()
self._coupling_map = coupling_map
self.initial_layout = initial_layout
self.requires.append(BarrierBeforeFinalMeasurements())
def run(self, dag):
"""Run one pass of the lookahead mapper on the provided DAG.
Args:
dag (DAGCircuit): the directed acyclic graph to be mapped
Returns:
DAGCircuit: A dag mapped to be compatible with the coupling_map in
the property_set.
Raises:
TranspilerError: If the provided DAG has more qubits than are
available in the coupling map.
"""
coupling_map = self._coupling_map
ordered_virtual_gates = list(dag.serial_layers())
if len(dag.get_qubits()) > len(coupling_map.physical_qubits):
raise TranspilerError('DAG contains more qubits than are '
'present in the coupling map.')
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
mapped_gates = []
layout = self.initial_layout.copy()
gates_remaining = ordered_virtual_gates.copy()
while gates_remaining:
best_step = _search_forward_n_swaps(layout, gates_remaining,
coupling_map)
layout = best_step['layout']
gates_mapped = best_step['gates_mapped']
gates_remaining = best_step['gates_remaining']
mapped_gates.extend(gates_mapped)
# Preserve input DAG's name, regs, wire_map, etc. but replace the graph.
mapped_dag = _copy_circuit_metadata(dag, coupling_map)
for gate in mapped_gates:
mapped_dag.apply_operation_back(**gate)
return mapped_dag
def _search_forward_n_swaps(layout, gates, coupling_map,
depth=SEARCH_DEPTH, width=SEARCH_WIDTH):
"""Search for SWAPs which allow for application of largest number of gates.
Arguments:
layout (Layout): Map from virtual qubit index to physical qubit index.
gates (list): Gates to be mapped.
coupling_map (CouplingMap): CouplingMap of the target backend.
depth (int): Number of SWAP layers to search before choosing a result.
width (int): Number of SWAPs to consider at each layer.
Returns:
dict: Describes solution step found.
layout (Layout): Virtual to physical qubit map after SWAPs.
gates_remaining (list): Gates that could not be mapped.
gates_mapped (list): Gates that were mapped, including added SWAPs.
"""
gates_mapped, gates_remaining = _map_free_gates(layout, gates, coupling_map)
base_step = {'layout': layout,
'swaps_added': 0,
'gates_mapped': gates_mapped,
'gates_remaining': gates_remaining}
if not gates_remaining or depth == 0:
return base_step
possible_swaps = coupling_map.get_edges()
def _score_swap(swap):
"""Calculate the relative score for a given SWAP."""
trial_layout = layout.copy()
trial_layout.swap(*swap)
return _calc_layout_distance(gates, coupling_map, trial_layout)
ranked_swaps = sorted(possible_swaps, key=_score_swap)
best_swap, best_step = None, None
for swap in ranked_swaps[:width]:
trial_layout = layout.copy()
trial_layout.swap(*swap)
next_step = _search_forward_n_swaps(trial_layout, gates_remaining,
coupling_map, depth - 1, width)
# ranked_swaps already sorted by distance, so distance is the tie-breaker.
if best_swap is None or _score_step(next_step) > _score_step(best_step):
best_swap, best_step = swap, next_step
best_swap_gate = _swap_ops_from_edge(best_swap, layout)
return {
'layout': best_step['layout'],
'swaps_added': 1 + best_step['swaps_added'],
'gates_remaining': best_step['gates_remaining'],
'gates_mapped': gates_mapped + best_swap_gate + best_step['gates_mapped'],
}
def _map_free_gates(layout, gates, coupling_map):
"""Map all gates that can be executed with the current layout.
Args:
layout (Layout): Map from virtual qubit index to physical qubit index.
gates (list): Gates to be mapped.
coupling_map (CouplingMap): CouplingMap for target device topology.
Returns:
tuple:
mapped_gates (list): ops for gates that can be executed, mapped onto layout.
remaining_gates (list): gates that cannot be executed on the layout.
"""
blocked_qubits = set()
mapped_gates = []
remaining_gates = []
for gate in gates:
# Gates without a partition (barrier, snapshot, save, load, noise) may
# still have associated qubits. Look for them in the qargs.
if not gate['partition']:
qubits = [n for n in gate['graph'].multi_graph.nodes.values()
if n['type'] == 'op'][0]['qargs']
if not qubits:
continue
if blocked_qubits.intersection(qubits):
blocked_qubits.update(qubits)
remaining_gates.append(gate)
else:
mapped_gate = _transform_gate_for_layout(gate, layout)
mapped_gates.append(mapped_gate)
continue
qubits = gate['partition'][0]
if blocked_qubits.intersection(qubits):
blocked_qubits.update(qubits)
remaining_gates.append(gate)
elif len(qubits) == 1:
mapped_gate = _transform_gate_for_layout(gate, layout)
mapped_gates.append(mapped_gate)
elif coupling_map.distance(*[layout[q] for q in qubits]) == 1:
mapped_gate = _transform_gate_for_layout(gate, layout)
mapped_gates.append(mapped_gate)
else:
blocked_qubits.update(qubits)
remaining_gates.append(gate)
return mapped_gates, remaining_gates
def _calc_layout_distance(gates, coupling_map, layout, max_gates=None):
"""Return the sum of the distances of two-qubit pairs in each CNOT in gates
according to the layout and the coupling.
"""
if max_gates is None:
max_gates = 50 + 10 * len(coupling_map.physical_qubits)
return sum(coupling_map.distance(*[layout[q] for q in gate['partition'][0]])
for gate in gates[:max_gates]
if gate['partition'] and len(gate['partition'][0]) == 2)
def _score_step(step):
"""Count the mapped two-qubit gates, less the number of added SWAPs."""
# Each added swap will add 3 ops to gates_mapped, so subtract 3.
return len([g for g in step['gates_mapped']
if len(g.get('qargs', [])) == 2]) - 3 * step['swaps_added']
def _copy_circuit_metadata(source_dag, coupling_map):
"""Return a copy of source_dag with metadata but without a multi_graph.
Generate only a single qreg in the output DAG, matching the size of the
coupling_map."""
target_dag = DAGCircuit()
target_dag.name = source_dag.name
for creg in source_dag.cregs.values():
target_dag.add_creg(creg)
device_qreg = QuantumRegister(len(coupling_map.physical_qubits), 'q')
target_dag.add_qreg(device_qreg)
for name, (num_qbits, num_cbits, num_params) in source_dag.basis.items():
target_dag.add_basis_element(name, num_qbits, num_cbits, num_params)
for name, gate_data in source_dag.gates.items():
target_dag.add_gate_data(name, gate_data)
return target_dag
def _transform_gate_for_layout(gate, layout):
"""Return op implementing a virtual gate on given layout."""
mapped_op = deepcopy([n for n in gate['graph'].multi_graph.nodes.values()
if n['type'] == 'op'][0])
device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q')
mapped_op['qargs'] = [(device_qreg, layout[a]) for a in mapped_op['qargs']]
mapped_op.pop('type')
mapped_op.pop('name')
return mapped_op
def _swap_ops_from_edge(edge, layout):
"""Generate list of ops to implement a SWAP gate along a coupling edge."""
device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q')
qreg_edge = [(device_qreg, i) for i in edge]
return [
{'op': SwapGate(*qreg_edge), 'qargs': qreg_edge},
]
<|code_end|>
qiskit/transpiler/passes/mapping/stochastic_swap.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A pass implementing the default Qiskit stochastic mapper.
"""
from logging import getLogger
from pprint import pformat
from math import inf
import numpy as np
from qiskit.transpiler._basepasses import TransformationPass
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.dagcircuit import DAGCircuit
from qiskit.extensions.standard import SwapGate
from qiskit.mapper import Layout
from .barrier_before_final_measurements import BarrierBeforeFinalMeasurements
logger = getLogger(__name__)
# Notes:
# 1. Measurements may occur and be followed by swaps that result in repeated
# measurement of the same qubit. Near-term experiments cannot implement
# these circuits, so some care is required when using this mapper
# with experimental backend targets.
# 2. We do not use the fact that the input state is zero to simplify
# the circuit.
class StochasticSwap(TransformationPass):
"""
Maps a DAGCircuit onto a `coupling_map` adding swap gates.
Uses a randomized algorithm.
"""
def __init__(self, coupling_map, initial_layout=None,
trials=20, seed=None):
"""
Map a DAGCircuit onto a `coupling_map` using swap gates.
If initial_layout is not None, we assume the input circuit
has been layed out before running this pass, and that
the layout process yields a DAG, coupling map, and layout
with the following properties:
1. All three have the same number of qubits
2. The layout a bijection from the DAG qubits to the coupling map
For this mapping pass, it may also be necessary that
3. The coupling map is a connected graph
If these are not satisfied, the behavior is undefined.
Args:
coupling_map (CouplingMap): Directed graph representing a coupling
map.
initial_layout (Layout): initial layout of qubits in mapping
trials (int): maximum number of iterations to attempt
seed (int): seed for random number generator
"""
super().__init__()
self.coupling_map = coupling_map
self.initial_layout = initial_layout
self.input_layout = None
self.trials = trials
self.seed = seed
self.requires.append(BarrierBeforeFinalMeasurements())
def run(self, dag):
"""
Run the StochasticSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
"""
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
self.input_layout = self.initial_layout.copy()
new_dag = self._mapper(dag, self.coupling_map, trials=self.trials, seed=self.seed)
# self.property_set["layout"] = self.initial_layout
return new_dag
def _layer_permutation(self, layer_partition, layout, qubit_subset,
coupling, trials, seed=None):
"""Find a swap circuit that implements a permutation for this layer.
The goal is to swap qubits such that qubits in the same two-qubit gates
are adjacent.
Based on S. Bravyi's algorithm.
layer_partition (list): The layer_partition is a list of (qu)bit
lists and each qubit is a tuple (qreg, index).
layout (Layout): The layout is a Layout object mapping virtual
qubits in the input circuit to physical qubits in the coupling
graph. It reflects the current positions of the data.
qubit_subset (list): The qubit_subset is the set of qubits in
the coupling graph that we have chosen to map into, as tuples
(Register, index).
coupling (CouplingMap): Directed graph representing a coupling map.
This coupling map should be one that was provided to the
stochastic mapper.
trials (int): Number of attempts the randomized algorithm makes.
seed (int): Optional seed for the random number generator. If it is
None we do not reseed.
Returns:
Tuple: success_flag, best_circuit, best_depth, best_layout, trivial_flag
If success_flag is True, then best_circuit contains a DAGCircuit with
the swap circuit, best_depth contains the depth of the swap circuit,
and best_layout contains the new positions of the data qubits after the
swap circuit has been applied. The trivial_flag is set if the layer
has no multi-qubit gates.
Raises:
TranspilerError: if anything went wrong.
"""
if seed is not None:
np.random.seed(seed)
logger.debug("layer_permutation: layer_partition = %s",
pformat(layer_partition))
logger.debug("layer_permutation: layout = %s",
pformat(layout.get_virtual_bits()))
logger.debug("layer_permutation: qubit_subset = %s",
pformat(qubit_subset))
logger.debug("layer_permutation: trials = %s", trials)
gates = [] # list of lists of tuples [[(register, index), ...], ...]
for gate_args in layer_partition:
if len(gate_args) > 2:
raise TranspilerError("Layer contains > 2-qubit gates")
elif len(gate_args) == 2:
gates.append(tuple(gate_args))
logger.debug("layer_permutation: gates = %s", pformat(gates))
# Can we already apply the gates? If so, there is no work to do.
dist = sum([coupling.distance(layout[g[0]], layout[g[1]])
for g in gates])
logger.debug("layer_permutation: distance = %s", dist)
if dist == len(gates):
logger.debug("layer_permutation: nothing to do")
circ = DAGCircuit()
for register in layout.get_virtual_bits().keys():
if register[0] not in circ.qregs.values():
circ.add_qreg(register[0])
circ.add_basis_element("swap", 2)
return True, circ, 0, layout, (not bool(gates))
# Begin loop over trials of randomized algorithm
num_qubits = len(layout)
best_depth = inf # initialize best depth
best_circuit = None # initialize best swap circuit
best_layout = None # initialize best final layout
cdist2 = coupling._dist_matrix**2
# Scaling matrix
scale = np.zeros((num_qubits, num_qubits))
utri_idx = np.triu_indices(num_qubits)
for trial in range(trials):
logger.debug("layer_permutation: trial %s", trial)
trial_layout = layout.copy()
trial_circuit = DAGCircuit() # SWAP circuit for this trial
for register in trial_layout.get_virtual_bits().keys():
if register[0] not in trial_circuit.qregs.values():
trial_circuit.add_qreg(register[0])
# Compute randomized distance
data = 1 + np.random.normal(0, 1/num_qubits,
size=num_qubits*(num_qubits+1)//2)
scale[utri_idx] = data
xi = (scale+scale.T)*cdist2 # pylint: disable=invalid-name
slice_circuit = DAGCircuit() # circuit for this swap slice
for register in trial_layout.get_virtual_bits().keys():
if register[0] not in slice_circuit.qregs.values():
slice_circuit.add_qreg(register[0])
slice_circuit.add_basis_element("swap", 2)
# Loop over depths from 1 up to a maximum depth
depth_step = 1
depth_max = 2 * num_qubits + 1
while depth_step < depth_max:
qubit_set = set(qubit_subset)
# While there are still qubits available
while qubit_set:
# Compute the objective function
min_cost = sum(xi[trial_layout[g[0]]][trial_layout[g[1]]] for g in gates)
# Try to decrease objective function
cost_reduced = False
# Loop over edges of coupling graph
need_copy = True
for edge in coupling.get_edges():
qubits = (trial_layout[edge[0]], trial_layout[edge[1]])
# Are the qubits available?
if qubits[0] in qubit_set and qubits[1] in qubit_set:
# Try this edge to reduce the cost
if need_copy:
new_layout = trial_layout.copy()
need_copy = False
new_layout.swap(edge[0], edge[1])
# Compute the objective function
new_cost = sum(xi[new_layout[g[0]]][new_layout[g[1]]] for g in gates)
# Record progress if we succceed
if new_cost < min_cost:
logger.debug("layer_permutation: min_cost "
"improved to %s", min_cost)
cost_reduced = True
min_cost = new_cost
optimal_layout = new_layout
optimal_edge = (self.initial_layout[edge[0]],
self.initial_layout[edge[1]])
optimal_qubits = qubits
need_copy = True
else:
new_layout.swap(edge[0], edge[1])
# Were there any good swap choices?
if cost_reduced:
qubit_set.remove(optimal_qubits[0])
qubit_set.remove(optimal_qubits[1])
trial_layout = optimal_layout
slice_circuit.apply_operation_back(
SwapGate(optimal_edge[0],
optimal_edge[1]))
logger.debug("layer_permutation: swap the pair %s",
pformat(optimal_edge))
else:
break
# We have either run out of swap pairs to try or
# failed to improve the cost.
# Compute the coupling graph distance
dist = sum(coupling.distance(trial_layout[g[0]],
trial_layout[g[1]])
for g in gates)
logger.debug("layer_permutation: new swap distance = %s", dist)
# If all gates can be applied now, we are finished.
# Otherwise we need to consider a deeper swap circuit
if dist == len(gates):
logger.debug("layer_permutation: all gates can be "
"applied now in this layer")
trial_circuit.extend_back(slice_circuit)
break
# Increment the depth
depth_step += 1
logger.debug("layer_permutation: increment depth to %s", depth_step)
# Either we have succeeded at some depth d < dmax or failed
dist = sum(coupling.distance(trial_layout[g[0]],
trial_layout[g[1]])
for g in gates)
logger.debug("layer_permutation: final distance for this trial = %s", dist)
if dist == len(gates):
if depth_step < best_depth:
logger.debug("layer_permutation: got circuit with improved depth %s",
depth_step)
best_circuit = trial_circuit
best_layout = trial_layout
best_depth = min(best_depth, depth_step)
# Break out of trial loop if we found a depth 1 circuit
# since we can't improve it further
if best_depth == 1:
break
# If we have no best circuit for this layer, all of the
# trials have failed
if best_circuit is None:
logger.debug("layer_permutation: failed!")
return False, None, None, None, False
# Otherwise, we return our result for this layer
logger.debug("layer_permutation: success!")
return True, best_circuit, best_depth, best_layout, False
def _layer_update(self, i, first_layer, best_layout, best_depth,
best_circuit, layer_list):
"""Provide a DAGCircuit for a new mapped layer.
i (int) = layer number
first_layer (bool) = True if this is the first layer in the
circuit with any multi-qubit gates
best_layout (Layout) = layout returned from _layer_permutation
best_depth (int) = depth returned from _layer_permutation
best_circuit (DAGCircuit) = swap circuit returned
from _layer_permutation
layer_list (list) = list of DAGCircuit objects for each layer,
output of DAGCircuit layers() method
Return a DAGCircuit object to append to the output DAGCircuit
that the _mapper method is building.
"""
layout = best_layout
logger.debug("layer_update: layout = %s", pformat(layout))
logger.debug("layer_update: self.initial_layout = %s", pformat(self.initial_layout))
dagcircuit_output = DAGCircuit()
for register in layout.get_virtual_bits().keys():
if register[0] not in dagcircuit_output.qregs.values():
dagcircuit_output.add_qreg(register[0])
# If this is the first layer with multi-qubit gates,
# output all layers up to this point and ignore any
# swap gates. Set the initial layout.
if first_layer:
logger.debug("layer_update: first multi-qubit gate layer")
# Output all layers up to this point
for j in range(i + 1):
# Make qubit edge map and extend by classical bits
edge_map = layout.combine_into_edge_map(self.initial_layout)
for bit in dagcircuit_output.get_bits():
edge_map[bit] = bit
dagcircuit_output.compose_back(layer_list[j]["graph"], edge_map)
# Otherwise, we output the current layer and the associated swap gates.
else:
# Output any swaps
if best_depth > 0:
logger.debug("layer_update: there are swaps in this layer, "
"depth %d", best_depth)
dagcircuit_output.extend_back(best_circuit)
else:
logger.debug("layer_update: there are no swaps in this layer")
# Make qubit edge map and extend by classical bits
edge_map = layout.combine_into_edge_map(self.initial_layout)
for bit in dagcircuit_output.get_bits():
edge_map[bit] = bit
# Output this layer
dagcircuit_output.compose_back(layer_list[i]["graph"], edge_map)
return dagcircuit_output
def _mapper(self, circuit_graph, coupling_graph,
trials=20, seed=None):
"""Map a DAGCircuit onto a CouplingMap using swap gates.
Use self.initial_layout for the initial layout.
Args:
circuit_graph (DAGCircuit): input DAG circuit
coupling_graph (CouplingMap): coupling graph to map onto
trials (int): number of trials.
seed (int): initial seed.
Returns:
DAGCircuit: object containing a circuit equivalent to
circuit_graph that respects couplings in coupling_graph
Layout: a layout object mapping qubits of circuit_graph into
qubits of coupling_graph. The layout may differ from the
initial_layout if the first layer of gates cannot be
executed on the initial_layout, since in this case
it is more efficient to modify the layout instead of swapping
Dict: a final-layer qubit permutation
Raises:
TranspilerError: if there was any error during the mapping
or with the parameters.
"""
# Schedule the input circuit by calling layers()
layerlist = list(circuit_graph.layers())
logger.debug("schedule:")
for i, v in enumerate(layerlist):
logger.debug(" %d: %s", i, v["partition"])
if self.initial_layout is not None:
qubit_subset = self.initial_layout.get_virtual_bits().keys()
else:
# Supply a default layout for this dag
self.initial_layout = Layout()
physical_qubit = 0
for qreg in circuit_graph.qregs.values():
for index in range(qreg.size):
self.initial_layout[(qreg, index)] = physical_qubit
physical_qubit += 1
qubit_subset = self.initial_layout.get_virtual_bits().keys()
# Restrict the coupling map to the image of the layout
coupling_graph = coupling_graph.subgraph(
self.initial_layout.get_physical_bits().keys())
if coupling_graph.size() < len(self.initial_layout):
raise TranspilerError("Coupling map too small for default layout")
self.input_layout = self.initial_layout.copy()
# Find swap circuit to preceed to each layer of input circuit
layout = self.initial_layout.copy()
# Construct an empty DAGCircuit with the same set of
# qregs and cregs as the input circuit
dagcircuit_output = DAGCircuit()
dagcircuit_output.name = circuit_graph.name
for qreg in circuit_graph.qregs.values():
dagcircuit_output.add_qreg(qreg)
for creg in circuit_graph.cregs.values():
dagcircuit_output.add_creg(creg)
# Make a trivial wire mapping between the subcircuits
# returned by _layer_update and the circuit we build
identity_wire_map = {}
for qubit in circuit_graph.get_qubits():
identity_wire_map[qubit] = qubit
for bit in circuit_graph.get_bits():
identity_wire_map[bit] = bit
first_layer = True # True until first layer is output
logger.debug("initial_layout = %s", layout)
# Iterate over layers
for i, layer in enumerate(layerlist):
# Attempt to find a permutation for this layer
success_flag, best_circuit, best_depth, best_layout, trivial_flag \
= self._layer_permutation(layer["partition"], layout,
qubit_subset, coupling_graph,
trials, seed)
logger.debug("mapper: layer %d", i)
logger.debug("mapper: success_flag=%s,best_depth=%s,trivial_flag=%s",
success_flag, str(best_depth), trivial_flag)
# If this fails, try one gate at a time in this layer
if not success_flag:
logger.debug("mapper: failed, layer %d, "
"retrying sequentially", i)
serial_layerlist = list(layer["graph"].serial_layers())
# Go through each gate in the layer
for j, serial_layer in enumerate(serial_layerlist):
success_flag, best_circuit, best_depth, best_layout, trivial_flag = \
self._layer_permutation(
serial_layer["partition"],
layout, qubit_subset,
coupling_graph,
trials, seed)
logger.debug("mapper: layer %d, sublayer %d", i, j)
logger.debug("mapper: success_flag=%s,best_depth=%s,"
"trivial_flag=%s",
success_flag, str(best_depth), trivial_flag)
# Give up if we fail again
if not success_flag:
raise TranspilerError("mapper failed: " +
"layer %d, sublayer %d" %
(i, j) + ", \"%s\"" %
serial_layer["graph"].qasm(
no_decls=True,
aliases=layout))
# If this layer is only single-qubit gates,
# and we have yet to see multi-qubit gates,
# continue to the next inner iteration
if trivial_flag and first_layer:
logger.debug("mapper: skip to next sublayer")
continue
if first_layer:
self.initial_layout = layout
# Update the record of qubit positions
# for each inner iteration
layout = best_layout
# Update the DAG
dagcircuit_output.extend_back(
self._layer_update(j,
first_layer,
best_layout,
best_depth,
best_circuit,
serial_layerlist),
identity_wire_map)
if first_layer:
first_layer = False
else:
# Update the record of qubit positions for each iteration
layout = best_layout
if first_layer:
self.initial_layout = layout
# Update the DAG
dagcircuit_output.extend_back(
self._layer_update(i,
first_layer,
best_layout,
best_depth,
best_circuit,
layerlist),
identity_wire_map)
if first_layer:
first_layer = False
# This is the final edgemap. We might use it to correctly replace
# any measurements that needed to be removed earlier.
logger.debug("mapper: self.initial_layout = %s", pformat(self.initial_layout))
logger.debug("mapper: layout = %s", pformat(layout))
last_edgemap = layout.combine_into_edge_map(self.initial_layout)
logger.debug("mapper: last_edgemap = %s", pformat(last_edgemap))
# If first_layer is still set, the circuit only has single-qubit gates
# so we can use the initial layout to output the entire circuit
# This code is dead due to changes to first_layer above.
if first_layer:
logger.debug("mapper: first_layer flag still set")
layout = self.initial_layout
for i, layer in enumerate(layerlist):
edge_map = layout.combine_into_edge_map(self.initial_layout)
dagcircuit_output.compose_back(layer["graph"], edge_map)
return dagcircuit_output
<|code_end|>
|
qiskit/transpiler/passes/mapping/basic_swap.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A pass implementing a basic mapper.
The basic mapper is a minimum effort to insert swap gates to map the DAG into a coupling map. When
a cx is not in the coupling map possibilities, it inserts one or more swaps in front to make it
compatible.
"""
from copy import copy
from qiskit.transpiler._basepasses import TransformationPass
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.dagcircuit import DAGCircuit
from qiskit.mapper import Layout
from qiskit.extensions.standard import SwapGate
from .barrier_before_final_measurements import BarrierBeforeFinalMeasurements
class BasicSwap(TransformationPass):
"""
Maps (with minimum effort) a DAGCircuit onto a `coupling_map` adding swap gates.
"""
def __init__(self,
coupling_map,
initial_layout=None):
"""
Maps a DAGCircuit onto a `coupling_map` using swap gates.
Args:
coupling_map (CouplingMap): Directed graph represented a coupling map.
initial_layout (Layout): initial layout of qubits in mapping
"""
super().__init__()
self.coupling_map = coupling_map
self.initial_layout = initial_layout
self.swap_gate = SwapGate
self.requires.append(BarrierBeforeFinalMeasurements())
def run(self, dag):
"""
Runs the BasicSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
Raises:
TranspilerError: if the coupling map or the layout are not
compatible with the DAG
"""
new_dag = DAGCircuit()
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
if len(dag.get_qubits()) != len(self.initial_layout):
raise TranspilerError('The layout does not match the amount of qubits in the DAG')
if len(self.coupling_map.physical_qubits) != len(self.initial_layout):
raise TranspilerError(
"Mappers require to have the layout to be the same size as the coupling map")
current_layout = copy(self.initial_layout)
for layer in dag.serial_layers():
subdag = layer['graph']
for gate in subdag.get_2q_nodes():
physical_q0 = current_layout[gate['qargs'][0]]
physical_q1 = current_layout[gate['qargs'][1]]
if self.coupling_map.distance(physical_q0, physical_q1) != 1:
# Insert a new layer with the SWAP(s).
swap_layer = DAGCircuit()
path = self.coupling_map.shortest_undirected_path(physical_q0, physical_q1)
for swap in range(len(path) - 2):
connected_wire_1 = path[swap]
connected_wire_2 = path[swap + 1]
qubit_1 = current_layout[connected_wire_1]
qubit_2 = current_layout[connected_wire_2]
# create qregs
for qreg in current_layout.get_registers():
if qreg[0] not in swap_layer.qregs.values():
swap_layer.add_qreg(qreg[0])
# create the swap operation
swap_layer.add_basis_element('swap', 2, 0, 0)
swap_layer.apply_operation_back(self.swap_gate(qubit_1, qubit_2),
qargs=[qubit_1, qubit_2])
# layer insertion
edge_map = current_layout.combine_into_edge_map(self.initial_layout)
new_dag.compose_back(swap_layer, edge_map)
# update current_layout
for swap in range(len(path) - 2):
current_layout.swap(path[swap], path[swap + 1])
edge_map = current_layout.combine_into_edge_map(self.initial_layout)
new_dag.extend_back(subdag, edge_map)
return new_dag
<|code_end|>
qiskit/transpiler/passes/mapping/lookahead_swap.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Implementation of Sven Jandura's swap mapper submission for the 2018 QISKit
Developer Challenge, adapted to integrate into the transpiler architecture.
The role of the mapper pass is to modify the starting circuit to be compatible
with the target device's topology (the set of two-qubit gates available on the
hardware.) To do this, the mapper will insert SWAP gates to relocate the virtual
qubits for each upcoming gate onto a set of coupled physical qubits. However, as
SWAP gates are particularly lossy, the goal is to accomplish this remapping while
introducing the fewest possible additional SWAPs.
This algorithm searches through the available combinations of SWAP gates by means
of a narrowed best first/beam search, described as follows:
- Start with a layout of virtual qubits onto physical qubits.
- Find any gates in the input circuit which can be performed with the current
layout and mark them as mapped.
- For all possible SWAP gates, calculate the layout that would result from their
application and rank them according to the distance of the resulting layout
over upcoming gates (see _calc_layout_distance.)
- For the four (SEARCH_WIDTH) highest-ranking SWAPs, repeat the above process on
the layout that would be generated if they were applied.
- Repeat this process down to a depth of four (SEARCH_DEPTH) SWAPs away from the
initial layout, for a total of 256 (SEARCH_WIDTH^SEARCH_DEPTH) prospective
layouts.
- Choose the layout which maximizes the number of two-qubit which could be
performed. Add its mapped gates, including the SWAPs generated, to the
output circuit.
- Repeat the above until all gates from the initial circuit are mapped.
For more details on the algorithm, see Sven's blog post:
https://medium.com/qiskit/improving-a-quantum-compiler-48410d7a7084
"""
from copy import deepcopy
from qiskit import QuantumRegister
from qiskit.dagcircuit import DAGCircuit
from qiskit.extensions.standard import SwapGate
from qiskit.transpiler._basepasses import TransformationPass
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.mapper import Layout
from .barrier_before_final_measurements import BarrierBeforeFinalMeasurements
SEARCH_DEPTH = 4
SEARCH_WIDTH = 4
class LookaheadSwap(TransformationPass):
"""Map input circuit onto a backend topology via insertion of SWAPs."""
def __init__(self, coupling_map, initial_layout=None):
"""Initialize a LookaheadSwap instance.
Arguments:
coupling_map (CouplingMap): CouplingMap of the target backend.
initial_layout (Layout): The initial layout of the DAG to analyze.
"""
super().__init__()
self._coupling_map = coupling_map
self.initial_layout = initial_layout
self.requires.append(BarrierBeforeFinalMeasurements())
def run(self, dag):
"""Run one pass of the lookahead mapper on the provided DAG.
Args:
dag (DAGCircuit): the directed acyclic graph to be mapped
Returns:
DAGCircuit: A dag mapped to be compatible with the coupling_map in
the property_set.
Raises:
TranspilerError: if the coupling map or the layout are not
compatible with the DAG
"""
coupling_map = self._coupling_map
ordered_virtual_gates = list(dag.serial_layers())
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
if len(dag.get_qubits()) != len(self.initial_layout):
raise TranspilerError('The layout does not match the amount of qubits in the DAG')
if len(self._coupling_map.physical_qubits) != len(self.initial_layout):
raise TranspilerError(
"Mappers require to have the layout to be the same size as the coupling map")
mapped_gates = []
layout = self.initial_layout.copy()
gates_remaining = ordered_virtual_gates.copy()
while gates_remaining:
best_step = _search_forward_n_swaps(layout, gates_remaining,
coupling_map)
layout = best_step['layout']
gates_mapped = best_step['gates_mapped']
gates_remaining = best_step['gates_remaining']
mapped_gates.extend(gates_mapped)
# Preserve input DAG's name, regs, wire_map, etc. but replace the graph.
mapped_dag = _copy_circuit_metadata(dag, coupling_map)
for gate in mapped_gates:
mapped_dag.apply_operation_back(**gate)
return mapped_dag
def _search_forward_n_swaps(layout, gates, coupling_map,
depth=SEARCH_DEPTH, width=SEARCH_WIDTH):
"""Search for SWAPs which allow for application of largest number of gates.
Arguments:
layout (Layout): Map from virtual qubit index to physical qubit index.
gates (list): Gates to be mapped.
coupling_map (CouplingMap): CouplingMap of the target backend.
depth (int): Number of SWAP layers to search before choosing a result.
width (int): Number of SWAPs to consider at each layer.
Returns:
dict: Describes solution step found.
layout (Layout): Virtual to physical qubit map after SWAPs.
gates_remaining (list): Gates that could not be mapped.
gates_mapped (list): Gates that were mapped, including added SWAPs.
"""
gates_mapped, gates_remaining = _map_free_gates(layout, gates, coupling_map)
base_step = {'layout': layout,
'swaps_added': 0,
'gates_mapped': gates_mapped,
'gates_remaining': gates_remaining}
if not gates_remaining or depth == 0:
return base_step
possible_swaps = coupling_map.get_edges()
def _score_swap(swap):
"""Calculate the relative score for a given SWAP."""
trial_layout = layout.copy()
trial_layout.swap(*swap)
return _calc_layout_distance(gates, coupling_map, trial_layout)
ranked_swaps = sorted(possible_swaps, key=_score_swap)
best_swap, best_step = None, None
for swap in ranked_swaps[:width]:
trial_layout = layout.copy()
trial_layout.swap(*swap)
next_step = _search_forward_n_swaps(trial_layout, gates_remaining,
coupling_map, depth - 1, width)
# ranked_swaps already sorted by distance, so distance is the tie-breaker.
if best_swap is None or _score_step(next_step) > _score_step(best_step):
best_swap, best_step = swap, next_step
best_swap_gate = _swap_ops_from_edge(best_swap, layout)
return {
'layout': best_step['layout'],
'swaps_added': 1 + best_step['swaps_added'],
'gates_remaining': best_step['gates_remaining'],
'gates_mapped': gates_mapped + best_swap_gate + best_step['gates_mapped'],
}
def _map_free_gates(layout, gates, coupling_map):
"""Map all gates that can be executed with the current layout.
Args:
layout (Layout): Map from virtual qubit index to physical qubit index.
gates (list): Gates to be mapped.
coupling_map (CouplingMap): CouplingMap for target device topology.
Returns:
tuple:
mapped_gates (list): ops for gates that can be executed, mapped onto layout.
remaining_gates (list): gates that cannot be executed on the layout.
"""
blocked_qubits = set()
mapped_gates = []
remaining_gates = []
for gate in gates:
# Gates without a partition (barrier, snapshot, save, load, noise) may
# still have associated qubits. Look for them in the qargs.
if not gate['partition']:
qubits = [n for n in gate['graph'].multi_graph.nodes.values()
if n['type'] == 'op'][0]['qargs']
if not qubits:
continue
if blocked_qubits.intersection(qubits):
blocked_qubits.update(qubits)
remaining_gates.append(gate)
else:
mapped_gate = _transform_gate_for_layout(gate, layout)
mapped_gates.append(mapped_gate)
continue
qubits = gate['partition'][0]
if blocked_qubits.intersection(qubits):
blocked_qubits.update(qubits)
remaining_gates.append(gate)
elif len(qubits) == 1:
mapped_gate = _transform_gate_for_layout(gate, layout)
mapped_gates.append(mapped_gate)
elif coupling_map.distance(*[layout[q] for q in qubits]) == 1:
mapped_gate = _transform_gate_for_layout(gate, layout)
mapped_gates.append(mapped_gate)
else:
blocked_qubits.update(qubits)
remaining_gates.append(gate)
return mapped_gates, remaining_gates
def _calc_layout_distance(gates, coupling_map, layout, max_gates=None):
"""Return the sum of the distances of two-qubit pairs in each CNOT in gates
according to the layout and the coupling.
"""
if max_gates is None:
max_gates = 50 + 10 * len(coupling_map.physical_qubits)
return sum(coupling_map.distance(*[layout[q] for q in gate['partition'][0]])
for gate in gates[:max_gates]
if gate['partition'] and len(gate['partition'][0]) == 2)
def _score_step(step):
"""Count the mapped two-qubit gates, less the number of added SWAPs."""
# Each added swap will add 3 ops to gates_mapped, so subtract 3.
return len([g for g in step['gates_mapped']
if len(g.get('qargs', [])) == 2]) - 3 * step['swaps_added']
def _copy_circuit_metadata(source_dag, coupling_map):
"""Return a copy of source_dag with metadata but without a multi_graph.
Generate only a single qreg in the output DAG, matching the size of the
coupling_map."""
target_dag = DAGCircuit()
target_dag.name = source_dag.name
for creg in source_dag.cregs.values():
target_dag.add_creg(creg)
device_qreg = QuantumRegister(len(coupling_map.physical_qubits), 'q')
target_dag.add_qreg(device_qreg)
for name, (num_qbits, num_cbits, num_params) in source_dag.basis.items():
target_dag.add_basis_element(name, num_qbits, num_cbits, num_params)
for name, gate_data in source_dag.gates.items():
target_dag.add_gate_data(name, gate_data)
return target_dag
def _transform_gate_for_layout(gate, layout):
"""Return op implementing a virtual gate on given layout."""
mapped_op = deepcopy([n for n in gate['graph'].multi_graph.nodes.values()
if n['type'] == 'op'][0])
device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q')
mapped_op['qargs'] = [(device_qreg, layout[a]) for a in mapped_op['qargs']]
mapped_op.pop('type')
mapped_op.pop('name')
return mapped_op
def _swap_ops_from_edge(edge, layout):
"""Generate list of ops to implement a SWAP gate along a coupling edge."""
device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q')
qreg_edge = [(device_qreg, i) for i in edge]
return [
{'op': SwapGate(*qreg_edge), 'qargs': qreg_edge},
]
<|code_end|>
qiskit/transpiler/passes/mapping/stochastic_swap.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A pass implementing the default Qiskit stochastic mapper.
"""
from logging import getLogger
from pprint import pformat
from math import inf
import numpy as np
from qiskit.transpiler._basepasses import TransformationPass
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.dagcircuit import DAGCircuit
from qiskit.extensions.standard import SwapGate
from qiskit.mapper import Layout
from .barrier_before_final_measurements import BarrierBeforeFinalMeasurements
logger = getLogger(__name__)
# Notes:
# 1. Measurements may occur and be followed by swaps that result in repeated
# measurement of the same qubit. Near-term experiments cannot implement
# these circuits, so some care is required when using this mapper
# with experimental backend targets.
# 2. We do not use the fact that the input state is zero to simplify
# the circuit.
class StochasticSwap(TransformationPass):
"""
Maps a DAGCircuit onto a `coupling_map` adding swap gates.
Uses a randomized algorithm.
"""
def __init__(self, coupling_map, initial_layout=None,
trials=20, seed=None):
"""
Map a DAGCircuit onto a `coupling_map` using swap gates.
If initial_layout is not None, we assume the input circuit
has been layed out before running this pass, and that
the layout process yields a DAG, coupling map, and layout
with the following properties:
1. All three have the same number of qubits
2. The layout a bijection from the DAG qubits to the coupling map
For this mapping pass, it may also be necessary that
3. The coupling map is a connected graph
If these are not satisfied, the behavior is undefined.
Args:
coupling_map (CouplingMap): Directed graph representing a coupling
map.
initial_layout (Layout): initial layout of qubits in mapping
trials (int): maximum number of iterations to attempt
seed (int): seed for random number generator
"""
super().__init__()
self.coupling_map = coupling_map
self.initial_layout = initial_layout
self.input_layout = None
self.trials = trials
self.seed = seed
self.requires.append(BarrierBeforeFinalMeasurements())
def run(self, dag):
"""
Run the StochasticSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
Raises:
TranspilerError: if the coupling map or the layout are not
compatible with the DAG
"""
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
if len(dag.get_qubits()) != len(self.initial_layout):
raise TranspilerError('The layout does not match the amount of qubits in the DAG')
if len(self.coupling_map.physical_qubits) != len(self.initial_layout):
raise TranspilerError(
"Mappers require to have the layout to be the same size as the coupling map")
self.input_layout = self.initial_layout.copy()
new_dag = self._mapper(dag, self.coupling_map, trials=self.trials, seed=self.seed)
# self.property_set["layout"] = self.initial_layout
return new_dag
def _layer_permutation(self, layer_partition, layout, qubit_subset,
coupling, trials, seed=None):
"""Find a swap circuit that implements a permutation for this layer.
The goal is to swap qubits such that qubits in the same two-qubit gates
are adjacent.
Based on S. Bravyi's algorithm.
layer_partition (list): The layer_partition is a list of (qu)bit
lists and each qubit is a tuple (qreg, index).
layout (Layout): The layout is a Layout object mapping virtual
qubits in the input circuit to physical qubits in the coupling
graph. It reflects the current positions of the data.
qubit_subset (list): The qubit_subset is the set of qubits in
the coupling graph that we have chosen to map into, as tuples
(Register, index).
coupling (CouplingMap): Directed graph representing a coupling map.
This coupling map should be one that was provided to the
stochastic mapper.
trials (int): Number of attempts the randomized algorithm makes.
seed (int): Optional seed for the random number generator. If it is
None we do not reseed.
Returns:
Tuple: success_flag, best_circuit, best_depth, best_layout, trivial_flag
If success_flag is True, then best_circuit contains a DAGCircuit with
the swap circuit, best_depth contains the depth of the swap circuit,
and best_layout contains the new positions of the data qubits after the
swap circuit has been applied. The trivial_flag is set if the layer
has no multi-qubit gates.
Raises:
TranspilerError: if anything went wrong.
"""
if seed is not None:
np.random.seed(seed)
logger.debug("layer_permutation: layer_partition = %s",
pformat(layer_partition))
logger.debug("layer_permutation: layout = %s",
pformat(layout.get_virtual_bits()))
logger.debug("layer_permutation: qubit_subset = %s",
pformat(qubit_subset))
logger.debug("layer_permutation: trials = %s", trials)
gates = [] # list of lists of tuples [[(register, index), ...], ...]
for gate_args in layer_partition:
if len(gate_args) > 2:
raise TranspilerError("Layer contains > 2-qubit gates")
elif len(gate_args) == 2:
gates.append(tuple(gate_args))
logger.debug("layer_permutation: gates = %s", pformat(gates))
# Can we already apply the gates? If so, there is no work to do.
dist = sum([coupling.distance(layout[g[0]], layout[g[1]])
for g in gates])
logger.debug("layer_permutation: distance = %s", dist)
if dist == len(gates):
logger.debug("layer_permutation: nothing to do")
circ = DAGCircuit()
for register in layout.get_virtual_bits().keys():
if register[0] not in circ.qregs.values():
circ.add_qreg(register[0])
circ.add_basis_element("swap", 2)
return True, circ, 0, layout, (not bool(gates))
# Begin loop over trials of randomized algorithm
num_qubits = len(layout)
best_depth = inf # initialize best depth
best_circuit = None # initialize best swap circuit
best_layout = None # initialize best final layout
cdist2 = coupling._dist_matrix**2
# Scaling matrix
scale = np.zeros((num_qubits, num_qubits))
utri_idx = np.triu_indices(num_qubits)
for trial in range(trials):
logger.debug("layer_permutation: trial %s", trial)
trial_layout = layout.copy()
trial_circuit = DAGCircuit() # SWAP circuit for this trial
for register in trial_layout.get_virtual_bits().keys():
if register[0] not in trial_circuit.qregs.values():
trial_circuit.add_qreg(register[0])
# Compute randomized distance
data = 1 + np.random.normal(0, 1/num_qubits,
size=num_qubits*(num_qubits+1)//2)
scale[utri_idx] = data
xi = (scale+scale.T)*cdist2 # pylint: disable=invalid-name
slice_circuit = DAGCircuit() # circuit for this swap slice
for register in trial_layout.get_virtual_bits().keys():
if register[0] not in slice_circuit.qregs.values():
slice_circuit.add_qreg(register[0])
slice_circuit.add_basis_element("swap", 2)
# Loop over depths from 1 up to a maximum depth
depth_step = 1
depth_max = 2 * num_qubits + 1
while depth_step < depth_max:
qubit_set = set(qubit_subset)
# While there are still qubits available
while qubit_set:
# Compute the objective function
min_cost = sum(xi[trial_layout[g[0]]][trial_layout[g[1]]] for g in gates)
# Try to decrease objective function
cost_reduced = False
# Loop over edges of coupling graph
need_copy = True
for edge in coupling.get_edges():
qubits = (trial_layout[edge[0]], trial_layout[edge[1]])
# Are the qubits available?
if qubits[0] in qubit_set and qubits[1] in qubit_set:
# Try this edge to reduce the cost
if need_copy:
new_layout = trial_layout.copy()
need_copy = False
new_layout.swap(edge[0], edge[1])
# Compute the objective function
new_cost = sum(xi[new_layout[g[0]]][new_layout[g[1]]] for g in gates)
# Record progress if we succceed
if new_cost < min_cost:
logger.debug("layer_permutation: min_cost "
"improved to %s", min_cost)
cost_reduced = True
min_cost = new_cost
optimal_layout = new_layout
optimal_edge = (self.initial_layout[edge[0]],
self.initial_layout[edge[1]])
optimal_qubits = qubits
need_copy = True
else:
new_layout.swap(edge[0], edge[1])
# Were there any good swap choices?
if cost_reduced:
qubit_set.remove(optimal_qubits[0])
qubit_set.remove(optimal_qubits[1])
trial_layout = optimal_layout
slice_circuit.apply_operation_back(
SwapGate(optimal_edge[0],
optimal_edge[1]))
logger.debug("layer_permutation: swap the pair %s",
pformat(optimal_edge))
else:
break
# We have either run out of swap pairs to try or
# failed to improve the cost.
# Compute the coupling graph distance
dist = sum(coupling.distance(trial_layout[g[0]],
trial_layout[g[1]])
for g in gates)
logger.debug("layer_permutation: new swap distance = %s", dist)
# If all gates can be applied now, we are finished.
# Otherwise we need to consider a deeper swap circuit
if dist == len(gates):
logger.debug("layer_permutation: all gates can be "
"applied now in this layer")
trial_circuit.extend_back(slice_circuit)
break
# Increment the depth
depth_step += 1
logger.debug("layer_permutation: increment depth to %s", depth_step)
# Either we have succeeded at some depth d < dmax or failed
dist = sum(coupling.distance(trial_layout[g[0]],
trial_layout[g[1]])
for g in gates)
logger.debug("layer_permutation: final distance for this trial = %s", dist)
if dist == len(gates):
if depth_step < best_depth:
logger.debug("layer_permutation: got circuit with improved depth %s",
depth_step)
best_circuit = trial_circuit
best_layout = trial_layout
best_depth = min(best_depth, depth_step)
# Break out of trial loop if we found a depth 1 circuit
# since we can't improve it further
if best_depth == 1:
break
# If we have no best circuit for this layer, all of the
# trials have failed
if best_circuit is None:
logger.debug("layer_permutation: failed!")
return False, None, None, None, False
# Otherwise, we return our result for this layer
logger.debug("layer_permutation: success!")
return True, best_circuit, best_depth, best_layout, False
def _layer_update(self, i, first_layer, best_layout, best_depth,
best_circuit, layer_list):
"""Provide a DAGCircuit for a new mapped layer.
i (int) = layer number
first_layer (bool) = True if this is the first layer in the
circuit with any multi-qubit gates
best_layout (Layout) = layout returned from _layer_permutation
best_depth (int) = depth returned from _layer_permutation
best_circuit (DAGCircuit) = swap circuit returned
from _layer_permutation
layer_list (list) = list of DAGCircuit objects for each layer,
output of DAGCircuit layers() method
Return a DAGCircuit object to append to the output DAGCircuit
that the _mapper method is building.
"""
layout = best_layout
logger.debug("layer_update: layout = %s", pformat(layout))
logger.debug("layer_update: self.initial_layout = %s", pformat(self.initial_layout))
dagcircuit_output = DAGCircuit()
for register in layout.get_virtual_bits().keys():
if register[0] not in dagcircuit_output.qregs.values():
dagcircuit_output.add_qreg(register[0])
# If this is the first layer with multi-qubit gates,
# output all layers up to this point and ignore any
# swap gates. Set the initial layout.
if first_layer:
logger.debug("layer_update: first multi-qubit gate layer")
# Output all layers up to this point
for j in range(i + 1):
# Make qubit edge map and extend by classical bits
edge_map = layout.combine_into_edge_map(self.initial_layout)
for bit in dagcircuit_output.get_bits():
edge_map[bit] = bit
dagcircuit_output.compose_back(layer_list[j]["graph"], edge_map)
# Otherwise, we output the current layer and the associated swap gates.
else:
# Output any swaps
if best_depth > 0:
logger.debug("layer_update: there are swaps in this layer, "
"depth %d", best_depth)
dagcircuit_output.extend_back(best_circuit)
else:
logger.debug("layer_update: there are no swaps in this layer")
# Make qubit edge map and extend by classical bits
edge_map = layout.combine_into_edge_map(self.initial_layout)
for bit in dagcircuit_output.get_bits():
edge_map[bit] = bit
# Output this layer
dagcircuit_output.compose_back(layer_list[i]["graph"], edge_map)
return dagcircuit_output
def _mapper(self, circuit_graph, coupling_graph,
trials=20, seed=None):
"""Map a DAGCircuit onto a CouplingMap using swap gates.
Use self.initial_layout for the initial layout.
Args:
circuit_graph (DAGCircuit): input DAG circuit
coupling_graph (CouplingMap): coupling graph to map onto
trials (int): number of trials.
seed (int): initial seed.
Returns:
DAGCircuit: object containing a circuit equivalent to
circuit_graph that respects couplings in coupling_graph
Layout: a layout object mapping qubits of circuit_graph into
qubits of coupling_graph. The layout may differ from the
initial_layout if the first layer of gates cannot be
executed on the initial_layout, since in this case
it is more efficient to modify the layout instead of swapping
Dict: a final-layer qubit permutation
Raises:
TranspilerError: if there was any error during the mapping
or with the parameters.
"""
# Schedule the input circuit by calling layers()
layerlist = list(circuit_graph.layers())
logger.debug("schedule:")
for i, v in enumerate(layerlist):
logger.debug(" %d: %s", i, v["partition"])
if self.initial_layout is not None:
qubit_subset = self.initial_layout.get_virtual_bits().keys()
else:
# Supply a default layout for this dag
self.initial_layout = Layout()
physical_qubit = 0
for qreg in circuit_graph.qregs.values():
for index in range(qreg.size):
self.initial_layout[(qreg, index)] = physical_qubit
physical_qubit += 1
qubit_subset = self.initial_layout.get_virtual_bits().keys()
# Restrict the coupling map to the image of the layout
coupling_graph = coupling_graph.subgraph(
self.initial_layout.get_physical_bits().keys())
if coupling_graph.size() < len(self.initial_layout):
raise TranspilerError("Coupling map too small for default layout")
self.input_layout = self.initial_layout.copy()
# Find swap circuit to preceed to each layer of input circuit
layout = self.initial_layout.copy()
# Construct an empty DAGCircuit with the same set of
# qregs and cregs as the input circuit
dagcircuit_output = DAGCircuit()
dagcircuit_output.name = circuit_graph.name
for qreg in circuit_graph.qregs.values():
dagcircuit_output.add_qreg(qreg)
for creg in circuit_graph.cregs.values():
dagcircuit_output.add_creg(creg)
# Make a trivial wire mapping between the subcircuits
# returned by _layer_update and the circuit we build
identity_wire_map = {}
for qubit in circuit_graph.get_qubits():
identity_wire_map[qubit] = qubit
for bit in circuit_graph.get_bits():
identity_wire_map[bit] = bit
first_layer = True # True until first layer is output
logger.debug("initial_layout = %s", layout)
# Iterate over layers
for i, layer in enumerate(layerlist):
# Attempt to find a permutation for this layer
success_flag, best_circuit, best_depth, best_layout, trivial_flag \
= self._layer_permutation(layer["partition"], layout,
qubit_subset, coupling_graph,
trials, seed)
logger.debug("mapper: layer %d", i)
logger.debug("mapper: success_flag=%s,best_depth=%s,trivial_flag=%s",
success_flag, str(best_depth), trivial_flag)
# If this fails, try one gate at a time in this layer
if not success_flag:
logger.debug("mapper: failed, layer %d, "
"retrying sequentially", i)
serial_layerlist = list(layer["graph"].serial_layers())
# Go through each gate in the layer
for j, serial_layer in enumerate(serial_layerlist):
success_flag, best_circuit, best_depth, best_layout, trivial_flag = \
self._layer_permutation(
serial_layer["partition"],
layout, qubit_subset,
coupling_graph,
trials, seed)
logger.debug("mapper: layer %d, sublayer %d", i, j)
logger.debug("mapper: success_flag=%s,best_depth=%s,"
"trivial_flag=%s",
success_flag, str(best_depth), trivial_flag)
# Give up if we fail again
if not success_flag:
raise TranspilerError("mapper failed: " +
"layer %d, sublayer %d" %
(i, j) + ", \"%s\"" %
serial_layer["graph"].qasm(
no_decls=True,
aliases=layout))
# If this layer is only single-qubit gates,
# and we have yet to see multi-qubit gates,
# continue to the next inner iteration
if trivial_flag and first_layer:
logger.debug("mapper: skip to next sublayer")
continue
if first_layer:
self.initial_layout = layout
# Update the record of qubit positions
# for each inner iteration
layout = best_layout
# Update the DAG
dagcircuit_output.extend_back(
self._layer_update(j,
first_layer,
best_layout,
best_depth,
best_circuit,
serial_layerlist),
identity_wire_map)
if first_layer:
first_layer = False
else:
# Update the record of qubit positions for each iteration
layout = best_layout
if first_layer:
self.initial_layout = layout
# Update the DAG
dagcircuit_output.extend_back(
self._layer_update(i,
first_layer,
best_layout,
best_depth,
best_circuit,
layerlist),
identity_wire_map)
if first_layer:
first_layer = False
# This is the final edgemap. We might use it to correctly replace
# any measurements that needed to be removed earlier.
logger.debug("mapper: self.initial_layout = %s", pformat(self.initial_layout))
logger.debug("mapper: layout = %s", pformat(layout))
last_edgemap = layout.combine_into_edge_map(self.initial_layout)
logger.debug("mapper: last_edgemap = %s", pformat(last_edgemap))
# If first_layer is still set, the circuit only has single-qubit gates
# so we can use the initial layout to output the entire circuit
# This code is dead due to changes to first_layer above.
if first_layer:
logger.debug("mapper: first_layer flag still set")
layout = self.initial_layout
for i, layer in enumerate(layerlist):
edge_map = layout.combine_into_edge_map(self.initial_layout)
dagcircuit_output.compose_back(layer["graph"], edge_map)
return dagcircuit_output
<|code_end|>
|
Include a copy method for QuantumCircuit
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
This code is often repeated a lot:
```
import copy
qc_copy = copy.deepcopy(qc)
```
It would be nice if there was a `copy()` method for `QuantumCircuit` that did this for you.
|
qiskit/circuit/quantumcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Quantum circuit object.
"""
from collections import OrderedDict
from copy import deepcopy
import itertools
import sys
import multiprocessing as mp
from qiskit.qasm import _qasm
from qiskit.exceptions import QiskitError
from .quantumregister import QuantumRegister
from .classicalregister import ClassicalRegister
class QuantumCircuit:
"""Quantum circuit."""
instances = 0
prefix = 'circuit'
# Class variable OPENQASM header
header = "OPENQASM 2.0;"
# Class variable with gate definitions
# This is a dict whose values are dicts with the
# following keys:
# "print" = True or False
# "opaque" = True or False
# "n_args" = number of real parameters
# "n_bits" = number of qubits
# "args" = list of parameter names
# "bits" = list of qubit names
# "body" = GateBody AST node
definitions = OrderedDict()
def __init__(self, *regs, name=None):
"""Create a new circuit.
A circuit is a list of instructions bound to some registers.
Args:
*regs (Registers): registers to include in the circuit.
name (str or None): the name of the quantum circuit. If
None, an automatically generated string will be assigned.
Raises:
QiskitError: if the circuit name, if given, is not valid.
"""
if name is None:
name = self.cls_prefix() + str(self.cls_instances())
# pylint: disable=not-callable
# (known pylint bug: https://github.com/PyCQA/pylint/issues/1699)
if sys.platform != "win32" and \
isinstance(mp.current_process(), mp.context.ForkProcess):
name += '-{}'.format(mp.current_process().pid)
self._increment_instances()
if not isinstance(name, str):
raise QiskitError("The circuit name should be a string "
"(or None to auto-generate a name).")
self.name = name
# Data contains a list of instructions in the order they were applied.
self.data = []
# This is a map of registers bound to this circuit, by name.
self.qregs = []
self.cregs = []
self.add_register(*regs)
def __str__(self):
return str(self.draw(output='text'))
def __eq__(self, other):
# TODO: removed the DAG from this function
from qiskit.converters import circuit_to_dag
return circuit_to_dag(self) == circuit_to_dag(other)
@classmethod
def _increment_instances(cls):
cls.instances += 1
@classmethod
def cls_instances(cls):
"""Return the current number of instances of this class,
useful for auto naming."""
return cls.instances
@classmethod
def cls_prefix(cls):
"""Return the prefix to use for auto naming."""
return cls.prefix
def has_register(self, register):
"""
Test if this circuit has the register r.
Args:
register (Register): a quantum or classical register.
Returns:
bool: True if the register is contained in this circuit.
"""
has_reg = False
if (isinstance(register, QuantumRegister) and
register in self.qregs):
has_reg = True
elif (isinstance(register, ClassicalRegister) and
register in self.cregs):
has_reg = True
return has_reg
def combine(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Return self + rhs as a new object.
"""
# Check registers in LHS are compatible with RHS
self._check_compatible_regs(rhs)
# Make new circuit with combined registers
combined_qregs = deepcopy(self.qregs)
combined_cregs = deepcopy(self.cregs)
for element in rhs.qregs:
if element not in self.qregs:
combined_qregs.append(element)
for element in rhs.cregs:
if element not in self.cregs:
combined_cregs.append(element)
circuit = QuantumCircuit(*combined_qregs, *combined_cregs)
for gate in itertools.chain(self.data, rhs.data):
gate.reapply(circuit)
return circuit
def extend(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Modify and return self.
"""
# Check registers in LHS are compatible with RHS
self._check_compatible_regs(rhs)
# Add new registers
for element in rhs.qregs:
if element not in self.qregs:
self.qregs.append(element)
for element in rhs.cregs:
if element not in self.cregs:
self.cregs.append(element)
# Add new gates
for gate in rhs.data:
gate.reapply(self)
return self
def __add__(self, rhs):
"""Overload + to implement self.combine."""
return self.combine(rhs)
def __iadd__(self, rhs):
"""Overload += to implement self.extend."""
return self.extend(rhs)
def __len__(self):
"""Return number of operations in circuit."""
return len(self.data)
def __getitem__(self, item):
"""Return indexed operation."""
return self.data[item]
def _attach(self, instruction):
"""Attach an instruction."""
self.data.append(instruction)
return instruction
def add_register(self, *regs):
"""Add registers."""
for register in regs:
if register in self.qregs or register in self.cregs:
raise QiskitError("register name \"%s\" already exists"
% register.name)
if isinstance(register, QuantumRegister):
self.qregs.append(register)
elif isinstance(register, ClassicalRegister):
self.cregs.append(register)
else:
raise QiskitError("expected a register")
def _check_qreg(self, register):
"""Raise exception if r is not in this circuit or not qreg."""
if not isinstance(register, QuantumRegister):
raise QiskitError("expected quantum register")
if not self.has_register(register):
raise QiskitError(
"register '%s' not in this circuit" %
register.name)
def _check_qubit(self, qubit):
"""Raise exception if qubit is not in this circuit or bad format."""
if not isinstance(qubit, tuple):
raise QiskitError("%s is not a tuple."
"A qubit should be formated as a tuple." % str(qubit))
if not len(qubit) == 2:
raise QiskitError("%s is not a tuple with two elements, but %i instead" % len(qubit))
if not isinstance(qubit[1], int):
raise QiskitError("The second element of a tuple defining a qubit should be an int:"
"%s was found instead" % type(qubit[1]).__name__)
self._check_qreg(qubit[0])
qubit[0].check_range(qubit[1])
def _check_creg(self, register):
"""Raise exception if r is not in this circuit or not creg."""
if not isinstance(register, ClassicalRegister):
raise QiskitError("Expected ClassicalRegister, but %s given" % type(register))
if not self.has_register(register):
raise QiskitError(
"register '%s' not in this circuit" %
register.name)
def _check_dups(self, qubits):
"""Raise exception if list of qubits contains duplicates."""
squbits = set(qubits)
if len(squbits) != len(qubits):
raise QiskitError("duplicate qubit arguments")
def _check_compatible_regs(self, rhs):
"""Raise exception if the circuits are defined on incompatible registers"""
list1 = self.qregs + self.cregs
list2 = rhs.qregs + rhs.cregs
for element1 in list1:
for element2 in list2:
if element2.name == element1.name:
if element1 != element2:
raise QiskitError("circuits are not compatible")
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.definitions[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.definitions[name]["n_args"] > 0:
out += "(" + ",".join(self.definitions[name]["args"]) + ")"
out += " " + ",".join(self.definitions[name]["bits"])
if self.definitions[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.definitions[name]["body"].qasm() + "}\n"
return out
def qasm(self):
"""Return OPENQASM string."""
string_temp = self.header + "\n"
for gate_name in self.definitions:
if self.definitions[gate_name]["print"]:
string_temp += self._gate_string(gate_name)
for register in self.qregs:
string_temp += register.qasm() + "\n"
for register in self.cregs:
string_temp += register.qasm() + "\n"
for instruction in self.data:
string_temp += instruction.qasm() + "\n"
return string_temp
def draw(self, scale=0.7, filename=None, style=None, output='text',
interactive=False, line_length=None, plot_barriers=True,
reverse_bits=False):
"""Draw the quantum circuit
Using the output parameter you can specify the format. The choices are:
0. text: ASCII art string
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style
file. You can refer to the
:ref:`Style Dict Doc <style-dict-doc>` for more information
on the contents.
output (str): Select the output method to use for drawing the
circuit. Valid choices are `text`, `latex`, `latex_source`,
`mpl`.
interactive (bool): when set true show the circuit in a new window
(for `mpl` this depends on the matplotlib backend being used
supporting this). Note when used with either the `text` or the
`latex_source` output type this has no effect and will be
silently ignored.
line_length (int): sets the length of the lines generated by `text`
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image or matplotlib.figure or str or TextDrawing:
* PIL.Image: (output `latex`) an in-memory representation of the
image of the circuit diagram.
* matplotlib.figure: (output `mpl`) a matplotlib figure object
for the circuit diagram.
* str: (output `latex_source`). The LaTeX source code.
* TextDrawing: (output `text`). A drawing that can be printed as
ascii art
Raises:
VisualizationError: when an invalid output method is selected
"""
from qiskit.tools import visualization
return visualization.circuit_drawer(self, scale=scale,
filename=filename, style=style,
output=output,
interactive=interactive,
line_length=line_length,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
def size(self):
"""Return total number of operations in circuit."""
# TODO: removed the DAG from this function
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.size()
def depth(self):
"""Return circuit depth (i.e. length of critical path)."""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.depth()
def width(self):
"""Return number of qubits in circuit."""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.width()
def count_ops(self):
"""Count each operation kind in the circuit.
Returns:
dict: a breakdown of how many operations of each kind.
"""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.count_ops()
def num_tensor_factors(self):
"""How many non-entangled subcircuits can the circuit be factored to."""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.num_tensor_factors()
@staticmethod
def from_qasm_file(path):
"""Take in a QASM file and generate a QuantumCircuit object.
Args:
path (str): Path to the file for a QASM program
Return:
QuantumCircuit: The QuantumCircuit object for the input QASM
"""
qasm = _qasm.Qasm(filename=path)
return _circuit_from_qasm(qasm)
@staticmethod
def from_qasm_str(qasm_str):
"""Take in a QASM string and generate a QuantumCircuit object.
Args:
qasm_str (str): A QASM program string
Return:
QuantumCircuit: The QuantumCircuit object for the input QASM
"""
qasm = _qasm.Qasm(data=qasm_str)
return _circuit_from_qasm(qasm)
def _circuit_from_qasm(qasm):
# pylint: disable=cyclic-import
from qiskit.converters import ast_to_dag
from qiskit.converters import dag_to_circuit
ast = qasm.parse()
dag = ast_to_dag(ast)
return dag_to_circuit(dag)
<|code_end|>
|
qiskit/circuit/quantumcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Quantum circuit object.
"""
from collections import OrderedDict
from copy import deepcopy
import itertools
import sys
import multiprocessing as mp
from qiskit.qasm import _qasm
from qiskit.exceptions import QiskitError
from .quantumregister import QuantumRegister
from .classicalregister import ClassicalRegister
class QuantumCircuit:
"""Quantum circuit."""
instances = 0
prefix = 'circuit'
# Class variable OPENQASM header
header = "OPENQASM 2.0;"
# Class variable with gate definitions
# This is a dict whose values are dicts with the
# following keys:
# "print" = True or False
# "opaque" = True or False
# "n_args" = number of real parameters
# "n_bits" = number of qubits
# "args" = list of parameter names
# "bits" = list of qubit names
# "body" = GateBody AST node
definitions = OrderedDict()
def __init__(self, *regs, name=None):
"""Create a new circuit.
A circuit is a list of instructions bound to some registers.
Args:
*regs (Registers): registers to include in the circuit.
name (str or None): the name of the quantum circuit. If
None, an automatically generated string will be assigned.
Raises:
QiskitError: if the circuit name, if given, is not valid.
"""
if name is None:
name = self.cls_prefix() + str(self.cls_instances())
# pylint: disable=not-callable
# (known pylint bug: https://github.com/PyCQA/pylint/issues/1699)
if sys.platform != "win32" and \
isinstance(mp.current_process(), mp.context.ForkProcess):
name += '-{}'.format(mp.current_process().pid)
self._increment_instances()
if not isinstance(name, str):
raise QiskitError("The circuit name should be a string "
"(or None to auto-generate a name).")
self.name = name
# Data contains a list of instructions in the order they were applied.
self.data = []
# This is a map of registers bound to this circuit, by name.
self.qregs = []
self.cregs = []
self.add_register(*regs)
def __str__(self):
return str(self.draw(output='text'))
def __eq__(self, other):
# TODO: removed the DAG from this function
from qiskit.converters import circuit_to_dag
return circuit_to_dag(self) == circuit_to_dag(other)
@classmethod
def _increment_instances(cls):
cls.instances += 1
@classmethod
def cls_instances(cls):
"""Return the current number of instances of this class,
useful for auto naming."""
return cls.instances
@classmethod
def cls_prefix(cls):
"""Return the prefix to use for auto naming."""
return cls.prefix
def has_register(self, register):
"""
Test if this circuit has the register r.
Args:
register (Register): a quantum or classical register.
Returns:
bool: True if the register is contained in this circuit.
"""
has_reg = False
if (isinstance(register, QuantumRegister) and
register in self.qregs):
has_reg = True
elif (isinstance(register, ClassicalRegister) and
register in self.cregs):
has_reg = True
return has_reg
def combine(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Return self + rhs as a new object.
"""
# Check registers in LHS are compatible with RHS
self._check_compatible_regs(rhs)
# Make new circuit with combined registers
combined_qregs = deepcopy(self.qregs)
combined_cregs = deepcopy(self.cregs)
for element in rhs.qregs:
if element not in self.qregs:
combined_qregs.append(element)
for element in rhs.cregs:
if element not in self.cregs:
combined_cregs.append(element)
circuit = QuantumCircuit(*combined_qregs, *combined_cregs)
for gate in itertools.chain(self.data, rhs.data):
gate.reapply(circuit)
return circuit
def extend(self, rhs):
"""
Append rhs to self if self contains compatible registers.
Two circuits are compatible if they contain the same registers
or if they contain different registers with unique names. The
returned circuit will contain all unique registers between both
circuits.
Modify and return self.
"""
# Check registers in LHS are compatible with RHS
self._check_compatible_regs(rhs)
# Add new registers
for element in rhs.qregs:
if element not in self.qregs:
self.qregs.append(element)
for element in rhs.cregs:
if element not in self.cregs:
self.cregs.append(element)
# Add new gates
for gate in rhs.data:
gate.reapply(self)
return self
def __add__(self, rhs):
"""Overload + to implement self.combine."""
return self.combine(rhs)
def __iadd__(self, rhs):
"""Overload += to implement self.extend."""
return self.extend(rhs)
def __len__(self):
"""Return number of operations in circuit."""
return len(self.data)
def __getitem__(self, item):
"""Return indexed operation."""
return self.data[item]
def _attach(self, instruction):
"""Attach an instruction."""
self.data.append(instruction)
return instruction
def add_register(self, *regs):
"""Add registers."""
for register in regs:
if register in self.qregs or register in self.cregs:
raise QiskitError("register name \"%s\" already exists"
% register.name)
if isinstance(register, QuantumRegister):
self.qregs.append(register)
elif isinstance(register, ClassicalRegister):
self.cregs.append(register)
else:
raise QiskitError("expected a register")
def _check_qreg(self, register):
"""Raise exception if r is not in this circuit or not qreg."""
if not isinstance(register, QuantumRegister):
raise QiskitError("expected quantum register")
if not self.has_register(register):
raise QiskitError(
"register '%s' not in this circuit" %
register.name)
def _check_qubit(self, qubit):
"""Raise exception if qubit is not in this circuit or bad format."""
if not isinstance(qubit, tuple):
raise QiskitError("%s is not a tuple."
"A qubit should be formated as a tuple." % str(qubit))
if not len(qubit) == 2:
raise QiskitError("%s is not a tuple with two elements, but %i instead" % len(qubit))
if not isinstance(qubit[1], int):
raise QiskitError("The second element of a tuple defining a qubit should be an int:"
"%s was found instead" % type(qubit[1]).__name__)
self._check_qreg(qubit[0])
qubit[0].check_range(qubit[1])
def _check_creg(self, register):
"""Raise exception if r is not in this circuit or not creg."""
if not isinstance(register, ClassicalRegister):
raise QiskitError("Expected ClassicalRegister, but %s given" % type(register))
if not self.has_register(register):
raise QiskitError(
"register '%s' not in this circuit" %
register.name)
def _check_dups(self, qubits):
"""Raise exception if list of qubits contains duplicates."""
squbits = set(qubits)
if len(squbits) != len(qubits):
raise QiskitError("duplicate qubit arguments")
def _check_compatible_regs(self, rhs):
"""Raise exception if the circuits are defined on incompatible registers"""
list1 = self.qregs + self.cregs
list2 = rhs.qregs + rhs.cregs
for element1 in list1:
for element2 in list2:
if element2.name == element1.name:
if element1 != element2:
raise QiskitError("circuits are not compatible")
def _gate_string(self, name):
"""Return a QASM string for the named gate."""
out = ""
if self.definitions[name]["opaque"]:
out = "opaque " + name
else:
out = "gate " + name
if self.definitions[name]["n_args"] > 0:
out += "(" + ",".join(self.definitions[name]["args"]) + ")"
out += " " + ",".join(self.definitions[name]["bits"])
if self.definitions[name]["opaque"]:
out += ";"
else:
out += "\n{\n" + self.definitions[name]["body"].qasm() + "}\n"
return out
def qasm(self):
"""Return OPENQASM string."""
string_temp = self.header + "\n"
for gate_name in self.definitions:
if self.definitions[gate_name]["print"]:
string_temp += self._gate_string(gate_name)
for register in self.qregs:
string_temp += register.qasm() + "\n"
for register in self.cregs:
string_temp += register.qasm() + "\n"
for instruction in self.data:
string_temp += instruction.qasm() + "\n"
return string_temp
def draw(self, scale=0.7, filename=None, style=None, output='text',
interactive=False, line_length=None, plot_barriers=True,
reverse_bits=False):
"""Draw the quantum circuit
Using the output parameter you can specify the format. The choices are:
0. text: ASCII art string
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style
file. You can refer to the
:ref:`Style Dict Doc <style-dict-doc>` for more information
on the contents.
output (str): Select the output method to use for drawing the
circuit. Valid choices are `text`, `latex`, `latex_source`,
`mpl`.
interactive (bool): when set true show the circuit in a new window
(for `mpl` this depends on the matplotlib backend being used
supporting this). Note when used with either the `text` or the
`latex_source` output type this has no effect and will be
silently ignored.
line_length (int): sets the length of the lines generated by `text`
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
Returns:
PIL.Image or matplotlib.figure or str or TextDrawing:
* PIL.Image: (output `latex`) an in-memory representation of the
image of the circuit diagram.
* matplotlib.figure: (output `mpl`) a matplotlib figure object
for the circuit diagram.
* str: (output `latex_source`). The LaTeX source code.
* TextDrawing: (output `text`). A drawing that can be printed as
ascii art
Raises:
VisualizationError: when an invalid output method is selected
"""
from qiskit.tools import visualization
return visualization.circuit_drawer(self, scale=scale,
filename=filename, style=style,
output=output,
interactive=interactive,
line_length=line_length,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits)
def size(self):
"""Return total number of operations in circuit."""
# TODO: removed the DAG from this function
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.size()
def depth(self):
"""Return circuit depth (i.e. length of critical path)."""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.depth()
def width(self):
"""Return number of qubits in circuit."""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.width()
def count_ops(self):
"""Count each operation kind in the circuit.
Returns:
dict: a breakdown of how many operations of each kind.
"""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.count_ops()
def num_tensor_factors(self):
"""How many non-entangled subcircuits can the circuit be factored to."""
from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(self)
return dag.num_tensor_factors()
def copy(self):
""" Returns a deepcopy of the circuit"""
return deepcopy(self)
@staticmethod
def from_qasm_file(path):
"""Take in a QASM file and generate a QuantumCircuit object.
Args:
path (str): Path to the file for a QASM program
Return:
QuantumCircuit: The QuantumCircuit object for the input QASM
"""
qasm = _qasm.Qasm(filename=path)
return _circuit_from_qasm(qasm)
@staticmethod
def from_qasm_str(qasm_str):
"""Take in a QASM string and generate a QuantumCircuit object.
Args:
qasm_str (str): A QASM program string
Return:
QuantumCircuit: The QuantumCircuit object for the input QASM
"""
qasm = _qasm.Qasm(data=qasm_str)
return _circuit_from_qasm(qasm)
def _circuit_from_qasm(qasm):
# pylint: disable=cyclic-import
from qiskit.converters import ast_to_dag
from qiskit.converters import dag_to_circuit
ast = qasm.parse()
dag = ast_to_dag(ast)
return dag_to_circuit(dag)
<|code_end|>
|
Using the rzz gate yields an error on circuit drawing
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**:
qiskit version 0.7.0
- **Python version**:
python 3.6.6
- **Operating system**:
Red Hat Entreprise Server 7.4
### Current behavior
At circuit draw I get the following error
```bash
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/site-packages/qiskit/circuit/quantumcircuit.py", line 83, in __str__
return str(self.draw(output='text'))
File "/usr/local/lib/python3.6/site-packages/qiskit/tools/visualization/_text.py", line 413, in __str__
return self.single_string()
File "/usr/local/lib/python3.6/site-packages/qiskit/tools/visualization/_text.py", line 438, in single_string
return "\n".join(self.lines())
File "/usr/local/lib/python3.6/site-packages/qiskit/tools/visualization/_text.py", line 472, in lines
layers = self.build_layers()
File "/usr/local/lib/python3.6/site-packages/qiskit/tools/visualization/_text.py", line 758, in build_layers
elif len(instruction['qubits']) >= 2 and not instruction['cargs']:
KeyError: 'qubits'
```
### Steps to reproduce the problem
```python
from qiskit import *
q = QuantumRegister(2)
qc = QuantumCircuit(q);
qc.rzz(0, q[0], q[1])
print(qc)
```
### What is the expected behavior?
It should draw the circuit with no problem, but here it gives a KeyError on "qubits"
### Suggested solutions
Maybe it is expecting "qargs" instead of "qubits"?
|
qiskit/tools/visualization/_text.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A module for drawing circuits in ascii art or some other text representation
"""
from shutil import get_terminal_size
import sys
from .exceptions import VisualizationError
class DrawElement():
""" An element is an instruction or an operation that need to be drawn."""
def __init__(self, label=None):
self._width = None
self.label = self.mid_content = label
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = self.bot_connect = " "
self.top_pad = self._mid_padding = self.bot_pad = " "
self.bot_connector = {}
self.top_connector = {}
self.right_fill = self.left_fill = 0
@property
def top(self):
""" Constructs the top line of the element"""
ret = self.top_format % self.top_connect.center(
self.width - self.left_fill - self.right_fill, self.top_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.top_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.top_pad)
return ret
@property
def mid(self):
""" Constructs the middle line of the element"""
ret = self.mid_format % self.mid_content.center(
self.width - self.left_fill - self.right_fill, self._mid_padding)
if self.right_fill:
ret = ret.ljust(self.right_fill, self._mid_padding)
if self.left_fill:
ret = ret.rjust(self.left_fill, self._mid_padding)
return ret
@property
def bot(self):
""" Constructs the bottom line of the element"""
ret = self.bot_format % self.bot_connect.center(
self.width - self.left_fill - self.right_fill, self.bot_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.bot_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.bot_pad)
return ret
@property
def length(self):
""" Returns the length of the element, including the box around."""
return max(len(self.top), len(self.mid), len(self.bot))
@length.setter
def length(self, value):
""" Adjusts width so the length fits."""
self.width = value - max(
[len(getattr(self, i) % '') for i in ["bot_format", "mid_format", "top_format"]])
@property
def width(self):
""" Returns the width of the label, including padding"""
if self._width:
return self._width
return len(self.mid_content)
@width.setter
def width(self, value):
self._width = value
def connect(self, wire_char, where, label=None):
"""
Connects boxes and elements using wire_char and setting proper connectors.
Args:
wire_char (char): For example '║' or '│'.
where (list["top", "bot"]): Where the connector should be set.
label (string): Some connectors have a label (see cu1, for example).
"""
if 'top' in where and self.top_connector:
self.top_connect = self.top_connector[wire_char]
if 'bot' in where and self.bot_connector:
self.bot_connect = self.bot_connector[wire_char]
if label:
self.top_format = self.top_format[:-1] + (label if label else "")
class BoxOnClWire(DrawElement):
""" Draws a box on the classical wire
top: ┌───┐ ┌───────┐
mid: ╡ A ╞ ╡ A ╞
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "╡ %s ╞"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
class BoxOnQuWire(DrawElement):
""" Draws a box on the quantum wire
top: ┌───┐ ┌───────┐
mid: ┤ A ├ ┤ A ├
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "┤ %s ├"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
self.top_connector = {"│": '┴'}
self.bot_connector = {"│": '┬'}
class MeasureTo(DrawElement):
""" The element on the classic wire to which the measure is performed
top: ║ ║
mid: ═╩═ ═══╩═══
bot:
"""
def __init__(self):
super().__init__()
self.top_connect = " ║ "
self.mid_content = "═╩═"
self.bot_connect = " "
self._mid_padding = "═"
class MeasureFrom(BoxOnQuWire):
""" The element on the quantum wire in which the measure is performed
top: ┌─┐ ┌─┐
mid: ┤M├ ───┤M├───
bot: └╥┘ └╥┘
"""
def __init__(self):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = "┌─┐"
self.mid_content = "┤M├"
self.bot_connect = "└╥┘"
class MultiBox(DrawElement):
"""Elements that is draw on over multiple wires."""
def center_label(self, input_length, order):
"""
In multi-bit elements, the label is centered vertically.
Args:
input_length (int): Rhe amount of wires affected.
order (int): Which middle element is this one?
"""
location_in_the_box = '*'.center(input_length * 2 - 1).index('*') + 1
top_limit = (order - 1) * 2 + 2
bot_limit = top_limit + 2
if top_limit <= location_in_the_box < bot_limit:
if location_in_the_box == top_limit:
self.top_connect = self.label
elif location_in_the_box == top_limit + 1:
self.mid_content = self.label
else:
self.bot_connect = self.label
class BoxOnQuWireTop(MultiBox, BoxOnQuWire):
""" Draws the top part of a box that affects more than one quantum wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnQuWireMid(MultiBox, BoxOnQuWire):
""" Draws the middle part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.center_label(input_length, order)
class BoxOnQuWireBot(MultiBox, BoxOnQuWire):
""" Draws the bottom part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length):
super().__init__(label)
self.top_format = "│ %s │"
self.mid_content = self.bot_connect = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class BoxOnClWireTop(MultiBox, BoxOnClWire):
""" Draws the top part of a conditional box that affects more than one classical wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnClWireMid(MultiBox, BoxOnClWire):
""" Draws the middle part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.mid_content = label
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.top_pad = self.bot_pad = ' '
self.top_connect = self.bot_connect = self.mid_content = ''
self.center_label(input_length, order)
class BoxOnClWireBot(MultiBox, BoxOnClWire):
""" Draws the bottom part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, bot_connect='─'):
super().__init__(label)
self.top_format = "│ %s │"
self.top_pad = " "
self.bot_connect = bot_connect
self.mid_content = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class DirectOnQuWire(DrawElement):
"""
Element to the wire (without the box).
"""
def __init__(self, label=""):
super().__init__(label)
self.top_format = ' %s '
self.mid_format = '─%s─'
self.bot_format = ' %s '
self._mid_padding = '─'
self.top_connector = {"│": '│'}
self.bot_connector = {"│": '│'}
class Barrier(DirectOnQuWire):
""" Draws a barrier.
top: ░ ░
mid: ─░─ ───░───
bot: ░ ░
"""
def __init__(self, label=""):
super().__init__("░")
self.top_connect = "░"
self.bot_connect = "░"
self.top_connector = {}
self.bot_connector = {}
class Ex(DirectOnQuWire):
""" Draws an X (usually with a connector). E.g. the top part of a swap gate
top:
mid: ─X─ ───X───
bot: │ │
"""
def __init__(self, bot_connect=" ", top_connect=" "):
super().__init__("X")
self.bot_connect = bot_connect
self.top_connect = top_connect
class Reset(DirectOnQuWire):
""" Draws a reset gate"""
def __init__(self):
super().__init__("|0>")
class Bullet(DirectOnQuWire):
""" Draws a bullet (usually with a connector). E.g. the top part of a CX gate.
top:
mid: ─■─ ───■───
bot: │ │
"""
def __init__(self, top_connect=" ", bot_connect=" "):
super().__init__('■')
self.top_connect = top_connect
self.bot_connect = bot_connect
class EmptyWire(DrawElement):
""" This element is just the wire, with no instructions nor operations."""
def __init__(self, wire):
super().__init__(wire)
self._mid_padding = wire
@staticmethod
def fillup_layer(layer, first_clbit):
"""
Given a layer, replace the Nones in it with EmptyWire elements.
Args:
layer (list): The layer that contains Nones.
first_clbit (int): The first wire that is classic.
Returns:
list: The new layer, with no Nones.
"""
for nones in [i for i, x in enumerate(layer) if x is None]:
layer[nones] = EmptyWire('═') if nones >= first_clbit else EmptyWire('─')
return layer
class BreakWire(DrawElement):
""" This element is used to break the drawing in several pages."""
def __init__(self, arrow_char):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = arrow_char
self.mid_content = arrow_char
self.bot_connect = arrow_char
@staticmethod
def fillup_layer(layer_length, arrow_char):
"""
Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer.
"""
breakwire_layer = []
for _ in range(layer_length):
breakwire_layer.append(BreakWire(arrow_char))
return breakwire_layer
class InputWire(DrawElement):
""" This element is the label and the initial value of a wire."""
def __init__(self, label):
super().__init__(label)
@staticmethod
def fillup_layer(names): # pylint: disable=arguments-differ
"""
Creates a layer with InputWire elements.
Args:
names (list): List of names for the wires.
Returns:
list: The new layer
"""
longest = max([len(name) for name in names])
inputs_wires = []
for name in names:
inputs_wires.append(InputWire(name.rjust(longest)))
return inputs_wires
class TextDrawing():
""" The text drawing"""
def __init__(self, qregs, cregs, instructions, plotbarriers=True, line_length=None):
self.qregs = qregs
self.cregs = cregs
self.instructions = instructions
self.plotbarriers = plotbarriers
self.line_length = line_length
def __str__(self):
return self.single_string()
def _repr_html_(self):
return '<pre style="word-wrap: normal;' \
'white-space: pre;' \
'line-height: 15px;">%s</pre>' % self.single_string()
def _get_qubit_labels(self):
qubits = []
for qubit in self.qregs:
qubits.append("%s_%s" % (qubit[0].name, qubit[1]))
return qubits
def _get_clbit_labels(self):
clbits = []
for clbit in self.cregs:
clbits.append("%s_%s" % (clbit[0].name, clbit[1]))
return clbits
def single_string(self):
"""
Creates a loong string with the ascii art
Returns:
str: The lines joined by '\n'
"""
return "\n".join(self.lines())
def dump(self, filename, encoding="utf8"):
"""
Dumps the ascii art in the file.
Args:
filename (str): File to dump the ascii art.
encoding (str): Optional. Default "utf-8".
"""
with open(filename, mode='w', encoding=encoding) as text_file:
text_file.write(self.single_string())
def lines(self, line_length=None):
"""
Generates a list with lines. These lines form the text drawing.
Args:
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
Returns:
list: A list of lines with the text drawing.
"""
if line_length is None:
line_length = self.line_length
if line_length is None:
if ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
line_length = 80
else:
line_length, _ = get_terminal_size()
noqubits = len(self.qregs)
layers = self.build_layers()
# TODO compress layers
# -| H |----------
# --------| H |---
# should be
# -| H |---
# -| H |---
if not line_length:
line_length = self.line_length
layer_groups = [[]]
rest_of_the_line = line_length
for layerno, layer in enumerate(layers):
# Replace the Nones with EmptyWire
layers[layerno] = EmptyWire.fillup_layer(layer, noqubits)
TextDrawing.normalize_width(layer)
if line_length == -1:
# Do not use pagination (aka line breaking. aka ignore line_length).
layer_groups[-1].append(layer)
continue
# chop the layer to the line_length (pager)
layer_length = layers[layerno][0].length
if layer_length < rest_of_the_line:
layer_groups[-1].append(layer)
rest_of_the_line -= layer_length
else:
layer_groups[-1].append(BreakWire.fillup_layer(len(layer), '»'))
# New group
layer_groups.append([BreakWire.fillup_layer(len(layer), '«')])
rest_of_the_line = line_length - layer_groups[-1][-1][0].length
layer_groups[-1].append(
InputWire.fillup_layer(self.wire_names(with_initial_value=False)))
rest_of_the_line -= layer_groups[-1][-1][0].length
layer_groups[-1].append(layer)
rest_of_the_line -= layer_groups[-1][-1][0].length
lines = []
for layer_group in layer_groups:
wires = [i for i in zip(*layer_group)]
lines += TextDrawing.draw_wires(wires)
return lines
def wire_names(self, with_initial_value=True):
"""
Returns a list of names for each wire.
Args:
with_initial_value (bool): Optional (Default: True). If true, adds the initial value to
the name.
Returns:
List: The list of wire names.
"""
qubit_labels = self._get_qubit_labels()
clbit_labels = self._get_clbit_labels()
if with_initial_value:
qubit_labels = ['%s: |0>' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: 0 ' % clbit for clbit in clbit_labels]
else:
qubit_labels = ['%s: ' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: ' % clbit for clbit in clbit_labels]
return qubit_labels + clbit_labels
@staticmethod
def draw_wires(wires):
"""
Given a list of wires, creates a list of lines with the text drawing.
Args:
wires (list): A list of wires with instructions.
Returns:
list: A list of lines with the text drawing.
"""
lines = []
bot_line = None
for wire in wires:
# TOP
top_line = ""
for instruction in wire:
top_line += instruction.top
if bot_line is None:
lines.append(top_line)
else:
lines.append(TextDrawing.merge_lines(lines.pop(), top_line))
# MID
mid_line = ""
for instruction in wire:
mid_line += instruction.mid
lines.append(TextDrawing.merge_lines(lines[-1], mid_line, icod="bot"))
# BOT
bot_line = ""
for instruction in wire:
bot_line += instruction.bot
lines.append(TextDrawing.merge_lines(lines[-1], bot_line, icod="bot"))
return lines
@staticmethod
def label_for_conditional(instruction):
""" Creates the label for a conditional instruction."""
return "%s %s" % ('=', instruction['condition'][1])
@staticmethod
def params_for_label(instruction):
"""Get the params and format them to add them to a label. None if there are no params."""
if 'op' in instruction and hasattr(instruction['op'], 'params'):
return ['%.5g' % i for i in instruction['op'].params]
return None
@staticmethod
def label_for_box(instruction):
""" Creates the label for a box."""
label = instruction['name'].capitalize()
params = TextDrawing.params_for_label(instruction)
if params:
label += "(%s)" % ','.join(params)
return label
@staticmethod
def merge_lines(top, bot, icod="top"):
"""
Merges two lines (top and bot) in the way that the overlapping make senses.
Args:
top (str): the top line
bot (str): the bottom line
icod (top or bot): in case of doubt, which line should have priority? Default: "top".
Returns:
str: The merge of both lines.
"""
ret = ""
for topc, botc in zip(top, bot):
if topc == botc:
ret += topc
elif topc in '┼╪' and botc == " ":
ret += "│"
elif topc == " ":
ret += botc
elif topc in '┬╥' and botc in " ║│":
ret += topc
elif topc in '┬│' and botc == "═":
ret += '╪'
elif topc in '┬│' and botc == "─":
ret += '┼'
elif topc in '└┘║│░' and botc == " ":
ret += topc
elif topc in '─═' and botc == " " and icod == "top":
ret += topc
elif topc in '─═' and botc == " " and icod == "bot":
ret += botc
elif topc in "║╥" and botc in "═":
ret += "╬"
elif topc in "║╥" and botc in "─":
ret += "╫"
elif topc in '╫╬' and botc in " ":
ret += "║"
elif topc == '└' and botc == "┌":
ret += "├"
elif topc == '┘' and botc == "┐":
ret += "┤"
else:
ret += botc
return ret
@staticmethod
def normalize_width(layer):
"""
When the elements of the layer have different widths, sets the width to the max elements.
Args:
layer (list): A list of elements.
"""
instructions = [instruction for instruction in filter(lambda x: x is not None, layer)]
longest = max([instruction.length for instruction in instructions])
for instruction in instructions:
instruction.length = longest
def build_layers(self):
"""
Constructs layers.
Returns:
list: List of DrawElements.
Raises:
VisualizationError: When the drawing is, for some reason, impossible to be drawn.
"""
layers = []
layers.append(InputWire.fillup_layer(self.wire_names(with_initial_value=True)))
for instruction in self.instructions:
layer = Layer(self.qregs, self.cregs)
connector_label = None
if instruction['name'] == 'measure':
layer.set_qubit(instruction['qargs'][0], MeasureFrom())
layer.set_clbit(instruction['cargs'][0], MeasureTo())
elif instruction['name'] in ['barrier', 'snapshot', 'save', 'load',
'noise']:
# barrier
if not self.plotbarriers:
continue
for qubit in instruction['qargs']:
layer.set_qubit(qubit, Barrier())
elif instruction['name'] == 'swap':
# swap
for qubit in instruction['qargs']:
layer.set_qubit(qubit, Ex())
elif instruction['name'] == 'cswap':
# cswap
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], Ex())
layer.set_qubit(instruction['qargs'][2], Ex())
elif instruction['name'] == 'reset':
layer.set_qubit(instruction['qargs'][0], Reset())
elif instruction['condition'] is not None:
# conditional
cllabel = TextDrawing.label_for_conditional(instruction)
qulabel = TextDrawing.label_for_box(instruction)
layer.set_cl_multibox(instruction['condition'][0], cllabel, top_connect='┴')
layer.set_qubit(instruction['qargs'][0], BoxOnQuWire(qulabel, bot_connect='┬'))
elif instruction['name'] in ['cx', 'CX', 'ccx']:
# cx/ccx
for qubit in [qubit for qubit in instruction['qargs'][:-1]]:
layer.set_qubit(qubit, Bullet())
layer.set_qubit(instruction['qargs'][-1], BoxOnQuWire('X'))
elif instruction['name'] == 'cy':
# cy
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], BoxOnQuWire('Y'))
elif instruction['name'] == 'cz':
# cz
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], Bullet())
elif instruction['name'] == 'ch':
# ch
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], BoxOnQuWire('H'))
elif instruction['name'] == 'cu1':
# cu1
connector_label = TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], Bullet())
elif instruction['name'] == 'cu3':
# cu3
params = TextDrawing.params_for_label(instruction)
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1],
BoxOnQuWire("U3(%s)" % ','.join(params)))
elif instruction['name'] == 'crz':
# crz
label = "Rz(%s)" % TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], BoxOnQuWire(label))
elif len(instruction['qargs']) == 1 and not instruction['cargs']:
# unitary gate
layer.set_qubit(instruction['qargs'][0],
BoxOnQuWire(TextDrawing.label_for_box(instruction)))
elif len(instruction['qubits']) >= 2 and not instruction['cargs']:
# multiple qubit gate
layer.set_qu_multibox(instruction['qubits'], TextDrawing.label_for_box(instruction))
else:
raise VisualizationError(
"Text visualizer does not know how to handle this instruction", instruction)
layer.connect_with("│", connector_label)
layers.append(layer.full_layer)
return layers
class Layer:
""" A layer is the "column" of the circuit. """
def __init__(self, qregs, cregs):
self.qregs = qregs
self.cregs = cregs
self.qubit_layer = [None] * len(qregs)
self.clbit_layer = [None] * len(cregs)
@property
def full_layer(self):
"""
Returns the composition of qubits and classic wires.
Returns:
String: self.qubit_layer + self.clbit_layer
"""
return self.qubit_layer + self.clbit_layer
def set_qubit(self, qubit, element):
"""
Sets the qubit to the element
Args:
qubit (qbit): Element of self.qregs.
element (DrawElement): Element to set in the qubit
"""
self.qubit_layer[self.qregs.index(qubit)] = element
def set_clbit(self, clbit, element):
"""
Sets the clbit to the element
Args:
clbit (cbit): Element of self.cregs.
element (DrawElement): Element to set in the clbit
"""
self.clbit_layer[self.cregs.index(clbit)] = element
def _set_multibox(self, wire_type, bits, label, top_connect=None):
# pylint: disable=invalid-name
if wire_type == "cl":
bit_index = sorted([i for i, x in enumerate(self.cregs) if x in bits])
bits.sort(key=self.cregs.index)
set_bit = self.set_clbit
BoxOnWire = BoxOnClWire
BoxOnWireTop = BoxOnClWireTop
BoxOnWireMid = BoxOnClWireMid
BoxOnWireBot = BoxOnClWireBot
elif wire_type == "qu":
bit_index = sorted([i for i, x in enumerate(self.qregs) if x in bits])
bits.sort(key=self.qregs.index)
set_bit = self.set_qubit
BoxOnWire = BoxOnQuWire
BoxOnWireTop = BoxOnQuWireTop
BoxOnWireMid = BoxOnQuWireMid
BoxOnWireBot = BoxOnQuWireBot
else:
raise VisualizationError("_set_multibox only supports 'cl' and 'qu' as wire types.")
# Checks if bits are consecutive
if bit_index != [i for i in range(bit_index[0], bit_index[-1] + 1)]:
raise VisualizationError("Text visualizaer does know how to build a gate with multiple"
"bits when they are not adjacent to each other")
if len(bit_index) == 1:
set_bit(bits[0], BoxOnWire(label, top_connect=top_connect))
else:
set_bit(bits[0], BoxOnWireTop(label, top_connect=top_connect))
for order, bit in enumerate(bits[1:-1], 1):
set_bit(bit, BoxOnWireMid(label, len(bit_index), order))
set_bit(bits[-1], BoxOnWireBot(label, len(bit_index)))
def set_cl_multibox(self, creg, label, top_connect='┴'):
"""
Sets the multi clbit box.
Args:
creg (string): The affected classical register.
label (string): The label for the multi clbit box.
top_connect (char): The char to connect the box on the top.
"""
clbit = [bit for bit in self.cregs if bit[0] == creg]
self._set_multibox("cl", clbit, label, top_connect=top_connect)
def set_qu_multibox(self, bits, label):
"""
Sets the multi qubit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi qubit box.
"""
self._set_multibox("qu", bits, label)
def connect_with(self, wire_char, label=None):
"""
Connects the elements in the layer using wire_char.
Args:
wire_char (char): For example '║' or '│'.
label (string): Some connectors have a label (see cu1, for example).
"""
affected_bits = [bit for bit in self.full_layer if bit is not None]
if len([qbit for qbit in self.qubit_layer if qbit is not None]) == 1:
# Nothing to connect
return
affected_bits[0].connect(wire_char, ['bot'])
for affected_bit in affected_bits[1:-1]:
affected_bit.connect(wire_char, ['bot', 'top'])
affected_bits[-1].connect(wire_char, ['top'], label)
if label:
for affected_bit in affected_bits:
affected_bit.right_fill = len(label) + len(affected_bit.mid)
<|code_end|>
|
qiskit/tools/visualization/_text.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
A module for drawing circuits in ascii art or some other text representation
"""
from shutil import get_terminal_size
import sys
from .exceptions import VisualizationError
class DrawElement():
""" An element is an instruction or an operation that need to be drawn."""
def __init__(self, label=None):
self._width = None
self.label = self.mid_content = label
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = self.bot_connect = " "
self.top_pad = self._mid_padding = self.bot_pad = " "
self.bot_connector = {}
self.top_connector = {}
self.right_fill = self.left_fill = 0
@property
def top(self):
""" Constructs the top line of the element"""
ret = self.top_format % self.top_connect.center(
self.width - self.left_fill - self.right_fill, self.top_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.top_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.top_pad)
return ret
@property
def mid(self):
""" Constructs the middle line of the element"""
ret = self.mid_format % self.mid_content.center(
self.width - self.left_fill - self.right_fill, self._mid_padding)
if self.right_fill:
ret = ret.ljust(self.right_fill, self._mid_padding)
if self.left_fill:
ret = ret.rjust(self.left_fill, self._mid_padding)
return ret
@property
def bot(self):
""" Constructs the bottom line of the element"""
ret = self.bot_format % self.bot_connect.center(
self.width - self.left_fill - self.right_fill, self.bot_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.bot_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.bot_pad)
return ret
@property
def length(self):
""" Returns the length of the element, including the box around."""
return max(len(self.top), len(self.mid), len(self.bot))
@length.setter
def length(self, value):
""" Adjusts width so the length fits."""
self.width = value - max(
[len(getattr(self, i) % '') for i in ["bot_format", "mid_format", "top_format"]])
@property
def width(self):
""" Returns the width of the label, including padding"""
if self._width:
return self._width
return len(self.mid_content)
@width.setter
def width(self, value):
self._width = value
def connect(self, wire_char, where, label=None):
"""
Connects boxes and elements using wire_char and setting proper connectors.
Args:
wire_char (char): For example '║' or '│'.
where (list["top", "bot"]): Where the connector should be set.
label (string): Some connectors have a label (see cu1, for example).
"""
if 'top' in where and self.top_connector:
self.top_connect = self.top_connector[wire_char]
if 'bot' in where and self.bot_connector:
self.bot_connect = self.bot_connector[wire_char]
if label:
self.top_format = self.top_format[:-1] + (label if label else "")
class BoxOnClWire(DrawElement):
""" Draws a box on the classical wire
top: ┌───┐ ┌───────┐
mid: ╡ A ╞ ╡ A ╞
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "╡ %s ╞"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
class BoxOnQuWire(DrawElement):
""" Draws a box on the quantum wire
top: ┌───┐ ┌───────┐
mid: ┤ A ├ ┤ A ├
bot: └───┘ └───────┘
"""
def __init__(self, label="", top_connect='─', bot_connect='─'):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "┤ %s ├"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = '─'
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
self.top_connector = {"│": '┴'}
self.bot_connector = {"│": '┬'}
class MeasureTo(DrawElement):
""" The element on the classic wire to which the measure is performed
top: ║ ║
mid: ═╩═ ═══╩═══
bot:
"""
def __init__(self):
super().__init__()
self.top_connect = " ║ "
self.mid_content = "═╩═"
self.bot_connect = " "
self._mid_padding = "═"
class MeasureFrom(BoxOnQuWire):
""" The element on the quantum wire in which the measure is performed
top: ┌─┐ ┌─┐
mid: ┤M├ ───┤M├───
bot: └╥┘ └╥┘
"""
def __init__(self):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = "┌─┐"
self.mid_content = "┤M├"
self.bot_connect = "└╥┘"
class MultiBox(DrawElement):
"""Elements that is draw on over multiple wires."""
def center_label(self, input_length, order):
"""
In multi-bit elements, the label is centered vertically.
Args:
input_length (int): Rhe amount of wires affected.
order (int): Which middle element is this one?
"""
location_in_the_box = '*'.center(input_length * 2 - 1).index('*') + 1
top_limit = (order - 1) * 2 + 2
bot_limit = top_limit + 2
if top_limit <= location_in_the_box < bot_limit:
if location_in_the_box == top_limit:
self.top_connect = self.label
elif location_in_the_box == top_limit + 1:
self.mid_content = self.label
else:
self.bot_connect = self.label
class BoxOnQuWireTop(MultiBox, BoxOnQuWire):
""" Draws the top part of a box that affects more than one quantum wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnQuWireMid(MultiBox, BoxOnQuWire):
""" Draws the middle part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.center_label(input_length, order)
class BoxOnQuWireBot(MultiBox, BoxOnQuWire):
""" Draws the bottom part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length, bot_connect='─'):
super().__init__(label)
self.top_format = "│ %s │"
self.top_pad = " "
self.bot_connect = bot_connect
self.mid_content = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class BoxOnClWireTop(MultiBox, BoxOnClWire):
""" Draws the top part of a conditional box that affects more than one classical wire"""
def __init__(self, label="", top_connect=None):
super().__init__(label)
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else '─'
self.bot_connect = self.bot_pad = " "
class BoxOnClWireMid(MultiBox, BoxOnClWire):
""" Draws the middle part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, order):
super().__init__(label)
self.mid_content = label
self.top_format = "│ %s │"
self.bot_format = "│ %s │"
self.top_pad = self.bot_pad = ' '
self.top_connect = self.bot_connect = self.mid_content = ''
self.center_label(input_length, order)
class BoxOnClWireBot(MultiBox, BoxOnClWire):
""" Draws the bottom part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, bot_connect='─'):
super().__init__(label)
self.top_format = "│ %s │"
self.top_pad = " "
self.bot_connect = bot_connect
self.mid_content = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class DirectOnQuWire(DrawElement):
"""
Element to the wire (without the box).
"""
def __init__(self, label=""):
super().__init__(label)
self.top_format = ' %s '
self.mid_format = '─%s─'
self.bot_format = ' %s '
self._mid_padding = '─'
self.top_connector = {"│": '│'}
self.bot_connector = {"│": '│'}
class Barrier(DirectOnQuWire):
""" Draws a barrier.
top: ░ ░
mid: ─░─ ───░───
bot: ░ ░
"""
def __init__(self, label=""):
super().__init__("░")
self.top_connect = "░"
self.bot_connect = "░"
self.top_connector = {}
self.bot_connector = {}
class Ex(DirectOnQuWire):
""" Draws an X (usually with a connector). E.g. the top part of a swap gate
top:
mid: ─X─ ───X───
bot: │ │
"""
def __init__(self, bot_connect=" ", top_connect=" "):
super().__init__("X")
self.bot_connect = bot_connect
self.top_connect = top_connect
class Reset(DirectOnQuWire):
""" Draws a reset gate"""
def __init__(self):
super().__init__("|0>")
class Bullet(DirectOnQuWire):
""" Draws a bullet (usually with a connector). E.g. the top part of a CX gate.
top:
mid: ─■─ ───■───
bot: │ │
"""
def __init__(self, top_connect=" ", bot_connect=" "):
super().__init__('■')
self.top_connect = top_connect
self.bot_connect = bot_connect
class EmptyWire(DrawElement):
""" This element is just the wire, with no instructions nor operations."""
def __init__(self, wire):
super().__init__(wire)
self._mid_padding = wire
@staticmethod
def fillup_layer(layer, first_clbit):
"""
Given a layer, replace the Nones in it with EmptyWire elements.
Args:
layer (list): The layer that contains Nones.
first_clbit (int): The first wire that is classic.
Returns:
list: The new layer, with no Nones.
"""
for nones in [i for i, x in enumerate(layer) if x is None]:
layer[nones] = EmptyWire('═') if nones >= first_clbit else EmptyWire('─')
return layer
class BreakWire(DrawElement):
""" This element is used to break the drawing in several pages."""
def __init__(self, arrow_char):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = arrow_char
self.mid_content = arrow_char
self.bot_connect = arrow_char
@staticmethod
def fillup_layer(layer_length, arrow_char):
"""
Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer.
"""
breakwire_layer = []
for _ in range(layer_length):
breakwire_layer.append(BreakWire(arrow_char))
return breakwire_layer
class InputWire(DrawElement):
""" This element is the label and the initial value of a wire."""
def __init__(self, label):
super().__init__(label)
@staticmethod
def fillup_layer(names): # pylint: disable=arguments-differ
"""
Creates a layer with InputWire elements.
Args:
names (list): List of names for the wires.
Returns:
list: The new layer
"""
longest = max([len(name) for name in names])
inputs_wires = []
for name in names:
inputs_wires.append(InputWire(name.rjust(longest)))
return inputs_wires
class TextDrawing():
""" The text drawing"""
def __init__(self, qregs, cregs, instructions, plotbarriers=True, line_length=None):
self.qregs = qregs
self.cregs = cregs
self.instructions = instructions
self.plotbarriers = plotbarriers
self.line_length = line_length
def __str__(self):
return self.single_string()
def _repr_html_(self):
return '<pre style="word-wrap: normal;' \
'white-space: pre;' \
'line-height: 15px;">%s</pre>' % self.single_string()
def _get_qubit_labels(self):
qubits = []
for qubit in self.qregs:
qubits.append("%s_%s" % (qubit[0].name, qubit[1]))
return qubits
def _get_clbit_labels(self):
clbits = []
for clbit in self.cregs:
clbits.append("%s_%s" % (clbit[0].name, clbit[1]))
return clbits
def single_string(self):
"""
Creates a loong string with the ascii art
Returns:
str: The lines joined by '\n'
"""
return "\n".join(self.lines())
def dump(self, filename, encoding="utf8"):
"""
Dumps the ascii art in the file.
Args:
filename (str): File to dump the ascii art.
encoding (str): Optional. Default "utf-8".
"""
with open(filename, mode='w', encoding=encoding) as text_file:
text_file.write(self.single_string())
def lines(self, line_length=None):
"""
Generates a list with lines. These lines form the text drawing.
Args:
line_length (int): Optional. Breaks the circuit drawing to this length. This
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
Returns:
list: A list of lines with the text drawing.
"""
if line_length is None:
line_length = self.line_length
if line_length is None:
if ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
line_length = 80
else:
line_length, _ = get_terminal_size()
noqubits = len(self.qregs)
layers = self.build_layers()
# TODO compress layers
# -| H |----------
# --------| H |---
# should be
# -| H |---
# -| H |---
if not line_length:
line_length = self.line_length
layer_groups = [[]]
rest_of_the_line = line_length
for layerno, layer in enumerate(layers):
# Replace the Nones with EmptyWire
layers[layerno] = EmptyWire.fillup_layer(layer, noqubits)
TextDrawing.normalize_width(layer)
if line_length == -1:
# Do not use pagination (aka line breaking. aka ignore line_length).
layer_groups[-1].append(layer)
continue
# chop the layer to the line_length (pager)
layer_length = layers[layerno][0].length
if layer_length < rest_of_the_line:
layer_groups[-1].append(layer)
rest_of_the_line -= layer_length
else:
layer_groups[-1].append(BreakWire.fillup_layer(len(layer), '»'))
# New group
layer_groups.append([BreakWire.fillup_layer(len(layer), '«')])
rest_of_the_line = line_length - layer_groups[-1][-1][0].length
layer_groups[-1].append(
InputWire.fillup_layer(self.wire_names(with_initial_value=False)))
rest_of_the_line -= layer_groups[-1][-1][0].length
layer_groups[-1].append(layer)
rest_of_the_line -= layer_groups[-1][-1][0].length
lines = []
for layer_group in layer_groups:
wires = [i for i in zip(*layer_group)]
lines += TextDrawing.draw_wires(wires)
return lines
def wire_names(self, with_initial_value=True):
"""
Returns a list of names for each wire.
Args:
with_initial_value (bool): Optional (Default: True). If true, adds the initial value to
the name.
Returns:
List: The list of wire names.
"""
qubit_labels = self._get_qubit_labels()
clbit_labels = self._get_clbit_labels()
if with_initial_value:
qubit_labels = ['%s: |0>' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: 0 ' % clbit for clbit in clbit_labels]
else:
qubit_labels = ['%s: ' % qubit for qubit in qubit_labels]
clbit_labels = ['%s: ' % clbit for clbit in clbit_labels]
return qubit_labels + clbit_labels
@staticmethod
def draw_wires(wires):
"""
Given a list of wires, creates a list of lines with the text drawing.
Args:
wires (list): A list of wires with instructions.
Returns:
list: A list of lines with the text drawing.
"""
lines = []
bot_line = None
for wire in wires:
# TOP
top_line = ""
for instruction in wire:
top_line += instruction.top
if bot_line is None:
lines.append(top_line)
else:
lines.append(TextDrawing.merge_lines(lines.pop(), top_line))
# MID
mid_line = ""
for instruction in wire:
mid_line += instruction.mid
lines.append(TextDrawing.merge_lines(lines[-1], mid_line, icod="bot"))
# BOT
bot_line = ""
for instruction in wire:
bot_line += instruction.bot
lines.append(TextDrawing.merge_lines(lines[-1], bot_line, icod="bot"))
return lines
@staticmethod
def label_for_conditional(instruction):
""" Creates the label for a conditional instruction."""
return "%s %s" % ('=', instruction['condition'][1])
@staticmethod
def params_for_label(instruction):
"""Get the params and format them to add them to a label. None if there are no params."""
if 'op' in instruction and hasattr(instruction['op'], 'params'):
return ['%.5g' % i for i in instruction['op'].params]
return None
@staticmethod
def label_for_box(instruction):
""" Creates the label for a box."""
label = instruction['name'].capitalize()
params = TextDrawing.params_for_label(instruction)
if params:
label += "(%s)" % ','.join(params)
return label
@staticmethod
def merge_lines(top, bot, icod="top"):
"""
Merges two lines (top and bot) in the way that the overlapping make senses.
Args:
top (str): the top line
bot (str): the bottom line
icod (top or bot): in case of doubt, which line should have priority? Default: "top".
Returns:
str: The merge of both lines.
"""
ret = ""
for topc, botc in zip(top, bot):
if topc == botc:
ret += topc
elif topc in '┼╪' and botc == " ":
ret += "│"
elif topc == " ":
ret += botc
elif topc in '┬╥' and botc in " ║│":
ret += topc
elif topc in '┬│' and botc == "═":
ret += '╪'
elif topc in '┬│' and botc == "─":
ret += '┼'
elif topc in '└┘║│░' and botc == " ":
ret += topc
elif topc in '─═' and botc == " " and icod == "top":
ret += topc
elif topc in '─═' and botc == " " and icod == "bot":
ret += botc
elif topc in "║╥" and botc in "═":
ret += "╬"
elif topc in "║╥" and botc in "─":
ret += "╫"
elif topc in '╫╬' and botc in " ":
ret += "║"
elif topc == '└' and botc == "┌":
ret += "├"
elif topc == '┘' and botc == "┐":
ret += "┤"
else:
ret += botc
return ret
@staticmethod
def normalize_width(layer):
"""
When the elements of the layer have different widths, sets the width to the max elements.
Args:
layer (list): A list of elements.
"""
instructions = [instruction for instruction in filter(lambda x: x is not None, layer)]
longest = max([instruction.length for instruction in instructions])
for instruction in instructions:
instruction.length = longest
def build_layers(self):
"""
Constructs layers.
Returns:
list: List of DrawElements.
Raises:
VisualizationError: When the drawing is, for some reason, impossible to be drawn.
"""
layers = []
layers.append(InputWire.fillup_layer(self.wire_names(with_initial_value=True)))
for instruction in self.instructions:
layer = Layer(self.qregs, self.cregs)
connector_label = None
if instruction['name'] == 'measure':
layer.set_qubit(instruction['qargs'][0], MeasureFrom())
layer.set_clbit(instruction['cargs'][0], MeasureTo())
elif instruction['name'] in ['barrier', 'snapshot', 'save', 'load',
'noise']:
# barrier
if not self.plotbarriers:
continue
for qubit in instruction['qargs']:
layer.set_qubit(qubit, Barrier())
elif instruction['name'] == 'swap':
# swap
for qubit in instruction['qargs']:
layer.set_qubit(qubit, Ex())
elif instruction['name'] == 'cswap':
# cswap
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], Ex())
layer.set_qubit(instruction['qargs'][2], Ex())
elif instruction['name'] == 'reset':
layer.set_qubit(instruction['qargs'][0], Reset())
elif instruction['condition'] is not None:
# conditional
cllabel = TextDrawing.label_for_conditional(instruction)
qulabel = TextDrawing.label_for_box(instruction)
layer.set_cl_multibox(instruction['condition'][0], cllabel, top_connect='┴')
layer.set_qubit(instruction['qargs'][0], BoxOnQuWire(qulabel, bot_connect='┬'))
elif instruction['name'] in ['cx', 'CX', 'ccx']:
# cx/ccx
for qubit in [qubit for qubit in instruction['qargs'][:-1]]:
layer.set_qubit(qubit, Bullet())
layer.set_qubit(instruction['qargs'][-1], BoxOnQuWire('X'))
elif instruction['name'] == 'cy':
# cy
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], BoxOnQuWire('Y'))
elif instruction['name'] == 'cz':
# cz
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], Bullet())
elif instruction['name'] == 'ch':
# ch
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], BoxOnQuWire('H'))
elif instruction['name'] == 'cu1':
# cu1
connector_label = TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], Bullet())
elif instruction['name'] == 'cu3':
# cu3
params = TextDrawing.params_for_label(instruction)
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1],
BoxOnQuWire("U3(%s)" % ','.join(params)))
elif instruction['name'] == 'crz':
# crz
label = "Rz(%s)" % TextDrawing.params_for_label(instruction)[0]
layer.set_qubit(instruction['qargs'][0], Bullet())
layer.set_qubit(instruction['qargs'][1], BoxOnQuWire(label))
elif len(instruction['qargs']) == 1 and not instruction['cargs']:
# unitary gate
layer.set_qubit(instruction['qargs'][0],
BoxOnQuWire(TextDrawing.label_for_box(instruction)))
elif len(instruction['qargs']) >= 2 and not instruction['cargs']:
# multiple qubit gate
layer.set_qu_multibox(instruction['qargs'], TextDrawing.label_for_box(instruction))
else:
raise VisualizationError(
"Text visualizer does not know how to handle this instruction", instruction)
layer.connect_with("│", connector_label)
layers.append(layer.full_layer)
return layers
class Layer:
""" A layer is the "column" of the circuit. """
def __init__(self, qregs, cregs):
self.qregs = qregs
self.cregs = cregs
self.qubit_layer = [None] * len(qregs)
self.clbit_layer = [None] * len(cregs)
@property
def full_layer(self):
"""
Returns the composition of qubits and classic wires.
Returns:
String: self.qubit_layer + self.clbit_layer
"""
return self.qubit_layer + self.clbit_layer
def set_qubit(self, qubit, element):
"""
Sets the qubit to the element
Args:
qubit (qbit): Element of self.qregs.
element (DrawElement): Element to set in the qubit
"""
self.qubit_layer[self.qregs.index(qubit)] = element
def set_clbit(self, clbit, element):
"""
Sets the clbit to the element
Args:
clbit (cbit): Element of self.cregs.
element (DrawElement): Element to set in the clbit
"""
self.clbit_layer[self.cregs.index(clbit)] = element
def _set_multibox(self, wire_type, bits, label, top_connect=None):
# pylint: disable=invalid-name
if wire_type == "cl":
bit_index = sorted([i for i, x in enumerate(self.cregs) if x in bits])
bits.sort(key=self.cregs.index)
set_bit = self.set_clbit
BoxOnWire = BoxOnClWire
BoxOnWireTop = BoxOnClWireTop
BoxOnWireMid = BoxOnClWireMid
BoxOnWireBot = BoxOnClWireBot
elif wire_type == "qu":
bit_index = sorted([i for i, x in enumerate(self.qregs) if x in bits])
bits.sort(key=self.qregs.index)
set_bit = self.set_qubit
BoxOnWire = BoxOnQuWire
BoxOnWireTop = BoxOnQuWireTop
BoxOnWireMid = BoxOnQuWireMid
BoxOnWireBot = BoxOnQuWireBot
else:
raise VisualizationError("_set_multibox only supports 'cl' and 'qu' as wire types.")
# Checks if bits are consecutive
if bit_index != [i for i in range(bit_index[0], bit_index[-1] + 1)]:
raise VisualizationError("Text visualizaer does know how to build a gate with multiple"
"bits when they are not adjacent to each other")
if len(bit_index) == 1:
set_bit(bits[0], BoxOnWire(label, top_connect=top_connect))
else:
set_bit(bits[0], BoxOnWireTop(label, top_connect=top_connect))
for order, bit in enumerate(bits[1:-1], 1):
set_bit(bit, BoxOnWireMid(label, len(bit_index), order))
set_bit(bits[-1], BoxOnWireBot(label, len(bit_index)))
def set_cl_multibox(self, creg, label, top_connect='┴'):
"""
Sets the multi clbit box.
Args:
creg (string): The affected classical register.
label (string): The label for the multi clbit box.
top_connect (char): The char to connect the box on the top.
"""
clbit = [bit for bit in self.cregs if bit[0] == creg]
self._set_multibox("cl", clbit, label, top_connect=top_connect)
def set_qu_multibox(self, bits, label):
"""
Sets the multi qubit box.
Args:
bits (list[int]): A list of affected bits.
label (string): The label for the multi qubit box.
"""
self._set_multibox("qu", bits, label)
def connect_with(self, wire_char, label=None):
"""
Connects the elements in the layer using wire_char.
Args:
wire_char (char): For example '║' or '│'.
label (string): Some connectors have a label (see cu1, for example).
"""
affected_bits = [bit for bit in self.full_layer if bit is not None]
if len([qbit for qbit in self.qubit_layer if qbit is not None]) == 1:
# Nothing to connect
return
affected_bits[0].connect(wire_char, ['bot'])
for affected_bit in affected_bits[1:-1]:
affected_bit.connect(wire_char, ['bot', 'top'])
if not isinstance(affected_bits[-1], MultiBox):
affected_bits[-1].connect(wire_char, ['top'], label)
if label:
for affected_bit in affected_bits:
affected_bit.right_fill = len(label) + len(affected_bit.mid)
<|code_end|>
|
[ENH] reverse order of operations when loading OpenQASM
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
When applying an operation to a quantum register in OpenQASM code, the operations get loaded in an order where the last qubit is first. It would be nice to have this reversed.
Currently:
```python
qasm = """OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
h q;"""
from qiskit import QuantumCircuit
circuit = QuantumCircuit.from_qasm_str(qasm)
print(circuit.qasm())
```
Yields H on q[2] first, then q[1], then q[0]
```
OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
h q[2];
h q[1];
h q[0];
```
|
qiskit/converters/dag_to_circuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Helper function for converting a dag to a circuit"""
import collections
import networkx as nx
from qiskit.circuit import QuantumCircuit
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
def dag_to_circuit(dag):
"""Build a ``QuantumCircuit`` object from a ``DAGCircuit``.
Args:
dag (DAGCircuit): the input dag.
Return:
QuantumCircuit: the circuit representing the input dag.
"""
qregs = collections.OrderedDict()
for qreg in dag.qregs.values():
qreg_tmp = QuantumRegister(qreg.size, name=qreg.name)
qregs[qreg.name] = qreg_tmp
cregs = collections.OrderedDict()
for creg in dag.cregs.values():
creg_tmp = ClassicalRegister(creg.size, name=creg.name)
cregs[creg.name] = creg_tmp
name = dag.name or None
circuit = QuantumCircuit(*qregs.values(), *cregs.values(), name=name)
graph = dag.multi_graph
for node in nx.topological_sort(graph):
n = graph.nodes[node]
if n['type'] == 'op':
if n['op'].name == 'U':
name = 'u_base'
elif n['op'].name == 'CX':
name = 'cx_base'
elif n['op'].name == 'id':
name = 'iden'
else:
name = n['op'].name
instr_method = getattr(circuit, name)
qubits = []
for qubit in n['qargs']:
qubits.append(qregs[qubit[0].name][qubit[1]])
clbits = []
for clbit in n['cargs']:
clbits.append(cregs[clbit[0].name][clbit[1]])
params = n['op'].params
if name in ['snapshot', 'save', 'noise', 'load']:
result = instr_method(params[0])
else:
result = instr_method(*params, *qubits, *clbits)
if 'condition' in n and n['condition']:
result.c_if(*n['condition'])
return circuit
<|code_end|>
|
qiskit/converters/dag_to_circuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Helper function for converting a dag to a circuit"""
import collections
from qiskit.circuit import QuantumCircuit
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
def dag_to_circuit(dag):
"""Build a ``QuantumCircuit`` object from a ``DAGCircuit``.
Args:
dag (DAGCircuit): the input dag.
Return:
QuantumCircuit: the circuit representing the input dag.
"""
qregs = collections.OrderedDict()
for qreg in dag.qregs.values():
qreg_tmp = QuantumRegister(qreg.size, name=qreg.name)
qregs[qreg.name] = qreg_tmp
cregs = collections.OrderedDict()
for creg in dag.cregs.values():
creg_tmp = ClassicalRegister(creg.size, name=creg.name)
cregs[creg.name] = creg_tmp
name = dag.name or None
circuit = QuantumCircuit(*qregs.values(), *cregs.values(), name=name)
graph = dag.multi_graph
for node in dag.node_nums_in_topological_order():
n = graph.nodes[node]
if n['type'] == 'op':
if n['op'].name == 'U':
name = 'u_base'
elif n['op'].name == 'CX':
name = 'cx_base'
elif n['op'].name == 'id':
name = 'iden'
else:
name = n['op'].name
instr_method = getattr(circuit, name)
qubits = []
for qubit in n['qargs']:
qubits.append(qregs[qubit[0].name][qubit[1]])
clbits = []
for clbit in n['cargs']:
clbits.append(cregs[clbit[0].name][clbit[1]])
params = n['op'].params
if name in ['snapshot', 'save', 'noise', 'load']:
result = instr_method(params[0])
else:
result = instr_method(*params, *qubits, *clbits)
if 'condition' in n and n['condition']:
result.c_if(*n['condition'])
return circuit
<|code_end|>
|
DAGCircuit node_counter variable doesn't update with transpiler passes
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: 0.7
- **Python version**: 3.6
- **Operating system**: Ubuntu 16
### What is the current behavior?
When executing the CX cancellation pass in transpiler, the actual number of nodes changed, but the variable in DAGCircuit called "node_counter" which tracks the number of nodes doesn't change with it.
### Steps to reproduce the problem
The following code can reproduce the error:
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.transpiler import PassManager, transpile_dag
from qiskit.transpiler.passes import CXCancellation
q = QuantumRegister(10)
q.cx(q[0], q[1])
pm = PassManager()
pm.add_passes(CXCancellation())
\# Number of nodes before
print(qdag.node_counter)
qdag = DAGCircuit.fromQuantumCircuit(q)
qdag = transpile_dag(qdag, pass_manager = pm)
\# Number of nodes after
print(qdag.node_counter)
### What is the expected behavior?
The two printed out number to be different.
### Suggested solutions
Remove the variable "node_counter" in DAGCircuit class
|
qiskit/dagcircuit/_dagcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Object to represent a quantum circuit as a directed acyclic graph.
The nodes in the graph are either input/output nodes or operation nodes.
The edges correspond to qubits or bits in the circuit. A directed edge
from node A to node B means that the (qu)bit passes from the output of A
to the input of B. The object's methods allow circuits to be constructed,
composed, and modified. Some natural properties like depth can be computed
directly from the graph.
"""
import re
from collections import OrderedDict
import copy
import itertools
import warnings
import networkx as nx
from qiskit.circuit.quantumregister import QuantumRegister
from qiskit.circuit.classicalregister import ClassicalRegister
from qiskit.circuit.gate import Gate
from .exceptions import DAGCircuitError
class DAGCircuit:
"""
Quantum circuit as a directed acyclic graph.
There are 3 types of nodes in the graph: inputs, outputs, and operations.
The nodes are connected by directed edges that correspond to qubits and
bits.
"""
# pylint: disable=invalid-name
def __init__(self):
"""Create an empty circuit."""
# Circuit name. Generally, this corresponds to the name
# of the QuantumCircuit from which the DAG was generated.
self.name = None
# Set of wires (Register,idx) in the dag
self.wires = []
# Map from wire (Register,idx) to input nodes of the graph
self.input_map = OrderedDict()
# Map from wire (Register,idx) to output nodes of the graph
self.output_map = OrderedDict()
# Running count of the total number of nodes
self.node_counter = 0
# Directed multigraph whose nodes are inputs, outputs, or operations.
# Operation nodes have equal in- and out-degrees and carry
# additional data about the operation, including the argument order
# and parameter values.
# Input nodes have out-degree 1 and output nodes have in-degree 1.
# Edges carry wire labels (reg,idx) and each operation has
# corresponding in- and out-edges with the same wire labels.
self.multi_graph = nx.MultiDiGraph()
# Map of qreg name to QuantumRegister object
self.qregs = OrderedDict()
# Map of creg name to ClassicalRegister object
self.cregs = OrderedDict()
def get_qubits(self):
"""Deprecated. Use qubits()."""
warnings.warn('The method get_qubits() is being replaced by qubits()',
DeprecationWarning, 2)
return self.qubits()
def qubits(self):
"""Return a list of qubits as (QuantumRegister, index) pairs."""
return [(v, i) for k, v in self.qregs.items() for i in range(v.size)]
def get_bits(self):
"""Deprecated. Use clbits()."""
warnings.warn('The method get_bits() is being replaced by clbits()',
DeprecationWarning, 2)
return self.clbits()
def clbits(self):
"""Return a list of bits as (ClassicalRegister, index) pairs."""
return [(v, i) for k, v in self.cregs.items() for i in range(v.size)]
# TODO: unused function. is it needed?
def rename_register(self, regname, newname):
"""Rename a classical or quantum register throughout the circuit.
regname = existing register name string
newname = replacement register name string
"""
if regname == newname:
return
if newname in self.qregs or newname in self.cregs:
raise DAGCircuitError("duplicate register name %s" % newname)
if regname not in self.qregs and regname not in self.cregs:
raise DAGCircuitError("no register named %s" % regname)
if regname in self.qregs:
reg = self.qregs[regname]
reg.name = newname
self.qregs[newname] = reg
self.qregs.pop(regname, None)
if regname in self.cregs:
reg = self.cregs[regname]
reg.name = newname
self.qregs[newname] = reg
self.qregs.pop(regname, None)
# n node d = data
for _, d in self.multi_graph.nodes(data=True):
if d["type"] == "in" or d["type"] == "out":
if regname in d["name"]:
d["name"] = re.sub(regname, newname, d["name"])
elif d["type"] == "op":
qa = []
for a in d["qargs"]:
if a[0] == regname:
a = (newname, a[1])
qa.append(a)
d["qargs"] = qa
ca = []
for a in d["cargs"]:
if a[0] == regname:
a = (newname, a[1])
ca.append(a)
d["cargs"] = ca
if d["condition"] is not None:
if d["condition"][0] == regname:
d["condition"] = (newname, d["condition"][1])
# eX = edge, d= data
for _, _, d in self.multi_graph.edges(data=True):
if regname in d["name"]:
d["name"] = re.sub(regname, newname, d["name"])
def remove_all_ops_named(self, opname):
"""Remove all operation nodes with the given name."""
for n in self.named_nodes(opname):
self._remove_op_node(n)
def add_qreg(self, qreg):
"""Add all wires in a quantum register."""
if not isinstance(qreg, QuantumRegister):
raise DAGCircuitError("not a QuantumRegister instance.")
if qreg.name in self.qregs:
raise DAGCircuitError("duplicate register %s" % qreg.name)
self.qregs[qreg.name] = qreg
for j in range(qreg.size):
self._add_wire((qreg, j))
def add_creg(self, creg):
"""Add all wires in a classical register."""
if not isinstance(creg, ClassicalRegister):
raise DAGCircuitError("not a ClassicalRegister instance.")
if creg.name in self.cregs:
raise DAGCircuitError("duplicate register %s" % creg.name)
self.cregs[creg.name] = creg
for j in range(creg.size):
self._add_wire((creg, j))
def _add_wire(self, wire):
"""Add a qubit or bit to the circuit.
Args:
wire (tuple): (Register,int) containing a register instance and index
This adds a pair of in and out nodes connected by an edge.
Raises:
DAGCircuitError: if trying to add duplicate wire
"""
if wire not in self.wires:
self.wires.append(wire)
self.node_counter += 1
self.input_map[wire] = self.node_counter
self.node_counter += 1
self.output_map[wire] = self.node_counter
in_node = self.input_map[wire]
out_node = self.output_map[wire]
self.multi_graph.add_edge(in_node, out_node)
self.multi_graph.node[in_node]["type"] = "in"
self.multi_graph.node[out_node]["type"] = "out"
self.multi_graph.node[in_node]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.node[out_node]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.node[in_node]["wire"] = wire
self.multi_graph.node[out_node]["wire"] = wire
self.multi_graph.adj[in_node][out_node][0]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.adj[in_node][out_node][0]["wire"] = wire
else:
raise DAGCircuitError("duplicate wire %s" % (wire,))
def _check_condition(self, name, condition):
"""Verify that the condition is valid.
Args:
name (string): used for error reporting
condition (tuple or None): a condition tuple (ClassicalRegister,int)
Raises:
DAGCircuitError: if conditioning on an invalid register
"""
# Verify creg exists
if condition is not None and condition[0].name not in self.cregs:
raise DAGCircuitError("invalid creg in condition for %s" % name)
def _check_bits(self, args, amap):
"""Check the values of a list of (qu)bit arguments.
For each element of args, check that amap contains it.
Args:
args (list): (register,idx) tuples
amap (dict): a dictionary keyed on (register,idx) tuples
Raises:
DAGCircuitError: if a qubit is not contained in amap
"""
# Check for each wire
for wire in args:
if wire not in amap:
raise DAGCircuitError("(qu)bit %s[%d] not found" % (wire[0].name, wire[1]))
def _bits_in_condition(self, cond):
"""Return a list of bits in the given condition.
Args:
cond (tuple or None): optional condition (ClassicalRegister, int)
Returns:
list[(ClassicalRegister, idx)]: list of bits
"""
all_bits = []
if cond is not None:
all_bits.extend([(cond[0], j) for j in range(self.cregs[cond[0].name].size)])
return all_bits
def _add_op_node(self, op, qargs, cargs, condition=None):
"""Add a new operation node to the graph and assign properties.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list): list of quantum wires to attach to.
cargs (list): list of classical wires to attach to.
condition (tuple or None): optional condition (ClassicalRegister, int)
"""
# Add a new operation node to the graph
self.node_counter += 1
self.multi_graph.add_node(self.node_counter)
# Update the operation itself. TODO: remove after qargs not connected to op
op.qargs = qargs
op.cargs = cargs
# Update that operation node's data
self.multi_graph.node[self.node_counter]["type"] = "op"
self.multi_graph.node[self.node_counter]["op"] = op
self.multi_graph.node[self.node_counter]["name"] = op.name
self.multi_graph.node[self.node_counter]["qargs"] = qargs
self.multi_graph.node[self.node_counter]["cargs"] = cargs
self.multi_graph.node[self.node_counter]["condition"] = condition
def apply_operation_back(self, op, qargs=None, cargs=None, condition=None):
"""Apply an operation to the output of the circuit.
TODO: make `qargs` and `cargs` mandatory, when they are dropped from op.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple]): cbits that op will be applied to
condition (tuple or None): optional condition (ClassicalRegister, int)
Raises:
DAGCircuitError: if a leaf node is connected to multiple outputs
"""
qargs = qargs or op.qargs
cargs = cargs or op.cargs
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_condition(op.name, condition)
self._check_bits(qargs, self.output_map)
self._check_bits(all_cbits, self.output_map)
self._add_op_node(op, qargs, cargs, condition)
# Add new in-edges from predecessors of the output nodes to the
# operation node while deleting the old in-edges of the output nodes
# and adding new edges from the operation node to each output node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.predecessors(self.output_map[q]))
if len(ie) != 1:
raise DAGCircuitError("output node has multiple in-edges")
self.multi_graph.add_edge(ie[0], self.node_counter,
name="%s[%s]" % (q[0].name, q[1]), wire=q)
self.multi_graph.remove_edge(ie[0], self.output_map[q])
self.multi_graph.add_edge(self.node_counter, self.output_map[q],
name="%s[%s]" % (q[0].name, q[1]), wire=q)
def apply_operation_front(self, op, qargs=None, cargs=None, condition=None):
"""Apply an operation to the input of the circuit.
TODO: make `qargs` and `cargs` mandatory, when they are dropped from op.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple]): cbits that op will be applied to
condition (tuple or None): optional condition (ClassicalRegister, value)
Raises:
DAGCircuitError: if initial nodes connected to multiple out edges
"""
qargs = qargs or op.qargs
cargs = cargs or op.cargs
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_condition(op.name, condition)
self._check_bits(qargs, self.input_map)
self._check_bits(all_cbits, self.input_map)
self._add_op_node(op, qargs, cargs, condition)
# Add new out-edges to successors of the input nodes from the
# operation node while deleting the old out-edges of the input nodes
# and adding new edges to the operation node from each input node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.successors(self.input_map[q]))
if len(ie) != 1:
raise DAGCircuitError("input node has multiple out-edges")
self.multi_graph.add_edge(self.node_counter, ie[0],
name="%s[%s]" % (q[0].name, q[1]), wire=q)
self.multi_graph.remove_edge(self.input_map[q], ie[0])
self.multi_graph.add_edge(self.input_map[q], self.node_counter,
name="%s[%s]" % (q[0].name, q[1]), wire=q)
def _check_edgemap_registers(self, edge_map, keyregs, valregs, valreg=True):
"""Check that wiremap neither fragments nor leaves duplicate registers.
1. There are no fragmented registers. A register in keyregs
is fragmented if not all of its (qu)bits are renamed by edge_map.
2. There are no duplicate registers. A register is duplicate if
it appears in both self and keyregs but not in edge_map.
Args:
edge_map (dict): map from (reg,idx) in keyregs to (reg,idx) in valregs
keyregs (dict): a map from register names to Register objects
valregs (dict): a map from register names to Register objects
valreg (bool): if False the method ignores valregs and does not
add regs for bits in the edge_map image that don't appear in valregs
Returns:
set(Register): the set of regs to add to self
Raises:
DAGCircuitError: if the wiremap fragments, or duplicates exist
"""
# FIXME: some mixing of objects and strings here are awkward (due to
# self.qregs/self.cregs still keying on string.
add_regs = set()
reg_frag_chk = {}
for v in keyregs.values():
reg_frag_chk[v] = {j: False for j in range(len(v))}
for k in edge_map.keys():
if k[0].name in keyregs:
reg_frag_chk[k[0]][k[1]] = True
for k, v in reg_frag_chk.items():
s = set(v.values())
if len(s) == 2:
raise DAGCircuitError("edge_map fragments reg %s" % k)
elif s == set([False]):
if k in self.qregs.values() or k in self.cregs.values():
raise DAGCircuitError("unmapped duplicate reg %s" % k)
else:
# Add registers that appear only in keyregs
add_regs.add(k)
else:
if valreg:
# If mapping to a register not in valregs, add it.
# (k,0) exists in edge_map because edge_map doesn't
# fragment k
if not edge_map[(k, 0)][0].name in valregs:
size = max(map(lambda x: x[1],
filter(lambda x: x[0] == edge_map[(k, 0)][0],
edge_map.values())))
qreg = QuantumRegister(size + 1, edge_map[(k, 0)][0].name)
add_regs.add(qreg)
return add_regs
def _check_wiremap_validity(self, wire_map, keymap, valmap):
"""Check that the wiremap is consistent.
Check that the wiremap refers to valid wires and that
those wires have consistent types.
Args:
wire_map (dict): map from (register,idx) in keymap to
(register,idx) in valmap
keymap (dict): a map whose keys are wire_map keys
valmap (dict): a map whose keys are wire_map values
Raises:
DAGCircuitError: if wire_map not valid
"""
for k, v in wire_map.items():
kname = "%s[%d]" % (k[0].name, k[1])
vname = "%s[%d]" % (v[0].name, v[1])
if k not in keymap:
raise DAGCircuitError("invalid wire mapping key %s" % kname)
if v not in valmap:
raise DAGCircuitError("invalid wire mapping value %s" % vname)
if type(k) is not type(v):
raise DAGCircuitError("inconsistent wire_map at (%s,%s)" %
(kname, vname))
def _map_condition(self, wire_map, condition):
"""Use the wire_map dict to change the condition tuple's creg name.
Args:
wire_map (dict): a map from wires to wires
condition (tuple): (ClassicalRegister,int)
Returns:
tuple(ClassicalRegister,int): new condition
"""
if condition is None:
new_condition = None
else:
# Map the register name, using fact that registers must not be
# fragmented by the wire_map (this must have been checked
# elsewhere)
bit0 = (condition[0], 0)
new_condition = (wire_map.get(bit0, bit0)[0], condition[1])
return new_condition
def extend_back(self, dag, edge_map=None):
"""Add `dag` at the end of `self`, using `edge_map`.
"""
edge_map = edge_map or {}
for qreg in dag.qregs.values():
if qreg.name not in self.qregs:
self.add_qreg(QuantumRegister(qreg.size, qreg.name))
edge_map.update([(qbit, qbit) for qbit in qreg if qbit not in edge_map])
for creg in dag.cregs.values():
if creg.name not in self.cregs:
self.add_creg(ClassicalRegister(creg.size, creg.name))
edge_map.update([(cbit, cbit) for cbit in creg if cbit not in edge_map])
self.compose_back(dag, edge_map)
def compose_back(self, input_circuit, edge_map=None):
"""Apply the input circuit to the output of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of input qubits of the input circuit are mapped
to a subset of output qubits of this circuit.
Args:
input_circuit (DAGCircuit): circuit to append
edge_map (dict): map {(Register, int): (Register, int)}
from the output wires of input_circuit to input wires
of self.
Raises:
DAGCircuitError: if missing, duplicate or incosistent wire
"""
edge_map = edge_map or {}
# Check the wire map for duplicate values
if len(set(edge_map.values())) != len(edge_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_edgemap_registers(edge_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(edge_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(edge_map, input_circuit.input_map,
self.output_map)
# Compose
for node in nx.topological_sort(input_circuit.multi_graph):
nd = input_circuit.multi_graph.node[node]
if nd["type"] == "in":
# if in wire_map, get new name, else use existing name
m_wire = edge_map.get(nd["wire"], nd["wire"])
# the mapped wire should already exist
if m_wire not in self.output_map:
raise DAGCircuitError("wire %s[%d] not in self" % (m_wire[0].name, m_wire[1]))
if nd["wire"] not in input_circuit.wires:
raise DAGCircuitError("inconsistent wire type for %s[%d] in input_circuit"
% (nd["wire"][0].name, nd["wire"][1]))
elif nd["type"] == "out":
# ignore output nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(edge_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: edge_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: edge_map.get(x, x), nd["cargs"]))
self.apply_operation_back(nd["op"], m_qargs, m_cargs, condition)
else:
raise DAGCircuitError("bad node type %s" % nd["type"])
# FIXME: this does not work as expected. it is also not used anywhere
def compose_front(self, input_circuit, wire_map=None):
"""Apply the input circuit to the input of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of output qubits of the input circuit are mapped
to a subset of input qubits of this circuit.
Args:
input_circuit (DAGCircuit): circuit to append
wire_map (dict): map {(Register, int): (Register, int)}
from the output wires of input_circuit to input wires
of self.
Raises:
DAGCircuitError: missing, duplicate or inconsistent wire
"""
wire_map = wire_map or {}
# Check the wire map
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_edgemap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.output_map,
self.input_map)
# Compose
for n in reversed(list(nx.topological_sort(input_circuit.multi_graph))):
nd = input_circuit.multi_graph.node[n]
if nd["type"] == "out":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["wire"], nd["wire"])
# the mapped wire should already exist
if m_name not in self.input_map:
raise DAGCircuitError("wire %s[%d] not in self" % (m_name[0].name, m_name[1]))
if nd["wire"] not in input_circuit.wires:
raise DAGCircuitError(
"inconsistent wire for %s[%d] in input_circuit"
% (nd["wire"][0].name, nd["wire"][1]))
elif nd["type"] == "in":
# ignore input nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
self.apply_operation_front(nd["op"], condition)
else:
raise DAGCircuitError("bad node type %s" % nd["type"])
def size(self):
"""Return the number of operations."""
return self.multi_graph.order() - 2 * len(self.wires)
def depth(self):
"""Return the circuit depth.
Returns:
int: the circuit depth
Raises:
DAGCircuitError: if not a directed acyclic graph
"""
if not nx.is_directed_acyclic_graph(self.multi_graph):
raise DAGCircuitError("not a DAG")
return nx.dag_longest_path_length(self.multi_graph) - 1
def width(self):
"""Return the total number of qubits used by the circuit."""
return len(self.wires) - self.num_cbits()
def num_cbits(self):
"""Return the total number of bits used by the circuit."""
return sum(creg.size for creg in self.cregs.values())
def num_tensor_factors(self):
"""Compute how many components the circuit can decompose into."""
return nx.number_weakly_connected_components(self.multi_graph)
def qasm(self):
"""Deprecated. use qiskit.converters.dag_to_circuit() then call
qasm() on the obtained QuantumCircuit instance.
"""
warnings.warn('printing qasm() from DAGCircuit is deprecated. '
'use qiskit.converters.dag_to_circuit() then call '
'qasm() on the obtained QuantumCircuit instance.',
DeprecationWarning, 2)
def _check_wires_list(self, wires, op, input_circuit, condition=None):
"""Check that a list of wires satisfies some conditions.
- no duplicate names
- correct length for operation
- elements are wires of input_circuit
Raise an exception otherwise.
Args:
wires (list[register, index]): gives an order for (qu)bits
in the input_circuit that is replacing the operation.
op (Instruction): operation
input_circuit (DAGCircuit): replacement circuit for operation
condition (tuple or None): if this instance of the
operation is classically controlled by a (ClassicalRegister, int)
Raises:
DAGCircuitError: if check doesn't pass.
"""
if len(set(wires)) != len(wires):
raise DAGCircuitError("duplicate wires")
wire_tot = len(op.qargs) + len(op.cargs)
if condition is not None:
wire_tot += condition[0].size
if len(wires) != wire_tot:
raise DAGCircuitError("expected %d wires, got %d"
% (wire_tot, len(wires)))
for w in wires:
if w not in input_circuit.wires:
raise DAGCircuitError("wire (%s,%d) not in input circuit"
% (w[0], w[1]))
def _make_pred_succ_maps(self, n):
"""Return predecessor and successor dictionaries.
Args:
n (int): reference to self.multi_graph node id
Returns:
tuple(dict): tuple(predecessor_map, successor_map)
These map from wire (Register, int) to predecessor (successor)
nodes of n.
"""
pred_map = {e[2]['wire']: e[0] for e in
self.multi_graph.in_edges(nbunch=n, data=True)}
succ_map = {e[2]['wire']: e[1] for e in
self.multi_graph.out_edges(nbunch=n, data=True)}
return pred_map, succ_map
def _full_pred_succ_maps(self, pred_map, succ_map, input_circuit,
wire_map):
"""Map all wires of the input circuit.
Map all wires of the input circuit to predecessor and
successor nodes in self, keyed on wires in self.
Args:
pred_map (dict): comes from _make_pred_succ_maps
succ_map (dict): comes from _make_pred_succ_maps
input_circuit (DAGCircuit): the input circuit
wire_map (dict): the map from wires of input_circuit to wires of self
Returns:
tuple: full_pred_map, full_succ_map (dict, dict)
Raises:
DAGCircuitError: if more than one predecessor for output nodes
"""
full_pred_map = {}
full_succ_map = {}
for w in input_circuit.input_map:
# If w is wire mapped, find the corresponding predecessor
# of the node
if w in wire_map:
full_pred_map[wire_map[w]] = pred_map[wire_map[w]]
full_succ_map[wire_map[w]] = succ_map[wire_map[w]]
else:
# Otherwise, use the corresponding output nodes of self
# and compute the predecessor.
full_succ_map[w] = self.output_map[w]
full_pred_map[w] = self.multi_graph.predecessors(
self.output_map[w])[0]
if len(list(self.multi_graph.predecessors(self.output_map[w]))) != 1:
raise DAGCircuitError("too many predecessors for %s[%d] "
"output node" % (w[0], w[1]))
return full_pred_map, full_succ_map
@staticmethod
def _match_dag_nodes(node1, node2):
"""
Check if DAG nodes are considered equivalent, e.g. as a node_match for nx.is_isomorphic.
Args:
node1 (dict): A node to compare.
node2 (dict): The other node to compare.
Returns:
Bool: If node1 == node2
"""
copy_node1 = {k: v for (k, v) in node1.items()}
copy_node2 = {k: v for (k, v) in node2.items()}
# For barriers, qarg order is not significant so compare as sets
if 'barrier' == copy_node1['name'] == copy_node2['name']:
node1_qargs = set(copy_node1.pop('qargs', []))
node2_qargs = set(copy_node2.pop('qargs', []))
if node1_qargs != node2_qargs:
return False
return copy_node1 == copy_node2
def __eq__(self, other):
return nx.is_isomorphic(self.multi_graph, other.multi_graph,
node_match=DAGCircuit._match_dag_nodes)
def node_nums_in_topological_order(self):
"""
Returns the nodes (their ids) in topological order.
Returns:
list: The list of node numbers in topological order
"""
return nx.lexicographical_topological_sort(self.multi_graph)
def substitute_circuit_all(self, op, input_circuit, wires=None):
"""Replace every occurrence of operation op with input_circuit.
Args:
op (Instruction): operation type to substitute across the dag.
input_circuit (DAGCircuit): what to replace with
wires (list[register, index]): gives an order for (qu)bits
in the input_circuit that is replacing the operation.
Raises:
DAGCircuitError: if met with unexpected predecessor/successors
"""
# TODO: rewrite this method to call substitute_node_with_dag
wires = wires or []
self._check_wires_list(wires, op, input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: (QuantumRegister(1, 'proxy'), 0) for w in wires}
add_qregs = self._check_edgemap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Iterate through the nodes of self and replace the selected nodes
# by iterating through the input_circuit, constructing and
# checking the validity of the wire_map for each replacement
# NOTE: We do not replace conditioned gates. One way to implement
# this later is to add or update the conditions of each gate
# that we add from the input_circuit.
for n in self.node_nums_in_topological_order():
nd = self.multi_graph.node[n]
if nd["type"] == "op" and nd["op"] == op:
if nd["condition"] is None:
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"], nd["cargs"]]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map)
pred_map, succ_map = self._make_pred_succ_maps(n)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(n)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map,
md["condition"])
m_qargs = [wire_map.get(x, x) for x in md["qargs0"]]
m_cargs = [wire_map.get(x, x) for x in md["cargs0"]]
self._add_op_node(md["op"], m_qargs, m_cargs, condition)
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter,
name="%s[%s]" % (q[0].name, q[1]),
wire=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w],
full_succ_map[w],
name="%s[%s]" % (w[0].name, w[1]),
wire=w)
o_pred = list(self.multi_graph.predecessors(
self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise DAGCircuitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise DAGCircuitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(
p[0], self.output_map[w])
def substitute_node_with_dag(self, node, input_dag, wires=None):
"""Replace one node with dag.
Args:
node (int): node of self.multi_graph (of type "op") to substitute
input_dag (DAGCircuit): circuit that will substitute the node
wires (list[(Register, index)]): gives an order for (qu)bits
in the input circuit. This order gets matched to the node wires
by qargs first, then cargs, then conditions.
Raises:
DAGCircuitError: if met with unexpected predecessor/successors
"""
nd = self.multi_graph.node[node]
condition = nd["condition"]
# the decomposition rule must be amended if used in a
# conditional context. delete the op nodes and replay
# them with the condition.
if condition:
input_dag.add_creg(condition[0])
to_replay = []
for n_it in nx.topological_sort(input_dag.multi_graph):
n = input_dag.multi_graph.nodes[n_it]
if n["type"] == "op":
n["op"].control = condition
to_replay.append(n)
for n in input_dag.op_nodes():
input_dag._remove_op_node(n)
for n in to_replay:
input_dag.apply_operation_back(n["op"], condition=condition)
if wires is None:
qwires = [w for w in input_dag.wires if isinstance(w[0], QuantumRegister)]
cwires = [w for w in input_dag.wires if isinstance(w[0], ClassicalRegister)]
wires = qwires + cwires
self._check_wires_list(wires, nd["op"], input_dag, nd["condition"])
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: QuantumRegister(1, 'proxy') for w in wires}
add_qregs = self._check_edgemap_registers(proxy_map,
input_dag.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(proxy_map,
input_dag.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Replace the node by iterating through the input_circuit.
# Constructing and checking the validity of the wire_map.
# If a gate is conditioned, we expect the replacement subcircuit
# to depend on those control bits as well.
if nd["type"] != "op":
raise DAGCircuitError("expected node type \"op\", got %s"
% nd["type"])
condition_bit_list = self._bits_in_condition(nd["condition"])
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"],
nd["cargs"],
condition_bit_list]
for i in s])}
self._check_wiremap_validity(wire_map, wires, self.input_map)
pred_map, succ_map = self._make_pred_succ_maps(node)
full_pred_map, full_succ_map = self._full_pred_succ_maps(pred_map, succ_map,
input_dag, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(node)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_dag.multi_graph):
md = input_dag.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map, md["condition"])
m_qargs = list(map(lambda x: wire_map.get(x, x),
md["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x),
md["cargs"]))
self._add_op_node(md["op"], m_qargs, m_cargs, condition)
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self.node_counter,
name="%s[%s]" % (q[0].name, q[1]),
wire=q)
full_pred_map[q] = copy.copy(self.node_counter)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w],
full_succ_map[w],
name="%s[%s]" % (w[0].name, w[1]),
wire=w)
o_pred = list(self.multi_graph.predecessors(self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise DAGCircuitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise DAGCircuitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(p[0], self.output_map[w])
def get_op_nodes(self, op=None, data=False):
"""Deprecated. Use op_nodes()."""
warnings.warn('The method get_op_nodes() is being replaced by op_nodes()',
DeprecationWarning, 2)
return self.op_nodes(op, data)
def op_nodes(self, op=None, data=False):
"""Get the list of "op" nodes in the dag.
Args:
op (Type): Instruction subclass op nodes to return. if op=None, return
all op nodes.
data (bool): Default: False. If True, return a list of tuple
(node_id, node_data). If False, return a list of int (node_id)
Returns:
list: the list of node ids containing the given op.
"""
nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data["type"] == "op":
if op is None or isinstance(node_data["op"], op):
nodes.append((node_id, node_data))
if not data:
nodes = [n[0] for n in nodes]
return nodes
def get_gate_nodes(self, data=False):
"""Deprecated. Use gate_nodes()."""
warnings.warn('The method get_gate_nodes() is being replaced by gate_nodes()',
DeprecationWarning, 2)
return self.gate_nodes(data)
def gate_nodes(self, data=False):
"""Get the list of gate nodes in the dag.
Args:
data (bool): Default: False. If True, return a list of tuple
(node_id, node_data). If False, return a list of int (node_id)
Returns:
list: the list of node ids that represent gates.
"""
nodes = []
for node_id, node_data in self.op_nodes(data=True):
if isinstance(node_data['op'], Gate):
nodes.append((node_id, node_data))
if not data:
nodes = [n[0] for n in nodes]
return nodes
def get_named_nodes(self, *names):
"""Deprecated. Use named_nodes()."""
warnings.warn('The method get_named_nodes() is being replaced by named_nodes()',
DeprecationWarning, 2)
return self.named_nodes(*names)
def named_nodes(self, *names):
"""Get the set of "op" nodes with the given name."""
named_nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data['type'] == 'op' and node_data['op'].name in names:
named_nodes.append(node_id)
return named_nodes
def get_2q_nodes(self):
"""Deprecated. Use twoQ_nodes()."""
warnings.warn('The method get_2q_nodes() is being replaced by twoQ_nodes()',
DeprecationWarning, 2)
return self.twoQ_nodes()
def twoQ_nodes(self):
"""Get list of 2-qubit nodes."""
two_q_nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data['type'] == 'op' and len(node_data['qargs']) == 2:
two_q_nodes.append(self.multi_graph.node[node_id])
return two_q_nodes
def get_3q_or_more_nodes(self):
"""Deprecated. Use threeQ_or_more_nodes()."""
warnings.warn('The method get_3q_or_more_nodes() is being replaced by'
' threeQ_or_more_nodes()', DeprecationWarning, 2)
return self.threeQ_or_more_nodes()
def threeQ_or_more_nodes(self):
"""Get list of 3-or-more-qubit nodes: (id, data)."""
three_q_nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data['type'] == 'op' and len(node_data['qargs']) >= 3:
three_q_nodes.append((node_id, self.multi_graph.node[node_id]))
return three_q_nodes
def successors(self, node):
"""Returns the successors of a node."""
return self.multi_graph.successors(node)
def ancestors(self, node):
"""Returns the ancestors of a node."""
return nx.ancestors(self.multi_graph, node)
def descendants(self, node):
"""Returns the descendants of a node."""
return nx.descendants(self.multi_graph, node)
def bfs_successors(self, node):
"""Returns successors of a node in BFS order"""
return nx.bfs_successors(self.multi_graph, node)
def quantum_successors(self, node):
"""Returns the successors of a node that are connected by a quantum edge"""
successors = []
for successor in self.successors(node):
if isinstance(self.multi_graph.get_edge_data(node, successor, key=0)['wire'][0],
QuantumRegister):
successors.append(successor)
return successors
def _remove_op_node(self, n):
"""Remove an operation node n.
Add edges from predecessors to successors.
"""
pred_map, succ_map = self._make_pred_succ_maps(n)
self.multi_graph.remove_node(n)
for w in pred_map.keys():
self.multi_graph.add_edge(pred_map[w], succ_map[w],
name="%s[%s]" % (w[0].name, w[1]), wire=w)
def remove_ancestors_of(self, node):
"""Remove all of the ancestor operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
# TODO: probably better to do all at once using
# multi_graph.remove_nodes_from; same for related functions ...
for n in anc:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_descendants_of(self, node):
"""Remove all of the descendant operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
for n in dec:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nonancestors_of(self, node):
"""Remove all of the non-ancestors operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(anc))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nondescendants_of(self, node):
"""Remove all of the non-descendants operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(dec))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def layers(self):
"""Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit.
A layer is a circuit whose gates act on disjoint qubits, i.e.
a layer has depth 1. The total number of layers equals the
circuit depth d. The layers are indexed from 0 to d-1 with the
earliest layer at index 0. The layers are constructed using a
greedy algorithm. Each returned layer is a dict containing
{"graph": circuit graph, "partition": list of qubit lists}.
TODO: Gates that use the same cbits will end up in different
layers as this is currently implemented. This may not be
the desired behavior.
"""
graph_layers = self.multigraph_layers()
try:
next(graph_layers) # Remove input nodes
except StopIteration:
return
def nodes_data(nodes):
"""Construct full nodes from just node ids."""
return ((node_id, self.multi_graph.nodes[node_id]) for node_id in nodes)
for graph_layer in graph_layers:
# Get the op nodes from the layer, removing any input and output nodes.
op_nodes = [node for node in nodes_data(graph_layer) if node[1]["type"] == "op"]
# Stop yielding once there are no more op_nodes in a layer.
if not op_nodes:
return
# Construct a shallow copy of self
new_layer = copy.copy(self)
new_layer.multi_graph = nx.MultiDiGraph()
new_layer.multi_graph.add_nodes_from(nodes_data(self.input_map.values()))
new_layer.multi_graph.add_nodes_from(nodes_data(self.output_map.values()))
# The quantum registers that have an operation in this layer.
support_list = [
op_node[1]["qargs"]
for op_node in op_nodes
if op_node[1]["op"].name not in {"barrier", "snapshot", "save", "load", "noise"}
]
new_layer.multi_graph.add_nodes_from(op_nodes)
# Now add the edges to the multi_graph
# By default we just wire inputs to the outputs.
wires = {self.input_map[wire]: self.output_map[wire]
for wire in self.wires}
# Wire inputs to op nodes, and op nodes to outputs.
for op_node in op_nodes:
args = self._bits_in_condition(op_node[1]["condition"]) \
+ op_node[1]["cargs"] + op_node[1]["qargs"]
arg_ids = (self.input_map[(arg[0], arg[1])] for arg in args)
for arg_id in arg_ids:
wires[arg_id], wires[op_node[0]] = op_node[0], wires[arg_id]
# Add wiring to/from the operations and between unused inputs & outputs.
new_layer.multi_graph.add_edges_from(wires.items())
yield {"graph": new_layer, "partition": support_list}
def serial_layers(self):
"""Yield a layer for all gates of this circuit.
A serial layer is a circuit with one gate. The layers have the
same structure as in layers().
"""
for n in self.node_nums_in_topological_order():
nxt_nd = self.multi_graph.node[n]
if nxt_nd["type"] == "op":
new_layer = DAGCircuit()
for qreg in self.qregs.values():
new_layer.add_qreg(qreg)
for creg in self.cregs.values():
new_layer.add_creg(creg)
# Save the support of the operation we add to the layer
support_list = []
# Operation data
op = copy.copy(nxt_nd["op"])
qa = copy.copy(nxt_nd["qargs"])
ca = copy.copy(nxt_nd["cargs"])
co = copy.copy(nxt_nd["condition"])
_ = self._bits_in_condition(co)
# Add node to new_layer
new_layer.apply_operation_back(op, qa, ca, co)
# Add operation to partition
if nxt_nd["name"] not in ["barrier",
"snapshot", "save", "load", "noise"]:
support_list.append(list(qa))
l_dict = {"graph": new_layer, "partition": support_list}
yield l_dict
def multigraph_layers(self):
"""Yield layers of the multigraph."""
predecessor_count = dict() # Dict[node, predecessors not visited]
cur_layer = [node for node in self.input_map.values()]
yield cur_layer
next_layer = []
while cur_layer:
for node in cur_layer:
# Count multiedges with multiplicity.
for successor in self.multi_graph.successors(node):
multiplicity = self.multi_graph.number_of_edges(node, successor)
if successor in predecessor_count:
predecessor_count[successor] -= multiplicity
else:
predecessor_count[successor] = \
self.multi_graph.in_degree(successor) - multiplicity
if predecessor_count[successor] == 0:
next_layer.append(successor)
del predecessor_count[successor]
yield next_layer
cur_layer = next_layer
next_layer = []
def collect_runs(self, namelist):
"""Return a set of runs of "op" nodes with the given names.
For example, "... h q[0]; cx q[0],q[1]; cx q[0],q[1]; h q[1]; .."
would produce the tuple of cx nodes as an element of the set returned
from a call to collect_runs(["cx"]). If instead the cx nodes were
"cx q[0],q[1]; cx q[1],q[0];", the method would still return the
pair in a tuple. The namelist can contain names that are not
in the circuit's basis.
Nodes must have only one successor to continue the run.
"""
group_list = []
# Iterate through the nodes of self in topological order
# and form tuples containing sequences of gates
# on the same qubit(s).
tops_node = list(self.node_nums_in_topological_order())
nodes_seen = dict(zip(tops_node, [False] * len(tops_node)))
for node in tops_node:
nd = self.multi_graph.node[node]
if nd["type"] == "op" and nd["name"] in namelist \
and not nodes_seen[node]:
group = [node]
nodes_seen[node] = True
s = list(self.multi_graph.successors(node))
while len(s) == 1 and \
self.multi_graph.node[s[0]]["type"] == "op" and \
self.multi_graph.node[s[0]]["name"] in namelist:
group.append(s[0])
nodes_seen[s[0]] = True
s = list(self.multi_graph.successors(s[0]))
if len(group) > 1:
group_list.append(tuple(group))
return set(group_list)
def count_ops(self):
"""Count the occurrences of operation names.
Returns a dictionary of counts keyed on the operation name.
"""
op_dict = {}
for node in self.node_nums_in_topological_order():
nd = self.multi_graph.node[node]
name = nd["name"]
if nd["type"] == "op":
if name not in op_dict:
op_dict[name] = 1
else:
op_dict[name] += 1
return op_dict
def properties(self):
"""Return a dictionary of circuit properties."""
summary = {"size": self.size(),
"depth": self.depth(),
"width": self.width(),
"bits": self.num_cbits(),
"factors": self.num_tensor_factors(),
"operations": self.count_ops()}
return summary
<|code_end|>
qiskit/transpiler/passes/mapping/barrier_before_final_measurements.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
This pass adds a barrier before the set of final measurements. Measurements
are considered final if they are followed by no other operations (aside from
other measurements or barriers.)
A new barrier will not be added if an equivalent barrier is already present.
"""
from qiskit.extensions.standard.barrier import Barrier
from qiskit.transpiler._basepasses import TransformationPass
from qiskit.dagcircuit import DAGCircuit
class BarrierBeforeFinalMeasurements(TransformationPass):
"""Adds a barrier before final measurements."""
def run(self, dag):
"""Return a circuit with a barrier before last measurments."""
# Collect DAG nodes which are followed only by barriers or other measures.
final_op_types = ['measure', 'barrier']
final_ops = []
for candidate_op in dag.named_nodes(*final_op_types):
is_final_op = True
for _, child_successors in dag.bfs_successors(candidate_op):
if any(dag.multi_graph.node[suc]['type'] == 'op' and
dag.multi_graph.node[suc]['op'].name not in final_op_types
for suc in child_successors):
is_final_op = False
break
if is_final_op:
final_ops.append(candidate_op)
if not final_ops:
return dag
# Create a layer with the barrier and add registers from the original dag.
barrier_layer = DAGCircuit()
for qreg in dag.qregs.values():
barrier_layer.add_qreg(qreg)
for creg in dag.cregs.values():
barrier_layer.add_creg(creg)
final_qubits = set(dag.multi_graph.node[final_op]['qargs'][0]
for final_op in final_ops)
barrier_layer.apply_operation_back(Barrier(qubits=final_qubits))
new_barrier_id = barrier_layer.node_counter
# Preserve order of final ops collected earlier from the original DAG.
ordered_node_ids = [node_id for node_id in dag.node_nums_in_topological_order()
if node_id in set(final_ops)]
ordered_final_nodes = [dag.multi_graph.node[node] for node in ordered_node_ids]
# Move final ops to the new layer and append the new layer to the DAG.
for final_node in ordered_final_nodes:
barrier_layer.apply_operation_back(final_node['op'])
for final_op in final_ops:
dag._remove_op_node(final_op)
# Check to see if the new barrier added to the DAG is equivalent to any
# existing barriers, and if so, consolidate the two.
our_ancestors = barrier_layer.ancestors(new_barrier_id)
our_descendants = barrier_layer.descendants(new_barrier_id)
our_qubits = final_qubits
existing_barriers = barrier_layer.named_nodes('barrier')
existing_barriers.remove(new_barrier_id)
for candidate_barrier in existing_barriers:
their_ancestors = barrier_layer.ancestors(candidate_barrier)
their_descendants = barrier_layer.descendants(candidate_barrier)
their_qubits = set(barrier_layer.multi_graph.nodes[candidate_barrier]['op'].qargs)
if (
not our_qubits.isdisjoint(their_qubits)
and our_ancestors.isdisjoint(their_descendants)
and our_descendants.isdisjoint(their_ancestors)
):
merge_barrier = Barrier(qubits=(our_qubits | their_qubits))
barrier_layer.apply_operation_front(merge_barrier)
merge_barrier_id = barrier_layer.node_counter
our_ancestors = our_ancestors | their_ancestors
our_descendants = our_descendants | their_descendants
barrier_layer._remove_op_node(candidate_barrier)
barrier_layer._remove_op_node(new_barrier_id)
new_barrier_id = merge_barrier_id
dag.extend_back(barrier_layer)
return dag
<|code_end|>
|
qiskit/dagcircuit/_dagcircuit.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Object to represent a quantum circuit as a directed acyclic graph.
The nodes in the graph are either input/output nodes or operation nodes.
The edges correspond to qubits or bits in the circuit. A directed edge
from node A to node B means that the (qu)bit passes from the output of A
to the input of B. The object's methods allow circuits to be constructed,
composed, and modified. Some natural properties like depth can be computed
directly from the graph.
"""
import re
from collections import OrderedDict
import copy
import itertools
import warnings
import networkx as nx
from qiskit.circuit.quantumregister import QuantumRegister
from qiskit.circuit.classicalregister import ClassicalRegister
from qiskit.circuit.gate import Gate
from .exceptions import DAGCircuitError
class DAGCircuit:
"""
Quantum circuit as a directed acyclic graph.
There are 3 types of nodes in the graph: inputs, outputs, and operations.
The nodes are connected by directed edges that correspond to qubits and
bits.
"""
# pylint: disable=invalid-name
def __init__(self):
"""Create an empty circuit."""
# Circuit name. Generally, this corresponds to the name
# of the QuantumCircuit from which the DAG was generated.
self.name = None
# Set of wires (Register,idx) in the dag
self.wires = []
# Map from wire (Register,idx) to input nodes of the graph
self.input_map = OrderedDict()
# Map from wire (Register,idx) to output nodes of the graph
self.output_map = OrderedDict()
# Stores the max id of a node added to the DAG
self._max_node_id = 0
# Directed multigraph whose nodes are inputs, outputs, or operations.
# Operation nodes have equal in- and out-degrees and carry
# additional data about the operation, including the argument order
# and parameter values.
# Input nodes have out-degree 1 and output nodes have in-degree 1.
# Edges carry wire labels (reg,idx) and each operation has
# corresponding in- and out-edges with the same wire labels.
self.multi_graph = nx.MultiDiGraph()
# Map of qreg name to QuantumRegister object
self.qregs = OrderedDict()
# Map of creg name to ClassicalRegister object
self.cregs = OrderedDict()
def get_qubits(self):
"""Deprecated. Use qubits()."""
warnings.warn('The method get_qubits() is being replaced by qubits()',
DeprecationWarning, 2)
return self.qubits()
def qubits(self):
"""Return a list of qubits as (QuantumRegister, index) pairs."""
return [(v, i) for k, v in self.qregs.items() for i in range(v.size)]
def get_bits(self):
"""Deprecated. Use clbits()."""
warnings.warn('The method get_bits() is being replaced by clbits()',
DeprecationWarning, 2)
return self.clbits()
def clbits(self):
"""Return a list of bits as (ClassicalRegister, index) pairs."""
return [(v, i) for k, v in self.cregs.items() for i in range(v.size)]
@property
def node_counter(self):
"""Deprecated usage to return max node id, now returns size of DAG"""
warnings.warn('Usage of node_counter to return the maximum node id is deprecated,'
' it now returns the number of nodes in the current DAG',
DeprecationWarning, 2)
return len(self.multi_graph)
# TODO: unused function. is it needed?
def rename_register(self, regname, newname):
"""Rename a classical or quantum register throughout the circuit.
regname = existing register name string
newname = replacement register name string
"""
if regname == newname:
return
if newname in self.qregs or newname in self.cregs:
raise DAGCircuitError("duplicate register name %s" % newname)
if regname not in self.qregs and regname not in self.cregs:
raise DAGCircuitError("no register named %s" % regname)
if regname in self.qregs:
reg = self.qregs[regname]
reg.name = newname
self.qregs[newname] = reg
self.qregs.pop(regname, None)
if regname in self.cregs:
reg = self.cregs[regname]
reg.name = newname
self.qregs[newname] = reg
self.qregs.pop(regname, None)
# n node d = data
for _, d in self.multi_graph.nodes(data=True):
if d["type"] == "in" or d["type"] == "out":
if regname in d["name"]:
d["name"] = re.sub(regname, newname, d["name"])
elif d["type"] == "op":
qa = []
for a in d["qargs"]:
if a[0] == regname:
a = (newname, a[1])
qa.append(a)
d["qargs"] = qa
ca = []
for a in d["cargs"]:
if a[0] == regname:
a = (newname, a[1])
ca.append(a)
d["cargs"] = ca
if d["condition"] is not None:
if d["condition"][0] == regname:
d["condition"] = (newname, d["condition"][1])
# eX = edge, d= data
for _, _, d in self.multi_graph.edges(data=True):
if regname in d["name"]:
d["name"] = re.sub(regname, newname, d["name"])
def remove_all_ops_named(self, opname):
"""Remove all operation nodes with the given name."""
for n in self.named_nodes(opname):
self._remove_op_node(n)
def add_qreg(self, qreg):
"""Add all wires in a quantum register."""
if not isinstance(qreg, QuantumRegister):
raise DAGCircuitError("not a QuantumRegister instance.")
if qreg.name in self.qregs:
raise DAGCircuitError("duplicate register %s" % qreg.name)
self.qregs[qreg.name] = qreg
for j in range(qreg.size):
self._add_wire((qreg, j))
def add_creg(self, creg):
"""Add all wires in a classical register."""
if not isinstance(creg, ClassicalRegister):
raise DAGCircuitError("not a ClassicalRegister instance.")
if creg.name in self.cregs:
raise DAGCircuitError("duplicate register %s" % creg.name)
self.cregs[creg.name] = creg
for j in range(creg.size):
self._add_wire((creg, j))
def _add_wire(self, wire):
"""Add a qubit or bit to the circuit.
Args:
wire (tuple): (Register,int) containing a register instance and index
This adds a pair of in and out nodes connected by an edge.
Raises:
DAGCircuitError: if trying to add duplicate wire
"""
if wire not in self.wires:
self.wires.append(wire)
self._max_node_id += 1
self.input_map[wire] = self._max_node_id
self._max_node_id += 1
self.output_map[wire] = self._max_node_id
in_node = self.input_map[wire]
out_node = self.output_map[wire]
self.multi_graph.add_edge(in_node, out_node)
self.multi_graph.node[in_node]["type"] = "in"
self.multi_graph.node[out_node]["type"] = "out"
self.multi_graph.node[in_node]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.node[out_node]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.node[in_node]["wire"] = wire
self.multi_graph.node[out_node]["wire"] = wire
self.multi_graph.adj[in_node][out_node][0]["name"] = "%s[%s]" % (wire[0].name, wire[1])
self.multi_graph.adj[in_node][out_node][0]["wire"] = wire
else:
raise DAGCircuitError("duplicate wire %s" % (wire,))
def _check_condition(self, name, condition):
"""Verify that the condition is valid.
Args:
name (string): used for error reporting
condition (tuple or None): a condition tuple (ClassicalRegister,int)
Raises:
DAGCircuitError: if conditioning on an invalid register
"""
# Verify creg exists
if condition is not None and condition[0].name not in self.cregs:
raise DAGCircuitError("invalid creg in condition for %s" % name)
def _check_bits(self, args, amap):
"""Check the values of a list of (qu)bit arguments.
For each element of args, check that amap contains it.
Args:
args (list): (register,idx) tuples
amap (dict): a dictionary keyed on (register,idx) tuples
Raises:
DAGCircuitError: if a qubit is not contained in amap
"""
# Check for each wire
for wire in args:
if wire not in amap:
raise DAGCircuitError("(qu)bit %s[%d] not found" % (wire[0].name, wire[1]))
def _bits_in_condition(self, cond):
"""Return a list of bits in the given condition.
Args:
cond (tuple or None): optional condition (ClassicalRegister, int)
Returns:
list[(ClassicalRegister, idx)]: list of bits
"""
all_bits = []
if cond is not None:
all_bits.extend([(cond[0], j) for j in range(self.cregs[cond[0].name].size)])
return all_bits
def _add_op_node(self, op, qargs, cargs, condition=None):
"""Add a new operation node to the graph and assign properties.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list): list of quantum wires to attach to.
cargs (list): list of classical wires to attach to.
condition (tuple or None): optional condition (ClassicalRegister, int)
"""
# Add a new operation node to the graph
self._max_node_id += 1
self.multi_graph.add_node(self._max_node_id)
# Update the operation itself. TODO: remove after qargs not connected to op
op.qargs = qargs
op.cargs = cargs
# Update that operation node's data
self.multi_graph.node[self._max_node_id]["type"] = "op"
self.multi_graph.node[self._max_node_id]["op"] = op
self.multi_graph.node[self._max_node_id]["name"] = op.name
self.multi_graph.node[self._max_node_id]["qargs"] = qargs
self.multi_graph.node[self._max_node_id]["cargs"] = cargs
self.multi_graph.node[self._max_node_id]["condition"] = condition
def apply_operation_back(self, op, qargs=None, cargs=None, condition=None):
"""Apply an operation to the output of the circuit.
TODO: make `qargs` and `cargs` mandatory, when they are dropped from op.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple]): cbits that op will be applied to
condition (tuple or None): optional condition (ClassicalRegister, int)
Returns:
int: the current max node id
Raises:
DAGCircuitError: if a leaf node is connected to multiple outputs
"""
qargs = qargs or op.qargs
cargs = cargs or op.cargs
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_condition(op.name, condition)
self._check_bits(qargs, self.output_map)
self._check_bits(all_cbits, self.output_map)
self._add_op_node(op, qargs, cargs, condition)
# Add new in-edges from predecessors of the output nodes to the
# operation node while deleting the old in-edges of the output nodes
# and adding new edges from the operation node to each output node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.predecessors(self.output_map[q]))
if len(ie) != 1:
raise DAGCircuitError("output node has multiple in-edges")
self.multi_graph.add_edge(ie[0], self._max_node_id,
name="%s[%s]" % (q[0].name, q[1]), wire=q)
self.multi_graph.remove_edge(ie[0], self.output_map[q])
self.multi_graph.add_edge(self._max_node_id, self.output_map[q],
name="%s[%s]" % (q[0].name, q[1]), wire=q)
return self._max_node_id
def apply_operation_front(self, op, qargs=None, cargs=None, condition=None):
"""Apply an operation to the input of the circuit.
TODO: make `qargs` and `cargs` mandatory, when they are dropped from op.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple]): cbits that op will be applied to
condition (tuple or None): optional condition (ClassicalRegister, value)
Returns:
int: the current max node id
Raises:
DAGCircuitError: if initial nodes connected to multiple out edges
"""
qargs = qargs or op.qargs
cargs = cargs or op.cargs
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_condition(op.name, condition)
self._check_bits(qargs, self.input_map)
self._check_bits(all_cbits, self.input_map)
self._add_op_node(op, qargs, cargs, condition)
# Add new out-edges to successors of the input nodes from the
# operation node while deleting the old out-edges of the input nodes
# and adding new edges to the operation node from each input node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self.multi_graph.successors(self.input_map[q]))
if len(ie) != 1:
raise DAGCircuitError("input node has multiple out-edges")
self.multi_graph.add_edge(self._max_node_id, ie[0],
name="%s[%s]" % (q[0].name, q[1]), wire=q)
self.multi_graph.remove_edge(self.input_map[q], ie[0])
self.multi_graph.add_edge(self.input_map[q], self._max_node_id,
name="%s[%s]" % (q[0].name, q[1]), wire=q)
return self._max_node_id
def _check_edgemap_registers(self, edge_map, keyregs, valregs, valreg=True):
"""Check that wiremap neither fragments nor leaves duplicate registers.
1. There are no fragmented registers. A register in keyregs
is fragmented if not all of its (qu)bits are renamed by edge_map.
2. There are no duplicate registers. A register is duplicate if
it appears in both self and keyregs but not in edge_map.
Args:
edge_map (dict): map from (reg,idx) in keyregs to (reg,idx) in valregs
keyregs (dict): a map from register names to Register objects
valregs (dict): a map from register names to Register objects
valreg (bool): if False the method ignores valregs and does not
add regs for bits in the edge_map image that don't appear in valregs
Returns:
set(Register): the set of regs to add to self
Raises:
DAGCircuitError: if the wiremap fragments, or duplicates exist
"""
# FIXME: some mixing of objects and strings here are awkward (due to
# self.qregs/self.cregs still keying on string.
add_regs = set()
reg_frag_chk = {}
for v in keyregs.values():
reg_frag_chk[v] = {j: False for j in range(len(v))}
for k in edge_map.keys():
if k[0].name in keyregs:
reg_frag_chk[k[0]][k[1]] = True
for k, v in reg_frag_chk.items():
s = set(v.values())
if len(s) == 2:
raise DAGCircuitError("edge_map fragments reg %s" % k)
elif s == set([False]):
if k in self.qregs.values() or k in self.cregs.values():
raise DAGCircuitError("unmapped duplicate reg %s" % k)
else:
# Add registers that appear only in keyregs
add_regs.add(k)
else:
if valreg:
# If mapping to a register not in valregs, add it.
# (k,0) exists in edge_map because edge_map doesn't
# fragment k
if not edge_map[(k, 0)][0].name in valregs:
size = max(map(lambda x: x[1],
filter(lambda x: x[0] == edge_map[(k, 0)][0],
edge_map.values())))
qreg = QuantumRegister(size + 1, edge_map[(k, 0)][0].name)
add_regs.add(qreg)
return add_regs
def _check_wiremap_validity(self, wire_map, keymap, valmap):
"""Check that the wiremap is consistent.
Check that the wiremap refers to valid wires and that
those wires have consistent types.
Args:
wire_map (dict): map from (register,idx) in keymap to
(register,idx) in valmap
keymap (dict): a map whose keys are wire_map keys
valmap (dict): a map whose keys are wire_map values
Raises:
DAGCircuitError: if wire_map not valid
"""
for k, v in wire_map.items():
kname = "%s[%d]" % (k[0].name, k[1])
vname = "%s[%d]" % (v[0].name, v[1])
if k not in keymap:
raise DAGCircuitError("invalid wire mapping key %s" % kname)
if v not in valmap:
raise DAGCircuitError("invalid wire mapping value %s" % vname)
if type(k) is not type(v):
raise DAGCircuitError("inconsistent wire_map at (%s,%s)" %
(kname, vname))
def _map_condition(self, wire_map, condition):
"""Use the wire_map dict to change the condition tuple's creg name.
Args:
wire_map (dict): a map from wires to wires
condition (tuple): (ClassicalRegister,int)
Returns:
tuple(ClassicalRegister,int): new condition
"""
if condition is None:
new_condition = None
else:
# Map the register name, using fact that registers must not be
# fragmented by the wire_map (this must have been checked
# elsewhere)
bit0 = (condition[0], 0)
new_condition = (wire_map.get(bit0, bit0)[0], condition[1])
return new_condition
def extend_back(self, dag, edge_map=None):
"""Add `dag` at the end of `self`, using `edge_map`.
"""
edge_map = edge_map or {}
for qreg in dag.qregs.values():
if qreg.name not in self.qregs:
self.add_qreg(QuantumRegister(qreg.size, qreg.name))
edge_map.update([(qbit, qbit) for qbit in qreg if qbit not in edge_map])
for creg in dag.cregs.values():
if creg.name not in self.cregs:
self.add_creg(ClassicalRegister(creg.size, creg.name))
edge_map.update([(cbit, cbit) for cbit in creg if cbit not in edge_map])
self.compose_back(dag, edge_map)
def compose_back(self, input_circuit, edge_map=None):
"""Apply the input circuit to the output of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of input qubits of the input circuit are mapped
to a subset of output qubits of this circuit.
Args:
input_circuit (DAGCircuit): circuit to append
edge_map (dict): map {(Register, int): (Register, int)}
from the output wires of input_circuit to input wires
of self.
Raises:
DAGCircuitError: if missing, duplicate or incosistent wire
"""
edge_map = edge_map or {}
# Check the wire map for duplicate values
if len(set(edge_map.values())) != len(edge_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_edgemap_registers(edge_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(edge_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(edge_map, input_circuit.input_map,
self.output_map)
# Compose
for node in nx.topological_sort(input_circuit.multi_graph):
nd = input_circuit.multi_graph.node[node]
if nd["type"] == "in":
# if in wire_map, get new name, else use existing name
m_wire = edge_map.get(nd["wire"], nd["wire"])
# the mapped wire should already exist
if m_wire not in self.output_map:
raise DAGCircuitError("wire %s[%d] not in self" % (m_wire[0].name, m_wire[1]))
if nd["wire"] not in input_circuit.wires:
raise DAGCircuitError("inconsistent wire type for %s[%d] in input_circuit"
% (nd["wire"][0].name, nd["wire"][1]))
elif nd["type"] == "out":
# ignore output nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(edge_map, nd["condition"])
self._check_condition(nd["name"], condition)
m_qargs = list(map(lambda x: edge_map.get(x, x), nd["qargs"]))
m_cargs = list(map(lambda x: edge_map.get(x, x), nd["cargs"]))
self.apply_operation_back(nd["op"], m_qargs, m_cargs, condition)
else:
raise DAGCircuitError("bad node type %s" % nd["type"])
# FIXME: this does not work as expected. it is also not used anywhere
def compose_front(self, input_circuit, wire_map=None):
"""Apply the input circuit to the input of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of output qubits of the input circuit are mapped
to a subset of input qubits of this circuit.
Args:
input_circuit (DAGCircuit): circuit to append
wire_map (dict): map {(Register, int): (Register, int)}
from the output wires of input_circuit to input wires
of self.
Raises:
DAGCircuitError: missing, duplicate or inconsistent wire
"""
wire_map = wire_map or {}
# Check the wire map
if len(set(wire_map.values())) != len(wire_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_edgemap_registers(wire_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(wire_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(wire_map, input_circuit.output_map,
self.input_map)
# Compose
for n in reversed(list(nx.topological_sort(input_circuit.multi_graph))):
nd = input_circuit.multi_graph.node[n]
if nd["type"] == "out":
# if in wire_map, get new name, else use existing name
m_name = wire_map.get(nd["wire"], nd["wire"])
# the mapped wire should already exist
if m_name not in self.input_map:
raise DAGCircuitError("wire %s[%d] not in self" % (m_name[0].name, m_name[1]))
if nd["wire"] not in input_circuit.wires:
raise DAGCircuitError(
"inconsistent wire for %s[%d] in input_circuit"
% (nd["wire"][0].name, nd["wire"][1]))
elif nd["type"] == "in":
# ignore input nodes
pass
elif nd["type"] == "op":
condition = self._map_condition(wire_map, nd["condition"])
self._check_condition(nd["name"], condition)
self.apply_operation_front(nd["op"], condition)
else:
raise DAGCircuitError("bad node type %s" % nd["type"])
def size(self):
"""Return the number of operations."""
return self.multi_graph.order() - 2 * len(self.wires)
def depth(self):
"""Return the circuit depth.
Returns:
int: the circuit depth
Raises:
DAGCircuitError: if not a directed acyclic graph
"""
if not nx.is_directed_acyclic_graph(self.multi_graph):
raise DAGCircuitError("not a DAG")
return nx.dag_longest_path_length(self.multi_graph) - 1
def width(self):
"""Return the total number of qubits used by the circuit."""
return len(self.wires) - self.num_cbits()
def num_cbits(self):
"""Return the total number of bits used by the circuit."""
return sum(creg.size for creg in self.cregs.values())
def num_tensor_factors(self):
"""Compute how many components the circuit can decompose into."""
return nx.number_weakly_connected_components(self.multi_graph)
def qasm(self):
"""Deprecated. use qiskit.converters.dag_to_circuit() then call
qasm() on the obtained QuantumCircuit instance.
"""
warnings.warn('printing qasm() from DAGCircuit is deprecated. '
'use qiskit.converters.dag_to_circuit() then call '
'qasm() on the obtained QuantumCircuit instance.',
DeprecationWarning, 2)
def _check_wires_list(self, wires, op, input_circuit, condition=None):
"""Check that a list of wires satisfies some conditions.
- no duplicate names
- correct length for operation
- elements are wires of input_circuit
Raise an exception otherwise.
Args:
wires (list[register, index]): gives an order for (qu)bits
in the input_circuit that is replacing the operation.
op (Instruction): operation
input_circuit (DAGCircuit): replacement circuit for operation
condition (tuple or None): if this instance of the
operation is classically controlled by a (ClassicalRegister, int)
Raises:
DAGCircuitError: if check doesn't pass.
"""
if len(set(wires)) != len(wires):
raise DAGCircuitError("duplicate wires")
wire_tot = len(op.qargs) + len(op.cargs)
if condition is not None:
wire_tot += condition[0].size
if len(wires) != wire_tot:
raise DAGCircuitError("expected %d wires, got %d"
% (wire_tot, len(wires)))
for w in wires:
if w not in input_circuit.wires:
raise DAGCircuitError("wire (%s,%d) not in input circuit"
% (w[0], w[1]))
def _make_pred_succ_maps(self, n):
"""Return predecessor and successor dictionaries.
Args:
n (int): reference to self.multi_graph node id
Returns:
tuple(dict): tuple(predecessor_map, successor_map)
These map from wire (Register, int) to predecessor (successor)
nodes of n.
"""
pred_map = {e[2]['wire']: e[0] for e in
self.multi_graph.in_edges(nbunch=n, data=True)}
succ_map = {e[2]['wire']: e[1] for e in
self.multi_graph.out_edges(nbunch=n, data=True)}
return pred_map, succ_map
def _full_pred_succ_maps(self, pred_map, succ_map, input_circuit,
wire_map):
"""Map all wires of the input circuit.
Map all wires of the input circuit to predecessor and
successor nodes in self, keyed on wires in self.
Args:
pred_map (dict): comes from _make_pred_succ_maps
succ_map (dict): comes from _make_pred_succ_maps
input_circuit (DAGCircuit): the input circuit
wire_map (dict): the map from wires of input_circuit to wires of self
Returns:
tuple: full_pred_map, full_succ_map (dict, dict)
Raises:
DAGCircuitError: if more than one predecessor for output nodes
"""
full_pred_map = {}
full_succ_map = {}
for w in input_circuit.input_map:
# If w is wire mapped, find the corresponding predecessor
# of the node
if w in wire_map:
full_pred_map[wire_map[w]] = pred_map[wire_map[w]]
full_succ_map[wire_map[w]] = succ_map[wire_map[w]]
else:
# Otherwise, use the corresponding output nodes of self
# and compute the predecessor.
full_succ_map[w] = self.output_map[w]
full_pred_map[w] = self.multi_graph.predecessors(
self.output_map[w])[0]
if len(list(self.multi_graph.predecessors(self.output_map[w]))) != 1:
raise DAGCircuitError("too many predecessors for %s[%d] "
"output node" % (w[0], w[1]))
return full_pred_map, full_succ_map
@staticmethod
def _match_dag_nodes(node1, node2):
"""
Check if DAG nodes are considered equivalent, e.g. as a node_match for nx.is_isomorphic.
Args:
node1 (dict): A node to compare.
node2 (dict): The other node to compare.
Returns:
Bool: If node1 == node2
"""
copy_node1 = {k: v for (k, v) in node1.items()}
copy_node2 = {k: v for (k, v) in node2.items()}
# For barriers, qarg order is not significant so compare as sets
if 'barrier' == copy_node1['name'] == copy_node2['name']:
node1_qargs = set(copy_node1.pop('qargs', []))
node2_qargs = set(copy_node2.pop('qargs', []))
if node1_qargs != node2_qargs:
return False
return copy_node1 == copy_node2
def __eq__(self, other):
return nx.is_isomorphic(self.multi_graph, other.multi_graph,
node_match=DAGCircuit._match_dag_nodes)
def node_nums_in_topological_order(self):
"""
Returns the nodes (their ids) in topological order.
Returns:
list: The list of node numbers in topological order
"""
return nx.lexicographical_topological_sort(self.multi_graph)
def substitute_circuit_all(self, op, input_circuit, wires=None):
"""Replace every occurrence of operation op with input_circuit.
Args:
op (Instruction): operation type to substitute across the dag.
input_circuit (DAGCircuit): what to replace with
wires (list[register, index]): gives an order for (qu)bits
in the input_circuit that is replacing the operation.
Raises:
DAGCircuitError: if met with unexpected predecessor/successors
"""
# TODO: rewrite this method to call substitute_node_with_dag
wires = wires or []
self._check_wires_list(wires, op, input_circuit)
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: (QuantumRegister(1, 'proxy'), 0) for w in wires}
add_qregs = self._check_edgemap_registers(proxy_map,
input_circuit.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(proxy_map,
input_circuit.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Iterate through the nodes of self and replace the selected nodes
# by iterating through the input_circuit, constructing and
# checking the validity of the wire_map for each replacement
# NOTE: We do not replace conditioned gates. One way to implement
# this later is to add or update the conditions of each gate
# that we add from the input_circuit.
for n in self.node_nums_in_topological_order():
nd = self.multi_graph.node[n]
if nd["type"] == "op" and nd["op"] == op:
if nd["condition"] is None:
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"], nd["cargs"]]
for i in s])}
self._check_wiremap_validity(wire_map, wires,
self.input_map)
pred_map, succ_map = self._make_pred_succ_maps(n)
full_pred_map, full_succ_map = \
self._full_pred_succ_maps(pred_map, succ_map,
input_circuit, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(n)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_circuit.multi_graph):
md = input_circuit.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map,
md["condition"])
m_qargs = [wire_map.get(x, x) for x in md["qargs0"]]
m_cargs = [wire_map.get(x, x) for x in md["cargs0"]]
self._add_op_node(md["op"], m_qargs, m_cargs, condition)
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self._max_node_id,
name="%s[%s]" % (q[0].name, q[1]),
wire=q)
full_pred_map[q] = copy.copy(self._max_node_id)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w],
full_succ_map[w],
name="%s[%s]" % (w[0].name, w[1]),
wire=w)
o_pred = list(self.multi_graph.predecessors(
self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise DAGCircuitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise DAGCircuitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(
p[0], self.output_map[w])
def substitute_node_with_dag(self, node, input_dag, wires=None):
"""Replace one node with dag.
Args:
node (int): node of self.multi_graph (of type "op") to substitute
input_dag (DAGCircuit): circuit that will substitute the node
wires (list[(Register, index)]): gives an order for (qu)bits
in the input circuit. This order gets matched to the node wires
by qargs first, then cargs, then conditions.
Raises:
DAGCircuitError: if met with unexpected predecessor/successors
"""
nd = self.multi_graph.node[node]
condition = nd["condition"]
# the decomposition rule must be amended if used in a
# conditional context. delete the op nodes and replay
# them with the condition.
if condition:
input_dag.add_creg(condition[0])
to_replay = []
for n_it in nx.topological_sort(input_dag.multi_graph):
n = input_dag.multi_graph.nodes[n_it]
if n["type"] == "op":
n["op"].control = condition
to_replay.append(n)
for n in input_dag.op_nodes():
input_dag._remove_op_node(n)
for n in to_replay:
input_dag.apply_operation_back(n["op"], condition=condition)
if wires is None:
qwires = [w for w in input_dag.wires if isinstance(w[0], QuantumRegister)]
cwires = [w for w in input_dag.wires if isinstance(w[0], ClassicalRegister)]
wires = qwires + cwires
self._check_wires_list(wires, nd["op"], input_dag, nd["condition"])
# Create a proxy wire_map to identify fragments and duplicates
# and determine what registers need to be added to self
proxy_map = {w: QuantumRegister(1, 'proxy') for w in wires}
add_qregs = self._check_edgemap_registers(proxy_map,
input_dag.qregs,
{}, False)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(proxy_map,
input_dag.cregs,
{}, False)
for creg in add_cregs:
self.add_creg(creg)
# Replace the node by iterating through the input_circuit.
# Constructing and checking the validity of the wire_map.
# If a gate is conditioned, we expect the replacement subcircuit
# to depend on those control bits as well.
if nd["type"] != "op":
raise DAGCircuitError("expected node type \"op\", got %s"
% nd["type"])
condition_bit_list = self._bits_in_condition(nd["condition"])
wire_map = {k: v for k, v in zip(wires,
[i for s in [nd["qargs"],
nd["cargs"],
condition_bit_list]
for i in s])}
self._check_wiremap_validity(wire_map, wires, self.input_map)
pred_map, succ_map = self._make_pred_succ_maps(node)
full_pred_map, full_succ_map = self._full_pred_succ_maps(pred_map, succ_map,
input_dag, wire_map)
# Now that we know the connections, delete node
self.multi_graph.remove_node(node)
# Iterate over nodes of input_circuit
for m in nx.topological_sort(input_dag.multi_graph):
md = input_dag.multi_graph.node[m]
if md["type"] == "op":
# Insert a new node
condition = self._map_condition(wire_map, md["condition"])
m_qargs = list(map(lambda x: wire_map.get(x, x),
md["qargs"]))
m_cargs = list(map(lambda x: wire_map.get(x, x),
md["cargs"]))
self._add_op_node(md["op"], m_qargs, m_cargs, condition)
# Add edges from predecessor nodes to new node
# and update predecessor nodes that change
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(m_cargs)
al = [m_qargs, all_cbits]
for q in itertools.chain(*al):
self.multi_graph.add_edge(full_pred_map[q],
self._max_node_id,
name="%s[%s]" % (q[0].name, q[1]),
wire=q)
full_pred_map[q] = copy.copy(self._max_node_id)
# Connect all predecessors and successors, and remove
# residual edges between input and output nodes
for w in full_pred_map:
self.multi_graph.add_edge(full_pred_map[w],
full_succ_map[w],
name="%s[%s]" % (w[0].name, w[1]),
wire=w)
o_pred = list(self.multi_graph.predecessors(self.output_map[w]))
if len(o_pred) > 1:
if len(o_pred) != 2:
raise DAGCircuitError("expected 2 predecessors here")
p = [x for x in o_pred if x != full_pred_map[w]]
if len(p) != 1:
raise DAGCircuitError("expected 1 predecessor to pass filter")
self.multi_graph.remove_edge(p[0], self.output_map[w])
def get_op_nodes(self, op=None, data=False):
"""Deprecated. Use op_nodes()."""
warnings.warn('The method get_op_nodes() is being replaced by op_nodes()',
DeprecationWarning, 2)
return self.op_nodes(op, data)
def op_nodes(self, op=None, data=False):
"""Get the list of "op" nodes in the dag.
Args:
op (Type): Instruction subclass op nodes to return. if op=None, return
all op nodes.
data (bool): Default: False. If True, return a list of tuple
(node_id, node_data). If False, return a list of int (node_id)
Returns:
list: the list of node ids containing the given op.
"""
nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data["type"] == "op":
if op is None or isinstance(node_data["op"], op):
nodes.append((node_id, node_data))
if not data:
nodes = [n[0] for n in nodes]
return nodes
def get_gate_nodes(self, data=False):
"""Deprecated. Use gate_nodes()."""
warnings.warn('The method get_gate_nodes() is being replaced by gate_nodes()',
DeprecationWarning, 2)
return self.gate_nodes(data)
def gate_nodes(self, data=False):
"""Get the list of gate nodes in the dag.
Args:
data (bool): Default: False. If True, return a list of tuple
(node_id, node_data). If False, return a list of int (node_id)
Returns:
list: the list of node ids that represent gates.
"""
nodes = []
for node_id, node_data in self.op_nodes(data=True):
if isinstance(node_data['op'], Gate):
nodes.append((node_id, node_data))
if not data:
nodes = [n[0] for n in nodes]
return nodes
def get_named_nodes(self, *names):
"""Deprecated. Use named_nodes()."""
warnings.warn('The method get_named_nodes() is being replaced by named_nodes()',
DeprecationWarning, 2)
return self.named_nodes(*names)
def named_nodes(self, *names):
"""Get the set of "op" nodes with the given name."""
named_nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data['type'] == 'op' and node_data['op'].name in names:
named_nodes.append(node_id)
return named_nodes
def get_2q_nodes(self):
"""Deprecated. Use twoQ_nodes()."""
warnings.warn('The method get_2q_nodes() is being replaced by twoQ_nodes()',
DeprecationWarning, 2)
return self.twoQ_nodes()
def twoQ_nodes(self):
"""Get list of 2-qubit nodes."""
two_q_nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data['type'] == 'op' and len(node_data['qargs']) == 2:
two_q_nodes.append(self.multi_graph.node[node_id])
return two_q_nodes
def get_3q_or_more_nodes(self):
"""Deprecated. Use threeQ_or_more_nodes()."""
warnings.warn('The method get_3q_or_more_nodes() is being replaced by'
' threeQ_or_more_nodes()', DeprecationWarning, 2)
return self.threeQ_or_more_nodes()
def threeQ_or_more_nodes(self):
"""Get list of 3-or-more-qubit nodes: (id, data)."""
three_q_nodes = []
for node_id, node_data in self.multi_graph.nodes(data=True):
if node_data['type'] == 'op' and len(node_data['qargs']) >= 3:
three_q_nodes.append((node_id, self.multi_graph.node[node_id]))
return three_q_nodes
def successors(self, node):
"""Returns the successors of a node."""
return self.multi_graph.successors(node)
def ancestors(self, node):
"""Returns the ancestors of a node."""
return nx.ancestors(self.multi_graph, node)
def descendants(self, node):
"""Returns the descendants of a node."""
return nx.descendants(self.multi_graph, node)
def bfs_successors(self, node):
"""Returns successors of a node in BFS order"""
return nx.bfs_successors(self.multi_graph, node)
def quantum_successors(self, node):
"""Returns the successors of a node that are connected by a quantum edge"""
successors = []
for successor in self.successors(node):
if isinstance(self.multi_graph.get_edge_data(node, successor, key=0)['wire'][0],
QuantumRegister):
successors.append(successor)
return successors
def _remove_op_node(self, n):
"""Remove an operation node n.
Add edges from predecessors to successors.
"""
pred_map, succ_map = self._make_pred_succ_maps(n)
self.multi_graph.remove_node(n)
for w in pred_map.keys():
self.multi_graph.add_edge(pred_map[w], succ_map[w],
name="%s[%s]" % (w[0].name, w[1]), wire=w)
def remove_ancestors_of(self, node):
"""Remove all of the ancestor operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
# TODO: probably better to do all at once using
# multi_graph.remove_nodes_from; same for related functions ...
for n in anc:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_descendants_of(self, node):
"""Remove all of the descendant operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
for n in dec:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nonancestors_of(self, node):
"""Remove all of the non-ancestors operation nodes of node."""
anc = nx.ancestors(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(anc))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def remove_nondescendants_of(self, node):
"""Remove all of the non-descendants operation nodes of node."""
dec = nx.descendants(self.multi_graph, node)
comp = list(set(self.multi_graph.nodes()) - set(dec))
for n in comp:
nd = self.multi_graph.node[n]
if nd["type"] == "op":
self._remove_op_node(n)
def layers(self):
"""Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit.
A layer is a circuit whose gates act on disjoint qubits, i.e.
a layer has depth 1. The total number of layers equals the
circuit depth d. The layers are indexed from 0 to d-1 with the
earliest layer at index 0. The layers are constructed using a
greedy algorithm. Each returned layer is a dict containing
{"graph": circuit graph, "partition": list of qubit lists}.
TODO: Gates that use the same cbits will end up in different
layers as this is currently implemented. This may not be
the desired behavior.
"""
graph_layers = self.multigraph_layers()
try:
next(graph_layers) # Remove input nodes
except StopIteration:
return
def nodes_data(nodes):
"""Construct full nodes from just node ids."""
return ((node_id, self.multi_graph.nodes[node_id]) for node_id in nodes)
for graph_layer in graph_layers:
# Get the op nodes from the layer, removing any input and output nodes.
op_nodes = [node for node in nodes_data(graph_layer) if node[1]["type"] == "op"]
# Stop yielding once there are no more op_nodes in a layer.
if not op_nodes:
return
# Construct a shallow copy of self
new_layer = copy.copy(self)
new_layer.multi_graph = nx.MultiDiGraph()
new_layer.multi_graph.add_nodes_from(nodes_data(self.input_map.values()))
new_layer.multi_graph.add_nodes_from(nodes_data(self.output_map.values()))
# The quantum registers that have an operation in this layer.
support_list = [
op_node[1]["qargs"]
for op_node in op_nodes
if op_node[1]["op"].name not in {"barrier", "snapshot", "save", "load", "noise"}
]
new_layer.multi_graph.add_nodes_from(op_nodes)
# Now add the edges to the multi_graph
# By default we just wire inputs to the outputs.
wires = {self.input_map[wire]: self.output_map[wire]
for wire in self.wires}
# Wire inputs to op nodes, and op nodes to outputs.
for op_node in op_nodes:
args = self._bits_in_condition(op_node[1]["condition"]) \
+ op_node[1]["cargs"] + op_node[1]["qargs"]
arg_ids = (self.input_map[(arg[0], arg[1])] for arg in args)
for arg_id in arg_ids:
wires[arg_id], wires[op_node[0]] = op_node[0], wires[arg_id]
# Add wiring to/from the operations and between unused inputs & outputs.
new_layer.multi_graph.add_edges_from(wires.items())
yield {"graph": new_layer, "partition": support_list}
def serial_layers(self):
"""Yield a layer for all gates of this circuit.
A serial layer is a circuit with one gate. The layers have the
same structure as in layers().
"""
for n in self.node_nums_in_topological_order():
nxt_nd = self.multi_graph.node[n]
if nxt_nd["type"] == "op":
new_layer = DAGCircuit()
for qreg in self.qregs.values():
new_layer.add_qreg(qreg)
for creg in self.cregs.values():
new_layer.add_creg(creg)
# Save the support of the operation we add to the layer
support_list = []
# Operation data
op = copy.copy(nxt_nd["op"])
qa = copy.copy(nxt_nd["qargs"])
ca = copy.copy(nxt_nd["cargs"])
co = copy.copy(nxt_nd["condition"])
_ = self._bits_in_condition(co)
# Add node to new_layer
new_layer.apply_operation_back(op, qa, ca, co)
# Add operation to partition
if nxt_nd["name"] not in ["barrier",
"snapshot", "save", "load", "noise"]:
support_list.append(list(qa))
l_dict = {"graph": new_layer, "partition": support_list}
yield l_dict
def multigraph_layers(self):
"""Yield layers of the multigraph."""
predecessor_count = dict() # Dict[node, predecessors not visited]
cur_layer = [node for node in self.input_map.values()]
yield cur_layer
next_layer = []
while cur_layer:
for node in cur_layer:
# Count multiedges with multiplicity.
for successor in self.multi_graph.successors(node):
multiplicity = self.multi_graph.number_of_edges(node, successor)
if successor in predecessor_count:
predecessor_count[successor] -= multiplicity
else:
predecessor_count[successor] = \
self.multi_graph.in_degree(successor) - multiplicity
if predecessor_count[successor] == 0:
next_layer.append(successor)
del predecessor_count[successor]
yield next_layer
cur_layer = next_layer
next_layer = []
def collect_runs(self, namelist):
"""Return a set of runs of "op" nodes with the given names.
For example, "... h q[0]; cx q[0],q[1]; cx q[0],q[1]; h q[1]; .."
would produce the tuple of cx nodes as an element of the set returned
from a call to collect_runs(["cx"]). If instead the cx nodes were
"cx q[0],q[1]; cx q[1],q[0];", the method would still return the
pair in a tuple. The namelist can contain names that are not
in the circuit's basis.
Nodes must have only one successor to continue the run.
"""
group_list = []
# Iterate through the nodes of self in topological order
# and form tuples containing sequences of gates
# on the same qubit(s).
tops_node = list(self.node_nums_in_topological_order())
nodes_seen = dict(zip(tops_node, [False] * len(tops_node)))
for node in tops_node:
nd = self.multi_graph.node[node]
if nd["type"] == "op" and nd["name"] in namelist \
and not nodes_seen[node]:
group = [node]
nodes_seen[node] = True
s = list(self.multi_graph.successors(node))
while len(s) == 1 and \
self.multi_graph.node[s[0]]["type"] == "op" and \
self.multi_graph.node[s[0]]["name"] in namelist:
group.append(s[0])
nodes_seen[s[0]] = True
s = list(self.multi_graph.successors(s[0]))
if len(group) > 1:
group_list.append(tuple(group))
return set(group_list)
def count_ops(self):
"""Count the occurrences of operation names.
Returns a dictionary of counts keyed on the operation name.
"""
op_dict = {}
for node in self.node_nums_in_topological_order():
nd = self.multi_graph.node[node]
name = nd["name"]
if nd["type"] == "op":
if name not in op_dict:
op_dict[name] = 1
else:
op_dict[name] += 1
return op_dict
def properties(self):
"""Return a dictionary of circuit properties."""
summary = {"size": self.size(),
"depth": self.depth(),
"width": self.width(),
"bits": self.num_cbits(),
"factors": self.num_tensor_factors(),
"operations": self.count_ops()}
return summary
<|code_end|>
qiskit/transpiler/passes/mapping/barrier_before_final_measurements.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
This pass adds a barrier before the set of final measurements. Measurements
are considered final if they are followed by no other operations (aside from
other measurements or barriers.)
A new barrier will not be added if an equivalent barrier is already present.
"""
from qiskit.extensions.standard.barrier import Barrier
from qiskit.transpiler._basepasses import TransformationPass
from qiskit.dagcircuit import DAGCircuit
class BarrierBeforeFinalMeasurements(TransformationPass):
"""Adds a barrier before final measurements."""
def run(self, dag):
"""Return a circuit with a barrier before last measurments."""
# Collect DAG nodes which are followed only by barriers or other measures.
final_op_types = ['measure', 'barrier']
final_ops = []
for candidate_op in dag.named_nodes(*final_op_types):
is_final_op = True
for _, child_successors in dag.bfs_successors(candidate_op):
if any(dag.multi_graph.node[suc]['type'] == 'op' and
dag.multi_graph.node[suc]['op'].name not in final_op_types
for suc in child_successors):
is_final_op = False
break
if is_final_op:
final_ops.append(candidate_op)
if not final_ops:
return dag
# Create a layer with the barrier and add registers from the original dag.
barrier_layer = DAGCircuit()
for qreg in dag.qregs.values():
barrier_layer.add_qreg(qreg)
for creg in dag.cregs.values():
barrier_layer.add_creg(creg)
final_qubits = set(dag.multi_graph.node[final_op]['qargs'][0]
for final_op in final_ops)
new_barrier_id = barrier_layer.apply_operation_back(Barrier(qubits=final_qubits))
# Preserve order of final ops collected earlier from the original DAG.
ordered_node_ids = [node_id for node_id in dag.node_nums_in_topological_order()
if node_id in set(final_ops)]
ordered_final_nodes = [dag.multi_graph.node[node] for node in ordered_node_ids]
# Move final ops to the new layer and append the new layer to the DAG.
for final_node in ordered_final_nodes:
barrier_layer.apply_operation_back(final_node['op'])
for final_op in final_ops:
dag._remove_op_node(final_op)
# Check to see if the new barrier added to the DAG is equivalent to any
# existing barriers, and if so, consolidate the two.
our_ancestors = barrier_layer.ancestors(new_barrier_id)
our_descendants = barrier_layer.descendants(new_barrier_id)
our_qubits = final_qubits
existing_barriers = barrier_layer.named_nodes('barrier')
existing_barriers.remove(new_barrier_id)
for candidate_barrier in existing_barriers:
their_ancestors = barrier_layer.ancestors(candidate_barrier)
their_descendants = barrier_layer.descendants(candidate_barrier)
their_qubits = set(barrier_layer.multi_graph.nodes[candidate_barrier]['op'].qargs)
if (
not our_qubits.isdisjoint(their_qubits)
and our_ancestors.isdisjoint(their_descendants)
and our_descendants.isdisjoint(their_ancestors)
):
merge_barrier = Barrier(qubits=(our_qubits | their_qubits))
merge_barrier_id = barrier_layer.apply_operation_front(merge_barrier)
our_ancestors = our_ancestors | their_ancestors
our_descendants = our_descendants | their_descendants
barrier_layer._remove_op_node(candidate_barrier)
barrier_layer._remove_op_node(new_barrier_id)
new_barrier_id = merge_barrier_id
dag.extend_back(barrier_layer)
return dag
<|code_end|>
|
Unify basis_gates parameter handling (using a list)
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->
### What is the expected enhancement?
(I have the feeling there is already an issue for this topic but can't seem to find it - apologies if it ends up being a duplicated issue).
After #1323, the `basis_gates` for a backend is defined in its configuration as a list:
```
'basis_gates': ['u1', 'u2', 'u3', 'cx', 'id', 'snapshot']
```
Traditionally, we have been passing a comma-separated string around for the internal functions (throughout the transpiler layers), which is a tad ackward and cumbersome (specially since the final "consumers" of the basis gates end up splitting the string into a list, such as the `DAGBackend`).
Actually one of the changes in #1323 was actually to "stringify" back the basis gates [at the right point in the transpilation process](https://github.com/Qiskit/qiskit-terra/blob/master/qiskit/transpiler/_transpiler.py#L62), mostly for avoiding modifying the function signatures. It might be a good time to avoid that going back and forth entirely, making it always a list throughout the whole transpilation process.
### Proposed solution
Remove the default value for `basis_gates` in the functions involved in the transpilation process, updating the docstrings and ensuring that it is handled properly at the main entry point. A potential drawback is that we might need to change the format of the argument in the public `compile()` method, deprecating or similar (although might not be a concern if we mostly keep the change internal).
|
qiskit/tools/compiler.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Helper module for simplified Qiskit usage."""
import warnings
import logging
from qiskit import transpiler
from qiskit.converters import circuits_to_qobj
from qiskit.qobj import RunConfig
from qiskit.qobj import QobjHeader
from qiskit.mapper import Layout
logger = logging.getLogger(__name__)
# pylint: disable=redefined-builtin
def compile(circuits, backend,
config=None, basis_gates=None, coupling_map=None, initial_layout=None,
shots=1024, max_credits=10, seed=None, qobj_id=None, seed_mapper=None,
pass_manager=None, memory=False):
"""Compile a list of circuits into a qobj.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend): a backend to compile for
config (dict): dictionary of parameters (e.g. noise) used by runner
basis_gates (str): comma-separated basis gate set to compile to
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
shots (int): number of repetitions of each circuit, for sampling
max_credits (int): maximum credits to use
seed (int): random seed for simulators
seed_mapper (int): random seed for swapper mapper
qobj_id (int): identifier for the generated qobj
pass_manager (PassManager): a pass manger for the transpiler pipeline
memory (bool): if True, per-shot measurement bitstrings are returned as well
Returns:
Qobj: the qobj to be run on the backends
Raises:
QiskitError: if the desired options are not supported by backend
"""
if config:
warnings.warn('The `config` argument is deprecated and '
'does not do anything', DeprecationWarning)
if initial_layout is not None and not isinstance(initial_layout, Layout):
initial_layout = Layout(initial_layout)
circuits = transpiler.transpile(circuits, backend, basis_gates, coupling_map, initial_layout,
seed_mapper, pass_manager)
# step 4: Making a qobj
run_config = RunConfig()
if seed:
run_config.seed = seed
if shots:
run_config.shots = shots
if max_credits:
run_config.max_credits = max_credits
if memory:
run_config.memory = memory
qobj = circuits_to_qobj(circuits, user_qobj_header=QobjHeader(), run_config=run_config,
qobj_id=qobj_id)
return qobj
def execute(circuits, backend, config=None, basis_gates=None, coupling_map=None,
initial_layout=None, shots=1024, max_credits=10, seed=None,
qobj_id=None, seed_mapper=None, pass_manager=None,
memory=False, **kwargs):
"""Executes a set of circuits.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute
backend (BaseBackend): a backend to execute the circuits on
config (dict): dictionary of parameters (e.g. noise) used by runner
basis_gates (str): comma-separated basis gate set to compile to
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
shots (int): number of repetitions of each circuit, for sampling
max_credits (int): maximum credits to use
seed (int): random seed for simulators
seed_mapper (int): random seed for swapper mapper
qobj_id (int): identifier for the generated qobj
pass_manager (PassManager): a pass manger for the transpiler pipeline
memory (bool): if True, per-shot measurement bitstrings are returned as well.
kwargs: extra arguments used by AER for running configurable backends.
Refer to the backend documentation for details on these arguments
Returns:
BaseJob: returns job instance derived from BaseJob
"""
qobj = compile(circuits, backend,
config, basis_gates, coupling_map, initial_layout,
shots, max_credits, seed, qobj_id, seed_mapper,
pass_manager, memory)
return backend.run(qobj, **kwargs)
<|code_end|>
qiskit/transpiler/_transpiler.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Tools for compiling a batch of quantum circuits."""
import logging
from qiskit.circuit import QuantumCircuit
from qiskit.mapper import CouplingMap, swap_mapper
from qiskit.tools.parallel import parallel_map
from qiskit.converters import circuit_to_dag
from qiskit.converters import dag_to_circuit
from qiskit.extensions.standard import SwapGate
from qiskit.mapper import Layout
from .passes.cx_cancellation import CXCancellation
from .passes.decompose import Decompose
from .passes.optimize_1q_gates import Optimize1qGates
from .passes.mapping.barrier_before_final_measurements import BarrierBeforeFinalMeasurements
from .passes.mapping.check_map import CheckMap
from .passes.mapping.cx_direction import CXDirection
from .passes.mapping.dense_layout import DenseLayout
from .passes.mapping.trivial_layout import TrivialLayout
from .passes.mapping.unroller import Unroller
from .exceptions import TranspilerError
logger = logging.getLogger(__name__)
def transpile(circuits, backend=None, basis_gates=None, coupling_map=None,
initial_layout=None, seed_mapper=None, pass_manager=None):
"""transpile one or more circuits.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend): a backend to compile for
basis_gates (str): comma-separated basis gate set to compile to
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
seed_mapper (int): random seed for the swap_mapper
pass_manager (PassManager): a pass_manager for the transpiler stages
Returns:
QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s).
Raises:
TranspilerError: if args are not complete for the transpiler to function
"""
return_form_is_single = False
if isinstance(circuits, QuantumCircuit):
circuits = [circuits]
return_form_is_single = True
# Check for valid parameters for the experiments.
basis_gates = basis_gates or ','.join(backend.configuration().basis_gates)
coupling_map = coupling_map or getattr(backend.configuration(),
'coupling_map', None)
if not basis_gates:
raise TranspilerError('no basis_gates or backend to compile to')
circuits = parallel_map(_transpilation, circuits,
task_kwargs={'basis_gates': basis_gates,
'coupling_map': coupling_map,
'initial_layout': initial_layout,
'seed_mapper': seed_mapper,
'pass_manager': pass_manager})
if return_form_is_single:
return circuits[0]
return circuits
def _transpilation(circuit, basis_gates=None, coupling_map=None,
initial_layout=None, seed_mapper=None,
pass_manager=None):
"""Perform transpilation of a single circuit.
Args:
circuit (QuantumCircuit): A circuit to transpile.
basis_gates (str): comma-separated basis gate set to compile to
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
seed_mapper (int): random seed for the swap_mapper
pass_manager (PassManager): a pass_manager for the transpiler stage
Returns:
QuantumCircuit: A transpiled circuit.
Raises:
TranspilerError: if args are not complete for transpiler to function.
"""
if pass_manager and not pass_manager.working_list:
return circuit
dag = circuit_to_dag(circuit)
# pick a trivial layout if the circuit already satisfies the coupling constraints
# else layout on the most densely connected physical qubit subset
# FIXME: this should be simplified once it is ported to a PassManager
if coupling_map and initial_layout is None:
check_map = CheckMap(CouplingMap(coupling_map))
check_map.run(dag)
if check_map.property_set['is_direction_mapped']:
trivial_layout = TrivialLayout(CouplingMap(coupling_map))
trivial_layout.run(dag)
initial_layout = trivial_layout.property_set['layout']
else:
dense_layout = DenseLayout(CouplingMap(coupling_map))
dense_layout.run(dag)
initial_layout = dense_layout.property_set['layout']
# temporarily build old-style layout dict
# (TODO: remove after transition to StochasticSwap pass)
if isinstance(initial_layout, Layout):
layout = initial_layout.copy()
virtual_qubits = layout.get_virtual_bits()
initial_layout = {(v[0].name, v[1]): ('q', layout[v]) for v in virtual_qubits}
final_dag = transpile_dag(dag, basis_gates=basis_gates,
coupling_map=coupling_map,
initial_layout=initial_layout,
seed_mapper=seed_mapper,
pass_manager=pass_manager)
out_circuit = dag_to_circuit(final_dag)
return out_circuit
# pylint: disable=redefined-builtin
def transpile_dag(dag, basis_gates='u1,u2,u3,cx,id', coupling_map=None,
initial_layout=None, seed_mapper=None, pass_manager=None):
"""Transform a dag circuit into another dag circuit (transpile), through
consecutive passes on the dag.
Args:
dag (DAGCircuit): dag circuit to transform via transpilation
basis_gates (str): a comma separated string for the target basis gates
coupling_map (list): A graph of coupling::
[
[control0(int), target0(int)],
[control1(int), target1(int)],
]
eg. [[0, 2], [1, 2], [1, 3], [3, 4]}
initial_layout (dict): A mapping of qubit to qubit::
{
("q", start(int)): ("q", final(int)),
...
}
eg.
{
("q", 0): ("q", 0),
("q", 1): ("q", 1),
("q", 2): ("q", 2),
("q", 3): ("q", 3)
}
seed_mapper (int): random seed_mapper for the swap mapper
pass_manager (PassManager): pass manager instance for the transpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
DAGCircuit: transformed dag
"""
# TODO: `basis_gates` will be removed after we have the unroller pass.
# TODO: `coupling_map`, `initial_layout`, `seed_mapper` removed after mapper pass.
# TODO: move this to the mapper pass
num_qubits = sum([qreg.size for qreg in dag.qregs.values()])
if num_qubits == 1 or coupling_map == "all-to-all":
coupling_map = None
final_layout = None
if pass_manager:
# run the passes specified by the pass manager
# TODO return the property set too. See #1086
dag = pass_manager.run_passes(dag)
else:
# default set of passes
# TODO: move each step here to a pass, and use a default passmanager below
basis = basis_gates.split(',') if basis_gates else []
name = dag.name
dag = Unroller(basis).run(dag)
dag = BarrierBeforeFinalMeasurements().run(dag)
# if a coupling map is given compile to the map
if coupling_map:
logger.info("pre-mapping properties: %s",
dag.properties())
# Insert swap gates
coupling = CouplingMap(coupling_map)
logger.info("initial layout: %s", initial_layout)
dag, final_layout = swap_mapper(
dag, coupling, initial_layout, trials=20, seed=seed_mapper)
logger.info("final layout: %s", final_layout)
# Expand swaps
dag = Decompose(SwapGate).run(dag)
# Change cx directions
dag = CXDirection(coupling).run(dag)
# Simplify cx gates
dag = CXCancellation().run(dag)
# Unroll to the basis
dag = Unroller(['u1', 'u2', 'u3', 'id', 'cx']).run(dag)
# Simplify single qubit gates
dag = Optimize1qGates().run(dag)
logger.info("post-mapping properties: %s",
dag.properties())
dag.name = name
return dag
<|code_end|>
|
qiskit/tools/compiler.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Helper module for simplified Qiskit usage."""
import warnings
import logging
from qiskit import transpiler
from qiskit.converters import circuits_to_qobj
from qiskit.qobj import RunConfig
from qiskit.qobj import QobjHeader
from qiskit.mapper import Layout
logger = logging.getLogger(__name__)
# pylint: disable=redefined-builtin
def compile(circuits, backend,
config=None, basis_gates=None, coupling_map=None, initial_layout=None,
shots=1024, max_credits=10, seed=None, qobj_id=None, seed_mapper=None,
pass_manager=None, memory=False):
"""Compile a list of circuits into a qobj.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend): a backend to compile for
config (dict): dictionary of parameters (e.g. noise) used by runner
basis_gates (list[str]): list of basis gates names supported by the
target. Default: ['u1','u2','u3','cx','id']
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
shots (int): number of repetitions of each circuit, for sampling
max_credits (int): maximum credits to use
seed (int): random seed for simulators
seed_mapper (int): random seed for swapper mapper
qobj_id (int): identifier for the generated qobj
pass_manager (PassManager): a pass manger for the transpiler pipeline
memory (bool): if True, per-shot measurement bitstrings are returned as well
Returns:
Qobj: the qobj to be run on the backends
Raises:
QiskitError: if the desired options are not supported by backend
"""
if config:
warnings.warn('The `config` argument is deprecated and '
'does not do anything', DeprecationWarning)
if initial_layout is not None and not isinstance(initial_layout, Layout):
initial_layout = Layout(initial_layout)
circuits = transpiler.transpile(circuits, backend, basis_gates, coupling_map, initial_layout,
seed_mapper, pass_manager)
# step 4: Making a qobj
run_config = RunConfig()
if seed:
run_config.seed = seed
if shots:
run_config.shots = shots
if max_credits:
run_config.max_credits = max_credits
if memory:
run_config.memory = memory
qobj = circuits_to_qobj(circuits, user_qobj_header=QobjHeader(), run_config=run_config,
qobj_id=qobj_id)
return qobj
def execute(circuits, backend, config=None, basis_gates=None, coupling_map=None,
initial_layout=None, shots=1024, max_credits=10, seed=None,
qobj_id=None, seed_mapper=None, pass_manager=None,
memory=False, **kwargs):
"""Executes a set of circuits.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute
backend (BaseBackend): a backend to execute the circuits on
config (dict): dictionary of parameters (e.g. noise) used by runner
basis_gates (list[str]): list of basis gate names supported by the
target. Default: ['u1','u2','u3','cx','id']
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
shots (int): number of repetitions of each circuit, for sampling
max_credits (int): maximum credits to use
seed (int): random seed for simulators
seed_mapper (int): random seed for swapper mapper
qobj_id (int): identifier for the generated qobj
pass_manager (PassManager): a pass manger for the transpiler pipeline
memory (bool): if True, per-shot measurement bitstrings are returned as well.
kwargs: extra arguments used by AER for running configurable backends.
Refer to the backend documentation for details on these arguments
Returns:
BaseJob: returns job instance derived from BaseJob
"""
qobj = compile(circuits, backend,
config, basis_gates, coupling_map, initial_layout,
shots, max_credits, seed, qobj_id, seed_mapper,
pass_manager, memory)
return backend.run(qobj, **kwargs)
<|code_end|>
qiskit/transpiler/_transpiler.py
<|code_start|># -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Tools for compiling a batch of quantum circuits."""
import logging
import warnings
from qiskit.circuit import QuantumCircuit
from qiskit.mapper import CouplingMap, swap_mapper
from qiskit.tools.parallel import parallel_map
from qiskit.converters import circuit_to_dag
from qiskit.converters import dag_to_circuit
from qiskit.extensions.standard import SwapGate
from qiskit.mapper import Layout
from .passes.cx_cancellation import CXCancellation
from .passes.decompose import Decompose
from .passes.optimize_1q_gates import Optimize1qGates
from .passes.mapping.barrier_before_final_measurements import BarrierBeforeFinalMeasurements
from .passes.mapping.check_map import CheckMap
from .passes.mapping.cx_direction import CXDirection
from .passes.mapping.dense_layout import DenseLayout
from .passes.mapping.trivial_layout import TrivialLayout
from .passes.mapping.unroller import Unroller
from .exceptions import TranspilerError
logger = logging.getLogger(__name__)
def transpile(circuits, backend=None, basis_gates=None, coupling_map=None,
initial_layout=None, seed_mapper=None, pass_manager=None):
"""transpile one or more circuits.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend): a backend to compile for
basis_gates (list[str]): list of basis gate names supported by the
target. Default: ['u1','u2','u3','cx','id']
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
seed_mapper (int): random seed for the swap_mapper
pass_manager (PassManager): a pass_manager for the transpiler stages
Returns:
QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s).
Raises:
TranspilerError: if args are not complete for the transpiler to function
"""
return_form_is_single = False
if isinstance(circuits, QuantumCircuit):
circuits = [circuits]
return_form_is_single = True
# Check for valid parameters for the experiments.
basis_gates = basis_gates or backend.configuration().basis_gates
coupling_map = coupling_map or getattr(backend.configuration(),
'coupling_map', None)
if not basis_gates:
raise TranspilerError('no basis_gates or backend to compile to')
circuits = parallel_map(_transpilation, circuits,
task_kwargs={'basis_gates': basis_gates,
'coupling_map': coupling_map,
'initial_layout': initial_layout,
'seed_mapper': seed_mapper,
'pass_manager': pass_manager})
if return_form_is_single:
return circuits[0]
return circuits
def _transpilation(circuit, basis_gates=None, coupling_map=None,
initial_layout=None, seed_mapper=None,
pass_manager=None):
"""Perform transpilation of a single circuit.
Args:
circuit (QuantumCircuit): A circuit to transpile.
basis_gates (list[str]): list of basis gate names supported by the
target. Default: ['u1','u2','u3','cx','id']
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
seed_mapper (int): random seed for the swap_mapper
pass_manager (PassManager): a pass_manager for the transpiler stage
Returns:
QuantumCircuit: A transpiled circuit.
Raises:
TranspilerError: if args are not complete for transpiler to function.
"""
if pass_manager and not pass_manager.working_list:
return circuit
dag = circuit_to_dag(circuit)
# pick a trivial layout if the circuit already satisfies the coupling constraints
# else layout on the most densely connected physical qubit subset
# FIXME: this should be simplified once it is ported to a PassManager
if coupling_map and initial_layout is None:
check_map = CheckMap(CouplingMap(coupling_map))
check_map.run(dag)
if check_map.property_set['is_direction_mapped']:
trivial_layout = TrivialLayout(CouplingMap(coupling_map))
trivial_layout.run(dag)
initial_layout = trivial_layout.property_set['layout']
else:
dense_layout = DenseLayout(CouplingMap(coupling_map))
dense_layout.run(dag)
initial_layout = dense_layout.property_set['layout']
# temporarily build old-style layout dict
# (TODO: remove after transition to StochasticSwap pass)
if isinstance(initial_layout, Layout):
layout = initial_layout.copy()
virtual_qubits = layout.get_virtual_bits()
initial_layout = {(v[0].name, v[1]): ('q', layout[v]) for v in virtual_qubits}
final_dag = transpile_dag(dag, basis_gates=basis_gates,
coupling_map=coupling_map,
initial_layout=initial_layout,
seed_mapper=seed_mapper,
pass_manager=pass_manager)
out_circuit = dag_to_circuit(final_dag)
return out_circuit
# pylint: disable=redefined-builtin
def transpile_dag(dag, basis_gates=None, coupling_map=None,
initial_layout=None, seed_mapper=None, pass_manager=None):
"""Transform a dag circuit into another dag circuit (transpile), through
consecutive passes on the dag.
Args:
dag (DAGCircuit): dag circuit to transform via transpilation
basis_gates (list[str]): list of basis gate names supported by the
target. Default: ['u1','u2','u3','cx','id']
coupling_map (list): A graph of coupling::
[
[control0(int), target0(int)],
[control1(int), target1(int)],
]
eg. [[0, 2], [1, 2], [1, 3], [3, 4]}
initial_layout (dict): A mapping of qubit to qubit::
{
("q", start(int)): ("q", final(int)),
...
}
eg.
{
("q", 0): ("q", 0),
("q", 1): ("q", 1),
("q", 2): ("q", 2),
("q", 3): ("q", 3)
}
seed_mapper (int): random seed_mapper for the swap mapper
pass_manager (PassManager): pass manager instance for the transpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
DAGCircuit: transformed dag
"""
# TODO: `basis_gates` will be removed after we have the unroller pass.
# TODO: `coupling_map`, `initial_layout`, `seed_mapper` removed after mapper pass.
# TODO: move this to the mapper pass
num_qubits = sum([qreg.size for qreg in dag.qregs.values()])
if num_qubits == 1 or coupling_map == "all-to-all":
coupling_map = None
if basis_gates is None:
basis_gates = ['u1', 'u2', 'u3', 'cx', 'id']
if isinstance(basis_gates, str):
warnings.warn("The parameter basis_gates is now a list of strings. "
"For example, this basis ['u1','u2','u3','cx'] should be used "
"instead of 'u1,u2,u3,cx'. The string format will be "
"removed after 0.9", DeprecationWarning, 2)
basis_gates = basis_gates.split(',')
if pass_manager:
# run the passes specified by the pass manager
# TODO return the property set too. See #1086
dag = pass_manager.run_passes(dag)
else:
# default set of passes
# TODO: move each step here to a pass, and use a default passmanager below
name = dag.name
dag = Unroller(basis_gates).run(dag)
dag = BarrierBeforeFinalMeasurements().run(dag)
# if a coupling map is given compile to the map
if coupling_map:
logger.info("pre-mapping properties: %s",
dag.properties())
# Insert swap gates
coupling = CouplingMap(coupling_map)
logger.info("initial layout: %s", initial_layout)
dag, final_layout = swap_mapper(
dag, coupling, initial_layout, trials=20, seed=seed_mapper)
logger.info("final layout: %s", final_layout)
# Expand swaps
dag = Decompose(SwapGate).run(dag)
# Change cx directions
dag = CXDirection(coupling).run(dag)
# Simplify cx gates
dag = CXCancellation().run(dag)
# Unroll to the basis
dag = Unroller(['u1', 'u2', 'u3', 'id', 'cx']).run(dag)
# Simplify single qubit gates
dag = Optimize1qGates().run(dag)
logger.info("post-mapping properties: %s",
dag.properties())
dag.name = name
return dag
<|code_end|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.