_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q268200 | BaseProgressBar.time_remaining_est | test | 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:
| python | {
"resource": ""
} |
q268201 | disassemble | test | 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 | python | {
"resource": ""
} |
q268202 | hamming_distance | test | 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
| python | {
"resource": ""
} |
q268203 | quaternion_from_axis_rotation | test | 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.
| python | {
"resource": ""
} |
q268204 | quaternion_from_euler | test | 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:
| python | {
"resource": ""
} |
q268205 | Quaternion.normalize | test | 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
| python | {
"resource": ""
} |
q268206 | Quaternion.to_matrix | test | 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],
| python | {
"resource": ""
} |
q268207 | Quaternion.to_zyz | test | 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])
| python | {
"resource": ""
} |
q268208 | process_data | test | 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))
| python | {
"resource": ""
} |
q268209 | iplot_histogram | test | 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,
| python | {
"resource": ""
} |
q268210 | InstructionParameter.check_type | test | 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)
| python | {
"resource": ""
} |
q268211 | Register.check_range | test | 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 | python | {
"resource": ""
} |
q268212 | is_square_matrix | test | def is_square_matrix(mat):
"""Test if an array is a square matrix."""
mat = np.array(mat)
if mat.ndim != 2:
| python | {
"resource": ""
} |
q268213 | is_diagonal_matrix | test | def is_diagonal_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
"""Test if an array is a diagonal matrix"""
if atol is None:
atol | python | {
"resource": ""
} |
q268214 | is_symmetric_matrix | test | def is_symmetric_matrix(op, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
"""Test if an array is a symmetrix matrix"""
if atol is None:
atol = ATOL_DEFAULT
if rtol is None:
rtol = RTOL_DEFAULT
mat = | python | {
"resource": ""
} |
q268215 | is_hermitian_matrix | test | def is_hermitian_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
"""Test if an array is a Hermitian matrix"""
if atol is None:
atol = ATOL_DEFAULT
if rtol is None:
rtol = RTOL_DEFAULT
mat = np.array(mat) | python | {
"resource": ""
} |
q268216 | is_positive_semidefinite_matrix | test | def is_positive_semidefinite_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
"""Test if a matrix is positive semidefinite"""
if atol is None:
atol = ATOL_DEFAULT
if rtol is None:
rtol = RTOL_DEFAULT
if not is_hermitian_matrix(mat, rtol=rtol, atol=atol):
return False
| python | {
"resource": ""
} |
q268217 | is_identity_matrix | test | def is_identity_matrix(mat,
ignore_phase=False,
rtol=RTOL_DEFAULT,
atol=ATOL_DEFAULT):
"""Test if an array is an identity matrix."""
if atol is None:
atol = ATOL_DEFAULT
if rtol is None:
rtol = RTOL_DEFAULT
mat = np.array(mat)
if mat.ndim != 2:
return False
if ignore_phase:
# If the matrix is equal to an identity up to a phase, we can
# remove the phase by multiplying each entry by the complex
| python | {
"resource": ""
} |
q268218 | is_unitary_matrix | test | def is_unitary_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
"""Test if an array is a unitary matrix."""
if atol is None:
atol = ATOL_DEFAULT
if rtol is None:
rtol = RTOL_DEFAULT
mat = np.array(mat)
# Compute A^dagger.A and see if | python | {
"resource": ""
} |
q268219 | _to_choi | test | def _to_choi(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Choi representation."""
if rep == 'Choi':
return data
if rep == 'Operator':
return _from_operator('Choi', data, input_dim, output_dim)
if rep == 'SuperOp':
return _superop_to_choi(data, input_dim, output_dim)
if rep == 'Kraus':
return _kraus_to_choi(data, input_dim, output_dim)
if rep == 'Chi':
| python | {
"resource": ""
} |
q268220 | _to_superop | test | def _to_superop(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the SuperOp representation."""
if rep == 'SuperOp':
return data
if rep == 'Operator':
return _from_operator('SuperOp', data, input_dim, output_dim)
if rep == 'Choi':
return _choi_to_superop(data, input_dim, output_dim)
if rep == 'Kraus':
return _kraus_to_superop(data, input_dim, output_dim)
if rep == 'Chi':
| python | {
"resource": ""
} |
q268221 | _to_kraus | test | def _to_kraus(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Kraus representation."""
if rep == 'Kraus':
return data
if rep == 'Stinespring':
return _stinespring_to_kraus(data, input_dim, output_dim)
if rep == 'Operator':
| python | {
"resource": ""
} |
q268222 | _to_chi | test | def _to_chi(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Chi representation."""
if rep == 'Chi':
return data
# Check valid n-qubit input
_check_nqubit_dim(input_dim, output_dim)
if rep == 'Operator':
return | python | {
"resource": ""
} |
q268223 | _to_ptm | test | def _to_ptm(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the PTM representation."""
if rep == 'PTM':
return data
# Check valid n-qubit input
_check_nqubit_dim(input_dim, output_dim)
if rep == 'Operator':
return | python | {
"resource": ""
} |
q268224 | _to_stinespring | test | def _to_stinespring(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Stinespring representation."""
if rep == 'Stinespring':
return data
if rep == 'Operator':
return _from_operator('Stinespring', data, input_dim, output_dim)
| python | {
"resource": ""
} |
q268225 | _to_operator | test | def _to_operator(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Operator representation."""
if rep == 'Operator':
return data
if rep == 'Stinespring':
return _stinespring_to_operator(data, input_dim, output_dim)
| python | {
"resource": ""
} |
q268226 | _from_operator | test | def _from_operator(rep, data, input_dim, output_dim):
"""Transform Operator representation to other representation."""
if rep == 'Operator':
return data
if rep == 'SuperOp':
return np.kron(np.conj(data), data)
if rep == 'Choi':
vec = np.ravel(data, order='F')
return np.outer(vec, np.conj(vec))
if rep == 'Kraus':
return ([data], None)
if rep == 'Stinespring':
return (data, None)
if rep == 'Chi':
_check_nqubit_dim(input_dim, output_dim)
data = _from_operator('Choi', data, input_dim, output_dim)
return _choi_to_chi(data, input_dim, | python | {
"resource": ""
} |
q268227 | _stinespring_to_operator | test | def _stinespring_to_operator(data, input_dim, output_dim):
"""Transform Stinespring representation to Operator representation."""
trace_dim = data[0].shape[0] // output_dim
if data[1] is not None or trace_dim != | python | {
"resource": ""
} |
q268228 | _superop_to_choi | test | def _superop_to_choi(data, input_dim, output_dim):
"""Transform SuperOp representation to Choi representation."""
shape = | python | {
"resource": ""
} |
q268229 | _choi_to_superop | test | def _choi_to_superop(data, input_dim, output_dim):
"""Transform Choi to SuperOp | python | {
"resource": ""
} |
q268230 | _kraus_to_choi | test | def _kraus_to_choi(data, input_dim, output_dim):
"""Transform Kraus representation to Choi representation."""
choi = 0
kraus_l, kraus_r = data
if kraus_r is None:
for i in kraus_l:
vec = i.ravel(order='F')
| python | {
"resource": ""
} |
q268231 | _choi_to_kraus | test | def _choi_to_kraus(data, input_dim, output_dim, atol=ATOL_DEFAULT):
"""Transform Choi representation to Kraus representation."""
# Check if hermitian matrix
if is_hermitian_matrix(data, atol=atol):
# Get eigen-decomposition of Choi-matrix
w, v = la.eigh(data)
# Check eigenvaleus are non-negative
if len(w[w < -atol]) == 0:
# CP-map Kraus representation
kraus = []
for val, vec in zip(w, v.T):
if abs(val) > atol:
k = np.sqrt(val) * vec.reshape(
(output_dim, input_dim), order='F')
kraus.append(k)
# If we are converting a zero matrix, we need to return a Kraus set
# with a single zero-element Kraus matrix
if not kraus:
kraus.append(np.zeros((output_dim, input_dim), dtype=complex))
return (kraus, None)
| python | {
"resource": ""
} |
q268232 | _stinespring_to_kraus | test | 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 = np.eye(output_dim)
kraus = []
for j in range(trace_dim):
| python | {
"resource": ""
} |
q268233 | _stinespring_to_choi | test | 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 | python | {
"resource": ""
} |
q268234 | _kraus_to_stinespring | test | 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)
| python | {
"resource": ""
} |
q268235 | _kraus_to_superop | test | 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:
| python | {
"resource": ""
} |
q268236 | _chi_to_choi | test | def _chi_to_choi(data, input_dim, output_dim):
"""Transform Chi representation to a Choi representation."""
num_qubits | python | {
"resource": ""
} |
q268237 | _choi_to_chi | test | def _choi_to_chi(data, input_dim, output_dim):
"""Transform Choi representation to the Chi representation."""
num_qubits | python | {
"resource": ""
} |
q268238 | _reravel | test | 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 | python | {
"resource": ""
} |
q268239 | _transform_from_pauli | test | 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 change of basis
# to avoid rounding errors from square-roots of 2.
cob = basis_mat
for _ in range(num_qubits - 1):
dim = int(np.sqrt(len(cob)))
cob = np.reshape(
np.transpose(
| python | {
"resource": ""
} |
q268240 | _check_nqubit_dim | test | 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 = | python | {
"resource": ""
} |
q268241 | _hide_tick_lines_and_labels | test | def _hide_tick_lines_and_labels(axis):
"""
Set visible property of ticklines and ticklabels of an axis to False
"""
for item in | python | {
"resource": ""
} |
q268242 | Bloch.set_label_convention | test | 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"
- "polarization jones"
- "polarization jones letters"
see also: http://en.wikipedia.org/wiki/Jones_calculus
- "polarization stokes"
see also: http://en.wikipedia.org/wiki/Stokes_parameters
Raises:
Exception: If convention is not valid.
"""
ketex = "$\\left.|%s\\right\\rangle$"
# \left.| is on purpose, so that every ket has the same size
if convention == "original":
self.xlabel = ['$x$', '']
self.ylabel = ['$y$', '']
self.zlabel = ['$\\left|0\\right>$', '$\\left|1\\right>$']
elif convention == "xyz":
| python | {
"resource": ""
} |
q268243 | Bloch.clear | test | def clear(self):
"""Resets Bloch sphere data sets to empty.
"""
self.points = []
| python | {
"resource": ""
} |
q268244 | Bloch.add_vectors | test | 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)):
| python | {
"resource": ""
} |
q268245 | Bloch.add_annotation | test | 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 elements.
text (str):
Annotation text.
You can use LaTeX, but remember to use raw string
e.g. r"$\\langle x \\rangle$"
| python | {
"resource": ""
} |
q268246 | Bloch.render | test | 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 = plt.figure(figsize=self.figsize)
if not self._ext_axes:
self.axes = Axes3D(self.fig, azim=self.view[0], elev=self.view[1])
| python | {
"resource": ""
} |
q268247 | Bloch.plot_front | test | 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.cos(v_angle))
self.axes.plot_surface(x_dir, y_dir, z_dir, rstride=2, cstride=2,
color=self.sphere_color, linewidth=0,
| python | {
"resource": ""
} |
q268248 | Bloch.show | test | def show(self, title=''):
"""
Display Bloch sphere and corresponding data sets.
"""
| python | {
"resource": ""
} |
q268249 | two_qubit_kak | test | def two_qubit_kak(unitary_matrix, verify_gate_sequence=False):
"""Deprecated after 0.8
"""
warnings.warn("two_qubit_kak function is now accessible under "
| python | {
"resource": ""
} |
q268250 | DrawElement.top | test | 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:
| python | {
"resource": ""
} |
q268251 | DrawElement.mid | test | 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: | python | {
"resource": ""
} |
q268252 | DrawElement.bot | test | 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: | python | {
"resource": ""
} |
q268253 | DrawElement.length | test | def length(self):
""" Returns the length of the element, including the box around."""
| python | {
"resource": ""
} |
q268254 | TextDrawing.params_for_label | test | 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.op.params]):
return None
| python | {
"resource": ""
} |
q268255 | TextDrawing.label_for_box | test | def label_for_box(instruction):
""" Creates the label for a box."""
label = instruction.name.capitalize()
| python | {
"resource": ""
} |
q268256 | Id.latex | test | 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: ",
"name=%s, " % self.name,
| python | {
"resource": ""
} |
q268257 | compile | test | def compile(circuits, backend,
config=None, basis_gates=None, coupling_map=None, initial_layout=None,
shots=1024, max_credits=10, seed=None, qobj_id=None, seed_mapper=None,
pass_manager=None, memory=False):
"""Compile a list of circuits into a qobj.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend): a backend to compile for
config (dict): dictionary of parameters (e.g. noise) used by runner
basis_gates (list[str]): list of basis gates names supported by the
target. Default: ['u1','u2','u3','cx','id']
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (list): initial layout of qubits in mapping
shots (int): number of repetitions of each circuit, for sampling
max_credits (int): maximum credits to use
seed (int): random seed for simulators
seed_mapper (int): random seed for swapper mapper
qobj_id (int): identifier for the generated qobj
pass_manager (PassManager): a pass manger for the transpiler pipeline
memory (bool): if True, per-shot measurement bitstrings are returned as well
Returns:
Qobj: the qobj to be run on the backends
Raises:
QiskitError: if the desired options are not supported by backend
"""
warnings.warn('qiskit.compile() is deprecated and will be removed in Qiskit Terra 0.9. '
| python | {
"resource": ""
} |
q268258 | _filter_deprecation_warnings | test | 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`
messages.
TODO: on Python 3.7, this might not be needed due to PEP-0565 [2].
[1] https://docs.python.org/3/library/warnings.html#default-warning-filters
[2] https://www.python.org/dev/peps/pep-0565/
"""
deprecation_filter = ('always', None, DeprecationWarning,
re.compile(r'^qiskit\.*', re.UNICODE), 0)
# Instead of using warnings.simple_filter() directly, the internal
# _add_filter() function is used for being able to match against the
| python | {
"resource": ""
} |
q268259 | local_hardware_info | test | 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 | python | {
"resource": ""
} |
q268260 | _has_connection | test | 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:
bool: Has connection | python | {
"resource": ""
} |
q268261 | _html_checker | test | 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 ipywidget for output ot screen
header (str): String representing HTML code for status.
_interval_set (bool): Was interval set by user?
"""
job_status = job_var.status()
job_status_name = job_status.name
job_status_msg = job_status.value
status.value = header % (job_status_msg)
while job_status_name not in ['DONE', 'CANCELLED']:
time.sleep(interval)
job_status = job_var.status()
job_status_name = job_status.name
job_status_msg = job_status.value
| python | {
"resource": ""
} |
q268262 | constant | test | def constant(times: np.ndarray, amp: complex) -> np.ndarray:
"""Continuous constant pulse.
Args:
times: Times to output pulse for.
| python | {
"resource": ""
} |
q268263 | square | test | 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.
| python | {
"resource": ""
} |
q268264 | triangle | test | 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.
| python | {
"resource": ""
} |
q268265 | cos | test | 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.
| python | {
"resource": ""
} |
q268266 | _fix_gaussian_width | test | 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 width.
This is acheived by subtracting $\Omega_g(center \pm zeroed_width/2)$ from all samples.
amp: Pulse amplitude at `2\times center+1`.
center: Center (mean) of pulse.
sigma: Width (standard deviation) of pulse.
zeroed_width: Subtract baseline to gaussian pulses to make sure
$\Omega_g(center \pm zeroed_width/2)=0$ is satisfied. This is used to avoid
large discontinuities at the start of a gaussian pulse. If unsupplied,
defaults to $2*(center+1)$ such that the samples are zero at $\Omega_g(-1)$.
| python | {
"resource": ""
} |
q268267 | gaussian | test | 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 curve is $\Omega_g(amp, sigma) = amp \times np.sqrt(2\pi \sigma^2)$
Args:
times: Times to output pulse for.
amp: Pulse amplitude at `center`. If `zeroed_width` is set pulse amplitude at center
will be $amp-\Omega_g(center\pm zeroed_width/2)$ unless `rescale_amp` is set,
in which case all samples will be rescaled such that the center
amplitude will be `amp`.
center: Center (mean) of pulse.
sigma: Width (standard deviation) of pulse.
zeroed_width: Subtract baseline to gaussian pulses to make sure
$\Omega_g(center \pm zeroed_width/2)=0$ is satisfied. This is used to avoid
large discontinuities at the start of a gaussian pulse.
rescale_amp: If `zeroed_width` is not `None` and `rescale_amp=True` the pulse will
be rescaled so that | python | {
"resource": ""
} |
q268268 | gaussian_deriv | test | 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 (mean) of pulse.
sigma: Width (standard deviation) of pulse.
| python | {
"resource": ""
} |
q268269 | gaussian_square | test | 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 of the square pulse component.
width: Width of the square pulse component.
sigma: Width (standard deviation) of gaussian rise/fall portion of the pulse.
zeroed_width: Subtract baseline of gaussian square pulse
to enforce $\OmegaSquare(center \pm zeroed_width/2)=0$.
"""
square_start = center-width/2
square_stop = center+width/2
if zeroed_width:
zeroed_width = min(width, zeroed_width)
gauss_zeroed_width = zeroed_width-width
| python | {
"resource": ""
} |
q268270 | default_pass_manager | test | 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.
initial_layout (Layout or None): initial layout of virtual qubits on physical qubits
seed_transpiler (int or None): random seed for stochastic passes.
Returns:
PassManager: A pass manager to map and optimize.
"""
pass_manager = PassManager()
pass_manager.property_set['layout'] = initial_layout
pass_manager.append(Unroller(basis_gates))
# Use the trivial layout if no layout is found
pass_manager.append(TrivialLayout(coupling_map),
condition=lambda property_set: not property_set['layout'])
# if the circuit and layout already satisfy the coupling_constraints, use that layout
# otherwise layout on the most densely connected physical qubit subset
pass_manager.append(CheckMap(coupling_map))
pass_manager.append(DenseLayout(coupling_map),
condition=lambda property_set: not property_set['is_swap_mapped'])
| python | {
"resource": ""
} |
q268271 | default_pass_manager_simulator | test | 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 = PassManager() | python | {
"resource": ""
} |
q268272 | QuantumCircuit.has_register | test | def has_register(self, register):
"""
Test if this circuit has the register r.
Args:
register (Register): a quantum or classical register.
Returns:
bool: True if the register is contained in this circuit.
"""
has_reg = False
if (isinstance(register, QuantumRegister) | python | {
"resource": ""
} |
q268273 | QuantumCircuit.mirror | test | 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')
| python | {
"resource": ""
} |
q268274 | QuantumCircuit.inverse | test | 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')
| python | {
"resource": ""
} |
q268275 | QuantumCircuit.append | test | 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
cargs (list(tuple)): clbits to attach instruction to
Returns:
Instruction: a handle to the instruction that was just added
Raises:
QiskitError: if the gate is of a different shape than the wires
it is being attached to.
"""
qargs = qargs or []
cargs = cargs or []
# Convert input to instruction
if not isinstance(instruction, Instruction) and hasattr(instruction, 'to_instruction'):
instruction = instruction.to_instruction()
if not isinstance(instruction, Instruction):
raise QiskitError('object is not an Instruction.')
# do some compatibility checks
self._check_dups(qargs)
self._check_qargs(qargs)
self._check_cargs(cargs)
if instruction.num_qubits != len(qargs) or \
instruction.num_clbits != len(cargs):
raise QiskitError("instruction %s with %d qubits and %d clbits "
| python | {
"resource": ""
} |
q268276 | QuantumCircuit._attach | test | def _attach(self, instruction, qargs, cargs):
"""DEPRECATED after 0.8"""
| python | {
"resource": ""
} |
q268277 | QuantumCircuit.add_register | test | 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 quantum wires e.g. QuantumCircuit(2)
regs = (QuantumRegister(regs[0], 'q'),)
elif len(regs) == 2 and all([isinstance(reg, int) for reg in regs]):
# QuantumCircuit with anonymous wires e.g. QuantumCircuit(2, 3)
regs = (QuantumRegister(regs[0], 'q'), ClassicalRegister(regs[1], 'c'))
else:
raise QiskitError("QuantumCircuit parameters can be Registers or Integers."
" If Integers, up to 2 arguments. QuantumCircuit was called"
" with %s." % (regs,))
| python | {
"resource": ""
} |
q268278 | QuantumCircuit._check_dups | test | def _check_dups(self, qubits):
"""Raise exception if list of qubits contains duplicates."""
squbits = set(qubits)
| python | {
"resource": ""
} |
q268279 | QuantumCircuit._check_qargs | test | 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 | python | {
"resource": ""
} |
q268280 | QuantumCircuit._check_cargs | test | 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 | python | {
"resource": ""
} |
q268281 | QuantumCircuit._check_compatible_regs | test | 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:
| python | {
"resource": ""
} |
q268282 | QuantumCircuit.qasm | test | 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"
for instruction, qargs, cargs in self.data:
if instruction.name == 'measure':
qubit = qargs[0]
clbit = cargs[0]
string_temp += "%s %s[%d] -> %s[%d];\n" % (instruction.qasm(),
qubit[0].name, qubit[1],
| python | {
"resource": ""
} |
q268283 | QuantumCircuit.draw | test | 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: ASCII art string
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overcomplete basis, in order to not alter gates.
Args:
scale (float): scale of image to draw (shrink if < 1)
filename (str): file path to save image to
style (dict or str): dictionary of style or file name of style
file. You can refer to the
:ref:`Style Dict Doc <style-dict-doc>` for more information
on the contents.
output (str): Select the output method to use for drawing the
circuit. Valid choices are `text`, `latex`, `latex_source`,
`mpl`.
interactive (bool): when set true show the circuit in a new window
(for `mpl` this depends on the matplotlib backend being used
supporting this). Note when used with either the `text` or the
`latex_source` output type this has no effect and will be
silently ignored.
line_length (int): sets the length of the lines generated by `text`
reverse_bits (bool): When set to True reverse the bit order inside
registers for the output visualization.
plot_barriers (bool): Enable/disable drawing barriers in the output
circuit. Defaults to True.
justify (string): Options are `left`, `right` or `none`, if anything
else is supplied it defaults to left justified. It refers to where
gates should be placed in the output circuit if there is an option.
`none` results in each gate being placed in its own column. Currently
only supported by text drawer.
Returns:
PIL.Image or matplotlib.figure or str or | python | {
"resource": ""
} |
q268284 | QuantumCircuit.size | test | 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:
| python | {
"resource": ""
} |
q268285 | QuantumCircuit.width | test | def width(self):
"""Return number of qubits plus clbits in circuit.
| python | {
"resource": ""
} |
q268286 | QuantumCircuit.count_ops | test | 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:
| python | {
"resource": ""
} |
q268287 | QuantumCircuit.num_connected_components | test | 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.
"""
# Convert registers to ints (as done in depth).
reg_offset = 0
reg_map = {}
if unitary_only:
regs = self.qregs
else:
regs = self.qregs+self.cregs
for reg in regs:
reg_map[reg.name] = reg_offset
reg_offset += reg.size
# Start with each qubit or cbit being its own subgraph.
sub_graphs = [[bit] for bit in range(reg_offset)]
num_sub_graphs = len(sub_graphs)
# Here we are traversing the gates and looking to see
# which of the sub_graphs the gate joins together.
for instr, qargs, cargs in self.data:
if unitary_only:
args = qargs
num_qargs = len(args)
else:
args = qargs+cargs
num_qargs = len(args) + (1 if instr.control else 0)
if num_qargs >= 2 and instr.name not in ['barrier', 'snapshot']:
graphs_touched = []
num_touched = 0
# Controls necessarily join all the cbits in the
# register that they use.
if instr.control and not unitary_only:
creg = instr.control[0]
creg_int = reg_map[creg.name]
for coff in range(creg.size):
temp_int = creg_int+coff
for k in range(num_sub_graphs):
if temp_int in sub_graphs[k]:
graphs_touched.append(k)
| python | {
"resource": ""
} |
q268288 | QuantumCircuit.bind_parameters | test | 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: copy of self with assignment substitution.
"""
new_circuit = self.copy()
if value_dict.keys() > self.parameters:
raise QiskitError('Cannot bind parameters ({}) not present in the circuit.'.format(
[str(p) for | python | {
"resource": ""
} |
q268289 | QuantumCircuit._bind_parameter | test | def _bind_parameter(self, parameter, value):
"""Assigns a parameter value to matching instructions in-place."""
| python | {
"resource": ""
} |
q268290 | pulse_drawer | test | 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): Pulse length (number of points).
dt (float): Time interval of samples.
interp_method (str): Method of interpolation
(set `None` for turn off the interpolation).
filename (str): Name required to save pulse image.
interactive (bool): When set true show the circuit in a new window
(this depends on the matplotlib backend being used supporting this).
dpi (int): Resolution of saved image.
nop (int): Data points for interpolation.
size (tuple): Size of figure.
Returns:
matplotlib.figure: A matplotlib figure object for the pulse envelope.
Raises:
ImportError: when the output methods requieres non-installed libraries.
QiskitError: when invalid interpolation method is specified.
"""
try:
from matplotlib import pyplot as plt
except ImportError:
raise ImportError('pulse_drawer need matplotlib. '
| python | {
"resource": ""
} |
q268291 | _search_forward_n_swaps | test | def _search_forward_n_swaps(layout, gates, coupling_map,
depth=SEARCH_DEPTH, width=SEARCH_WIDTH):
"""Search for SWAPs which allow for application of largest number of gates.
Arguments:
layout (Layout): Map from virtual qubit index to physical qubit index.
gates (list): Gates to be mapped.
coupling_map (CouplingMap): CouplingMap of the target backend.
depth (int): Number of SWAP layers to search before choosing a result.
width (int): Number of SWAPs to consider at each layer.
Returns:
dict: Describes solution step found.
layout (Layout): Virtual to physical qubit map after SWAPs.
gates_remaining (list): Gates that could not be mapped.
gates_mapped (list): Gates that were mapped, including added SWAPs.
"""
gates_mapped, gates_remaining = _map_free_gates(layout, gates, coupling_map)
base_step = {'layout': layout,
'swaps_added': 0,
'gates_mapped': gates_mapped,
'gates_remaining': gates_remaining}
if not gates_remaining or depth == 0:
return base_step
possible_swaps = coupling_map.get_edges()
def _score_swap(swap):
"""Calculate the relative score for a given SWAP."""
trial_layout = layout.copy()
trial_layout.swap(*swap)
return _calc_layout_distance(gates, coupling_map, trial_layout)
| python | {
"resource": ""
} |
q268292 | _map_free_gates | test | def _map_free_gates(layout, gates, coupling_map):
"""Map all gates that can be executed with the current layout.
Args:
layout (Layout): Map from virtual qubit index to physical qubit index.
gates (list): Gates to be mapped.
coupling_map (CouplingMap): CouplingMap for target device topology.
Returns:
tuple:
mapped_gates (list): ops for gates that can be executed, mapped onto layout.
remaining_gates (list): gates that cannot be executed on the layout.
"""
blocked_qubits = set()
mapped_gates = []
remaining_gates = []
for gate in gates:
# Gates without a partition (barrier, snapshot, save, load, noise) may
# still have associated qubits. Look for them in the qargs.
if not gate['partition']:
qubits = [n for n in gate['graph'].nodes() if n.type == 'op'][0].qargs
if not qubits:
continue
if blocked_qubits.intersection(qubits):
blocked_qubits.update(qubits)
remaining_gates.append(gate)
else:
| python | {
"resource": ""
} |
q268293 | _calc_layout_distance | test | 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.
| python | {
"resource": ""
} |
q268294 | _score_step | test | 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 | python | {
"resource": ""
} |
q268295 | _copy_circuit_metadata | test | 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."""
| python | {
"resource": ""
} |
q268296 | _transform_gate_for_layout | test | 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.get_physical_bits()), 'q') | python | {
"resource": ""
} |
q268297 | _swap_ops_from_edge | test | def _swap_ops_from_edge(edge, layout):
"""Generate list of ops to implement a SWAP gate along a coupling edge."""
device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q')
qreg_edge = [(device_qreg, i) for i in edge]
| python | {
"resource": ""
} |
q268298 | LookaheadSwap.run | test | def run(self, dag):
"""Run one pass of the lookahead mapper on the provided DAG.
Args:
dag (DAGCircuit): the directed acyclic graph to be mapped
Returns:
DAGCircuit: A dag mapped to be compatible with the coupling_map in
the property_set.
Raises:
TranspilerError: if the coupling map or the layout are not
compatible with the DAG
"""
coupling_map = self._coupling_map
ordered_virtual_gates = list(dag.serial_layers())
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
if len(dag.qubits()) != len(self.initial_layout):
raise TranspilerError('The layout does not match the amount of qubits in the DAG')
if len(self._coupling_map.physical_qubits) != len(self.initial_layout):
raise TranspilerError(
"Mappers require to have the layout to be the same size as the coupling map")
mapped_gates = []
layout = self.initial_layout.copy()
gates_remaining = ordered_virtual_gates.copy()
while gates_remaining:
| python | {
"resource": ""
} |
q268299 | CouplingMap.add_physical_qubit | test | def add_physical_qubit(self, physical_qubit):
"""Add a physical qubit to the coupling graph as a node.
physical_qubit (int): An integer representing a physical qubit.
Raises:
CouplingError: if trying to add duplicate qubit
"""
if not isinstance(physical_qubit, int):
raise CouplingError("Physical qubits should be integers.")
if | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.