INSTRUCTION
stringlengths 1
8.43k
| RESPONSE
stringlengths 75
104k
|
|---|---|
Get the matrix for a single qubit.
|
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)]])
|
Return the index string for Numpy. eignsum matrix - matrix multiplication.
|
def einsum_matmul_index(gate_indices, number_of_qubits):
"""Return the index string for Numpy.eignsum matrix-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.
"""
mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices,
number_of_qubits)
# Right indices for the N-qubit input and output tensor
tens_r = ascii_uppercase[:number_of_qubits]
# Combine indices into matrix multiplication string format
# for numpy.einsum function
return "{mat_l}{mat_r}, ".format(mat_l=mat_l, mat_r=mat_r) + \
"{tens_lin}{tens_r}->{tens_lout}{tens_r}".format(tens_lin=tens_lin,
tens_lout=tens_lout,
tens_r=tens_r)
|
Return the index string for Numpy. eignsum matrix - vector multiplication.
|
def einsum_vecmul_index(gate_indices, number_of_qubits):
"""Return the index string for Numpy.eignsum matrix-vector multiplication.
The returned indices are to perform a matrix multiplication A.v where
the matrix A is an M-qubit matrix, vector v is an N-qubit vector, and
M <= N, and identity matrices are implied on the subsystems where A has no
support on v.
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.
"""
mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices,
number_of_qubits)
# Combine indices into matrix multiplication string format
# for numpy.einsum function
return "{mat_l}{mat_r}, ".format(mat_l=mat_l, mat_r=mat_r) + \
"{tens_lin}->{tens_lout}".format(tens_lin=tens_lin,
tens_lout=tens_lout)
|
Return the index string for Numpy. eignsum matrix multiplication.
|
def _einsum_matmul_index_helper(gate_indices, number_of_qubits):
"""Return the index string for Numpy.eignsum matrix multiplication.
The returned indices are to perform a matrix multiplication A.v where
the matrix A is an M-qubit matrix, matrix v is an N-qubit vector, and
M <= N, and identity matrices are implied on the subsystems where A has no
support on v.
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:
tuple: (mat_left, mat_right, tens_in, tens_out) of index strings for
that may be combined into a Numpy.einsum function string.
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")
# Indicies for N-qubit input tensor
tens_in = ascii_lowercase[:number_of_qubits]
# Indices for the N-qubit output tensor
tens_out = list(tens_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 += tens_in[-1 - idx]
tens_out[-1 - idx] = ascii_lowercase[-1 - pos]
tens_out = "".join(tens_out)
# Combine indices into matrix multiplication string format
# for numpy.einsum function
return mat_left, mat_right, tens_in, tens_out
|
Build a DAGCircuit object from a QuantumCircuit.
|
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)
for instruction, qargs, cargs in circuit.data:
# 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.copy(),
qargs, cargs, control)
return dagcircuit
|
Function used to fit the exponential decay.
|
def exp_fit_fun(x, a, tau, c):
"""Function used to fit the exponential decay."""
# pylint: disable=invalid-name
return a * np.exp(-x / tau) + c
|
Function used to fit the decay cosine.
|
def osc_fit_fun(x, a, tau, f, phi, c):
"""Function used to fit the decay cosine."""
# pylint: disable=invalid-name
return a * np.exp(-x / tau) * np.cos(2 * np.pi * f * x + phi) + c
|
Plot coherence data.
|
def plot_coherence(xdata, ydata, std_error, fit, fit_function, xunit, exp_str,
qubit_label):
"""Plot coherence data.
Args:
xdata
ydata
std_error
fit
fit_function
xunit
exp_str
qubit_label
Raises:
ImportError: If matplotlib is not installed.
"""
if not HAS_MATPLOTLIB:
raise ImportError('The function plot_coherence needs matplotlib. '
'Run "pip install matplotlib" before.')
plt.errorbar(xdata, ydata, std_error, marker='.',
markersize=9, c='b', linestyle='')
plt.plot(xdata, fit_function(xdata, *fit), c='r', linestyle='--',
label=(exp_str + '= %s %s' % (str(round(fit[1])), xunit)))
plt.xticks(fontsize=14, rotation=70)
plt.yticks(fontsize=14)
plt.xlabel('time [%s]' % (xunit), fontsize=16)
plt.ylabel('P(1)', fontsize=16)
plt.title(exp_str + ' measurement of Q$_{%s}$' % (str(qubit_label)), fontsize=18)
plt.legend(fontsize=12)
plt.grid(True)
plt.show()
|
Take the raw rb data and convert it into averages and std dev
|
def shape_rb_data(raw_rb):
"""Take the raw rb data and convert it into averages and std dev
Args:
raw_rb (numpy.array): m x n x l list where m is the number of seeds, n
is the number of Clifford sequences and l is the number of qubits
Return:
numpy_array: 2 x n x l list where index 0 is the mean over seeds, 1 is
the std dev overseeds
"""
rb_data = []
rb_data.append(np.mean(raw_rb, 0))
rb_data.append(np.std(raw_rb, 0))
return rb_data
|
Take the rb fit data and convert it into EPC ( error per Clifford )
|
def rb_epc(fit, rb_pattern):
"""Take the rb fit data and convert it into EPC (error per Clifford)
Args:
fit (dict): dictionary of the fit quantities (A, alpha, B) with the
keys 'qn' where n is the qubit and subkeys 'fit', e.g.
{'q0':{'fit': [1, 0, 0.9], 'fiterr': [0, 0, 0]}}}
rb_pattern (list): (see randomized benchmarking functions). Pattern
which specifies which qubits performing RB with which qubits. E.g.
[[1],[0,2]] is Q1 doing 1Q RB simultaneously with Q0/Q2 doing
2Q RB
Return:
dict: updates the passed in fit dictionary with the epc
"""
for patterns in rb_pattern:
for qubit in patterns:
fitalpha = fit['q%d' % qubit]['fit'][1]
fitalphaerr = fit['q%d' % qubit]['fiterr'][1]
nrb = 2 ** len(patterns)
fit['q%d' % qubit]['fit_calcs'] = {}
fit['q%d' % qubit]['fit_calcs']['epc'] = [(nrb - 1) / nrb * (1 - fitalpha),
fitalphaerr / fitalpha]
fit['q%d' % qubit]['fit_calcs']['epc'][1] *= fit['q%d' % qubit]['fit_calcs']['epc'][0]
return fit
|
Plot randomized benchmarking data.
|
def plot_rb_data(xdata, ydatas, yavg, yerr, fit, survival_prob, ax=None,
show_plt=True):
"""Plot randomized benchmarking data.
Args:
xdata (list): list of subsequence lengths
ydatas (list): list of lists of survival probabilities for each
sequence
yavg (list): mean of the survival probabilities at each sequence
length
yerr (list): error of the survival
fit (list): fit parameters
survival_prob (callable): function that computes survival probability
ax (Axes or None): plot axis (if passed in)
show_plt (bool): display the plot.
Raises:
ImportError: If matplotlib is not installed.
"""
# pylint: disable=invalid-name
if not HAS_MATPLOTLIB:
raise ImportError('The function plot_rb_data needs matplotlib. '
'Run "pip install matplotlib" before.')
if ax is None:
plt.figure()
ax = plt.gca()
# Plot the result for each sequence
for ydata in ydatas:
ax.plot(xdata, ydata, color='gray', linestyle='none', marker='x')
# Plot the mean with error bars
ax.errorbar(xdata, yavg, yerr=yerr, color='r', linestyle='--', linewidth=3)
# Plot the fit
ax.plot(xdata, survival_prob(xdata, *fit), color='blue', linestyle='-', linewidth=2)
ax.tick_params(labelsize=14)
# ax.tick_params(axis='x',labelrotation=70)
ax.set_xlabel('Clifford Length', fontsize=16)
ax.set_ylabel('Z', fontsize=16)
ax.grid(True)
if show_plt:
plt.show()
|
Finds runs containing parameterized gates and splits them into sequential runs excluding the parameterized gates.
|
def _split_runs_on_parameters(runs):
"""Finds runs containing parameterized gates and splits them into sequential
runs excluding the parameterized gates.
"""
def _is_dagnode_parameterized(node):
return any(isinstance(param, Parameter) for param in node.op.params)
out = []
for run in runs:
groups = groupby(run, _is_dagnode_parameterized)
for group_is_parameterized, gates in groups:
if not group_is_parameterized:
out.append(list(gates))
return out
|
Return a new circuit that has been optimized.
|
def run(self, dag):
"""Return a new circuit that has been optimized."""
runs = dag.collect_runs(["u1", "u2", "u3", "id"])
runs = _split_runs_on_parameters(runs)
for run in runs:
right_name = "u1"
right_parameters = (0, 0, 0) # (theta, phi, lambda)
for current_node in run:
left_name = current_node.name
if (current_node.condition is not None
or len(current_node.qargs) != 1
or left_name not in ["u1", "u2", "u3", "id"]):
raise TranspilerError("internal error")
if left_name == "u1":
left_parameters = (0, 0, current_node.op.params[0])
elif left_name == "u2":
left_parameters = (np.pi / 2, current_node.op.params[0],
current_node.op.params[1])
elif left_name == "u3":
left_parameters = tuple(current_node.op.params)
else:
left_name = "u1" # replace id with u1
left_parameters = (0, 0, 0)
# If there are any sympy objects coming from the gate convert
# to numpy.
left_parameters = tuple([float(x) for x in left_parameters])
# Compose gates
name_tuple = (left_name, right_name)
if name_tuple == ("u1", "u1"):
# u1(lambda1) * u1(lambda2) = u1(lambda1 + lambda2)
right_parameters = (0, 0, right_parameters[2] +
left_parameters[2])
elif name_tuple == ("u1", "u2"):
# u1(lambda1) * u2(phi2, lambda2) = u2(phi2 + lambda1, lambda2)
right_parameters = (np.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 = (np.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 = (np.pi - left_parameters[2] -
right_parameters[1], left_parameters[1] +
np.pi / 2, right_parameters[2] +
np.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
right_parameters = Optimize1qGates.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 np.mod(right_parameters[0], (2 * np.pi)) == 0 \
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 np.mod((right_parameters[0] - np.pi / 2), (2 * np.pi)) == 0:
right_name = "u2"
right_parameters = (np.pi / 2, right_parameters[1],
right_parameters[2] +
(right_parameters[0] - np.pi / 2))
# theta = -pi/2 + 2*k*pi
if np.mod((right_parameters[0] + np.pi / 2), (2 * np.pi)) == 0:
right_name = "u2"
right_parameters = (np.pi / 2, right_parameters[1] +
np.pi, right_parameters[2] -
np.pi + (right_parameters[0] +
np.pi / 2))
# u1 and lambda is 0 mod 2*pi so gate is nop (up to a global phase)
if right_name == "u1" and np.mod(right_parameters[2], (2 * np.pi)) == 0:
right_name = "nop"
# Replace the the first node in the run with a dummy DAG which contains a dummy
# qubit. The name is irrelevant, because substitute_node_with_dag will take care of
# putting it in the right place.
run_qarg = (QuantumRegister(1, 'q'), 0)
new_op = Gate(name="", num_qubits=1, params=[])
if right_name == "u1":
new_op = U1Gate(right_parameters[2])
if right_name == "u2":
new_op = U2Gate(right_parameters[1], right_parameters[2])
if right_name == "u3":
new_op = U3Gate(*right_parameters)
if right_name != 'nop':
new_dag = DAGCircuit()
new_dag.add_qreg(run_qarg[0])
new_dag.apply_operation_back(new_op, [run_qarg], [])
dag.substitute_node_with_dag(run[0], new_dag)
# Delete the other nodes in the run
for current_node in run[1:]:
dag.remove_op_node(current_node)
if right_name == "nop":
dag.remove_op_node(run[0])
return dag
|
Return a triple theta phi lambda for the product.
|
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 = Optimize1qGates.yzy_to_zyz((lambda1 + phi2), theta1, theta2)
(theta, phi, lamb) = (thetap, phi1 + phip, lambda2 + lambdap)
return (theta, phi, lamb)
|
Express a Y. Z. Y single qubit gate as a Z. Y. Z gate.
|
def yzy_to_zyz(xi, theta1, theta2, eps=1e-9): # pylint: disable=invalid-name
"""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.
"""
quaternion_yzy = quaternion_from_euler([theta1, xi, theta2], 'yzy')
euler = quaternion_yzy.to_zyz()
quaternion_zyz = quaternion_from_euler(euler, 'zyz')
# output order different than rotation order
out_angles = (euler[1], euler[0], euler[2])
abs_inner = abs(quaternion_zyz.data.dot(quaternion_yzy.data))
if not np.allclose(abs_inner, 1, eps):
raise TranspilerError('YZY and ZYZ angles do not give same rotation matrix.')
out_angles = tuple(0 if np.abs(angle) < _CHOP_THRESHOLD else angle
for angle in out_angles)
return out_angles
|
Extend the layout with new ( physical qubit virtual qubit ) pairs.
|
def run(self, dag):
"""
Extend the layout with new (physical qubit, virtual qubit) pairs.
The dag signals which virtual qubits are already in the circuit.
This pass will allocate new virtual qubits such that no collision occurs
(i.e. Layout bijectivity is preserved)
The coupling_map and layout together determine which physical qubits are free.
Args:
dag (DAGCircuit): circuit to analyze
Returns:
DAGCircuit: returns the same dag circuit, unmodified
Raises:
TranspilerError: If there is not layout in the property set or not set at init time.
"""
self.layout = self.layout or self.property_set.get('layout')
if self.layout is None:
raise TranspilerError("FullAncilla pass requires property_set[\"layout\"] or"
" \"layout\" parameter to run")
layout_physical_qubits = self.layout.get_physical_bits().keys()
coupling_physical_qubits = self.coupling_map.physical_qubits
idle_physical_qubits = [q for q in coupling_physical_qubits
if q not in layout_physical_qubits]
if idle_physical_qubits:
if self.ancilla_name in dag.qregs:
save_prefix = QuantumRegister.prefix
QuantumRegister.prefix = self.ancilla_name
qreg = QuantumRegister(len(idle_physical_qubits))
QuantumRegister.prefix = save_prefix
else:
qreg = QuantumRegister(len(idle_physical_qubits), name=self.ancilla_name)
for idx, idle_q in enumerate(idle_physical_qubits):
self.property_set['layout'][idle_q] = qreg[idx]
return dag
|
Validates the input to state visualization functions.
|
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
|
Trim a PIL image and remove white space.
|
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
|
Given a circuit return a tuple ( qregs cregs ops ) where qregs and cregs are the quantum and classical registers in order ( based on reverse_bits ) and ops is a list of DAG nodes which type is operation. Args: circuit ( QuantumCircuit ): From where the information is extracted. reverse_bits ( 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.
|
def _get_layered_instructions(circuit, reverse_bits=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 reverse_bits) and ops is a list
of DAG nodes which type is "operation".
Args:
circuit (QuantumCircuit): From where the information is extracted.
reverse_bits (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 = 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 in dag.topological_op_nodes():
ops.append([node])
if justify == 'left':
for dag_layer in dag.layers():
layers = []
current_layer = []
dag_nodes = dag_layer['graph'].op_nodes()
dag_nodes.sort(key=lambda nd: nd._node_id)
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 check_node in dag_nodes:
if check_node != node:
all_indices += _get_gate_span(qregs, check_node)
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)
if current_layer:
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'].op_nodes()
# sort into the order they were input
dag_instructions.sort(key=lambda nd: nd._node_id)
for instruction_node in dag_instructions:
gate_span = _get_gate_span(qregs, instruction_node)
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_node
layer_dicts.append(new_dict)
else:
curr_dict = layer_dicts[-i]
for index in gate_span:
curr_dict[index] = instruction_node
break
if not added:
for index in gate_span:
layer_dicts[0][index] = instruction_node
# need to convert from dict format to layers
layer_dicts.reverse()
ops = [list(layer.values()) for layer in layer_dicts]
if reverse_bits:
qregs.reverse()
cregs.reverse()
return qregs, cregs, ops
|
Get the list of qubits drawing this gate would cover
|
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]
|
Build an Instruction object from a QuantumCircuit.
|
def circuit_to_instruction(circuit):
"""Build an ``Instruction`` object from a ``QuantumCircuit``.
The instruction is anonymous (not tied to a named quantum register),
and so can be inserted into another circuit. The instruction will
have the same string name as the circuit.
Args:
circuit (QuantumCircuit): the input circuit.
Return:
Instruction: an instruction equivalent to the action of the
input circuit. Upon decomposition, this instruction will
yield the components comprising the original circuit.
"""
instruction = Instruction(name=circuit.name,
num_qubits=sum([qreg.size for qreg in circuit.qregs]),
num_clbits=sum([creg.size for creg in circuit.cregs]),
params=[])
instruction.control = None
def find_bit_position(bit):
"""find the index of a given bit (Register, int) within
a flat ordered list of bits of the circuit
"""
if isinstance(bit[0], QuantumRegister):
ordered_regs = circuit.qregs
else:
ordered_regs = circuit.cregs
reg_index = ordered_regs.index(bit[0])
return sum([reg.size for reg in ordered_regs[:reg_index]]) + bit[1]
definition = circuit.data.copy()
if instruction.num_qubits > 0:
q = QuantumRegister(instruction.num_qubits, 'q')
if instruction.num_clbits > 0:
c = ClassicalRegister(instruction.num_clbits, 'c')
definition = list(map(lambda x:
(x[0],
list(map(lambda y: (q, find_bit_position(y)), x[1])),
list(map(lambda y: (c, find_bit_position(y)), x[2]))), definition))
instruction.definition = definition
return instruction
|
Pick a convenient layout depending on the best matching qubit connectivity and set the property layout.
|
def run(self, dag):
"""
Pick a convenient layout depending on the best matching
qubit connectivity, and set the property `layout`.
Args:
dag (DAGCircuit): DAG to find layout for.
Raises:
TranspilerError: if dag wider than self.coupling_map
"""
num_dag_qubits = sum([qreg.size for qreg in dag.qregs.values()])
if num_dag_qubits > self.coupling_map.size():
raise TranspilerError('Number of qubits greater than device.')
best_sub = self._best_subset(num_dag_qubits)
layout = Layout()
map_iter = 0
for qreg in dag.qregs.values():
for i in range(qreg.size):
layout[(qreg, i)] = int(best_sub[map_iter])
map_iter += 1
self.property_set['layout'] = layout
|
Computes the qubit mapping with the best connectivity.
|
def _best_subset(self, n_qubits):
"""Computes the qubit mapping with the best connectivity.
Args:
n_qubits (int): Number of subset qubits to consider.
Returns:
ndarray: Array of qubits to use for best connectivity mapping.
"""
if n_qubits == 1:
return np.array([0])
device_qubits = self.coupling_map.size()
cmap = np.asarray(self.coupling_map.get_edges())
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
sub_graph = []
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
sub_graph.append([node_idx, node])
break
if connection_count > best:
best = connection_count
best_map = bfs[0:n_qubits]
# Return a best mapping that has reduced bandwidth
mapping = {}
for edge in range(best_map.shape[0]):
mapping[best_map[edge]] = edge
new_cmap = [[mapping[c[0]], mapping[c[1]]] for c in sub_graph]
rows = [edge[0] for edge in new_cmap]
cols = [edge[1] for edge in new_cmap]
data = [1]*len(rows)
sp_sub_graph = sp.coo_matrix((data, (rows, cols)),
shape=(n_qubits, n_qubits)).tocsr()
perm = cs.reverse_cuthill_mckee(sp_sub_graph)
best_map = best_map[perm]
return best_map
|
Return True if completely - positive trace - preserving.
|
def is_cptp(self, atol=None, rtol=None):
"""Return True if completely-positive trace-preserving."""
if self._data[1] is not None:
return False
if atol is None:
atol = self._atol
if rtol is None:
rtol = self._rtol
accum = 0j
for op in self._data[0]:
accum += np.dot(np.transpose(np.conj(op)), op)
return is_identity_matrix(accum, rtol=rtol, atol=atol)
|
Return the conjugate of the QuantumChannel.
|
def conjugate(self):
"""Return the conjugate of the QuantumChannel."""
kraus_l, kraus_r = self._data
kraus_l = [k.conj() for k in kraus_l]
if kraus_r is not None:
kraus_r = [k.conj() for k in kraus_r]
return Kraus((kraus_l, kraus_r), self.input_dims(), self.output_dims())
|
Return the transpose of the QuantumChannel.
|
def transpose(self):
"""Return the transpose of the QuantumChannel."""
kraus_l, kraus_r = self._data
kraus_l = [k.T for k in kraus_l]
if kraus_r is not None:
kraus_r = [k.T for k in kraus_r]
return Kraus((kraus_l, kraus_r),
input_dims=self.output_dims(),
output_dims=self.input_dims())
|
Return the composition channel self∘other.
|
def compose(self, other, qargs=None, front=False):
"""Return the composition channel self∘other.
Args:
other (QuantumChannel): a quantum channel subclass.
qargs (list): a list of subsystem positions to compose other on.
front (bool): If False compose in standard order other(self(input))
otherwise compose in reverse order self(other(input))
[default: False]
Returns:
Kraus: The composition channel as a Kraus object.
Raises:
QiskitError: if other cannot be converted to a channel, or
has incompatible dimensions.
"""
if qargs is not None:
return Kraus(
SuperOp(self).compose(other, qargs=qargs, front=front))
if not isinstance(other, Kraus):
other = Kraus(other)
# Check dimensions match up
if front and self._input_dim != other._output_dim:
raise QiskitError(
'input_dim of self must match output_dim of other')
if not front and self._output_dim != other._input_dim:
raise QiskitError(
'input_dim of other must match output_dim of self')
if front:
ka_l, ka_r = self._data
kb_l, kb_r = other._data
input_dim = other._input_dim
output_dim = self._output_dim
else:
ka_l, ka_r = other._data
kb_l, kb_r = self._data
input_dim = self._input_dim
output_dim = other._output_dim
kab_l = [np.dot(a, b) for a in ka_l for b in kb_l]
if ka_r is None and kb_r is None:
kab_r = None
elif ka_r is None:
kab_r = [np.dot(a, b) for a in ka_l for b in kb_r]
elif kb_r is None:
kab_r = [np.dot(a, b) for a in ka_r for b in kb_l]
else:
kab_r = [np.dot(a, b) for a in ka_r for b in kb_r]
return Kraus((kab_l, kab_r), input_dim, output_dim)
|
The matrix power of the channel.
|
def power(self, n):
"""The matrix power of the channel.
Args:
n (int): compute the matrix power of the superoperator matrix.
Returns:
Kraus: the matrix power of the SuperOp converted to a Kraus channel.
Raises:
QiskitError: if the input and output dimensions of the
QuantumChannel are not equal, or the power is not an integer.
"""
if n > 0:
return super().power(n)
return Kraus(SuperOp(self).power(n))
|
Return the QuantumChannel self + other.
|
def multiply(self, other):
"""Return the QuantumChannel self + other.
Args:
other (complex): a complex number.
Returns:
Kraus: the scalar multiplication other * self as a Kraus object.
Raises:
QiskitError: if other is not a valid scalar.
"""
if not isinstance(other, Number):
raise QiskitError("other is not a number")
# If the number is complex we need to convert to general
# kraus channel so we multiply via Choi representation
if isinstance(other, complex) or other < 0:
# Convert to Choi-matrix
return Kraus(Choi(self).multiply(other))
# If the number is real we can update the Kraus operators
# directly
val = np.sqrt(other)
kraus_r = None
kraus_l = [val * k for k in self._data[0]]
if self._data[1] is not None:
kraus_r = [val * k for k in self._data[1]]
return Kraus((kraus_l, kraus_r), self._input_dim, self._output_dim)
|
Evolve a quantum state by the QuantumChannel.
|
def _evolve(self, state, qargs=None):
"""Evolve a quantum state by the QuantumChannel.
Args:
state (QuantumState): The input statevector or density matrix.
qargs (list): a list of QuantumState subsystem positions to apply
the operator on.
Returns:
QuantumState: the output quantum state.
Raises:
QiskitError: if the operator dimension does not match the
specified QuantumState subsystem dimensions.
"""
# If subsystem evolution we use the SuperOp representation
if qargs is not None:
return SuperOp(self)._evolve(state, qargs)
# Otherwise we compute full evolution directly
state = self._format_state(state)
if state.shape[0] != self._input_dim:
raise QiskitError(
"QuantumChannel input dimension is not equal to state dimension."
)
if state.ndim == 1 and self._data[1] is None and len(
self._data[0]) == 1:
# If we only have a single Kraus operator we can implement unitary-type
# evolution of a state vector psi -> K[0].psi
return np.dot(self._data[0][0], state)
# Otherwise we always return a density matrix
state = self._format_state(state, density_matrix=True)
kraus_l, kraus_r = self._data
if kraus_r is None:
kraus_r = kraus_l
return np.einsum('AiB,BC,AjC->ij', kraus_l, state,
np.conjugate(kraus_r))
|
Return the tensor product channel.
|
def _tensor_product(self, other, reverse=False):
"""Return the tensor product channel.
Args:
other (QuantumChannel): a quantum channel subclass.
reverse (bool): If False return self ⊗ other, if True return
if True return (other ⊗ self) [Default: False
Returns:
Kraus: the tensor product channel as a Kraus object.
Raises:
QiskitError: if other cannot be converted to a channel.
"""
# Convert other to Kraus
if not isinstance(other, Kraus):
other = Kraus(other)
# Get tensor matrix
ka_l, ka_r = self._data
kb_l, kb_r = other._data
if reverse:
input_dims = self.input_dims() + other.input_dims()
output_dims = self.output_dims() + other.output_dims()
kab_l = [np.kron(b, a) for a in ka_l for b in kb_l]
else:
input_dims = other.input_dims() + self.input_dims()
output_dims = other.output_dims() + self.output_dims()
kab_l = [np.kron(a, b) for a in ka_l for b in kb_l]
if ka_r is None and kb_r is None:
kab_r = None
else:
if ka_r is None:
ka_r = ka_l
if kb_r is None:
kb_r = kb_l
if reverse:
kab_r = [np.kron(b, a) for a in ka_r for b in kb_r]
else:
kab_r = [np.kron(a, b) for a in ka_r for b in kb_r]
data = (kab_l, kab_r)
return Kraus(data, input_dims, output_dims)
|
A decorator for generating SamplePulse from python callable. Args: func ( callable ): A function describing pulse envelope. Raises: PulseError: when invalid function is specified.
|
def functional_pulse(func):
"""A decorator for generating SamplePulse from python callable.
Args:
func (callable): A function describing pulse envelope.
Raises:
PulseError: when invalid function is specified.
"""
@functools.wraps(func)
def to_pulse(duration, *args, name=None, **kwargs):
"""Return SamplePulse."""
if isinstance(duration, int) and duration > 0:
samples = func(duration, *args, **kwargs)
samples = np.asarray(samples, dtype=np.complex128)
return SamplePulse(samples=samples, name=name)
raise PulseError('The first argument must be an integer value representing duration.')
return to_pulse
|
Return the correspond floating point number.
|
def real(self, nested_scope=None):
"""Return the correspond floating point number."""
operation = self.children[0].operation()
lhs = self.children[1].real(nested_scope)
rhs = self.children[2].real(nested_scope)
return operation(lhs, rhs)
|
Return the correspond symbolic number.
|
def sym(self, nested_scope=None):
"""Return the correspond symbolic number."""
operation = self.children[0].operation()
lhs = self.children[1].sym(nested_scope)
rhs = self.children[2].sym(nested_scope)
return operation(lhs, rhs)
|
Apply barrier to circuit. If qargs is None applies to all the qbits. Args is a list of QuantumRegister or single qubits. For QuantumRegister applies barrier to all the qubits in that register.
|
def barrier(self, *qargs):
"""Apply barrier to circuit.
If qargs is None, applies to all the qbits.
Args is a list of QuantumRegister or single qubits.
For QuantumRegister, applies barrier to all the qubits in that register."""
qubits = []
qargs = _convert_to_bits(qargs, [qbit for qreg in self.qregs for qbit in qreg])
if not qargs: # None
for qreg in self.qregs:
for j in range(qreg.size):
qubits.append((qreg, j))
for qarg in qargs:
if isinstance(qarg, (QuantumRegister, list)):
if isinstance(qarg, QuantumRegister):
qubits.extend([(qarg, j) for j in range(qarg.size)])
else:
qubits.extend(qarg)
else:
qubits.append(qarg)
return self.append(Barrier(len(qubits)), qubits, [])
|
Compute the mean value of an diagonal observable.
|
def average_data(counts, observable):
"""Compute the mean value of an diagonal observable.
Takes in a diagonal observable in dictionary, list or matrix format and then
calculates the sum_i value(i) P(i) where value(i) is the value of the
observable for state i.
Args:
counts (dict): a dict of outcomes from an experiment
observable (dict or matrix or list): The observable to be averaged over.
As an example, ZZ on qubits can be given as:
* dict: {"00": 1, "11": 1, "01": -1, "10": -1}
* matrix: [[1, 0, 0, 0], [0, -1, 0, 0, ], [0, 0, -1, 0], [0, 0, 0, 1]]
* matrix diagonal (list): [1, -1, -1, 1]
Returns:
Double: Average of the observable
"""
if not isinstance(observable, dict):
observable = make_dict_observable(observable)
temp = 0
tot = sum(counts.values())
for key in counts:
if key in observable:
temp += counts[key] * observable[key] / tot
return temp
|
Process an Id or IndexedId node as a bit or register type.
|
def _process_bit_id(self, node):
"""Process an Id or IndexedId node as a bit or register type.
Return a list of tuples (Register,index).
"""
# pylint: disable=inconsistent-return-statements
reg = None
if node.name in self.dag.qregs:
reg = self.dag.qregs[node.name]
elif node.name in self.dag.cregs:
reg = self.dag.cregs[node.name]
else:
raise QiskitError("expected qreg or creg name:",
"line=%s" % node.line,
"file=%s" % node.file)
if node.type == "indexed_id":
# An indexed bit or qubit
return [(reg, node.index)]
elif node.type == "id":
# A qubit or qreg or creg
if not self.bit_stack[-1]:
# Global scope
return [(reg, j) for j in range(reg.size)]
else:
# local scope
if node.name in self.bit_stack[-1]:
return [self.bit_stack[-1][node.name]]
raise QiskitError("expected local bit name:",
"line=%s" % node.line,
"file=%s" % node.file)
return None
|
Process a custom unitary node.
|
def _process_custom_unitary(self, node):
"""Process a custom unitary node."""
name = node.name
if node.arguments is not None:
args = self._process_node(node.arguments)
else:
args = []
bits = [self._process_bit_id(node_element)
for node_element in node.bitlist.children]
if name in self.gates:
gargs = self.gates[name]["args"]
gbits = self.gates[name]["bits"]
# Loop over register arguments, if any.
maxidx = max(map(len, bits))
for idx in range(maxidx):
self.arg_stack.append({gargs[j]: args[j]
for j in range(len(gargs))})
# Only index into register arguments.
element = [idx*x for x in
[len(bits[j]) > 1 for j in range(len(bits))]]
self.bit_stack.append({gbits[j]: bits[j][element[j]]
for j in range(len(gbits))})
self._create_dag_op(name,
[self.arg_stack[-1][s].sym() for s in gargs],
[self.bit_stack[-1][s] for s in gbits])
self.arg_stack.pop()
self.bit_stack.pop()
else:
raise QiskitError("internal error undefined gate:",
"line=%s" % node.line, "file=%s" % node.file)
|
Process a gate node.
|
def _process_gate(self, node, opaque=False):
"""Process a gate node.
If opaque is True, process the node as an opaque gate node.
"""
self.gates[node.name] = {}
de_gate = self.gates[node.name]
de_gate["print"] = True # default
de_gate["opaque"] = opaque
de_gate["n_args"] = node.n_args()
de_gate["n_bits"] = node.n_bits()
if node.n_args() > 0:
de_gate["args"] = [element.name for element in node.arguments.children]
else:
de_gate["args"] = []
de_gate["bits"] = [c.name for c in node.bitlist.children]
if opaque:
de_gate["body"] = None
else:
de_gate["body"] = node.body
|
Process a CNOT gate node.
|
def _process_cnot(self, node):
"""Process a CNOT gate node."""
id0 = self._process_bit_id(node.children[0])
id1 = self._process_bit_id(node.children[1])
if not(len(id0) == len(id1) or len(id0) == 1 or len(id1) == 1):
raise QiskitError("internal error: qreg size mismatch",
"line=%s" % node.line, "file=%s" % node.file)
maxidx = max([len(id0), len(id1)])
for idx in range(maxidx):
if len(id0) > 1 and len(id1) > 1:
self.dag.apply_operation_back(CXBase(), [id0[idx], id1[idx]], [], self.condition)
elif len(id0) > 1:
self.dag.apply_operation_back(CXBase(), [id0[idx], id1[0]], [], self.condition)
else:
self.dag.apply_operation_back(CXBase(), [id0[0], id1[idx]], [], self.condition)
|
Process a measurement node.
|
def _process_measure(self, node):
"""Process a measurement node."""
id0 = self._process_bit_id(node.children[0])
id1 = self._process_bit_id(node.children[1])
if len(id0) != len(id1):
raise QiskitError("internal error: reg size mismatch",
"line=%s" % node.line, "file=%s" % node.file)
for idx, idy in zip(id0, id1):
self.dag.apply_operation_back(Measure(), [idx], [idy], self.condition)
|
Process an if node.
|
def _process_if(self, node):
"""Process an if node."""
creg_name = node.children[0].name
creg = self.dag.cregs[creg_name]
cval = node.children[1].value
self.condition = (creg, cval)
self._process_node(node.children[2])
self.condition = None
|
Carry out the action associated with a node.
|
def _process_node(self, node):
"""Carry out the action associated with a node."""
if node.type == "program":
self._process_children(node)
elif node.type == "qreg":
qreg = QuantumRegister(node.index, node.name)
self.dag.add_qreg(qreg)
elif node.type == "creg":
creg = ClassicalRegister(node.index, node.name)
self.dag.add_creg(creg)
elif node.type == "id":
raise QiskitError("internal error: _process_node on id")
elif node.type == "int":
raise QiskitError("internal error: _process_node on int")
elif node.type == "real":
raise QiskitError("internal error: _process_node on real")
elif node.type == "indexed_id":
raise QiskitError("internal error: _process_node on indexed_id")
elif node.type == "id_list":
# We process id_list nodes when they are leaves of barriers.
return [self._process_bit_id(node_children)
for node_children in node.children]
elif node.type == "primary_list":
# We should only be called for a barrier.
return [self._process_bit_id(m) for m in node.children]
elif node.type == "gate":
self._process_gate(node)
elif node.type == "custom_unitary":
self._process_custom_unitary(node)
elif node.type == "universal_unitary":
args = self._process_node(node.children[0])
qid = self._process_bit_id(node.children[1])
for element in qid:
self.dag.apply_operation_back(UBase(*args, element), self.condition)
elif node.type == "cnot":
self._process_cnot(node)
elif node.type == "expression_list":
return node.children
elif node.type == "binop":
raise QiskitError("internal error: _process_node on binop")
elif node.type == "prefix":
raise QiskitError("internal error: _process_node on prefix")
elif node.type == "measure":
self._process_measure(node)
elif node.type == "format":
self.version = node.version()
elif node.type == "barrier":
ids = self._process_node(node.children[0])
qubits = []
for qubit in ids:
for j, _ in enumerate(qubit):
qubits.append(qubit[j])
self.dag.apply_operation_back(Barrier(len(qubits)), qubits, [])
elif node.type == "reset":
id0 = self._process_bit_id(node.children[0])
for i, _ in enumerate(id0):
self.dag.apply_operation_back(Reset(), [id0[i]], [], self.condition)
elif node.type == "if":
self._process_if(node)
elif node.type == "opaque":
self._process_gate(node, opaque=True)
elif node.type == "external":
raise QiskitError("internal error: _process_node on external")
else:
raise QiskitError("internal error: undefined node type",
node.type, "line=%s" % node.line,
"file=%s" % node.file)
return None
|
Create a DAG node out of a parsed AST op node.
|
def _create_dag_op(self, name, params, qargs):
"""
Create a DAG node out of a parsed AST op node.
Args:
name (str): operation name to apply to the dag.
params (list): op parameters
qargs (list(QuantumRegister, int)): qubits to attach to
Raises:
QiskitError: if encountering a non-basis opaque gate
"""
if name == "u0":
op_class = U0Gate
elif name == "u1":
op_class = U1Gate
elif name == "u2":
op_class = U2Gate
elif name == "u3":
op_class = U3Gate
elif name == "x":
op_class = XGate
elif name == "y":
op_class = YGate
elif name == "z":
op_class = ZGate
elif name == "t":
op_class = TGate
elif name == "tdg":
op_class = TdgGate
elif name == "s":
op_class = SGate
elif name == "sdg":
op_class = SdgGate
elif name == "swap":
op_class = SwapGate
elif name == "rx":
op_class = RXGate
elif name == "ry":
op_class = RYGate
elif name == "rz":
op_class = RZGate
elif name == "rzz":
op_class = RZZGate
elif name == "id":
op_class = IdGate
elif name == "h":
op_class = HGate
elif name == "cx":
op_class = CnotGate
elif name == "cy":
op_class = CyGate
elif name == "cz":
op_class = CzGate
elif name == "ch":
op_class = CHGate
elif name == "crz":
op_class = CrzGate
elif name == "cu1":
op_class = Cu1Gate
elif name == "cu3":
op_class = Cu3Gate
elif name == "ccx":
op_class = ToffoliGate
elif name == "cswap":
op_class = FredkinGate
else:
raise QiskitError("unknown operation for ast node name %s" % name)
op = op_class(*params)
self.dag.apply_operation_back(op, qargs, [], condition=self.condition)
|
Return the corresponding OPENQASM string.
|
def qasm(self, prec=15):
"""Return the corresponding OPENQASM string."""
return "measure " + self.children[0].qasm(prec) + " -> " + \
self.children[1].qasm(prec) + ";"
|
Return duration of supplied channels.
|
def ch_duration(self, *channels: List[Channel]) -> int:
"""Return duration of supplied channels.
Args:
*channels: Supplied channels
"""
return self.timeslots.ch_duration(*channels)
|
Return minimum start time for supplied channels.
|
def ch_start_time(self, *channels: List[Channel]) -> int:
"""Return minimum start time for supplied channels.
Args:
*channels: Supplied channels
"""
return self.timeslots.ch_start_time(*channels)
|
Return maximum start time for supplied channels.
|
def ch_stop_time(self, *channels: List[Channel]) -> int:
"""Return maximum start time for supplied channels.
Args:
*channels: Supplied channels
"""
return self.timeslots.ch_stop_time(*channels)
|
Iterable for flattening Schedule tree.
|
def _instructions(self, time: int = 0) -> Iterable[Tuple[int, 'Instruction']]:
"""Iterable for flattening Schedule tree.
Args:
time: Shifted time due to parent
Yields:
Tuple[int, ScheduleComponent]: Tuple containing time `ScheduleComponent` starts
at and the flattened `ScheduleComponent`.
"""
for insert_time, child_sched in self.children:
yield from child_sched._instructions(time + insert_time)
|
Print with indent.
|
def to_string(self, indent):
"""Print with indent."""
ind = indent * ' '
print(ind, 'indexed_id', self.name, self.index)
|
Validates a value against the correct type of the field.
|
def check_type(self, value, attr, data):
"""Validates a value against the correct type of the field.
It calls ``_expected_types`` to get a list of valid types.
Subclasses can do one of the following:
1. They can override the ``valid_types`` property with a tuple with
the expected types for this field.
2. They can override the ``_expected_types`` method to return a
tuple of expected types for the field.
3. They can change ``check_type`` completely to customize
validation.
This method or the overrides must return the ``value`` parameter
untouched.
"""
expected_types = self._expected_types()
if not isinstance(value, expected_types):
raise self._not_expected_type(
value, expected_types, fields=[self], field_names=attr, data=data)
return value
|
Include unknown fields after dumping.
|
def dump_additional_data(self, valid_data, many, original_data):
"""Include unknown fields after dumping.
Unknown fields are added with no processing at all.
Args:
valid_data (dict or list): data collected and returned by ``dump()``.
many (bool): if True, data and original_data are a list.
original_data (object or list): object passed to ``dump()`` in the
first place.
Returns:
dict: the same ``valid_data`` extended with the unknown attributes.
Inspired by https://github.com/marshmallow-code/marshmallow/pull/595.
"""
if many:
for i, _ in enumerate(valid_data):
additional_keys = set(original_data[i].__dict__) - set(valid_data[i])
for key in additional_keys:
valid_data[i][key] = getattr(original_data[i], key)
else:
additional_keys = set(original_data.__dict__) - set(valid_data)
for key in additional_keys:
valid_data[key] = getattr(original_data, key)
return valid_data
|
Include unknown fields after load.
|
def load_additional_data(self, valid_data, many, original_data):
"""Include unknown fields after load.
Unknown fields are added with no processing at all.
Args:
valid_data (dict or list): validated data returned by ``load()``.
many (bool): if True, data and original_data are a list.
original_data (dict or list): data passed to ``load()`` in the
first place.
Returns:
dict: the same ``valid_data`` extended with the unknown attributes.
Inspired by https://github.com/marshmallow-code/marshmallow/pull/595.
"""
if many:
for i, _ in enumerate(valid_data):
additional_keys = set(original_data[i]) - set(valid_data[i])
for key in additional_keys:
valid_data[i][key] = original_data[i][key]
else:
additional_keys = set(original_data) - set(valid_data)
for key in additional_keys:
valid_data[key] = original_data[key]
return valid_data
|
Create a patched Schema for validating models.
|
def _create_validation_schema(schema_cls):
"""Create a patched Schema for validating models.
Model validation is not part of Marshmallow. Schemas have a ``validate``
method but this delegates execution on ``load`` and discards the result.
Similarly, ``load`` will call ``_deserialize`` on every field in the
schema.
This function patches the ``_deserialize`` instance method of each
field to make it call a custom defined method ``check_type``
provided by Qiskit in the different fields at
``qiskit.validation.fields``.
Returns:
BaseSchema: a copy of the original Schema, overriding the
``_deserialize()`` call of its fields.
"""
validation_schema = schema_cls()
for _, field in validation_schema.fields.items():
if isinstance(field, ModelTypeValidator):
validate_function = field.__class__.check_type
field._deserialize = MethodType(validate_function, field)
return validation_schema
|
Validate the internal representation of the instance.
|
def _validate(instance):
"""Validate the internal representation of the instance."""
try:
_ = instance.schema.validate(instance.to_dict())
except ValidationError as ex:
raise ModelValidationError(
ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs)
|
Add validation after instantiation.
|
def _validate_after_init(init_method):
"""Add validation after instantiation."""
@wraps(init_method)
def _decorated(self, **kwargs):
try:
_ = self.shallow_schema.validate(kwargs)
except ValidationError as ex:
raise ModelValidationError(
ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs) from None
init_method(self, **kwargs)
return _decorated
|
Serialize the model into a Python dict of simple types.
|
def to_dict(self):
"""Serialize the model into a Python dict of simple types.
Note that this method requires that the model is bound with
``@bind_schema``.
"""
try:
data, _ = self.schema.dump(self)
except ValidationError as ex:
raise ModelValidationError(
ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs) from None
return data
|
Deserialize a dict of simple types into an instance of this class.
|
def from_dict(cls, dict_):
"""Deserialize a dict of simple types into an instance of this class.
Note that this method requires that the model is bound with
``@bind_schema``.
"""
try:
data, _ = cls.schema.load(dict_)
except ValidationError as ex:
raise ModelValidationError(
ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs) from None
return data
|
n - qubit QFT on q in circ.
|
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])
|
Partial trace over subsystems of multi - partite matrix.
|
def partial_trace(state, trace_systems, dimensions=None, reverse=True):
"""
Partial trace over subsystems of multi-partite matrix.
Note that subsystems are ordered as rho012 = rho0(x)rho1(x)rho2.
Args:
state (matrix_like): a matrix NxN
trace_systems (list(int)): a list of subsystems (starting from 0) to
trace over.
dimensions (list(int)): a list of the dimensions of the subsystems.
If this is not set it will assume all
subsystems are qubits.
reverse (bool): ordering of systems in operator.
If True system-0 is the right most system in tensor product.
If False system-0 is the left most system in tensor product.
Returns:
matrix_like: A density matrix with the appropriate subsystems traced
over.
Raises:
Exception: if input is not a multi-qubit state.
"""
state = np.array(state) # convert op to density matrix
if dimensions is None: # compute dims if not specified
num_qubits = int(np.log2(len(state)))
dimensions = [2 for _ in range(num_qubits)]
if len(state) != 2 ** num_qubits:
raise Exception("Input is not a multi-qubit state, "
"specify input state dims")
else:
dimensions = list(dimensions)
if isinstance(trace_systems, int):
trace_systems = [trace_systems]
else: # reverse sort trace sys
trace_systems = sorted(trace_systems, reverse=True)
# trace out subsystems
if state.ndim == 1:
# optimized partial trace for input state vector
return __partial_trace_vec(state, trace_systems, dimensions, reverse)
# standard partial trace for input density matrix
return __partial_trace_mat(state, trace_systems, dimensions, reverse)
|
Partial trace over subsystems of multi - partite vector.
|
def __partial_trace_vec(vec, trace_systems, dimensions, reverse=True):
"""
Partial trace over subsystems of multi-partite vector.
Args:
vec (vector_like): complex vector N
trace_systems (list(int)): a list of subsystems (starting from 0) to
trace over.
dimensions (list(int)): a list of the dimensions of the subsystems.
If this is not set it will assume all
subsystems are qubits.
reverse (bool): ordering of systems in operator.
If True system-0 is the right most system in tensor product.
If False system-0 is the left most system in tensor product.
Returns:
ndarray: A density matrix with the appropriate subsystems traced over.
"""
# trace sys positions
if reverse:
dimensions = dimensions[::-1]
trace_systems = len(dimensions) - 1 - np.array(trace_systems)
rho = vec.reshape(dimensions)
rho = np.tensordot(rho, rho.conj(), axes=(trace_systems, trace_systems))
d = int(np.sqrt(np.product(rho.shape)))
return rho.reshape(d, d)
|
Partial trace over subsystems of multi - partite matrix.
|
def __partial_trace_mat(mat, trace_systems, dimensions, reverse=True):
"""
Partial trace over subsystems of multi-partite matrix.
Note that subsystems are ordered as rho012 = rho0(x)rho1(x)rho2.
Args:
mat (matrix_like): a matrix NxN.
trace_systems (list(int)): a list of subsystems (starting from 0) to
trace over.
dimensions (list(int)): a list of the dimensions of the subsystems.
If this is not set it will assume all
subsystems are qubits.
reverse (bool): ordering of systems in operator.
If True system-0 is the right most system in tensor product.
If False system-0 is the left most system in tensor product.
Returns:
ndarray: A density matrix with the appropriate subsystems traced over.
"""
trace_systems = sorted(trace_systems, reverse=True)
for j in trace_systems:
# Partition subsystem dimensions
dimension_trace = int(dimensions[j]) # traced out system
if reverse:
left_dimensions = dimensions[j + 1:]
right_dimensions = dimensions[:j]
dimensions = right_dimensions + left_dimensions
else:
left_dimensions = dimensions[:j]
right_dimensions = dimensions[j + 1:]
dimensions = left_dimensions + right_dimensions
# Contract remaining dimensions
dimension_left = int(np.prod(left_dimensions))
dimension_right = int(np.prod(right_dimensions))
# Reshape input array into tri-partite system with system to be
# traced as the middle index
mat = mat.reshape([dimension_left, dimension_trace, dimension_right,
dimension_left, dimension_trace, dimension_right])
# trace out the middle system and reshape back to a matrix
mat = mat.trace(axis1=1, axis2=4).reshape(
dimension_left * dimension_right,
dimension_left * dimension_right)
return mat
|
Flatten an operator to a vector in a specified basis.
|
def vectorize(density_matrix, method='col'):
"""Flatten an operator to a vector in a specified basis.
Args:
density_matrix (ndarray): a density matrix.
method (str): the method of vectorization. Allowed values are
- 'col' (default) flattens to column-major vector.
- 'row' flattens to row-major vector.
- 'pauli'flattens in the n-qubit Pauli basis.
- 'pauli-weights': flattens in the n-qubit Pauli basis ordered by
weight.
Returns:
ndarray: the resulting vector.
Raises:
Exception: if input state is not a n-qubit state
"""
density_matrix = np.array(density_matrix)
if method == 'col':
return density_matrix.flatten(order='F')
elif method == 'row':
return density_matrix.flatten(order='C')
elif method in ['pauli', 'pauli_weights']:
num = int(np.log2(len(density_matrix))) # number of qubits
if len(density_matrix) != 2**num:
raise Exception('Input state must be n-qubit state')
if method == 'pauli_weights':
pgroup = pauli_group(num, case='weight')
else:
pgroup = pauli_group(num, case='tensor')
vals = [np.trace(np.dot(p.to_matrix(), density_matrix))
for p in pgroup]
return np.array(vals)
return None
|
Devectorize a vectorized square matrix.
|
def devectorize(vectorized_mat, method='col'):
"""Devectorize a vectorized square matrix.
Args:
vectorized_mat (ndarray): a vectorized density matrix.
method (str): the method of devectorization. Allowed values are
- 'col' (default): flattens to column-major vector.
- 'row': flattens to row-major vector.
- 'pauli': flattens in the n-qubit Pauli basis.
- 'pauli-weights': flattens in the n-qubit Pauli basis ordered by
weight.
Returns:
ndarray: the resulting matrix.
Raises:
Exception: if input state is not a n-qubit state
"""
vectorized_mat = np.array(vectorized_mat)
dimension = int(np.sqrt(vectorized_mat.size))
if len(vectorized_mat) != dimension * dimension:
raise Exception('Input is not a vectorized square matrix')
if method == 'col':
return vectorized_mat.reshape(dimension, dimension, order='F')
elif method == 'row':
return vectorized_mat.reshape(dimension, dimension, order='C')
elif method in ['pauli', 'pauli_weights']:
num_qubits = int(np.log2(dimension)) # number of qubits
if dimension != 2 ** num_qubits:
raise Exception('Input state must be n-qubit state')
if method == 'pauli_weights':
pgroup = pauli_group(num_qubits, case='weight')
else:
pgroup = pauli_group(num_qubits, case='tensor')
pbasis = np.array([p.to_matrix() for p in pgroup]) / 2 ** num_qubits
return np.tensordot(vectorized_mat, pbasis, axes=1)
return None
|
Convert a Choi - matrix to a Pauli - basis superoperator.
|
def choi_to_rauli(choi, order=1):
"""
Convert a Choi-matrix to a Pauli-basis superoperator.
Note that this function assumes that the Choi-matrix
is defined in the standard column-stacking convention
and is normalized to have trace 1. For a channel E this
is defined as: choi = (I \\otimes E)(bell_state).
The resulting 'rauli' R acts on input states as
|rho_out>_p = R.|rho_in>_p
where |rho> = vectorize(rho, method='pauli') for order=1
and |rho> = vectorize(rho, method='pauli_weights') for order=0.
Args:
choi (matrix): the input Choi-matrix.
order (int): ordering of the Pauli group vector.
order=1 (default) is standard lexicographic ordering.
Eg: [II, IX, IY, IZ, XI, XX, XY,...]
order=0 is ordered by weights.
Eg. [II, IX, IY, IZ, XI, XY, XZ, XX, XY,...]
Returns:
np.array: A superoperator in the Pauli basis.
"""
if order == 0:
order = 'weight'
elif order == 1:
order = 'tensor'
# get number of qubits'
num_qubits = int(np.log2(np.sqrt(len(choi))))
pgp = pauli_group(num_qubits, case=order)
rauli = []
for i in pgp:
for j in pgp:
pauliop = np.kron(j.to_matrix().T, i.to_matrix())
rauli += [np.trace(np.dot(choi, pauliop))]
return np.array(rauli).reshape(4 ** num_qubits, 4 ** num_qubits)
|
Truncate small values of a complex array.
|
def chop(array, epsilon=1e-10):
"""
Truncate small values of a complex array.
Args:
array (array_like): array to truncte small values.
epsilon (float): threshold.
Returns:
np.array: A new operator with small values set to zero.
"""
ret = np.array(array)
if np.isrealobj(ret):
ret[abs(ret) < epsilon] = 0.0
else:
ret.real[abs(ret.real) < epsilon] = 0.0
ret.imag[abs(ret.imag) < epsilon] = 0.0
return ret
|
Construct the outer product of two vectors.
|
def outer(vector1, vector2=None):
"""
Construct the outer product of two vectors.
The second vector argument is optional, if absent the projector
of the first vector will be returned.
Args:
vector1 (ndarray): the first vector.
vector2 (ndarray): the (optional) second vector.
Returns:
np.array: The matrix |v1><v2|.
"""
if vector2 is None:
vector2 = np.array(vector1).conj()
else:
vector2 = np.array(vector2).conj()
return np.outer(vector1, vector2)
|
Deprecated in 0. 8 +
|
def random_unitary_matrix(dim, seed=None):
"""Deprecated in 0.8+
"""
warnings.warn('The random_unitary_matrix() function in qiskit.tools.qi has been '
'deprecated and will be removed in the future. Instead use '
'the function in qiskit.quantum_info.random',
DeprecationWarning)
return random.random_unitary(dim, seed).data
|
Deprecated in 0. 8 +
|
def random_density_matrix(length, rank=None, method='Hilbert-Schmidt', seed=None):
"""Deprecated in 0.8+
"""
warnings.warn('The random_density_matrix() function in qiskit.tools.qi has been '
'deprecated and will be removed in the future. Instead use '
'the function in qiskit.quantum_info.random',
DeprecationWarning)
return random.random_density_matrix(length, rank, method, seed)
|
Calculate the concurrence.
|
def concurrence(state):
"""Calculate the concurrence.
Args:
state (np.array): a quantum state (1x4 array) or a density matrix (4x4
array)
Returns:
float: concurrence.
Raises:
Exception: if attempted on more than two qubits.
"""
rho = np.array(state)
if rho.ndim == 1:
rho = outer(state)
if len(state) != 4:
raise Exception("Concurrence is only defined for more than two qubits")
YY = np.fliplr(np.diag([-1, 1, 1, -1]))
A = rho.dot(YY).dot(rho.conj()).dot(YY)
w = la.eigh(A, eigvals_only=True)
w = np.sqrt(np.maximum(w, 0))
return max(0.0, w[-1] - np.sum(w[0:-1]))
|
Compute the Shannon entropy of a probability vector.
|
def shannon_entropy(pvec, base=2):
"""
Compute the Shannon entropy of a probability vector.
The shannon entropy of a probability vector pv is defined as
$H(pv) = - \\sum_j pv[j] log_b (pv[j])$ where $0 log_b 0 = 0$.
Args:
pvec (array_like): a probability vector.
base (int): the base of the logarith
Returns:
float: The Shannon entropy H(pvec).
"""
# pylint: disable=missing-docstring
if base == 2:
def logfn(x):
return - x * np.log2(x)
elif base == np.e:
def logfn(x):
return - x * np.log(x)
else:
def logfn(x):
return -x * np.log(x) / np.log(base)
h = 0.
for x in pvec:
if 0 < x < 1:
h += logfn(x)
return h
|
Compute the von - Neumann entropy of a quantum state.
|
def entropy(state):
"""
Compute the von-Neumann entropy of a quantum state.
Args:
state (array_like): a density matrix or state vector.
Returns:
float: The von-Neumann entropy S(rho).
"""
rho = np.array(state)
if rho.ndim == 1:
return 0
evals = np.maximum(np.linalg.eigvalsh(state), 0.)
return shannon_entropy(evals, base=np.e)
|
Compute the mutual information of a bipartite state.
|
def mutual_information(state, d0, d1=None):
"""
Compute the mutual information of a bipartite state.
Args:
state (array_like): a bipartite state-vector or density-matrix.
d0 (int): dimension of the first subsystem.
d1 (int or None): dimension of the second subsystem.
Returns:
float: The mutual information S(rho_A) + S(rho_B) - S(rho_AB).
"""
if d1 is None:
d1 = int(len(state) / d0)
mi = entropy(partial_trace(state, [0], dimensions=[d0, d1]))
mi += entropy(partial_trace(state, [1], dimensions=[d0, d1]))
mi -= entropy(state)
return mi
|
Compute the entanglement of formation of quantum state.
|
def entanglement_of_formation(state, d0, d1=None):
"""
Compute the entanglement of formation of quantum state.
The input quantum state must be either a bipartite state vector, or a
2-qubit density matrix.
Args:
state (array_like): (N) array_like or (4,4) array_like, a
bipartite quantum state.
d0 (int): the dimension of the first subsystem.
d1 (int or None): the dimension of the second subsystem.
Returns:
float: The entanglement of formation.
"""
state = np.array(state)
if d1 is None:
d1 = int(len(state) / d0)
if state.ndim == 2 and len(state) == 4 and d0 == 2 and d1 == 2:
return __eof_qubit(state)
elif state.ndim == 1:
# trace out largest dimension
if d0 < d1:
tr = [1]
else:
tr = [0]
state = partial_trace(state, tr, dimensions=[d0, d1])
return entropy(state)
else:
print('Input must be a state-vector or 2-qubit density matrix.')
return None
|
Compute the Entanglement of Formation of a 2 - qubit density matrix.
|
def __eof_qubit(rho):
"""
Compute the Entanglement of Formation of a 2-qubit density matrix.
Args:
rho ((array_like): (4,4) array_like, input density matrix.
Returns:
float: The entanglement of formation.
"""
c = concurrence(rho)
c = 0.5 + 0.5 * np.sqrt(1 - c * c)
return shannon_entropy([c, 1 - c])
|
Create a union ( and also shift if desired ) of all input Schedule s.
|
def union(*schedules: List[Union[ScheduleComponent, Tuple[int, ScheduleComponent]]],
name: str = None) -> Schedule:
"""Create a union (and also shift if desired) of all input `Schedule`s.
Args:
*schedules: Schedules to take the union of
name: Name of the new schedule. Defaults to first element of `schedules`
"""
if name is None and schedules:
sched = schedules[0]
if isinstance(sched, (list, tuple)):
name = sched[1].name
else:
name = sched.name
return Schedule(*schedules, name=name)
|
Create a flattened schedule.
|
def flatten(schedule: ScheduleComponent, name: str = None) -> Schedule:
"""Create a flattened schedule.
Args:
schedule: Schedules to flatten
name: Name of the new schedule. Defaults to first element of `schedules`
"""
if name is None:
name = schedule.name
return Schedule(*schedule.instructions, name=name)
|
Return schedule shifted by time.
|
def shift(schedule: ScheduleComponent, time: int, name: str = None) -> Schedule:
"""Return schedule shifted by `time`.
Args:
schedule: The schedule to shift
time: The time to shift by
name: Name of shifted schedule. Defaults to name of `schedule`
"""
if name is None:
name = schedule.name
return union((time, schedule), name=name)
|
Return a new schedule with the child schedule inserted into the parent at start_time.
|
def insert(parent: ScheduleComponent, time: int, child: ScheduleComponent,
name: str = None) -> Schedule:
"""Return a new schedule with the `child` schedule inserted into the `parent` at `start_time`.
Args:
parent: Schedule to be inserted into
time: Time to be inserted defined with respect to `parent`
child: Schedule to insert
name: Name of the new schedule. Defaults to name of parent
"""
return union(parent, (time, child), name=name)
|
r Return a new schedule with by appending child to parent at the last time of the parent schedule s channels over the intersection of the parent and child schedule s channels.
|
def append(parent: ScheduleComponent, child: ScheduleComponent,
name: str = None) -> Schedule:
r"""Return a new schedule with by appending `child` to `parent` at
the last time of the `parent` schedule's channels
over the intersection of the parent and child schedule's channels.
$t = \textrm{max}({x.stop\_time |x \in parent.channels \cap child.channels})$
Args:
parent: The schedule to be inserted into
child: The schedule to insert
name: Name of the new schedule. Defaults to name of parent
"""
common_channels = set(parent.channels) & set(child.channels)
insertion_time = parent.ch_stop_time(*common_channels)
return insert(parent, insertion_time, child, name=name)
|
Apply u3 to q.
|
def u3(self, theta, phi, lam, q):
"""Apply u3 to q."""
return self.append(U3Gate(theta, phi, lam), [q], [])
|
Return backend status.
|
def status(self):
"""Return backend status.
Returns:
BackendStatus: the status of the backend.
"""
return BackendStatus(backend_name=self.name(),
backend_version=__version__,
operational=True,
pending_jobs=0,
status_msg='')
|
Start the progress bar.
|
def start(self, iterations):
"""Start the progress bar.
Parameters:
iterations (int): Number of iterations.
"""
self.touched = True
self.iter = int(iterations)
self.t_start = time.time()
|
Estimate the remaining time left.
|
def time_remaining_est(self, completed_iter):
"""Estimate the remaining time left.
Parameters:
completed_iter (int): Number of iterations completed.
Returns:
est_time: Estimated time remaining.
"""
if completed_iter:
t_r_est = (time.time() - self.t_start) / \
completed_iter*(self.iter-completed_iter)
else:
t_r_est = 0
date_time = datetime.datetime(1, 1, 1) + datetime.timedelta(seconds=t_r_est)
time_string = "%02d:%02d:%02d:%02d" % \
(date_time.day - 1, date_time.hour, date_time.minute, date_time.second)
return time_string
|
Run the CommutativeCancellation pass on a dag
|
def run(self, dag):
"""Run the CommutativeCancellation pass on a dag
Args:
dag (DAGCircuit): the DAG to be optimized.
Returns:
DAGCircuit: the optimized DAG.
Raises:
TranspilerError: when the 1 qubit rotation gates are not found
"""
q_gate_list = ['cx', 'cy', 'cz', 'h', 'x', 'y', 'z']
# Gate sets to be cancelled
cancellation_sets = defaultdict(lambda: [])
for wire in dag.wires:
wire_name = "{0}[{1}]".format(str(wire[0].name), str(wire[1]))
wire_commutation_set = self.property_set['commutation_set'][wire_name]
for com_set_idx, com_set in enumerate(wire_commutation_set):
if com_set[0].type in ['in', 'out']:
continue
for node in com_set:
num_qargs = len(node.qargs)
if num_qargs == 1 and node.name in q_gate_list:
cancellation_sets[(node.name, wire_name, com_set_idx)].append(node)
if num_qargs == 1 and node.name in ['u1', 'rz', 't', 's']:
cancellation_sets[('z_rotation', wire_name, com_set_idx)].append(node)
elif num_qargs == 2 and node.qargs[0] == wire:
second_op_name = "{0}[{1}]".format(str(node.qargs[1][0].name),
str(node.qargs[1][1]))
q2_key = (node.name, wire_name, second_op_name,
self.property_set['commutation_set'][(node, second_op_name)])
cancellation_sets[q2_key].append(node)
for cancel_set_key in cancellation_sets:
set_len = len(cancellation_sets[cancel_set_key])
if ((set_len) > 1 and cancel_set_key[0] in q_gate_list):
gates_to_cancel = cancellation_sets[cancel_set_key]
for c_node in gates_to_cancel[:(set_len // 2) * 2]:
dag.remove_op_node(c_node)
elif((set_len) > 1 and cancel_set_key[0] == 'z_rotation'):
run = cancellation_sets[cancel_set_key]
run_qarg = run[0].qargs[0]
total_angle = 0.0 # lambda
for current_node in run:
if (current_node.condition is not None
or len(current_node.qargs) != 1
or current_node.qargs[0] != run_qarg):
raise TranspilerError("internal error")
if current_node.name in ['u1', 'rz']:
current_angle = float(current_node.op.params[0])
elif current_node.name == 't':
current_angle = sympy.pi / 4
elif current_node.name == 's':
current_angle = sympy.pi / 2
# Compose gates
total_angle = current_angle + total_angle
# Replace the data of the first node in the run
new_op = U1Gate(total_angle)
new_qarg = (QuantumRegister(1, 'q'), 0)
new_dag = DAGCircuit()
new_dag.add_qreg(new_qarg[0])
new_dag.apply_operation_back(new_op, [new_qarg])
dag.substitute_node_with_dag(run[0], new_dag)
# Delete the other nodes in the run
for current_node in run[1:]:
dag.remove_op_node(current_node)
return dag
|
Return a list of QuantumCircuit object ( s ) from a qobj
|
def _experiments_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 = [QuantumRegister(i[1], name=i[0])
for i in x.header.qreg_sizes]
classical_registers = [ClassicalRegister(i[1], name=i[0])
for i in x.header.creg_sizes]
circuit = 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 = []
try:
for qubit in i.qubits:
qubit_label = x.header.qubit_labels[qubit]
qubits.append(
qreg_dict[qubit_label[0]][qubit_label[1]])
except Exception: # pylint: disable=broad-except
pass
clbits = []
try:
for clbit in i.memory:
clbit_label = x.header.clbit_labels[clbit]
clbits.append(
creg_dict[clbit_label[0]][clbit_label[1]])
except Exception: # pylint: disable=broad-except
pass
params = []
try:
params = i.params
except Exception: # pylint: disable=broad-except
pass
if i.name in ['snapshot']:
instr_method(
i.label,
snapshot_type=i.snapshot_type,
qubits=qubits,
params=params)
elif i.name == 'initialize':
instr_method(params, qubits)
else:
instr_method(*params, *qubits, *clbits)
circuits.append(circuit)
return circuits
return None
|
Dissasemble a qobj and return the circuits run_config and user header
|
def disassemble(qobj):
"""Dissasemble a qobj and return the circuits, run_config, and user header
Args:
qobj (Qobj): The input qobj object to dissasemble
Returns:
circuits (list): A list of quantum circuits
run_config (dict): The dist of the run config
user_qobj_header (dict): The dict of any user headers in the qobj
"""
run_config = qobj.config.to_dict()
user_qobj_header = qobj.header.to_dict()
circuits = _experiments_to_circuits(qobj)
return circuits, run_config, user_qobj_header
|
Calculate the Hamming distance between two bit strings
|
def hamming_distance(str1, str2):
"""Calculate the Hamming distance between two bit strings
Args:
str1 (str): First string.
str2 (str): Second string.
Returns:
int: Distance between strings.
Raises:
VisualizationError: Strings not same length
"""
if len(str1) != len(str2):
raise VisualizationError('Strings not same length.')
return sum(s1 != s2 for s1, s2 in zip(str1, str2))
|
Plot a histogram of data.
|
def plot_histogram(data, figsize=(7, 5), color=None, number_to_keep=None,
sort='asc', target_string=None,
legend=None, bar_labels=True, title=None):
"""Plot a histogram of data.
Args:
data (list or dict): This is either a list of dictionaries or a single
dict containing the values to represent (ex {'001': 130})
figsize (tuple): Figure size in inches.
color (list or str): String or list of strings for histogram bar colors.
number_to_keep (int): The number of terms to plot and rest
is made into a single bar called 'rest'.
sort (string): Could be 'asc', 'desc', or 'hamming'.
target_string (str): Target string if 'sort' is a distance measure.
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)
bar_labels (bool): Label each bar in histogram with probability value.
title (str): A string to use for the plot title
Returns:
matplotlib.Figure: A figure for the rendered histogram.
Raises:
ImportError: Matplotlib not available.
VisualizationError: When legend is provided and the length doesn't
match the input data.
"""
if not HAS_MATPLOTLIB:
raise ImportError('Must have Matplotlib installed.')
if sort not in VALID_SORTS:
raise VisualizationError("Value of sort option, %s, isn't a "
"valid choice. Must be 'asc', "
"'desc', or 'hamming'")
elif sort in DIST_MEAS.keys() and target_string is None:
err_msg = 'Must define target_string when using distance measure.'
raise VisualizationError(err_msg)
if isinstance(data, dict):
data = [data]
if legend and len(legend) != len(data):
raise VisualizationError("Length of legendL (%s) doesn't match "
"number of input executions: %s" %
(len(legend), len(data)))
fig, ax = plt.subplots(figsize=figsize)
labels = list(sorted(
functools.reduce(lambda x, y: x.union(y.keys()), data, set())))
if number_to_keep is not None:
labels.append('rest')
if sort in DIST_MEAS.keys():
dist = []
for item in labels:
dist.append(DIST_MEAS[sort](item, target_string))
labels = [list(x) for x in zip(*sorted(zip(dist, labels),
key=lambda pair: pair[0]))][1]
labels_dict = OrderedDict()
# Set bar colors
if color is None:
color = ['#648fff', '#dc267f', '#785ef0', '#ffb000', '#fe6100']
elif isinstance(color, str):
color = [color]
all_pvalues = []
length = len(data)
for item, execution in enumerate(data):
if number_to_keep is not None:
data_temp = dict(Counter(execution).most_common(number_to_keep))
data_temp["rest"] = sum(execution.values()) - sum(data_temp.values())
execution = data_temp
values = []
for key in labels:
if key not in execution:
if number_to_keep is None:
labels_dict[key] = 1
values.append(0)
else:
values.append(-1)
else:
labels_dict[key] = 1
values.append(execution[key])
values = np.array(values, dtype=float)
where_idx = np.where(values >= 0)[0]
pvalues = values[where_idx] / sum(values[where_idx])
for value in pvalues:
all_pvalues.append(value)
numelem = len(values[where_idx])
ind = np.arange(numelem) # the x locations for the groups
width = 1/(len(data)+1) # the width of the bars
rects = []
for idx, val in enumerate(pvalues):
label = None
if not idx and legend:
label = legend[item]
if val >= 0:
rects.append(ax.bar(idx+item*width, val, width, label=label,
color=color[item % len(color)],
zorder=2))
bar_center = (width / 2) * (length - 1)
ax.set_xticks(ind + bar_center)
ax.set_xticklabels(labels_dict.keys(), fontsize=14, rotation=70)
# attach some text labels
if bar_labels:
for rect in rects:
for rec in rect:
height = rec.get_height()
if height >= 1e-3:
ax.text(rec.get_x() + rec.get_width() / 2., 1.05 * height,
'%.3f' % float(height),
ha='center', va='bottom', zorder=3)
else:
ax.text(rec.get_x() + rec.get_width() / 2., 1.05 * height,
'0',
ha='center', va='bottom', zorder=3)
# add some text for labels, title, and axes ticks
ax.set_ylabel('Probabilities', fontsize=14)
ax.set_ylim([0., min([1.2, max([1.2 * val for val in all_pvalues])])])
if sort == 'desc':
ax.invert_xaxis()
ax.yaxis.set_major_locator(MaxNLocator(5))
for tick in ax.yaxis.get_major_ticks():
tick.label.set_fontsize(14)
ax.set_facecolor('#eeeeee')
plt.grid(which='major', axis='y', zorder=0, linestyle='--')
if title:
plt.title(title)
if legend:
ax.legend(loc='upper left', bbox_to_anchor=(1.01, 1.0), ncol=1,
borderaxespad=0, frameon=True, fontsize=12)
if fig:
plt.close(fig)
return fig
|
Return quaternion for rotation about given axis.
|
def quaternion_from_axis_rotation(angle, axis):
"""Return quaternion for rotation about given axis.
Args:
angle (float): Angle in radians.
axis (str): Axis for rotation
Returns:
Quaternion: Quaternion for axis rotation.
Raises:
ValueError: Invalid input axis.
"""
out = np.zeros(4, dtype=float)
if axis == 'x':
out[1] = 1
elif axis == 'y':
out[2] = 1
elif axis == 'z':
out[3] = 1
else:
raise ValueError('Invalid axis input.')
out *= math.sin(angle/2.0)
out[0] = math.cos(angle/2.0)
return Quaternion(out)
|
Generate a quaternion from a set of Euler angles.
|
def quaternion_from_euler(angles, order='yzy'):
"""Generate a quaternion from a set of Euler angles.
Args:
angles (array_like): Array of Euler angles.
order (str): Order of Euler rotations. 'yzy' is default.
Returns:
Quaternion: Quaternion representation of Euler rotation.
"""
angles = np.asarray(angles, dtype=float)
quat = quaternion_from_axis_rotation(angles[0], order[0])\
* (quaternion_from_axis_rotation(angles[1], order[1])
* quaternion_from_axis_rotation(angles[2], order[2]))
quat.normalize(inplace=True)
return quat
|
Normalizes a Quaternion to unit length so that it represents a valid rotation.
|
def normalize(self, inplace=False):
"""Normalizes a Quaternion to unit length
so that it represents a valid rotation.
Args:
inplace (bool): Do an inplace normalization.
Returns:
Quaternion: Normalized quaternion.
"""
if inplace:
nrm = self.norm()
self.data /= nrm
return None
nrm = self.norm()
data_copy = np.array(self.data, copy=True)
data_copy /= nrm
return Quaternion(data_copy)
|
Converts a unit - length quaternion to a rotation matrix.
|
def to_matrix(self):
"""Converts a unit-length quaternion to a rotation matrix.
Returns:
ndarray: Rotation matrix.
"""
w, x, y, z = self.normalize().data # pylint: disable=C0103
mat = np.array([
[1-2*y**2-2*z**2, 2*x*y-2*z*w, 2*x*z+2*y*w],
[2*x*y+2*z*w, 1-2*x**2-2*z**2, 2*y*z-2*x*w],
[2*x*z-2*y*w, 2*y*z+2*x*w, 1-2*x**2-2*y**2]
], dtype=float)
return mat
|
Converts a unit - length quaternion to a sequence of ZYZ Euler angles.
|
def to_zyz(self):
"""Converts a unit-length quaternion to a sequence
of ZYZ Euler angles.
Returns:
ndarray: Array of Euler angles.
"""
mat = self.to_matrix()
euler = np.zeros(3, dtype=float)
if mat[2, 2] < 1:
if mat[2, 2] > -1:
euler[0] = math.atan2(mat[1, 2], mat[0, 2])
euler[1] = math.acos(mat[2, 2])
euler[2] = math.atan2(mat[2, 1], -mat[2, 0])
else:
euler[0] = -math.atan2(mat[1, 0], mat[1, 1])
euler[1] = np.pi
else:
euler[0] = math.atan2(mat[1, 0], mat[1, 1])
return euler
|
Prepare received data for representation.
|
def process_data(data, number_to_keep):
""" Prepare received data for representation.
Args:
data (dict): values to represent (ex. {'001' : 130})
number_to_keep (int): number of elements to show individually.
Returns:
dict: processed data to show.
"""
result = dict()
if number_to_keep != 0:
data_temp = dict(Counter(data).most_common(number_to_keep))
data_temp['rest'] = sum(data.values()) - sum(data_temp.values())
data = data_temp
labels = data
values = np.array([data[key] for key in labels], dtype=float)
pvalues = values / sum(values)
for position, label in enumerate(labels):
result[label] = round(pvalues[position], 5)
return result
|
Create a histogram representation.
|
def iplot_histogram(data, figsize=None, number_to_keep=None,
sort='asc', legend=None):
""" Create a histogram representation.
Graphical representation of the input array using a vertical bars
style graph.
Args:
data (list or dict): This is either a list of dicts or a single
dict containing the values to represent (ex. {'001' : 130})
figsize (tuple): Figure size in pixels.
number_to_keep (int): The number of terms to plot and
rest is made into a single bar called other values
sort (string): Could be 'asc' or 'desc'
legend (list): A list of strings to use for labels of the data.
The number of entries must match the length of data.
Raises:
VisualizationError: When legend is provided and the length doesn't
match the input data.
"""
# HTML
html_template = Template("""
<p>
<div id="histogram_$divNumber"></div>
</p>
""")
# JavaScript
javascript_template = Template("""
<script>
requirejs.config({
paths: {
qVisualization: "https://qvisualization.mybluemix.net/q-visualizations"
}
});
require(["qVisualization"], function(qVisualizations) {
qVisualizations.plotState("histogram_$divNumber",
"histogram",
$executions,
$options);
});
</script>
""")
# Process data and execute
div_number = str(time.time())
div_number = re.sub('[.]', '', div_number)
# set default figure size if none provided
if figsize is None:
figsize = (7, 5)
options = {'number_to_keep': 0 if number_to_keep is None else number_to_keep,
'sort': sort,
'show_legend': 0,
'width': int(figsize[0]),
'height': int(figsize[1])}
if legend:
options['show_legend'] = 1
data_to_plot = []
if isinstance(data, dict):
data = [data]
if legend and len(legend) != len(data):
raise VisualizationError("Length of legendL (%s) doesn't match number "
"of input executions: %s" %
(len(legend), len(data)))
for item, execution in enumerate(data):
exec_data = process_data(execution, options['number_to_keep'])
out_dict = {'data': exec_data}
if legend:
out_dict['name'] = legend[item]
data_to_plot.append(out_dict)
html = html_template.substitute({
'divNumber': div_number
})
javascript = javascript_template.substitute({
'divNumber': div_number,
'executions': data_to_plot,
'options': options
})
display(HTML(html + javascript))
|
Customize check_type for handling containers.
|
def check_type(self, value, attr, data):
"""Customize check_type for handling containers."""
# Check the type in the standard way first, in order to fail quickly
# in case of invalid values.
root_value = super(InstructionParameter, self).check_type(
value, attr, data)
if is_collection(value):
_ = [super(InstructionParameter, self).check_type(item, attr, data)
for item in value]
return root_value
|
Check that j is a valid index into self.
|
def check_range(self, j):
"""Check that j is a valid index into self."""
if isinstance(j, int):
if j < 0 or j >= self.size:
raise QiskitIndexError("register index out of range")
elif isinstance(j, slice):
if j.start < 0 or j.stop >= self.size or (j.step is not None and
j.step <= 0):
raise QiskitIndexError("register index slice out of range")
|
Print with indent.
|
def to_string(self, indent):
"""Print with indent."""
ind = indent * ' '
if self.root:
print(ind, self.type, '---', self.root)
else:
print(ind, self.type)
indent = indent + 3
ind = indent * ' '
for children in self.children:
if children is None:
print("OOPS! type of parent is", type(self))
print(self.children)
if isinstance(children, str):
print(ind, children)
elif isinstance(children, int):
print(ind, str(children))
elif isinstance(children, float):
print(ind, str(children))
else:
children.to_string(indent)
|
Assemble a QasmQobjInstruction
|
def assemble(self):
"""Assemble a QasmQobjInstruction"""
instruction = super().assemble()
if self.label:
instruction.label = self.label
return instruction
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.