_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() - ...
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...
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) != ...
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. """ ...
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. """...
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 =...
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...
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: ...
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. """ re...
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 ...
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 j.start < 0 or j.stop >= self.size or (j...
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.d...
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=...
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(ma...
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 # Chec...
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.arr...
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).d...
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...
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, ...
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', da...
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)...
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)...
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 representati...
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 != 'K...
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.ou...
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 representatio...
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 zi...
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 ...
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 = n...
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) stine = np.zeros((output_dim * num_kraus, input_...
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): ...
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 m...
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...
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(in...
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" ...
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...
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 ...
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 =...
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.c...
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...
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(s...
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_f...
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...
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: ", ...
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 (Q...
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` ...
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: b...
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 ipywidg...
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 = t...
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. """ r...
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*tim...
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 w...
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 cu...
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 (...
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 ...
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. ...
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 = PassMa...
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 (isinstanc...
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 ...
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 ...
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 (QuantumRegi...
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 (ClassicalR...
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: ...
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" ...
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: ...
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...
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] += ...
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. """ # Co...
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:...
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): Puls...
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...
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 topol...
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(couplin...
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...
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....
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 [ ...
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: ...
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):...
python
{ "resource": "" }