_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
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: 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
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 """ 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
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 """ if len(str1) != len(str2): raise VisualizationError('Strings not same length.') return sum(s1 != s2 for s1, s2 in zip(str1, str2))
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. 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)
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: 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
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 return None nrm = self.norm() data_copy = np.array(self.data, copy=True) data_copy /= nrm return Quaternion(data_copy)
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], [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
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]) 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
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)) 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
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, '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))
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) if is_collection(value): _ = [super(InstructionParameter, self).check_type(item, attr, data) for item in value] return root_value
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 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")
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: return False shape = mat.shape return shape[0] == shape[1]
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 = ATOL_DEFAULT if rtol is None: rtol = RTOL_DEFAULT mat = np.array(mat) if mat.ndim != 2: return False return np.allclose(mat, np.diag(np.diagonal(mat)), rtol=rtol, atol=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 = np.array(op) if mat.ndim != 2: return False return np.allclose(mat, mat.T, rtol=rtol, atol=atol)
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) if mat.ndim != 2: return False return np.allclose(mat, np.conj(mat.T), rtol=rtol, atol=atol)
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 # Check eigenvalues are all positive vals = np.linalg.eigvalsh(mat) for v in vals: if v < -atol: return False return True
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 # conjugate of the phase of the [0, 0] entry. theta = np.angle(mat[0, 0]) mat = np.exp(-1j * theta) * mat # Check if square identity iden = np.eye(len(mat)) return np.allclose(mat, iden, rtol=rtol, atol=atol)
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 it is identity matrix mat = np.conj(mat.T).dot(mat) return is_identity_matrix(mat, ignore_phase=False, rtol=rtol, atol=atol)
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': return _chi_to_choi(data, input_dim, output_dim) if rep == 'PTM': data = _ptm_to_superop(data, input_dim, output_dim) return _superop_to_choi(data, input_dim, output_dim) if rep == 'Stinespring': return _stinespring_to_choi(data, input_dim, output_dim) raise QiskitError('Invalid QuantumChannel {}'.format(rep))
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': data = _chi_to_choi(data, input_dim, output_dim) return _choi_to_superop(data, input_dim, output_dim) if rep == 'PTM': return _ptm_to_superop(data, input_dim, output_dim) if rep == 'Stinespring': return _stinespring_to_superop(data, input_dim, output_dim) raise QiskitError('Invalid QuantumChannel {}'.format(rep))
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': return _from_operator('Kraus', data, input_dim, output_dim) # Convert via Choi and Kraus if rep != 'Choi': data = _to_choi(rep, data, input_dim, output_dim) return _choi_to_kraus(data, input_dim, output_dim)
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 _from_operator('Chi', data, input_dim, output_dim) # Convert via Choi representation if rep != 'Choi': data = _to_choi(rep, data, input_dim, output_dim) return _choi_to_chi(data, input_dim, output_dim)
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 _from_operator('PTM', data, input_dim, output_dim) # Convert via Superoperator representation if rep != 'SuperOp': data = _to_superop(rep, data, input_dim, output_dim) return _superop_to_ptm(data, input_dim, output_dim)
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) # Convert via Superoperator representation if rep != 'Kraus': data = _to_kraus(rep, data, input_dim, output_dim) return _kraus_to_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) # Convert via Kraus representation if rep != 'Kraus': data = _to_kraus(rep, data, input_dim, output_dim) return _kraus_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, output_dim) if rep == 'PTM': _check_nqubit_dim(input_dim, output_dim) data = _from_operator('SuperOp', data, input_dim, output_dim) return _superop_to_ptm(data, input_dim, output_dim) raise QiskitError('Invalid QuantumChannel {}'.format(rep))
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 != 1: raise QiskitError( 'Channel cannot be converted to Operator representation') return data[0]
python
{ "resource": "" }
q268228
_superop_to_choi
test
def _superop_to_choi(data, input_dim, output_dim): """Transform SuperOp representation to Choi representation.""" shape = (output_dim, output_dim, input_dim, input_dim) return _reshuffle(data, shape)
python
{ "resource": "" }
q268229
_choi_to_superop
test
def _choi_to_superop(data, input_dim, output_dim): """Transform Choi to SuperOp representation.""" shape = (input_dim, output_dim, input_dim, output_dim) return _reshuffle(data, shape)
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') choi += np.outer(vec, vec.conj()) else: for i, j in zip(kraus_l, kraus_r): choi += np.outer(i.ravel(order='F'), j.ravel(order='F').conj()) return choi
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) # Non-CP-map generalized Kraus representation mat_u, svals, mat_vh = la.svd(data) kraus_l = [] kraus_r = [] for val, vec_l, vec_r in zip(svals, mat_u.T, mat_vh.conj()): kraus_l.append( np.sqrt(val) * vec_l.reshape((output_dim, input_dim), order='F')) kraus_r.append( np.sqrt(val) * vec_r.reshape((output_dim, input_dim), order='F')) return (kraus_l, kraus_r)
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): vec = np.zeros(trace_dim) vec[j] = 1 kraus.append(np.kron(iden, vec[None, :]).dot(stine)) kraus_pair.append(kraus) return tuple(kraus_pair)
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 = np.reshape(data[1], (output_dim, trace_dim, input_dim)) return np.reshape( np.einsum('iAj,kAl->jilk', stine_l, stine_r.conj()), 2 * [input_dim * output_dim])
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) stine = np.zeros((output_dim * num_kraus, input_dim), dtype=complex) for j, mat in enumerate(kraus): vec = np.zeros(num_kraus) vec[j] = 1 stine += np.kron(mat, vec[:, None]) stine_pair[i] = stine return tuple(stine_pair)
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: superop += np.kron(np.conj(i), i) else: for i, j in zip(kraus_l, kraus_r): superop += np.kron(np.conj(j), i) return superop
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 = int(np.log2(input_dim)) return _transform_from_pauli(data, 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 = int(np.log2(input_dim)) return _transform_to_pauli(data, 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 product matrices data = np.kron(mat1, mat2) data = np.reshape( np.transpose(np.reshape(data, tensor_shape), (0, 2, 1, 3, 4, 6, 5, 7)), final_shape) return data
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( np.reshape( np.kron(basis_mat, cob), (2, 2, dim, dim, 4, dim * dim)), (0, 2, 1, 3, 4, 5)), (4 * dim * dim, 4 * dim * dim)) return np.dot(np.dot(cob, data), cob.conj().T) / 2**num_qubits
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 = int(np.log2(input_dim)) if 2**num_qubits != input_dim: raise QiskitError('Not an n-qubit channel: input_dim != 2 ** n')
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 axis.get_ticklines() + axis.get_ticklabels(): item.set_visible(False)
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": self.xlabel = ['$x$', ''] self.ylabel = ['$y$', ''] self.zlabel = ['$z$', ''] elif convention == "sx sy sz": self.xlabel = ['$s_x$', ''] self.ylabel = ['$s_y$', ''] self.zlabel = ['$s_z$', ''] elif convention == "01": self.xlabel = ['', ''] self.ylabel = ['', ''] self.zlabel = ['$\\left|0\\right>$', '$\\left|1\\right>$'] elif convention == "polarization jones": self.xlabel = [ketex % "\\nearrow\\hspace{-1.46}\\swarrow", ketex % "\\nwarrow\\hspace{-1.46}\\searrow"] self.ylabel = [ketex % "\\circlearrowleft", ketex % "\\circlearrowright"] self.zlabel = [ketex % "\\leftrightarrow", ketex % "\\updownarrow"] elif convention == "polarization jones letters": self.xlabel = [ketex % "D", ketex % "A"] self.ylabel = [ketex % "L", ketex % "R"] self.zlabel = [ketex % "H", ketex % "V"] elif convention == "polarization stokes": self.ylabel = ["$\\nearrow\\hspace{-1.46}\\swarrow$", "$\\nwarrow\\hspace{-1.46}\\searrow$"] self.zlabel = ["$\\circlearrowleft$", "$\\circlearrowright$"] self.xlabel = ["$\\leftrightarrow$", "$\\updownarrow$"] else: raise Exception("No such convention.")
python
{ "resource": "" }
q268243
Bloch.clear
test
def clear(self): """Resets Bloch sphere data sets to empty. """ self.points = [] self.vectors = [] self.point_style = [] self.annotations = []
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)): for vec in vectors: self.vectors.append(vec) else: self.vectors.append(vectors)
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$" or escape backslashes e.g. "$\\\\langle x \\\\rangle$". **kwargs: Options as for mplot3d.axes3d.text, including: fontsize, color, horizontalalignment, verticalalignment. Raises: Exception: If input not array_like or tuple. """ if isinstance(state_or_vector, (list, np.ndarray, tuple)) \ and len(state_or_vector) == 3: vec = state_or_vector else: raise Exception("Position needs to be specified by a qubit " + "state or a 3D vector.") self.annotations.append({'position': vec, 'text': text, 'opts': kwargs})
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]) if self.background: self.axes.clear() self.axes.set_xlim3d(-1.3, 1.3) self.axes.set_ylim3d(-1.3, 1.3) self.axes.set_zlim3d(-1.3, 1.3) else: self.plot_axes() self.axes.set_axis_off() self.axes.set_xlim3d(-0.7, 0.7) self.axes.set_ylim3d(-0.7, 0.7) self.axes.set_zlim3d(-0.7, 0.7) self.axes.grid(False) self.plot_back() self.plot_points() self.plot_vectors() self.plot_front() self.plot_axes_labels() self.plot_annotations() self.axes.set_title(title, fontsize=self.font_size, y=1.08)
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, alpha=self.sphere_alpha) # wireframe self.axes.plot_wireframe(x_dir, y_dir, z_dir, rstride=5, cstride=5, color=self.frame_color, alpha=self.frame_alpha) # equator self.axes.plot(1.0 * np.cos(u_angle), 1.0 * np.sin(u_angle), zs=0, zdir='z', lw=self.frame_width, color=self.frame_color) self.axes.plot(1.0 * np.cos(u_angle), 1.0 * np.sin(u_angle), zs=0, zdir='x', lw=self.frame_width, color=self.frame_color)
python
{ "resource": "" }
q268248
Bloch.show
test
def show(self, title=''): """ Display Bloch sphere and corresponding data sets. """ self.render(title=title) if self.fig: plt.show(self.fig)
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 " "qiskit.quantum_info.synthesis", DeprecationWarning) return synthesis.two_qubit_kak(unitary_matrix)
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: ret = ret.rjust(self.left_fill, self.top_pad) ret = ret.center(self.layer_width, self.top_bck) return ret
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: ret = ret.rjust(self.left_fill, self._mid_padding) ret = ret.center(self.layer_width, self.mid_bck) return ret
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: ret = ret.rjust(self.left_fill, self.bot_pad) ret = ret.center(self.layer_width, self.bot_bck) return ret
python
{ "resource": "" }
q268253
DrawElement.length
test
def length(self): """ Returns the length of the element, including the box around.""" return max(len(self.top), len(self.mid), len(self.bot))
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 ret = [] for param in instruction.op.params: if isinstance(param, (sympy.Number, float)): ret.append('%.5g' % param) else: ret.append('%s' % param) return ret
python
{ "resource": "" }
q268255
TextDrawing.label_for_box
test
def label_for_box(instruction): """ Creates the label for a box.""" label = instruction.name.capitalize() params = TextDrawing.params_for_label(instruction) if params: label += "(%s)" % ','.join(params) return label
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, "line=%s, " % self.line, "file=%s" % self.file) else: return nested_scope[-1][self.name].latex(prec, nested_scope[0:-1])
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. ' 'Please use qiskit.compiler.transpile() to transform circuits ' 'and qiskit.compiler.assemble() to produce a runnable qobj.', DeprecationWarning) new_circuits = transpile(circuits, basis_gates=basis_gates, coupling_map=coupling_map, initial_layout=initial_layout, seed_transpiler=seed_mapper, backend=backend, pass_manager=pass_manager) qobj = assemble(new_circuits, qobj_header=None, shots=shots, max_credits=max_credits, seed_simulator=seed, memory=memory, qobj_id=qobj_id, config=config) # deprecated return qobj
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 # module. try: warnings._add_filter(*deprecation_filter, append=False) except AttributeError: # ._add_filter is internal and not available in some Python versions. pass # Add a filter for ignoring ChangedInMarshmallow3Warning, as we depend on # marhsmallow 2 explicitly. 2.17.0 introduced new deprecation warnings that # are useful for eventually migrating, but too verbose for our purposes. warnings.simplefilter('ignore', category=ChangedInMarshmallow3Warning)
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 = { 'os': platform.system(), 'memory': psutil.virtual_memory().total / (1024 ** 3), 'cpus': psutil.cpu_count(logical=False) or 1 } return 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 or not """ try: host = socket.gethostbyname(hostname) socket.create_connection((host, port), 2) return True except Exception: # pylint: disable=broad-except return False
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 if job_status_name == 'ERROR': break else: if job_status_name == 'QUEUED': job_status_msg += ' (%s)' % job_var.queue_position() if not _interval_set: interval = max(job_var.queue_position(), 2) else: if not _interval_set: interval = 2 status.value = header % (job_status_msg) status.value = header % (job_status_msg)
python
{ "resource": "" }
q268262
constant
test
def constant(times: np.ndarray, amp: complex) -> np.ndarray: """Continuous constant pulse. Args: times: Times to output pulse for. amp: Complex pulse amplitude. """ return np.full(len(times), amp, dtype=np.complex_)
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. phase: Pulse phase. """ x = times/period+phase/np.pi return amp*(2*(2*np.floor(x) - np.floor(2*x)) + 1).astype(np.complex_)
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. phase: Pulse phase. """ return amp*(-2*np.abs(sawtooth(times, 1, period, (phase-np.pi/2)/2)) + 1).astype(np.complex_)
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. freq: Pulse frequency, units of 1/dt. phase: Pulse phase. """ return amp*np.cos(2*np.pi*freq*times+phase).astype(np.complex_)
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)$. rescale_amp: If `zeroed_width` is not `None` and `rescale_amp=True` the pulse will be rescaled so that $\Omega_g(center)-\Omega_g(center\pm zeroed_width/2)=amp$. ret_scale_factor: Return amplitude scale factor. """ if zeroed_width is None: zeroed_width = 2*(center+1) zero_offset = gaussian(np.array([-zeroed_width/2]), amp, center, sigma) gaussian_samples -= zero_offset amp_scale_factor = 1. if rescale_amp: amp_scale_factor = amp/(amp-zero_offset) gaussian_samples *= amp_scale_factor if ret_scale_factor: return gaussian_samples, amp_scale_factor return gaussian_samples
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 $\Omega_g(center)-\Omega_g(center\pm zeroed_width/2)=amp$. ret_x: Return centered and standard deviation normalized pulse location. $x=(times-center)/sigma. """ times = np.asarray(times, dtype=np.complex_) x = (times-center)/sigma gauss = amp*np.exp(-x**2/2).astype(np.complex_) if zeroed_width is not None: gauss = _fix_gaussian_width(gauss, amp=amp, center=center, sigma=sigma, zeroed_width=zeroed_width, rescale_amp=rescale_amp) if ret_x: return gauss, x return gauss
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. ret_gaussian: Return gaussian with which derivative was taken with. """ gauss, x = gaussian(times, amp=amp, center=center, sigma=sigma, ret_x=True) gauss_deriv = -x/sigma*gauss if ret_gaussian: return gauss_deriv, gauss return gauss_deriv
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 else: gauss_zeroed_width = None funclist = [functools.partial(gaussian, amp=amp, center=square_start, sigma=sigma, zeroed_width=gauss_zeroed_width, rescale_amp=True), functools.partial(gaussian, amp=amp, center=square_stop, sigma=sigma, zeroed_width=gauss_zeroed_width, rescale_amp=True), functools.partial(constant, amp=amp)] condlist = [times <= square_start, times >= square_stop] return np.piecewise(times.astype(np.complex_), condlist, funclist)
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']) # Extend the the dag/layout with ancillas using the full coupling map pass_manager.append(FullAncillaAllocation(coupling_map)) pass_manager.append(EnlargeWithAncilla()) # Circuit must only contain 1- or 2-qubit interactions for swapper to work pass_manager.append(Unroll3qOrMore()) # Swap mapper pass_manager.append(LegacySwap(coupling_map, trials=20, seed=seed_transpiler)) # Expand swaps pass_manager.append(Decompose(SwapGate)) # Change CX directions pass_manager.append(CXDirection(coupling_map)) # Unroll to the basis pass_manager.append(Unroller(['u1', 'u2', 'u3', 'id', 'cx'])) # Simplify single qubit gates and CXs simplification_passes = [Optimize1qGates(), CXCancellation(), RemoveResetInZeroState()] pass_manager.append(simplification_passes + [Depth(), FixedPoint('depth')], do_while=lambda property_set: not property_set['depth_fixed_point']) return pass_manager
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() pass_manager.append(Unroller(basis_gates)) pass_manager.append([RemoveResetInZeroState(), Depth(), FixedPoint('depth')], do_while=lambda property_set: not property_set['depth_fixed_point']) return pass_manager
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) and register in self.qregs): has_reg = True elif (isinstance(register, ClassicalRegister) and register in self.cregs): has_reg = True return has_reg
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') reverse_circ.data = [] for inst, qargs, cargs in reversed(self.data): reverse_circ.data.append((inst.mirror(), qargs, cargs)) return reverse_circ
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') inverse_circ.data = [] for inst, qargs, cargs in reversed(self.data): inverse_circ.data.append((inst.inverse(), qargs, cargs)) return inverse_circ
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 " "cannot be appended onto %d qubits and %d clbits." % (instruction.name, instruction.num_qubits, instruction.num_clbits, len(qargs), len(cargs))) # add the instruction onto the given wires instruction_context = instruction, qargs, cargs self.data.append(instruction_context) # track variable parameters in instruction for param_index, param in enumerate(instruction.params): if isinstance(param, Parameter): current_symbols = self.parameters if param in current_symbols: self._parameter_table[param].append((instruction, param_index)) else: self._parameter_table[param] = [(instruction, param_index)] return instruction
python
{ "resource": "" }
q268276
QuantumCircuit._attach
test
def _attach(self, instruction, qargs, cargs): """DEPRECATED after 0.8""" self.append(instruction, qargs, cargs)
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,)) for register in regs: if register in self.qregs or register in self.cregs: raise QiskitError("register name \"%s\" already exists" % register.name) if isinstance(register, QuantumRegister): self.qregs.append(register) elif isinstance(register, ClassicalRegister): self.cregs.append(register) else: raise QiskitError("expected a register")
python
{ "resource": "" }
q268278
QuantumCircuit._check_dups
test
def _check_dups(self, qubits): """Raise exception if list of qubits contains duplicates.""" squbits = set(qubits) if len(squbits) != len(qubits): raise QiskitError("duplicate qubit arguments")
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 not (QuantumRegister, int) tuple") if not all(self.has_register(i[0]) for i in qargs): raise QiskitError("register not in this circuit") for qubit in qargs: qubit[0].check_range(qubit[1])
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 not (ClassicalRegister, int) tuple") if not all(self.has_register(i[0]) for i in cargs): raise QiskitError("register not in this circuit") for clbit in cargs: clbit[0].check_range(clbit[1])
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: if element2.name == element1.name: if element1 != element2: raise QiskitError("circuits are not compatible")
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], clbit[0].name, clbit[1]) else: string_temp += "%s %s;\n" % (instruction.qasm(), ",".join(["%s[%d]" % (j[0].name, j[1]) for j in qargs + cargs])) return string_temp
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 TextDrawing: * PIL.Image: (output `latex`) an in-memory representation of the image of the circuit diagram. * matplotlib.figure: (output `mpl`) a matplotlib figure object for the circuit diagram. * str: (output `latex_source`). The LaTeX source code. * TextDrawing: (output `text`). A drawing that can be printed as ascii art Raises: VisualizationError: when an invalid output method is selected """ from qiskit.tools import visualization return visualization.circuit_drawer(self, scale=scale, filename=filename, style=style, output=output, interactive=interactive, line_length=line_length, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify)
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: if instr.name not in ['barrier', 'snapshot']: gate_ops += 1 return gate_ops
python
{ "resource": "" }
q268285
QuantumCircuit.width
test
def width(self): """Return number of qubits plus clbits in circuit. Returns: int: Width of circuit. """ return sum(reg.size for reg in self.qregs+self.cregs)
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: if instr.name in count_ops.keys(): count_ops[instr.name] += 1 else: count_ops[instr.name] = 1 return count_ops
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) num_touched += 1 break for item in args: reg_int = reg_map[item[0].name]+item[1] for k in range(num_sub_graphs): if reg_int in sub_graphs[k]: if k not in graphs_touched: graphs_touched.append(k) num_touched += 1 break # If the gate touches more than one subgraph # join those graphs together and return # reduced number of subgraphs if num_touched > 1: connections = [] for idx in graphs_touched: connections.extend(sub_graphs[idx]) _sub_graphs = [] for idx in range(num_sub_graphs): if idx not in graphs_touched: _sub_graphs.append(sub_graphs[idx]) _sub_graphs.append(connections) sub_graphs = _sub_graphs num_sub_graphs -= (num_touched-1) # Cannot go lower than one so break if num_sub_graphs == 1: break return num_sub_graphs
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 p in value_dict.keys() - self.parameters])) for parameter, value in value_dict.items(): new_circuit._bind_parameter(parameter, value) # clear evaluated expressions for parameter in value_dict: del new_circuit._parameter_table[parameter] return new_circuit
python
{ "resource": "" }
q268289
QuantumCircuit._bind_parameter
test
def _bind_parameter(self, parameter, value): """Assigns a parameter value to matching instructions in-place.""" for (instr, param_index) in self._parameter_table[parameter]: instr.params[param_index] = value
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. ' 'Run "pip install matplotlib" before.') if dt: _dt = dt else: _dt = 1 re_y = np.real(samples) im_y = np.imag(samples) image = plt.figure(figsize=size) ax0 = image.add_subplot(111) if interp_method == 'CubicSpline': # spline interpolation, use mid-point of dt time = np.arange(0, duration + 1) * _dt + 0.5 * _dt cs_ry = CubicSpline(time[:-1], re_y) cs_iy = CubicSpline(time[:-1], im_y) _time = np.linspace(0, duration * _dt, nop) _re_y = cs_ry(_time) _im_y = cs_iy(_time) elif interp_method == 'None': # pseudo-DAC output time = np.arange(0, duration + 1) * _dt _time = np.r_[time[0], np.repeat(time[1:-1], 2), time[-1]] _re_y = np.repeat(re_y, 2) _im_y = np.repeat(im_y, 2) else: raise QiskitError('Invalid interpolation method "%s"' % interp_method) # plot ax0.fill_between(x=_time, y1=_re_y, y2=np.zeros_like(_time), facecolor='red', alpha=0.3, edgecolor='red', linewidth=1.5, label='real part') ax0.fill_between(x=_time, y1=_im_y, y2=np.zeros_like(_time), facecolor='blue', alpha=0.3, edgecolor='blue', linewidth=1.5, label='imaginary part') ax0.set_xlim(0, duration * _dt) ax0.grid(b=True, linestyle='-') ax0.legend(bbox_to_anchor=(0.5, 1.00), loc='lower center', ncol=2, frameon=False, fontsize=14) if filename: image.savefig(filename, dpi=dpi, bbox_inches='tight') plt.close(image) if image and interactive: plt.show(image) return image
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) ranked_swaps = sorted(possible_swaps, key=_score_swap) best_swap, best_step = None, None for swap in ranked_swaps[:width]: trial_layout = layout.copy() trial_layout.swap(*swap) next_step = _search_forward_n_swaps(trial_layout, gates_remaining, coupling_map, depth - 1, width) # ranked_swaps already sorted by distance, so distance is the tie-breaker. if best_swap is None or _score_step(next_step) > _score_step(best_step): best_swap, best_step = swap, next_step best_swap_gate = _swap_ops_from_edge(best_swap, layout) return { 'layout': best_step['layout'], 'swaps_added': 1 + best_step['swaps_added'], 'gates_remaining': best_step['gates_remaining'], 'gates_mapped': gates_mapped + best_swap_gate + best_step['gates_mapped'], }
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: mapped_gate = _transform_gate_for_layout(gate, layout) mapped_gates.append(mapped_gate) continue qubits = gate['partition'][0] if blocked_qubits.intersection(qubits): blocked_qubits.update(qubits) remaining_gates.append(gate) elif len(qubits) == 1: mapped_gate = _transform_gate_for_layout(gate, layout) mapped_gates.append(mapped_gate) elif coupling_map.distance(*[layout[q] for q in qubits]) == 1: mapped_gate = _transform_gate_for_layout(gate, layout) mapped_gates.append(mapped_gate) else: blocked_qubits.update(qubits) remaining_gates.append(gate) return mapped_gates, remaining_gates
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. """ if max_gates is None: max_gates = 50 + 10 * len(coupling_map.physical_qubits) return sum(coupling_map.distance(*[layout[q] for q in gate['partition'][0]]) for gate in gates[:max_gates] if gate['partition'] and len(gate['partition'][0]) == 2)
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 in step['gates_mapped'] if len(g.qargs) == 2]) - 3 * step['swaps_added']
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.""" target_dag = DAGCircuit() target_dag.name = source_dag.name for creg in source_dag.cregs.values(): target_dag.add_creg(creg) device_qreg = QuantumRegister(len(coupling_map.physical_qubits), 'q') target_dag.add_qreg(device_qreg) return target_dag
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') mapped_qargs = [(device_qreg, layout[a]) for a in mapped_op_node.qargs] mapped_op_node.qargs = mapped_op_node.op.qargs = mapped_qargs mapped_op_node.pop('name') return mapped_op_node
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] # TODO shouldn't be making other nodes not by the DAG!! return [ DAGNode({'op': SwapGate(), 'qargs': qreg_edge, 'cargs': [], 'type': 'op'}) ]
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: best_step = _search_forward_n_swaps(layout, gates_remaining, coupling_map) layout = best_step['layout'] gates_mapped = best_step['gates_mapped'] gates_remaining = best_step['gates_remaining'] mapped_gates.extend(gates_mapped) # Preserve input DAG's name, regs, wire_map, etc. but replace the graph. mapped_dag = _copy_circuit_metadata(dag, coupling_map) for node in mapped_gates: mapped_dag.apply_operation_back(op=node.op, qargs=node.qargs, cargs=node.cargs) return mapped_dag
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 physical_qubit in self.physical_qubits: raise CouplingError( "The physical qubit %s is already in the coupling graph" % physical_qubit) self.graph.add_node(physical_qubit) self._dist_matrix = None # invalidate self._qubit_list = None
python
{ "resource": "" }