Search is not available for this dataset
text stringlengths 75 104k |
|---|
def _stinespring_to_kraus(data, input_dim, output_dim):
"""Transform Stinespring representation to Kraus representation."""
kraus_pair = []
for stine in data:
if stine is None:
kraus_pair.append(None)
else:
trace_dim = stine.shape[0] // output_dim
iden = n... |
def _stinespring_to_choi(data, input_dim, output_dim):
"""Transform Stinespring representation to Choi representation."""
trace_dim = data[0].shape[0] // output_dim
stine_l = np.reshape(data[0], (output_dim, trace_dim, input_dim))
if data[1] is None:
stine_r = stine_l
else:
stine_r =... |
def _kraus_to_stinespring(data, input_dim, output_dim):
"""Transform Kraus representation to Stinespring representation."""
stine_pair = [None, None]
for i, kraus in enumerate(data):
if kraus is not None:
num_kraus = len(kraus)
stine = np.zeros((output_dim * num_kraus, input_... |
def _kraus_to_superop(data, input_dim, output_dim):
"""Transform Kraus representation to SuperOp representation."""
kraus_l, kraus_r = data
superop = 0
if kraus_r is None:
for i in kraus_l:
superop += np.kron(np.conj(i), i)
else:
for i, j in zip(kraus_l, kraus_r):
... |
def _chi_to_choi(data, input_dim, output_dim):
"""Transform Chi representation to a Choi representation."""
num_qubits = int(np.log2(input_dim))
return _transform_from_pauli(data, num_qubits) |
def _choi_to_chi(data, input_dim, output_dim):
"""Transform Choi representation to the Chi representation."""
num_qubits = int(np.log2(input_dim))
return _transform_to_pauli(data, num_qubits) |
def _bipartite_tensor(mat1, mat2, shape1=None, shape2=None):
"""Tensor product (A β B) to bipartite matrices and reravel indicies.
This is used for tensor product of superoperators and Choi matrices.
Args:
mat1 (matrix_like): a bipartite matrix A
mat2 (matrix_like): a bipartite matrix B
... |
def _reravel(mat1, mat2, shape1, shape2):
"""Reravel two bipartite matrices."""
# Reshuffle indicies
left_dims = shape1[:2] + shape2[:2]
right_dims = shape1[2:] + shape2[2:]
tensor_shape = left_dims + right_dims
final_shape = (np.product(left_dims), np.product(right_dims))
# Tensor product m... |
def _transform_from_pauli(data, num_qubits):
"""Change of basis of bipartite matrix represenation."""
# Change basis: sum_{i=0}^3 =|\sigma_i>><i|
basis_mat = np.array(
[[1, 0, 0, 1], [0, 1, 1j, 0], [0, 1, -1j, 0], [1, 0j, 0, -1]],
dtype=complex)
# Note that we manually renormalized after... |
def _reshuffle(mat, shape):
"""Reshuffle the indicies of a bipartite matrix A[ij,kl] -> A[lj,ki]."""
return np.reshape(
np.transpose(np.reshape(mat, shape), (3, 1, 2, 0)),
(shape[3] * shape[1], shape[0] * shape[2])) |
def _check_nqubit_dim(input_dim, output_dim):
"""Return true if dims correspond to an n-qubit channel."""
if input_dim != output_dim:
raise QiskitError(
'Not an n-qubit channel: input_dim' +
' ({}) != output_dim ({})'.format(input_dim, output_dim))
num_qubits = int(np.log2(in... |
def _hide_tick_lines_and_labels(axis):
"""
Set visible property of ticklines and ticklabels of an axis to False
"""
for item in axis.get_ticklines() + axis.get_ticklabels():
item.set_visible(False) |
def set_label_convention(self, convention):
"""Set x, y and z labels according to one of conventions.
Args:
convention (str):
One of the following:
- "original"
- "xyz"
- "sx sy sz"
- "01"
... |
def clear(self):
"""Resets Bloch sphere data sets to empty.
"""
self.points = []
self.vectors = []
self.point_style = []
self.annotations = [] |
def add_points(self, points, meth='s'):
"""Add a list of data points to bloch sphere.
Args:
points (array_like):
Collection of data points.
meth (str):
Type of points to plot, use 'm' for multicolored, 'l' for points
connected with ... |
def add_vectors(self, vectors):
"""Add a list of vectors to Bloch sphere.
Args:
vectors (array_like):
Array with vectors of unit length or smaller.
"""
if isinstance(vectors[0], (list, np.ndarray)):
for vec in vectors:
self.vectors... |
def add_annotation(self, state_or_vector, text, **kwargs):
"""Add a text or LaTeX annotation to Bloch sphere,
parametrized by a qubit state or a vector.
Args:
state_or_vector (array_like):
Position for the annotation.
Qobj of a qubit or a vector of 3 ... |
def render(self, title=''):
"""
Render the Bloch sphere and its data sets in on given figure and axes.
"""
if self._rendered:
self.axes.clear()
self._rendered = True
# Figure instance for Bloch sphere plot
if not self._ext_fig:
self.fig =... |
def plot_front(self):
"""front half of sphere"""
u_angle = np.linspace(-np.pi, 0, 25)
v_angle = np.linspace(0, np.pi, 25)
x_dir = np.outer(np.cos(u_angle), np.sin(v_angle))
y_dir = np.outer(np.sin(u_angle), np.sin(v_angle))
z_dir = np.outer(np.ones(u_angle.shape[0]), np.c... |
def plot_axes(self):
"""axes"""
span = np.linspace(-1.0, 1.0, 2)
self.axes.plot(span, 0 * span, zs=0, zdir='z', label='X',
lw=self.frame_width, color=self.frame_color)
self.axes.plot(0 * span, span, zs=0, zdir='z', label='Y',
lw=self.frame_wi... |
def plot_axes_labels(self):
"""axes labels"""
opts = {'fontsize': self.font_size,
'color': self.font_color,
'horizontalalignment': 'center',
'verticalalignment': 'center'}
self.axes.text(0, -self.xlpos[0], 0, self.xlabel[0], **opts)
self.ax... |
def plot_vectors(self):
"""Plot vector"""
# -X and Y data are switched for plotting purposes
for k in range(len(self.vectors)):
xs3d = self.vectors[k][1] * np.array([0, 1])
ys3d = -self.vectors[k][0] * np.array([0, 1])
zs3d = self.vectors[k][2] * np.array([0,... |
def plot_points(self):
"""Plot points"""
# -X and Y data are switched for plotting purposes
for k in range(len(self.points)):
num = len(self.points[k][0])
dist = [np.sqrt(self.points[k][0][j] ** 2 +
self.points[k][1][j] ** 2 +
... |
def plot_annotations(self):
"""Plot annotations"""
# -X and Y data are switched for plotting purposes
for annotation in self.annotations:
vec = annotation['position']
opts = {'fontsize': self.font_size,
'color': self.font_color,
'ho... |
def show(self, title=''):
"""
Display Bloch sphere and corresponding data sets.
"""
self.render(title=title)
if self.fig:
plt.show(self.fig) |
def save(self, name=None, output='png', dirc=None):
"""Saves Bloch sphere to file of type ``format`` in directory ``dirc``.
Args:
name (str):
Name of saved image. Must include path and format as well.
i.e. '/Users/Paul/Desktop/bloch.png'
This o... |
def two_qubit_kak(unitary_matrix, verify_gate_sequence=False):
"""Deprecated after 0.8
"""
warnings.warn("two_qubit_kak function is now accessible under "
"qiskit.quantum_info.synthesis", DeprecationWarning)
return synthesis.two_qubit_kak(unitary_matrix) |
def top(self):
""" Constructs the top line of the element"""
ret = self.top_format % self.top_connect.center(
self.width, 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... |
def mid(self):
""" Constructs the middle line of the element"""
ret = self.mid_format % self.mid_content.center(
self.width, self._mid_padding)
if self.right_fill:
ret = ret.ljust(self.right_fill, self._mid_padding)
if self.left_fill:
ret = ret.rjust(s... |
def bot(self):
""" Constructs the bottom line of the element"""
ret = self.bot_format % self.bot_connect.center(
self.width, 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_f... |
def length(self):
""" Returns the length of the element, including the box around."""
return max(len(self.top), len(self.mid), len(self.bot)) |
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 ... |
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_leng... |
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... |
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.
... |
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... |
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... |
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
... |
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 wir... |
def draw_wires(wires, vertically_compressed=True):
"""
Given a list of wires, creates a list of lines with the text drawing.
Args:
wires (list): A list of wires with instructions.
vertically_compressed (bool): Default is `True`. It merges the lines
... |
def params_for_label(instruction):
"""Get the params and format them to add them to a label. None if there
are no params of if the params are numpy.ndarrays."""
if not hasattr(instruction.op, 'params'):
return None
if all([isinstance(param, ndarray) for param in instruction... |
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 |
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"... |
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... |
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 build_layers(self):
"""
Constructs layers.
Returns:
list: List of DrawElements.
Raises:
VisualizationError: When the drawing is, for some reason, impossible to be drawn.
"""
wire_names = self.wire_names(with_initial_value=True)
if not w... |
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_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.
... |
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
... |
def latex(self, prec=15, nested_scope=None):
"""Return the correspond math mode latex string."""
if not nested_scope:
return "\textrm{" + self.name + "}"
else:
if self.name not in nested_scope[-1]:
raise NodeException("Expected local parameter name: ",
... |
def sym(self, nested_scope=None):
"""Return the correspond symbolic number."""
if not nested_scope or self.name not in nested_scope[-1]:
raise NodeException("Expected local parameter name: ",
"name=%s, line=%s, file=%s" % (
... |
def real(self, nested_scope=None):
"""Return the correspond floating point number."""
if not nested_scope or self.name not in nested_scope[-1]:
raise NodeException("Expected local parameter name: ",
"name=%s, line=%s, file=%s" % (
... |
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 (Q... |
def _filter_deprecation_warnings():
"""Apply filters to 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. Additionally, silence the `ChangedInMarshmallow3Warning`
... |
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 = {
... |
def _has_connection(hostname, port):
"""Checks 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:
b... |
def compose(self, other, qargs=None, front=False):
"""Return the composition channel selfβother.
Args:
other (QuantumChannel): a quantum channel.
qargs (list): a list of subsystem positions to compose other on.
front (bool): If False compose in standard order other(s... |
def power(self, n):
"""The matrix power of the channel.
Args:
n (int): compute the matrix power of the superoperator matrix.
Returns:
PTM: the matrix power of the SuperOp converted to a PTM channel.
Raises:
QiskitError: if the input and output dimen... |
def _html_checker(job_var, interval, status, header,
_interval_set=False):
"""Internal function that updates the status
of a HTML job monitor.
Args:
job_var (BaseJob): The job to keep track of.
interval (int): The status check interval
status (widget): HTML ipywidg... |
def constant(times: np.ndarray, amp: complex) -> np.ndarray:
"""Continuous constant pulse.
Args:
times: Times to output pulse for.
amp: Complex pulse amplitude.
"""
return np.full(len(times), amp, dtype=np.complex_) |
def square(times: np.ndarray, amp: complex, period: float, phase: float = 0) -> np.ndarray:
"""Continuous square wave.
Args:
times: Times to output wave for.
amp: Pulse amplitude. Wave range is [-amp, amp].
period: Pulse period, units of dt.
phase: Pulse phase.
"""
x = t... |
def triangle(times: np.ndarray, amp: complex, period: float, phase: float = 0) -> np.ndarray:
"""Continuous triangle wave.
Args:
times: Times to output wave for.
amp: Pulse amplitude. Wave range is [-amp, amp].
period: Pulse period, units of dt.
phase: Pulse phase.
"""
r... |
def cos(times: np.ndarray, amp: complex, freq: float, phase: float = 0) -> np.ndarray:
"""Continuous cosine wave.
Args:
times: Times to output wave for.
amp: Pulse amplitude.
freq: Pulse frequency, units of 1/dt.
phase: Pulse phase.
"""
return amp*np.cos(2*np.pi*freq*tim... |
def _fix_gaussian_width(gaussian_samples, amp: float, center: float, sigma: float,
zeroed_width: Union[None, float] = None, rescale_amp: bool = False,
ret_scale_factor: bool = False) -> np.ndarray:
r"""Enforce that the supplied gaussian pulse is zeroed at a specific w... |
def gaussian(times: np.ndarray, amp: complex, center: float, sigma: float,
zeroed_width: Union[None, float] = None, rescale_amp: bool = False,
ret_x: bool = False) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]:
r"""Continuous unnormalized gaussian pulse.
Integrated area under cu... |
def gaussian_deriv(times: np.ndarray, amp: complex, center: float, sigma: float,
ret_gaussian: bool = False) -> np.ndarray:
"""Continuous unnormalized gaussian derivative pulse.
Args:
times: Times to output pulse for.
amp: Pulse amplitude at `center`.
center: Center (... |
def gaussian_square(times: np.ndarray, amp: complex, center: float, width: float,
sigma: float, zeroed_width: Union[None, float] = None) -> np.ndarray:
r"""Continuous gaussian square pulse.
Args:
times: Times to output pulse for.
amp: Pulse amplitude.
center: Center ... |
def drag(times: np.ndarray, amp: complex, center: float, sigma: float, beta: float,
zeroed_width: Union[None, float] = None, rescale_amp: bool = False) -> np.ndarray:
r"""Continuous Y-only correction DRAG pulse for standard nonlinear oscillator (SNO) [1].
[1] Gambetta, J. M., Motzoi, F., Merkel, S. T.... |
def default_pass_manager(basis_gates, coupling_map, initial_layout, seed_transpiler):
"""
The default pass manager that maps to the coupling map.
Args:
basis_gates (list[str]): list of basis gate names supported by the target.
coupling_map (CouplingMap): coupling map to target in mapping.
... |
def default_pass_manager_simulator(basis_gates):
"""
The default pass manager without a coupling map.
Args:
basis_gates (list[str]): list of basis gate names to unroll to.
Returns:
PassManager: A passmanager that just unrolls, without any optimization.
"""
pass_manager = PassMa... |
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 (isinstanc... |
def mirror(self):
"""Mirror the circuit by reversing the instructions.
This is done by recursively mirroring all instructions.
It does not invert any gate.
Returns:
QuantumCircuit: the mirrored circuit
"""
reverse_circ = self.copy(name=self.name+'_mirror')
... |
def inverse(self):
"""Invert this circuit.
This is done by recursively inverting all gates.
Returns:
QuantumCircuit: the inverted circuit
Raises:
QiskitError: if the circuit cannot be inverted.
"""
inverse_circ = self.copy(name=self.name+'_dg')
... |
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
... |
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
... |
def append(self, instruction, qargs=None, cargs=None):
"""Append an instruction to the end of the circuit, modifying
the circuit in place.
Args:
instruction (Instruction or Operator): Instruction instance to append
qargs (list(tuple)): qubits to attach instruction to
... |
def _attach(self, instruction, qargs, cargs):
"""DEPRECATED after 0.8"""
self.append(instruction, qargs, cargs) |
def add_register(self, *regs):
"""Add registers."""
if not regs:
return
if any([isinstance(reg, int) for reg in regs]):
# QuantumCircuit defined without registers
if len(regs) == 1 and isinstance(regs[0], int):
# QuantumCircuit with anonymous ... |
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_qargs(self, qargs):
"""Raise exception if a qarg is not in this circuit or bad format."""
if not all(isinstance(i, tuple) and
isinstance(i[0], QuantumRegister) and
isinstance(i[1], int) for i in qargs):
raise QiskitError("qarg not (QuantumRegi... |
def _check_cargs(self, cargs):
"""Raise exception if clbit is not in this circuit or bad format."""
if not all(isinstance(i, tuple) and
isinstance(i[0], ClassicalRegister) and
isinstance(i[1], int) for i in cargs):
raise QiskitError("carg not (ClassicalR... |
def decompose(self):
"""Call a decomposition pass on this circuit,
to decompose one level (shallow decompose).
Returns:
QuantumCircuit: a circuit one level decomposed
"""
from qiskit.transpiler.passes.decompose import Decompose
from qiskit.converters.circuit_... |
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:
... |
def qasm(self):
"""Return OpenQASM string."""
string_temp = self.header + "\n"
string_temp += self.extension_lib + "\n"
for register in self.qregs:
string_temp += register.qasm() + "\n"
for register in self.cregs:
string_temp += register.qasm() + "\n"
... |
def draw(self, scale=0.7, filename=None, style=None, output='text',
interactive=False, line_length=None, plot_barriers=True,
reverse_bits=False, justify=None):
"""Draw the quantum circuit
Using the output parameter you can specify the format. The choices are:
0. text: ... |
def size(self):
"""Returns total number of gate operations in circuit.
Returns:
int: Total number of gate operations.
"""
gate_ops = 0
for instr, _, _ in self.data:
if instr.name not in ['barrier', 'snapshot']:
gate_ops += 1
return... |
def depth(self):
"""Return circuit depth (i.e. length of critical path).
This does not include compiler or simulator directives
such as 'barrier' or 'snapshot'.
Returns:
int: Depth of circuit.
Notes:
The circuit depth and the DAG depth need not bt the
... |
def width(self):
"""Return number of qubits plus clbits in circuit.
Returns:
int: Width of circuit.
"""
return sum(reg.size for reg in self.qregs+self.cregs) |
def count_ops(self):
"""Count each operation kind in the circuit.
Returns:
dict: a breakdown of how many operations of each kind.
"""
count_ops = {}
for instr, _, _ in self.data:
if instr.name in count_ops.keys():
count_ops[instr.name] += ... |
def num_connected_components(self, unitary_only=False):
"""How many non-entangled subcircuits can the circuit be factored to.
Args:
unitary_only (bool): Compute only unitary part of graph.
Returns:
int: Number of connected components in circuit.
"""
# Co... |
def bind_parameters(self, value_dict):
"""Assign parameters to values yielding a new circuit.
Args:
value_dict (dict): {parameter: value, ...}
Raises:
QiskitError: If value_dict contains parameters not present in the circuit
Returns:
QuantumCircuit:... |
def _bind_parameter(self, parameter, value):
"""Assigns a parameter value to matching instructions in-place."""
for (instr, param_index) in self._parameter_table[parameter]:
instr.params[param_index] = value |
def pulse_drawer(samples, duration, dt=None, interp_method='None',
filename=None, interactive=False,
dpi=150, nop=1000, size=(6, 5)):
"""Plot the interpolated envelope of pulse
Args:
samples (ndarray): Data points of complex pulse envelope.
duration (int): Puls... |
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... |
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 topol... |
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(couplin... |
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.qargs) == 2]) - 3 * step['swaps_added'] |
def _copy_circuit_metadata(source_dag, coupling_map):
"""Return a copy of source_dag with metadata but empty.
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... |
def _transform_gate_for_layout(gate, layout):
"""Return op implementing a virtual gate on given layout."""
mapped_op_node = deepcopy([n for n in gate['graph'].nodes() if n.type == 'op'][0])
# Workaround until #1816, apply mapped to qargs to both DAGNode and op
device_qreg = QuantumRegister(len(layout.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.