INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Test if an array is a square matrix.
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]
Test if an array is a diagonal matrix
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...
Test if an array is a symmetrix matrix
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=...
Test if an array is a Hermitian matrix
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...
Test if a matrix is positive semidefinite
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...
Test if an array is an identity matrix.
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...
Test if an array is a unitary matrix.
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...
Return a new circuit that has been optimized.
def run(self, dag): """Return a new circuit that has been optimized.""" swaps = dag.op_nodes(SwapGate) for swap in swaps: final_successor = [] for successor in dag.successors(swap): final_successor.append(successor.type == 'out' or (successor.type == 'op' ...
Left sample a continuous function. Args: continuous_pulse: Continuous pulse function to sample. duration: Duration to sample for. * args: Continuous pulse function args. ** kwargs: Continuous pulse function kwargs.
def left_sample(continuous_pulse: Callable, duration: int, *args, **kwargs) -> np.ndarray: """Left sample a continuous function. Args: continuous_pulse: Continuous pulse function to sample. duration: Duration to sample for. *args: Continuous pulse function args. **kwargs: Continu...
Transform a QuantumChannel to the Choi representation.
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...
Transform a QuantumChannel to the SuperOp representation.
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, ...
Transform a QuantumChannel to the Kraus representation.
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...
Transform a QuantumChannel to the Chi representation.
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)...
Transform a QuantumChannel to the PTM representation.
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)...
Transform a QuantumChannel to the Stinespring representation.
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...
Transform a QuantumChannel to the Operator representation.
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...
Transform Operator representation to other representation.
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...
Transform Stinespring representation to Operator representation.
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...
Transform SuperOp representation to Choi representation.
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)
Transform Choi to SuperOp representation.
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)
Transform Kraus representation to Choi representation.
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...
Transform Choi representation to Kraus representation.
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 ...
Transform Stinespring representation to Kraus representation.
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...
Transform Stinespring representation to Choi representation.
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 =...
Transform Kraus representation to Stinespring representation.
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_...
Transform Kraus representation to SuperOp representation.
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): ...
Transform Chi representation to a Choi representation.
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)
Transform Choi representation to the Chi representation.
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)
Tensor product ( A ⊗ B ) to bipartite matrices and reravel indicies.
def _bipartite_tensor(mat1, mat2, shape1=None, shape2=None): """Tensor product (A ⊗ B) to bipartite matrices and reravel indicies. This is used for tensor product of superoperators and Choi matrices. Args: mat1 (matrix_like): a bipartite matrix A mat2 (matrix_like): a bipartite matrix B ...
Reravel two bipartite matrices.
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...
Change of basis of bipartite matrix represenation.
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...
Reshuffle the indicies of a bipartite matrix A [ ij kl ] - > A [ lj ki ].
def _reshuffle(mat, shape): """Reshuffle the indicies of a bipartite matrix A[ij,kl] -> A[lj,ki].""" return np.reshape( np.transpose(np.reshape(mat, shape), (3, 1, 2, 0)), (shape[3] * shape[1], shape[0] * shape[2]))
Return true if dims correspond to an n - qubit channel.
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...
Set visible property of ticklines and ticklabels of an axis to False
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)
Set x y and z labels according to one of conventions.
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" ...
Resets Bloch sphere data sets to empty.
def clear(self): """Resets Bloch sphere data sets to empty. """ self.points = [] self.vectors = [] self.point_style = [] self.annotations = []
Add a list of data points to bloch sphere. Args: points ( array_like ): Collection of data points. meth ( str ): Type of points to plot use m for multicolored l for points connected with a line.
def add_points(self, points, meth='s'): """Add a list of data points to bloch sphere. Args: points (array_like): Collection of data points. meth (str): Type of points to plot, use 'm' for multicolored, 'l' for points connected with ...
Add a list of vectors to Bloch sphere.
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...
Add a text or LaTeX annotation to Bloch sphere parametrized by a qubit state or a vector.
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 ...
Render the Bloch sphere and its data sets in on given figure and axes.
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 =...
front half of sphere
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...
axes
def plot_axes(self): """axes""" span = np.linspace(-1.0, 1.0, 2) self.axes.plot(span, 0 * span, zs=0, zdir='z', label='X', lw=self.frame_width, color=self.frame_color) self.axes.plot(0 * span, span, zs=0, zdir='z', label='Y', lw=self.frame_wi...
axes labels
def plot_axes_labels(self): """axes labels""" opts = {'fontsize': self.font_size, 'color': self.font_color, 'horizontalalignment': 'center', 'verticalalignment': 'center'} self.axes.text(0, -self.xlpos[0], 0, self.xlabel[0], **opts) self.ax...
Plot vector
def plot_vectors(self): """Plot vector""" # -X and Y data are switched for plotting purposes for k in range(len(self.vectors)): xs3d = self.vectors[k][1] * np.array([0, 1]) ys3d = -self.vectors[k][0] * np.array([0, 1]) zs3d = self.vectors[k][2] * np.array([0,...
Plot points
def plot_points(self): """Plot points""" # -X and Y data are switched for plotting purposes for k in range(len(self.points)): num = len(self.points[k][0]) dist = [np.sqrt(self.points[k][0][j] ** 2 + self.points[k][1][j] ** 2 + ...
Plot annotations
def plot_annotations(self): """Plot annotations""" # -X and Y data are switched for plotting purposes for annotation in self.annotations: vec = annotation['position'] opts = {'fontsize': self.font_size, 'color': self.font_color, 'ho...
Display Bloch sphere and corresponding data sets.
def show(self, title=''): """ Display Bloch sphere and corresponding data sets. """ self.render(title=title) if self.fig: plt.show(self.fig)
Saves Bloch sphere to file of type format in directory dirc. Args: name ( str ): Name of saved image. Must include path and format as well. i. e./ Users/ Paul/ Desktop/ bloch. png This overrides the format and dirc arguments. output ( str ): Format of output image. dirc ( str ): Directory for output images. Defaults to...
def save(self, name=None, output='png', dirc=None): """Saves Bloch sphere to file of type ``format`` in directory ``dirc``. Args: name (str): Name of saved image. Must include path and format as well. i.e. '/Users/Paul/Desktop/bloch.png' This o...
Deprecated after 0. 8
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)
Constructs the top line of the element
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...
Constructs the middle line of the element
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...
Constructs the bottom line of the element
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...
Returns the length of the element including the box around.
def length(self): """ Returns the length of the element, including the box around.""" return max(len(self.top), len(self.mid), len(self.bot))
Connects boxes and elements using wire_char and setting proper connectors. Args: wire_char ( char ): For example ║ or │. where ( list [ top bot ] ): Where the connector should be set. label ( string ): Some connectors have a label ( see cu1 for example ).
def connect(self, wire_char, where, label=None): """ Connects boxes and elements using wire_char and setting proper connectors. Args: wire_char (char): For example '║' or '│'. where (list["top", "bot"]): Where the connector should be set. label (string): Some ...
In multi - bit elements the label is centered vertically. Args: input_length ( int ): Rhe amount of wires affected. order ( int ): Which middle element is this one?
def center_label(self, input_length, order): """ In multi-bit elements, the label is centered vertically. Args: input_length (int): Rhe amount of wires affected. order (int): Which middle element is this one? """ location_in_the_box = '*'.center(input_leng...
Given a layer replace the Nones in it with EmptyWire elements. Args: layer ( list ): The layer that contains Nones. first_clbit ( int ): The first wire that is classic.
def fillup_layer(layer, first_clbit): """ Given a layer, replace the Nones in it with EmptyWire elements. Args: layer (list): The layer that contains Nones. first_clbit (int): The first wire that is classic. Returns: list: The new layer, with no Nones...
Creates a layer with BreakWire elements. Args: layer_length ( int ): The length of the layer to create arrow_char ( char ): The char used to create the BreakWire element.
def fillup_layer(layer_length, arrow_char): """ Creates a layer with BreakWire elements. Args: layer_length (int): The length of the layer to create arrow_char (char): The char used to create the BreakWire element. Returns: list: The new layer. ...
Creates a layer with InputWire elements. Args: names ( list ): List of names for the wires.
def fillup_layer(names): # pylint: disable=arguments-differ """ Creates a layer with InputWire elements. Args: names (list): List of names for the wires. Returns: list: The new layer """ longest = max([len(name) for name in names]) inputs...
Dumps the ascii art in the file. Args: filename ( str ): File to dump the ascii art. encoding ( str ): Optional. Default utf - 8.
def dump(self, filename, encoding="utf8"): """ Dumps the ascii art in the file. Args: filename (str): File to dump the ascii art. encoding (str): Optional. Default "utf-8". """ with open(filename, mode='w', encoding=encoding) as text_file: text...
Generates a list with lines. These lines form the text drawing. Args: line_length ( int ): Optional. Breaks the circuit drawing to this length. This useful when the drawing does not fit in the console. If None ( default ) it will try to guess the console width using shutil. get_terminal_size (). If you don t want pagin...
def lines(self, line_length=None): """ Generates a list with lines. These lines form the text drawing. Args: line_length (int): Optional. Breaks the circuit drawing to this length. This useful when the drawing does not fit in the console. If ...
Returns a list of names for each wire. Args: with_initial_value ( bool ): Optional ( Default: True ). If true adds the initial value to the name.
def wire_names(self, with_initial_value=True): """ Returns a list of names for each wire. Args: with_initial_value (bool): Optional (Default: True). If true, adds the initial value to the name. Returns: List: The list of wir...
Given a list of wires creates a list of lines with the text drawing. Args: wires ( list ): A list of wires with instructions. vertically_compressed ( bool ): Default is True. It merges the lines so the drawing will take less vertical room. Returns: list: A list of lines with the text drawing.
def draw_wires(wires, vertically_compressed=True): """ Given a list of wires, creates a list of lines with the text drawing. Args: wires (list): A list of wires with instructions. vertically_compressed (bool): Default is `True`. It merges the lines ...
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.
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...
Creates the label for a box.
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
Merges two lines ( top and bot ) in the way that the overlapping make senses. Args: top ( str ): the top line bot ( str ): the bottom line icod ( top or bot ): in case of doubt which line should have priority? Default: top. Returns: str: The merge of both lines.
def merge_lines(top, bot, icod="top"): """ Merges two lines (top and bot) in the way that the overlapping make senses. Args: top (str): the top line bot (str): the bottom line icod (top or bot): in case of doubt, which line should have priority? Default: "top"...
When the elements of the layer have different widths sets the width to the max elements. Args: layer ( list ): A list of elements.
def normalize_width(layer): """ When the elements of the layer have different widths, sets the width to the max elements. Args: layer (list): A list of elements. """ instructions = [instruction for instruction in filter(lambda x: x is not None, layer)] longest...
Convert an instruction into its corresponding Gate object and establish any connections it introduces between qubits
def _instruction_to_gate(self, instruction, layer): """ Convert an instruction into its corresponding Gate object, and establish any connections it introduces between qubits""" current_cons = [] connection_label = None # add in a gate that operates over multiple qubits ...
Constructs layers. Returns: list: List of DrawElements. Raises: VisualizationError: When the drawing is for some reason impossible to be drawn.
def build_layers(self): """ Constructs layers. Returns: list: List of DrawElements. Raises: VisualizationError: When the drawing is, for some reason, impossible to be drawn. """ wire_names = self.wire_names(with_initial_value=True) if not w...
Sets the qubit to the element Args: qubit ( qbit ): Element of self. qregs. element ( DrawElement ): Element to set in the qubit
def set_qubit(self, qubit, element): """ Sets the qubit to the element Args: qubit (qbit): Element of self.qregs. element (DrawElement): Element to set in the qubit """ self.qubit_layer[self.qregs.index(qubit)] = element
Sets the clbit to the element Args: clbit ( cbit ): Element of self. cregs. element ( DrawElement ): Element to set in the clbit
def set_clbit(self, clbit, element): """ Sets the clbit to the element Args: clbit (cbit): Element of self.cregs. element (DrawElement): Element to set in the clbit """ self.clbit_layer[self.cregs.index(clbit)] = element
Sets the multi clbit box. Args: creg ( string ): The affected classical register. label ( string ): The label for the multi clbit box. top_connect ( char ): The char to connect the box on the top.
def set_cl_multibox(self, creg, label, top_connect='┴'): """ Sets the multi clbit box. Args: creg (string): The affected classical register. label (string): The label for the multi clbit box. top_connect (char): The char to connect the box on the top. ...
Connects the elements in the layer using wire_char. Args: wire_char ( char ): For example ║ or │.
def connect_with(self, wire_char): """ Connects the elements in the layer using wire_char. Args: wire_char (char): For example '║' or '│'. """ if len([qbit for qbit in self.qubit_layer if qbit is not None]) == 1: # Nothing to connect return ...
Return the correspond math mode latex string.
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: ", ...
Return the correspond symbolic number.
def sym(self, nested_scope=None): """Return the correspond symbolic number.""" if not nested_scope or self.name not in nested_scope[-1]: raise NodeException("Expected local parameter name: ", "name=%s, line=%s, file=%s" % ( ...
Return the correspond floating point number.
def real(self, nested_scope=None): """Return the correspond floating point number.""" if not nested_scope or self.name not in nested_scope[-1]: raise NodeException("Expected local parameter name: ", "name=%s, line=%s, file=%s" % ( ...
Compile a list of circuits into a qobj.
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...
Apply filters to deprecation warnings.
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` ...
Basic hardware information about the local machine.
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 = { ...
Checks if internet connection exists to host via specified port.
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...
Return the composition channel self∘other.
def compose(self, other, qargs=None, front=False): """Return the composition channel self∘other. Args: other (QuantumChannel): a quantum channel. qargs (list): a list of subsystem positions to compose other on. front (bool): If False compose in standard order other(s...
The matrix power of the channel.
def power(self, n): """The matrix power of the channel. Args: n (int): compute the matrix power of the superoperator matrix. Returns: PTM: the matrix power of the SuperOp converted to a PTM channel. Raises: QiskitError: if the input and output dimen...
Internal function that updates the status of a HTML job monitor.
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...
Continuous constant pulse.
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_)
Continuous square wave.
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...
Continuous triangle wave.
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...
Continuous cosine wave.
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...
r Enforce that the supplied gaussian pulse is zeroed at a specific width.
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...
r Continuous unnormalized gaussian pulse.
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...
Continuous unnormalized gaussian derivative pulse.
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 (...
r Continuous gaussian square pulse.
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 ...
r Continuous Y - only correction DRAG pulse for standard nonlinear oscillator ( SNO ) [ 1 ].
def drag(times: np.ndarray, amp: complex, center: float, sigma: float, beta: float, zeroed_width: Union[None, float] = None, rescale_amp: bool = False) -> np.ndarray: r"""Continuous Y-only correction DRAG pulse for standard nonlinear oscillator (SNO) [1]. [1] Gambetta, J. M., Motzoi, F., Merkel, S. T....
The default pass manager that maps to the coupling map.
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. ...
The default pass manager without a coupling map.
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...
Test if this circuit has the register r.
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...
Mirror the circuit by reversing the instructions.
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') ...
Invert this circuit.
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') ...
Append rhs to self if self contains compatible registers.
def combine(self, rhs): """ Append rhs to self if self contains compatible registers. Two circuits are compatible if they contain the same registers or if they contain different registers with unique names. The returned circuit will contain all unique registers between both ...
Append rhs to self if self contains compatible registers.
def extend(self, rhs): """ Append rhs to self if self contains compatible registers. Two circuits are compatible if they contain the same registers or if they contain different registers with unique names. The returned circuit will contain all unique registers between both ...
Append an instruction to the end of the circuit modifying the circuit in place.
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 ...
DEPRECATED after 0. 8
def _attach(self, instruction, qargs, cargs): """DEPRECATED after 0.8""" self.append(instruction, qargs, cargs)