my_thread = threading.currentThread()<EOL>current_interval = <NUM_LIT:0><EOL>started = False<EOL>all_dead = False<EOL>stati = [None]*len(self._backends)<EOL>while getattr(my_thread, "<STR_LIT>", True) and not all_dead:<EOL><INDENT>if current_interval == interval or started is False:<EOL><INDENT>for ind, back in enumerate(self._backends):<EOL><INDENT>_value = self.children[ind].children[<NUM_LIT:2>].value<EOL>_head = _value.split('<STR_LIT>')[<NUM_LIT:0>]<EOL>try:<EOL><INDENT>_status = back.status()<EOL>stati[ind] = _status<EOL><DEDENT>except Exception:  <EOL><INDENT>self.children[ind].children[<NUM_LIT:2>].value = _value.replace(<EOL>_head, "<STR_LIT>")<EOL>self.children[ind]._is_alive = False<EOL><DEDENT>else:<EOL><INDENT>self.children[ind]._is_alive = True<EOL>self.children[ind].children[<NUM_LIT:2>].value = _value.replace(<EOL>_head, "<STR_LIT>")<EOL><DEDENT><DEDENT>idx = list(range(len(self._backends)))<EOL>pending = [s.pending_jobs for s in stati]<EOL>_, least_idx = zip(*sorted(zip(pending, idx)))<EOL>for ind in least_idx:<EOL><INDENT>if stati[ind].operational:<EOL><INDENT>least_pending_idx = ind<EOL>break<EOL><DEDENT><DEDENT>for var in idx:<EOL><INDENT>if var == least_pending_idx:<EOL><INDENT>self.children[var].children[<NUM_LIT:4>].value = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>self.children[var].children[<NUM_LIT:4>].value = "<STR_LIT>"<EOL><DEDENT>self.children[var].children[<NUM_LIT:3>].children[<NUM_LIT:1>].value = pending[var]<EOL>self.children[var].children[<NUM_LIT:3>].children[<NUM_LIT:1>].max = max(<EOL>self.children[var].children[<NUM_LIT:3>].children[<NUM_LIT:1>].max, pending[var]+<NUM_LIT:10>)<EOL>if stati[var].operational:<EOL><INDENT>self.children[var].children[<NUM_LIT:5>].value = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>self.children[var].children[<NUM_LIT:5>].value = "<STR_LIT>"<EOL><DEDENT><DEDENT>started = True<EOL>current_interval = <NUM_LIT:0><EOL><DEDENT>time.sleep(<NUM_LIT:1>)<EOL>all_dead = not any([wid._is_alive for wid in self.children])<EOL>current_interval += <NUM_LIT:1><EOL><DEDENT>

Updates the monitor info
    Called from another thread.


pbar = widgets.IntProgress(<EOL>value=<NUM_LIT:0>,<EOL>min=<NUM_LIT:0>,<EOL>max=<NUM_LIT:50>,<EOL>description='<STR_LIT>',<EOL>orientation='<STR_LIT>', layout=widgets.Layout(max_width='<STR_LIT>'))<EOL>pbar.style.bar_color = '<STR_LIT>'<EOL>pbar_current = widgets.Label(<EOL>value=str(pbar.value), layout=widgets.Layout(min_width='<STR_LIT>'))<EOL>pbar_max = widgets.Label(<EOL>value=str(pbar.max), layout=widgets.Layout(min_width='<STR_LIT>'))<EOL>def _on_max_change(change):<EOL><INDENT>pbar_max.value = str(change['<STR_LIT>'])<EOL><DEDENT>def _on_val_change(change):<EOL><INDENT>pbar_current.value = str(change['<STR_LIT>'])<EOL><DEDENT>pbar.observe(_on_max_change, names='<STR_LIT>')<EOL>pbar.observe(_on_val_change, names='<STR_LIT:value>')<EOL>jobs_widget = widgets.HBox([pbar_current, pbar, pbar_max],<EOL>layout=widgets.Layout(max_width='<STR_LIT>',<EOL>min_width='<STR_LIT>',<EOL>justify_content='<STR_LIT>'))<EOL>return jobs_widget<EOL>

Generates a jobs_pending progress bar widget.


args = magic_arguments.parse_argstring(<EOL>self.qiskit_backend_overview, line)<EOL>unique_hardware_backends = get_unique_backends()<EOL>_value = "<STR_LIT>"<EOL>_value += "<STR_LIT>"<EOL>_value += "<STR_LIT>"<EOL>backend_title = widgets.HTML(value=_value,<EOL>layout=widgets.Layout(margin='<STR_LIT>'))<EOL>build_back_widgets = [backend_widget(b)<EOL>for b in unique_hardware_backends]<EOL>_backends = []<EOL>oper_ord_backends = []<EOL>for n, back in enumerate(unique_hardware_backends):<EOL><INDENT>if back.status().operational:<EOL><INDENT>oper_ord_backends = [build_back_widgets[n]] + oper_ord_backends<EOL>_backends = [back] + _backends<EOL><DEDENT>else:<EOL><INDENT>oper_ord_backends = oper_ord_backends + [build_back_widgets[n]]<EOL>_backends = _backends + [back]<EOL><DEDENT><DEDENT>qubit_label = widgets.Label(value='<STR_LIT>')<EOL>pend_label = widgets.Label(value='<STR_LIT>')<EOL>least_label = widgets.Label(value='<STR_LIT>')<EOL>oper_label = widgets.Label(<EOL>value='<STR_LIT>', layout=widgets.Layout(margin='<STR_LIT>'))<EOL>t1_label = widgets.Label(<EOL>value='<STR_LIT>', layout=widgets.Layout(margin='<STR_LIT>'))<EOL>t2_label = widgets.Label(<EOL>value='<STR_LIT>', layout=widgets.Layout(margin='<STR_LIT>'))<EOL>labels_widget = widgets.VBox([qubit_label, pend_label, least_label,<EOL>oper_label, t1_label, t2_label],<EOL>layout=widgets.Layout(margin='<STR_LIT>',<EOL>min_width='<STR_LIT>'))<EOL>backend_grid = GridBox_with_thread(children=oper_ord_backends,<EOL>layout=widgets.Layout(<EOL>grid_template_columns='<STR_LIT>' *<EOL>len(unique_hardware_backends),<EOL>grid_template_rows='<STR_LIT>',<EOL>grid_gap='<STR_LIT>'))<EOL>backend_grid._backends = _backends        <EOL>backend_grid._update = types.MethodType(  <EOL>update_backend_info, backend_grid)<EOL>backend_grid._thread = threading.Thread(  <EOL>target=backend_grid._update, args=(args.interval,))<EOL>backend_grid._thread.start()<EOL>back_box = widgets.HBox([labels_widget, backend_grid])<EOL>back_monitor = widgets.VBox([backend_title, back_box])<EOL>display(back_monitor)<EOL>

A Jupyter magic function to monitor backends.


if hasattr(self, '<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>self._thread.do_run = False<EOL>self._thread.join()<EOL><DEDENT>except Exception:  <EOL><INDENT>pass<EOL><DEDENT><DEDENT>self.close()<EOL>


return str(bin(int(hexstring, <NUM_LIT:16>)))[<NUM_LIT:2>:]<EOL>

Convert hexadecimal readouts (memory) to binary readouts.


return format(int(bitstring, <NUM_LIT:2>), '<STR_LIT>'.format(memory_slots))<EOL>

If the bitstring is truncated, pad extra zeros to make its
    length equal to memory_slots


substrings = []<EOL>running_index = <NUM_LIT:0><EOL>for _, size in reversed(creg_sizes):<EOL><INDENT>substrings.append(bitstring[running_index: running_index + size])<EOL>running_index += size<EOL><DEDENT>return '<STR_LIT:U+0020>'.join(substrings)<EOL>

Separate a bitstring according to the registers defined in the result header.


if shot_memory.startswith('<STR_LIT>'):<EOL><INDENT>shot_memory = _hex_to_bin(shot_memory)<EOL><DEDENT>if header:<EOL><INDENT>creg_sizes = header.get('<STR_LIT>', None)<EOL>memory_slots = header.get('<STR_LIT>', None)<EOL>if memory_slots:<EOL><INDENT>shot_memory = _pad_zeros(shot_memory, memory_slots)<EOL><DEDENT>if creg_sizes and memory_slots:<EOL><INDENT>shot_memory = _separate_bitstring(shot_memory, creg_sizes)<EOL><DEDENT><DEDENT>return shot_memory<EOL>

Format a single bitstring (memory) from a single shot experiment.

- The hexadecimals are expanded to bitstrings

- Spaces are inserted at register divisions.

Args:
    shot_memory (str): result of a single experiment.
    header (dict): the experiment header dictionary containing
        useful information for postprocessing. creg_sizes
        are a nested list where the inner element is a list
        of creg name, creg size pairs. memory_slots is an integers
        specifying the number of total memory_slots in the experiment.

Returns:
    dict: a formatted memory


arr = np.asarray(complex_list, dtype=np.complex_)<EOL>if not arr.shape[-<NUM_LIT:1>] == <NUM_LIT:2>:<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>return arr[..., <NUM_LIT:0>] + <NUM_LIT>*arr[..., <NUM_LIT:1>]<EOL>

Convert nested list of shape (..., 2) to complex numpy array with shape (...)

    Args:
        complex_list (list): List to convert.

    Returns:
        np.ndarray: Complex numpy aray

    Raises:
        QiskitError: If inner most array of input nested list is not of length 2.


formatted_memory = _list_to_complex_array(memory)<EOL>if not <NUM_LIT:2> <= len(formatted_memory.shape) <= <NUM_LIT:3>:<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>return formatted_memory<EOL>

Format an experiment result memory object for measurement level 0.

    Args:
        memory (list): Memory from experiment with `meas_level==1`. `avg` or
            `single` will be inferred from shape of result memory.

    Returns:
        np.ndarray: Measurement level 0 complex numpy array

    Raises:
        QiskitError: If the returned numpy array does not have 2 (avg) or 3 (single)
            indicies.


formatted_memory = _list_to_complex_array(memory)<EOL>if not <NUM_LIT:1> <= len(formatted_memory.shape) <= <NUM_LIT:2>:<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>return formatted_memory<EOL>

Format an experiment result memory object for measurement level 1.

    Args:
        memory (list): Memory from experiment with `meas_level==1`. `avg` or
            `single` will be inferred from shape of result memory.

    Returns:
        np.ndarray: Measurement level 1 complex numpy array

    Raises:
        QiskitError: If the returned numpy array does not have 1 (avg) or 2 (single)
            indicies.


memory_list = []<EOL>for shot_memory in memory:<EOL><INDENT>memory_list.append(format_counts_memory(shot_memory, header))<EOL><DEDENT>return memory_list<EOL>

Format an experiment result memory object for measurement level 2.

    Args:
        memory (list): Memory from experiment with `meas_level==2` and `memory==True`.
        header (dict): the experiment header dictionary containing
            useful information for postprocessing.

    Returns:
        list[str]: List of bitstrings


counts_dict = {}<EOL>for key, val in counts.items():<EOL><INDENT>key = format_counts_memory(key, header)<EOL>counts_dict[key] = val<EOL><DEDENT>return counts_dict<EOL>

Format a single experiment result coming from backend to present
    to the Qiskit user.

    Args:
        counts (dict): counts histogram of multiple shots
        header (dict): the experiment header dictionary containing
            useful information for postprocessing.

    Returns:
        dict: a formatted counts


num_basis = len(vec)<EOL>vec_complex = np.zeros(num_basis, dtype=complex)<EOL>for i in range(num_basis):<EOL><INDENT>vec_complex[i] = vec[i][<NUM_LIT:0>] + <NUM_LIT> * vec[i][<NUM_LIT:1>]<EOL><DEDENT>if decimals:<EOL><INDENT>vec_complex = np.around(vec_complex, decimals=decimals)<EOL><DEDENT>return vec_complex<EOL>

Format statevector coming from the backend to present to the Qiskit user.

    Args:
        vec (list): a list of [re, im] complex numbers.
        decimals (int): the number of decimals in the statevector.
            If None, no rounding is done.

    Returns:
        list[complex]: a list of python complex numbers.


num_basis = len(mat)<EOL>mat_complex = np.zeros((num_basis, num_basis), dtype=complex)<EOL>for i, vec in enumerate(mat):<EOL><INDENT>mat_complex[i] = format_statevector(vec, decimals)<EOL><DEDENT>return mat_complex<EOL>

Format unitary coming from the backend to present to the Qiskit user.

    Args:
        mat (list[list]): a list of list of [re, im] complex numbers
        decimals (int): the number of decimals in the statevector.
            If None, no rounding is done.

    Returns:
        list[list[complex]]: a matrix of complex numbers


try:<EOL><INDENT>return self._get_experiment(experiment).data.to_dict()<EOL><DEDENT>except (KeyError, TypeError):<EOL><INDENT>raise QiskitError('<STR_LIT>'.format(experiment))<EOL><DEDENT>

Get the raw data for an experiment.

        Note this data will be a single classical and quantum register and in a
        format required by the results schema. We recomened that most users use
        the get_xxx method, and the data will be post-processed for the data type.

        Args:
            experiment (str or QuantumCircuit or Schedule or int or None): the index of the
                experiment. Several types are accepted for convenience::
                * str: the name of the experiment.
                * QuantumCircuit: the name of the circuit instance will be used.
                * Schedule: the name of the schedule instance will be used.
                * int: the position of the experiment.
                * None: if there is only one experiment, returns it.

        Returns:
            dict: A dictionary of results data for an experiment. The data
            depends on the backend it ran on and the settings of `meas_level`,
            `meas_return` and `memory`.

            QASM backends return a dictionary of dictionary with the key
            'counts' and  with the counts, with the second dictionary keys
            containing a string in hex format (``0x123``) and values equal to
            the number of times this outcome was measured.

            Statevector backends return a dictionary with key 'statevector' and
            values being a list[list[complex components]] list of 2^n_qubits
            complex amplitudes. Where each complex number is represented as a 2
            entry list for each component. For example, a list of
            [0.5+1j, 0-1j] would be represented as [[0.5, 1], [0, -1]].

            Unitary backends return a dictionary with key 'unitary' and values
            being a list[list[list[complex components]]] list of
            2^n_qubits x 2^n_qubits complex amplitudes in a two entry list for
            each component. For example if the amplitude is
            [[0.5+0j, 0-1j], ...] the value returned will be
            [[[0.5, 0], [0, -1]], ...].

            The simulator backends also have an optional key 'snapshots' which
            returns a dict of snapshots specified by the simulator backend.
            The value is of the form dict[slot: dict[str: array]]
            where the keys are the requested snapshot slots, and the values are
            a dictionary of the snapshots.

        Raises:
            QiskitError: if data for the experiment could not be retrieved.


try:<EOL><INDENT>exp_result = self._get_experiment(experiment)<EOL>try:  <EOL><INDENT>header = exp_result.header.to_dict()<EOL><DEDENT>except (AttributeError, QiskitError):<EOL><INDENT>header = None<EOL><DEDENT>meas_level = exp_result.meas_level<EOL>memory = self.data(experiment)['<STR_LIT>']<EOL>if meas_level == <NUM_LIT:2>:<EOL><INDENT>return postprocess.format_level_2_memory(memory, header)<EOL><DEDENT>elif meas_level == <NUM_LIT:1>:<EOL><INDENT>return postprocess.format_level_1_memory(memory)<EOL><DEDENT>elif meas_level == <NUM_LIT:0>:<EOL><INDENT>return postprocess.format_level_0_memory(memory)<EOL><DEDENT>else:<EOL><INDENT>raise QiskitError('<STR_LIT>'.format(meas_level))<EOL><DEDENT><DEDENT>except KeyError:<EOL><INDENT>raise QiskitError('<STR_LIT>'.format(experiment))<EOL><DEDENT>

Get the sequence of memory states (readouts) for each shot
        The data from the experiment is a list of format
        ['00000', '01000', '10100', '10100', '11101', '11100', '00101', ..., '01010']

        Args:
            experiment (str or QuantumCircuit or Schedule or int or None): the index of the
                experiment, as specified by ``data()``.

        Returns:
            List[str] or np.ndarray: Either the list of each outcome, formatted according to
                registers in circuit or a complex numpy np.darray with shape:

                | `meas_level` | `meas_return` | shape                                             |
                |--------------|---------------|---------------------------------------------------|
                | 0            | `single`      | np.ndarray[shots, memory_slots, memory_slot_size] |
                | 0            | `avg`         | np.ndarray[memory_slots, memory_slot_size]        |
                | 1            | `single`      | np.ndarray[shots, memory_slots]                   |
                | 1            | `avg`         | np.ndarray[memory_slots]                          |
                | 2            | `memory=True` | list                                              |

        Raises:
            QiskitError: if there is no memory data for the circuit.


try:<EOL><INDENT>exp = self._get_experiment(experiment)<EOL>try:<EOL><INDENT>header = exp.header.to_dict()<EOL><DEDENT>except (AttributeError, QiskitError):  <EOL><INDENT>header = None<EOL><DEDENT>return postprocess.format_counts(self.data(experiment)['<STR_LIT>'],<EOL>header)<EOL><DEDENT>except KeyError:<EOL><INDENT>raise QiskitError('<STR_LIT>'.format(experiment))<EOL><DEDENT>

Get the histogram data of an experiment.

        Args:
            experiment (str or QuantumCircuit or Schedule or int or None): the index of the
                experiment, as specified by ``get_data()``.

        Returns:
            dict[str:int]: a dictionary with the counts for each qubit, with
                the keys containing a string in binary format and separated
                according to the registers in circuit (e.g. ``0100 1110``).
                The string is little-endian (cr[0] on the right hand side).

        Raises:
            QiskitError: if there are no counts for the experiment.


def get_statevector(self, experiment=None, decimals=None):

Get the final statevector of an experiment.

        Args:
            experiment (str or QuantumCircuit or Schedule or int or None): the index of the
                experiment, as specified by ``data()``.
            decimals (int): the number of decimals in the statevector.
                If None, does not round.

        Returns:
            list[complex]: list of 2^n_qubits complex amplitudes.

        Raises:
            QiskitError: if there is no statevector for the experiment.


def get_unitary(self, experiment=None, decimals=None):

Get the final unitary of an experiment.

        Args:
            experiment (str or QuantumCircuit or Schedule or int or None): the index of the
                experiment, as specified by ``data()``.
            decimals (int): the number of decimals in the unitary.
                If None, does not round.

        Returns:
            list[list[complex]]: list of 2^n_qubits x 2^n_qubits complex
                amplitudes.

        Raises:
            QiskitError: if there is no unitary for the experiment.


if not self.success:<EOL><INDENT>raise QiskitError(getattr(self, '<STR_LIT:status>',<EOL>'<STR_LIT>'))<EOL><DEDENT>if key is None:<EOL><INDENT>if len(self.results) != <NUM_LIT:1>:<EOL><INDENT>raise QiskitError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>key = <NUM_LIT:0><EOL><DEDENT>if isinstance(key, int):<EOL><INDENT>return self.results[key]<EOL><DEDENT>if isinstance(key, (QuantumCircuit, Schedule)):<EOL><INDENT>key = key.name<EOL><DEDENT>try:<EOL><INDENT>return next(result for result in self.results<EOL>if getattr(getattr(result, '<STR_LIT>', None),<EOL>'<STR_LIT:name>', '<STR_LIT>') == key)<EOL><DEDENT>except StopIteration:<EOL><INDENT>raise QiskitError('<STR_LIT>' %<EOL>key)<EOL><DEDENT>

Return a single experiment result from a given key.

        Args:
            key (str or QuantumCircuit or Schedule or int or None): the index of the
                experiment, as specified by ``get_data()``.

        Returns:
            ExperimentResult: the results for an experiment.

        Raises:
            QiskitError: if there is no data for the experiment, or an unhandled
                error occurred while fetching the data.


def __init__(self, name, num_qubits, num_clbits, params):

if not isinstance(num_qubits, int) or not isinstance(num_clbits, int):<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>if num_qubits < <NUM_LIT:0> or num_clbits < <NUM_LIT:0>:<EOL><INDENT>raise QiskitError(<EOL>"<STR_LIT>" %<EOL>num_qubits, num_clbits)<EOL><DEDENT>self.name = name<EOL>self.num_qubits = num_qubits<EOL>self.num_clbits = num_clbits<EOL>self._params = []  <EOL>self.control = None<EOL>self._definition = None<EOL>self.params = params<EOL>

Create a new instruction.
        Args:
            name (str): instruction name
            num_qubits (int): instruction's qubit width
            num_clbits (int): instructions's clbit width
            params (list[sympy.Basic|qasm.Node|int|float|complex|str|ndarray]): list of parameters
        Raises:
            QiskitError: when the register is not in the correct format.


if type(self) is not type(other) orself.name != other.name orself.num_qubits != other.num_qubits orself.num_clbits != other.num_clbits orself.definition != other.definition:<EOL><INDENT>return False<EOL><DEDENT>for self_param, other_param in zip_longest(self.params, other.params):<EOL><INDENT>if self_param == other_param:<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>if numpy.isclose(float(self_param), float(other_param),<EOL>atol=_CUTOFF_PRECISION):<EOL><INDENT>continue<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>pass<EOL><DEDENT>return False<EOL><DEDENT>return True<EOL>

Two instructions are the same if they have the same name,
        same dimensions, and same params.

        Args:
            other (instruction): other instruction

        Returns:
            bool: are self and other equal.


pass<EOL>

Populates self.definition with a decomposition of this gate.


<EOL>if self._definition and not self._params:<EOL><INDENT>self._params = []<EOL>for sub_instr, _, _ in self._definition:<EOL><INDENT>self._params.extend(sub_instr.params)  <EOL><DEDENT>return self._params<EOL><DEDENT>else:<EOL><INDENT>return self._params<EOL><DEDENT>


if self._definition is None:<EOL><INDENT>self._define()<EOL><DEDENT>return self._definition<EOL>

Return definition in terms of other basic gates.


self._definition = array<EOL>


instruction = QasmQobjInstruction(name=self.name)<EOL>if self.params:<EOL><INDENT>params = [<EOL>x.evalf() if hasattr(x, '<STR_LIT>') else x for x in self.params<EOL>]<EOL>params = [<EOL>sympy.matrix2numpy(x, dtype=complex) if isinstance(<EOL>x, sympy.Matrix) else x for x in params<EOL>]<EOL>instruction.params = params<EOL><DEDENT>if self.num_qubits:<EOL><INDENT>instruction.qubits = list(range(self.num_qubits))<EOL><DEDENT>if self.num_clbits:<EOL><INDENT>instruction.memory = list(range(self.num_clbits))<EOL><DEDENT>if self.control:<EOL><INDENT>instruction._control = self.control<EOL><DEDENT>return instruction<EOL>


if not self._definition:<EOL><INDENT>return self.copy()<EOL><DEDENT>reverse_inst = self.copy(name=self.name + '<STR_LIT>')<EOL>reverse_inst.definition = []<EOL>for inst, qargs, cargs in reversed(self._definition):<EOL><INDENT>reverse_inst._definition.append((inst.mirror(), qargs, cargs))<EOL><DEDENT>return reverse_inst<EOL>

For a composite instruction, reverse the order of sub-gates.

        This is done by recursively mirroring all sub-instructions.
        It does not invert any gate.

        Returns:
            Instruction: a fresh gate with sub-gates reversed


if not self.definition:<EOL><INDENT>raise QiskitError("<STR_LIT>" % self.name)<EOL><DEDENT>inverse_gate = self.copy(name=self.name + '<STR_LIT>')<EOL>inverse_gate._definition = []<EOL>for inst, qargs, cargs in reversed(self._definition):<EOL><INDENT>inverse_gate._definition.append((inst.inverse(), qargs, cargs))<EOL><DEDENT>return inverse_gate<EOL>

Invert this instruction.

        If the instruction is composite (i.e. has a definition),
        then its definition will be recursively inverted.

        Special instructions inheriting from Instruction can
        implement their own inverse (e.g. T and Tdg, Barrier, etc.)

        Returns:
            Instruction: a fresh instruction for the inverse

        Raises:
            QiskitError: if the instruction is not composite
                and an inverse has not been implemented for it.


if not isinstance(classical, ClassicalRegister):<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>if val < <NUM_LIT:0>:<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>self.control = (classical, val)<EOL>return self<EOL>

Add classical control on register classical and value val.


cpy = copy.copy(self)<EOL>if name:<EOL><INDENT>cpy.name = name<EOL><DEDENT>return cpy<EOL>

shallow copy of the instruction.

Args:
  name (str): name to be given to the copied circuit,
    if None then the name stays the same

Returns:
  Instruction: a shallow copy of the current instruction, with the name
    updated if it was provided


if self.control is None:<EOL><INDENT>return string<EOL><DEDENT>return "<STR_LIT>" % (self.control[<NUM_LIT:0>].name, self.control[<NUM_LIT:1>]) + string<EOL>


name_param = self.name<EOL>if self.params:<EOL><INDENT>name_param = "<STR_LIT>" % (name_param, "<STR_LIT:U+002C>".join(<EOL>[str(i) for i in self.params]))<EOL><DEDENT>return self._qasmif(name_param)<EOL>

Return a default OpenQASM string for the instruction.

        Derived instructions may override this to print in a
        different format (e.g. measure q[0] -> c[0];).


return self.append(Reset(), [qubit], [])<EOL>


super().__init__("<STR_LIT>", <NUM_LIT:1>, <NUM_LIT:0>, [])<EOL>


return "<STR_LIT>" % (self.name, self.size)<EOL>

Return OPENQASM string for this register.


self._table = dict(*args, **kwargs)<EOL>

the structure of _table is,
   {var_object: [(instruction_object, parameter_index), ...]}


def __setitem__(self, parameter, instr_params):

for instruction, param_index in instr_params:<EOL><INDENT>assert isinstance(instruction, Instruction)<EOL>assert isinstance(param_index, int)<EOL><DEDENT>self._table[parameter] = instr_params<EOL>

Sets list of Instructions that depend on Parameter.

        Args:
            parameter (Parameter): the parameter to set
            instr_params (list): List of (Instruction, int) tuples. Int is the
              parameter index at which the parameter appears in the instruction.


if name is None:<EOL><INDENT>name = '<STR_LIT>' % (self.prefix, next(self.instances_counter))<EOL><DEDENT>if not isinstance(name, str):<EOL><INDENT>raise QiskitError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>test = re.compile('<STR_LIT>')<EOL>if test.match(name) is None:<EOL><INDENT>raise QiskitError("<STR_LIT>" % name)<EOL><DEDENT>self.name = name<EOL>self.size = size<EOL>if size <= <NUM_LIT:0>:<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>


return "<STR_LIT>" % (self.__class__.__qualname__,<EOL>self.size, self.name)<EOL>

Return the official string representing the register.


return self.size<EOL>


if isinstance(j, int):<EOL><INDENT>if j < <NUM_LIT:0> or j >= self.size:<EOL><INDENT>raise QiskitIndexError("<STR_LIT>")<EOL><DEDENT>elif isinstance(j, slice):<EOL><INDENT>if j.start < <NUM_LIT:0> or j.stop >= self.size or (j.step is not None and<EOL>j.step <= <NUM_LIT:0>):<EOL><INDENT>raise QiskitIndexError("<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>

Check that j is a valid index into self.


if not isinstance(key, (int, slice, list)):<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>if isinstance(key, int) and key < <NUM_LIT:0>:<EOL><INDENT>key = self.size + key<EOL><DEDENT>self.check_range(key)<EOL>if isinstance(key, slice):<EOL><INDENT>return [(self, ind) for ind in range(*key.indices(len(self)))]<EOL><DEDENT>elif isinstance(key, list):  <EOL><INDENT>if max(key) < len(self):<EOL><INDENT>return [(self, ind) for ind in key]<EOL><DEDENT>else:<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return self, key<EOL><DEDENT>

Arg:
    key (int|slice|list): index of the bit/qubit to be retrieved.

Returns:
    tuple[Register, int]: a tuple in the form `(self, key)` if key is int.
        If key is a slice, return a `list((self,key))`.

Raises:
    QiskitError: if the `key` is not an integer.
    QiskitIndexError: if the `key` is not in the range
        `(0, self.size)`.


return zip([self]*self.size, range(self.size))<EOL>

Returns:
    iterator: an iterator over the bits/qubits of the register, in the
        form `tuple (Register, int)`.


res = False<EOL>if type(self) is type(other) andself.name == other.name andself.size == other.size:<EOL><INDENT>res = True<EOL><DEDENT>return res<EOL>

Two Registers are the same if they are of the same type
        (i.e. quantum/classical), and have the same name and size.

        Args:
            other (Register): other Register

        Returns:
            bool: are self and other equal.


return hash((type(self), self.name, self.size))<EOL>

Make object hashable, based on the name and size to hash.


@_to_bits(<NUM_LIT:1>, <NUM_LIT:1>)<EOL>@_op_expand(<NUM_LIT:2>, broadcastable=[True, False])<EOL>def measure(self, qubit, cbit):

return self.append(Measure(), [qubit], [cbit])<EOL>

Measure quantum bit into classical bit (tuples).

    Args:
        qubit (QuantumRegister|list|tuple): quantum register
        cbit (ClassicalRegister|list|tuple): classical register

    Returns:
        qiskit.Instruction: the attached measure instruction.

    Raises:
        QiskitError: if qubit is not in this circuit or bad format;
            if cbit is not in this circuit or not creg.


super().__init__("<STR_LIT>", <NUM_LIT:1>, <NUM_LIT:1>, [])<EOL>


self.instructions = []<EOL>self.qargs = []<EOL>self.cargs = []<EOL>

New collection of instructions.

        The context (qargs and cargs that each instruction is attached to),
        is also stored separately for each instruction.


return len(self.instructions)<EOL>


return self.instructions[i]<EOL>


if not isinstance(gate, Instruction):<EOL><INDENT>raise QiskitError("<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>self.instructions.append(gate)<EOL>self.qargs.append(qargs)<EOL>self.cargs.append(cargs)<EOL>

Add an instruction and its context (where it's attached).


for index, instruction in enumerate(self.instructions):<EOL><INDENT>self.instructions[index] = instruction.inverse()<EOL><DEDENT>return self<EOL>


for gate in self.instructions:<EOL><INDENT>gate.q_if(*qregs)<EOL><DEDENT>return self<EOL>


for gate in self.instructions:<EOL><INDENT>gate.c_if(classical, val)<EOL><DEDENT>return self<EOL>

Add classical control register to all instructions.


def __init__(self, name, num_qubits, params, label=None):

self._label = label<EOL>super().__init__(name, num_qubits, <NUM_LIT:0>, params)<EOL>

Create a new gate.

        Args:
            name (str): the Qobj name of the gate
            num_qubits (int): the number of qubits the gate acts on.
            params (list): a list of parameters.
            label (str or None): An optional label for the gate [Default: None]


raise QiskitError("<STR_LIT>".format(type(self)))<EOL>

Return a Numpy.array for the gate unitary matrix.

        Additional Information
        ----------------------
        If a Gate subclass does not implement this method an exception
        will be raised when this base class method is called.


instruction = super().assemble()<EOL>if self.label:<EOL><INDENT>instruction.label = self.label<EOL><DEDENT>return instruction<EOL>


return self._label<EOL>


if isinstance(name, (str, type(None))):<EOL><INDENT>self._label = name<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>

Set gate label to name

        Args:
            name (str or None): label to assign unitary

        Raises:
            TypeError: name is not string or None.


<EOL>if isinstance(obj, tuple) and len(obj) == <NUM_LIT:2>:<EOL><INDENT>if isinstance(obj[<NUM_LIT:0>], Register) and isinstance(obj[<NUM_LIT:1>], int) and obj[<NUM_LIT:1>] < len(obj[<NUM_LIT:0>]):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>


new_list = []<EOL>for item in a_list:<EOL><INDENT>if isinstance(item, (int, slice)):<EOL><INDENT>try:<EOL><INDENT>new_list.append(bits[item])<EOL><DEDENT>except IndexError:<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT><DEDENT>elif isinstance(item, list):<EOL><INDENT>new_list.append(_convert_to_bits(item, bits))<EOL><DEDENT>elif isinstance(item, range):<EOL><INDENT>new_list.append(_convert_to_bits([index for index in item], bits))<EOL><DEDENT>else:<EOL><INDENT>new_list.append(item)<EOL><DEDENT><DEDENT>return new_list<EOL>

Recursively converts the integers, tuples and ranges in a_list
    for a qu/clbit from the bits. E.g. bits[item_in_a_list]


def _to_bits(nqbits, ncbits=<NUM_LIT:0>, func=None):

if func is None:<EOL><INDENT>return functools.partial(_to_bits, nqbits, ncbits)<EOL><DEDENT>@functools.wraps(func)<EOL>def wrapper(self, *args):<EOL><INDENT>qbits = self.qubits()<EOL>cbits = self.clbits()<EOL>nparams = len(args) - nqbits - ncbits<EOL>params = args[:nparams]<EOL>qb_args = args[nparams:nparams + nqbits]<EOL>cl_args = args[nparams + nqbits:]<EOL>args = list(params) + _convert_to_bits(qb_args, qbits) + _convert_to_bits(cl_args, cbits)<EOL>return func(self, *args)<EOL><DEDENT>return wrapper<EOL>

Convert gate arguments to [qu|cl]bits from integers, slices, ranges, etc.
    For example circuit.h(0) -> circuit.h(QuantumRegister(2)[0])


def _op_expand(n_bits, func=None, broadcastable=None):

if func is None:<EOL><INDENT>return functools.partial(_op_expand, n_bits, broadcastable=broadcastable)<EOL><DEDENT>@functools.wraps(func)<EOL>def wrapper(self, *args):<EOL><INDENT>params = args[<NUM_LIT:0>:-n_bits] if len(args) > n_bits else tuple()<EOL>rargs = args[-n_bits:]<EOL>if broadcastable is None:<EOL><INDENT>blist = [True] * len(rargs)<EOL><DEDENT>else:<EOL><INDENT>blist = broadcastable<EOL><DEDENT>if not all([_is_bit(arg) for arg in rargs]):<EOL><INDENT>rarg_size = [<NUM_LIT:1>] * n_bits<EOL>for iarg, arg in enumerate(rargs):<EOL><INDENT>if isinstance(arg, Register):<EOL><INDENT>rarg_size[iarg] = len(arg)<EOL><DEDENT>elif isinstance(arg, list) and all([_is_bit(bit) for bit in arg]):<EOL><INDENT>rarg_size[iarg] = len(arg)<EOL><DEDENT>elif _is_bit(arg):<EOL><INDENT>rarg_size[iarg] = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT><DEDENT>broadcast_size = max(rarg_size)<EOL>expanded_rargs = []<EOL>for arg, broadcast in zip(rargs, blist):<EOL><INDENT>if isinstance(arg, Register):<EOL><INDENT>arg = [(arg, i) for i in range(len(arg))]<EOL><DEDENT>elif isinstance(arg, tuple):<EOL><INDENT>arg = [arg]<EOL><DEDENT>if isinstance(arg, list) and len(arg) == <NUM_LIT:1> and broadcast:<EOL><INDENT>arg = arg * broadcast_size<EOL><DEDENT>if len(arg) != broadcast_size:<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>expanded_rargs.append(arg)<EOL><DEDENT>rargs = expanded_rargs<EOL>if all([isinstance(arg, list) for arg in rargs]):<EOL><INDENT>if all(rargs):<EOL><INDENT>instructions = InstructionSet()<EOL>for irargs in zip(*rargs):<EOL><INDENT>instructions.add(func(self, *params, *irargs),<EOL>[i for i in irargs if isinstance(i[<NUM_LIT:0>], QuantumRegister)],<EOL>[i for i in irargs if isinstance(i[<NUM_LIT:0>], ClassicalRegister)])<EOL><DEDENT>return instructions<EOL><DEDENT>else:<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>return func(self, *params, *rargs)<EOL><DEDENT>return wrapper<EOL>

Decorator for expanding an operation across a whole register or register subset.
    Args:
        n_bits (int): the number of register bit arguments the decorated function takes
        func (function): used for decorators with keyword args
        broadcastable (list(bool)): list of bool for which register args can be
            broadcast from 1 bit to the max size of the rest of the args. Defaults
            to all True if not specified.

    Return:
        type: partial function object


if name is None:<EOL><INDENT>name = self.cls_prefix() + str(self.cls_instances())<EOL>if sys.platform != "<STR_LIT:win32>" andisinstance(mp.current_process(), mp.context.ForkProcess):<EOL><INDENT>name += '<STR_LIT>'.format(mp.current_process().pid)<EOL><DEDENT><DEDENT>self._increment_instances()<EOL>if not isinstance(name, str):<EOL><INDENT>raise QiskitError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>self.name = name<EOL>self.data = []<EOL>self.qregs = []<EOL>self.cregs = []<EOL>self.add_register(*regs)<EOL>self._parameter_table = ParameterTable()<EOL>

Create a new circuit.
        A circuit is a list of instructions bound to some registers.
        Args:
            *regs (list(Register) or list(Int)): To be included in the circuit.
                  - If [Register], the QuantumRegister and/or ClassicalRegister
                    to include in the circuit.
                    E.g.: QuantumCircuit(QuantumRegister(4))
                          QuantumCircuit(QuantumRegister(4), ClassicalRegister(3))
                          QuantumCircuit(QuantumRegister(4, 'qr0'), QuantumRegister(2, 'qr1'))
                  - If [Int], the amount of qubits and/or classical bits to include
                  in the circuit. It can be (Int, ) or (Int, Int).
                    E.g.: QuantumCircuit(4) # A QuantumCircuit with 4 qubits
                          QuantumCircuit(4, 3) # A QuantumCircuit with 4 qubits and 3 classical bits
            name (str or None): the name of the quantum circuit. If
                None, an automatically generated string will be assigned.

        Raises:
            QiskitError: if the circuit name, if given, is not valid.


return cls.instances<EOL>

Return the current number of instances of this class,
        useful for auto naming.


return cls.prefix<EOL>

Return the prefix to use for auto naming.


has_reg = False<EOL>if (isinstance(register, QuantumRegister) and<EOL>register in self.qregs):<EOL><INDENT>has_reg = True<EOL><DEDENT>elif (isinstance(register, ClassicalRegister) and<EOL>register in self.cregs):<EOL><INDENT>has_reg = True<EOL><DEDENT>return has_reg<EOL>

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.


reverse_circ = self.copy(name=self.name+'<STR_LIT>')<EOL>reverse_circ.data = []<EOL>for inst, qargs, cargs in reversed(self.data):<EOL><INDENT>reverse_circ.data.append((inst.mirror(), qargs, cargs))<EOL><DEDENT>return reverse_circ<EOL>

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


inverse_circ = self.copy(name=self.name+'<STR_LIT>')<EOL>inverse_circ.data = []<EOL>for inst, qargs, cargs in reversed(self.data):<EOL><INDENT>inverse_circ.data.append((inst.inverse(), qargs, cargs))<EOL><DEDENT>return inverse_circ<EOL>

Invert this circuit.

        This is done by recursively inverting all gates.

        Returns:
            QuantumCircuit: the inverted circuit

        Raises:
            QiskitError: if the circuit cannot be inverted.


<EOL>self._check_compatible_regs(rhs)<EOL>combined_qregs = deepcopy(self.qregs)<EOL>combined_cregs = deepcopy(self.cregs)<EOL>for element in rhs.qregs:<EOL><INDENT>if element not in self.qregs:<EOL><INDENT>combined_qregs.append(element)<EOL><DEDENT><DEDENT>for element in rhs.cregs:<EOL><INDENT>if element not in self.cregs:<EOL><INDENT>combined_cregs.append(element)<EOL><DEDENT><DEDENT>circuit = QuantumCircuit(*combined_qregs, *combined_cregs)<EOL>for instruction_context in itertools.chain(self.data, rhs.data):<EOL><INDENT>circuit.append(*instruction_context)<EOL><DEDENT>return circuit<EOL>

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
circuits.

Return self + rhs as a new object.


<EOL>self._check_compatible_regs(rhs)<EOL>for element in rhs.qregs:<EOL><INDENT>if element not in self.qregs:<EOL><INDENT>self.qregs.append(element)<EOL><DEDENT><DEDENT>for element in rhs.cregs:<EOL><INDENT>if element not in self.cregs:<EOL><INDENT>self.cregs.append(element)<EOL><DEDENT><DEDENT>for instruction_context in rhs.data:<EOL><INDENT>self.append(*instruction_context)<EOL><DEDENT>return self<EOL>

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
circuits.

Modify and return self.


return [qbit for qreg in self.qregs for qbit in qreg]<EOL>

Returns a list of quantum bits in the order that the registers had been added.


return [cbit for creg in self.cregs for cbit in creg]<EOL>

Returns a list of classical bits in the order that the registers had been added.


return self.combine(rhs)<EOL>


return self.extend(rhs)<EOL>


return len(self.data)<EOL>


return self.data[item]<EOL>


def append(self, instruction, qargs=None, cargs=None):

qargs = qargs or []<EOL>cargs = cargs or []<EOL>if not isinstance(instruction, Instruction) and hasattr(instruction, '<STR_LIT>'):<EOL><INDENT>instruction = instruction.to_instruction()<EOL><DEDENT>if not isinstance(instruction, Instruction):<EOL><INDENT>raise QiskitError('<STR_LIT>')<EOL><DEDENT>self._check_dups(qargs)<EOL>self._check_qargs(qargs)<EOL>self._check_cargs(cargs)<EOL>if instruction.num_qubits != len(qargs) orinstruction.num_clbits != len(cargs):<EOL><INDENT>raise QiskitError("<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>(instruction.name,<EOL>instruction.num_qubits, instruction.num_clbits,<EOL>len(qargs), len(cargs)))<EOL><DEDENT>instruction_context = instruction, qargs, cargs<EOL>self.data.append(instruction_context)<EOL>for param_index, param in enumerate(instruction.params):<EOL><INDENT>if isinstance(param, Parameter):<EOL><INDENT>current_symbols = self.parameters<EOL>if param in current_symbols:<EOL><INDENT>self._parameter_table[param].append((instruction, param_index))<EOL><DEDENT>else:<EOL><INDENT>self._parameter_table[param] = [(instruction, param_index)]<EOL><DEDENT><DEDENT><DEDENT>return instruction<EOL>

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.


def _attach(self, instruction, qargs, cargs):

self.append(instruction, qargs, cargs)<EOL>


if not regs:<EOL><INDENT>return<EOL><DEDENT>if any([isinstance(reg, int) for reg in regs]):<EOL><INDENT>if len(regs) == <NUM_LIT:1> and isinstance(regs[<NUM_LIT:0>], int):<EOL><INDENT>regs = (QuantumRegister(regs[<NUM_LIT:0>], '<STR_LIT:q>'),)<EOL><DEDENT>elif len(regs) == <NUM_LIT:2> and all([isinstance(reg, int) for reg in regs]):<EOL><INDENT>regs = (QuantumRegister(regs[<NUM_LIT:0>], '<STR_LIT:q>'), ClassicalRegister(regs[<NUM_LIT:1>], '<STR_LIT:c>'))<EOL><DEDENT>else:<EOL><INDENT>raise QiskitError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (regs,))<EOL><DEDENT><DEDENT>for register in regs:<EOL><INDENT>if register in self.qregs or register in self.cregs:<EOL><INDENT>raise QiskitError("<STR_LIT>"<EOL>% register.name)<EOL><DEDENT>if isinstance(register, QuantumRegister):<EOL><INDENT>self.qregs.append(register)<EOL><DEDENT>elif isinstance(register, ClassicalRegister):<EOL><INDENT>self.cregs.append(register)<EOL><DEDENT>else:<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT><DEDENT>


squbits = set(qubits)<EOL>if len(squbits) != len(qubits):<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>

Raise exception if list of qubits contains duplicates.


if not all(isinstance(i, tuple) and<EOL>isinstance(i[<NUM_LIT:0>], QuantumRegister) and<EOL>isinstance(i[<NUM_LIT:1>], int) for i in qargs):<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>if not all(self.has_register(i[<NUM_LIT:0>]) for i in qargs):<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>for qubit in qargs:<EOL><INDENT>qubit[<NUM_LIT:0>].check_range(qubit[<NUM_LIT:1>])<EOL><DEDENT>

Raise exception if a qarg is not in this circuit or bad format.


if not all(isinstance(i, tuple) and<EOL>isinstance(i[<NUM_LIT:0>], ClassicalRegister) and<EOL>isinstance(i[<NUM_LIT:1>], int) for i in cargs):<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>if not all(self.has_register(i[<NUM_LIT:0>]) for i in cargs):<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>for clbit in cargs:<EOL><INDENT>clbit[<NUM_LIT:0>].check_range(clbit[<NUM_LIT:1>])<EOL><DEDENT>

Raise exception if clbit is not in this circuit or bad format.


from qiskit.converters.circuit_to_instruction import circuit_to_instruction<EOL>return circuit_to_instruction(self)<EOL>

Create an Instruction out of this circuit.

        Returns:
            Instruction: a composite instruction encapsulating this circuit
                (can be decomposed back)


from qiskit.transpiler.passes.decompose import Decompose<EOL>from qiskit.converters.circuit_to_dag import circuit_to_dag<EOL>from qiskit.converters.dag_to_circuit import dag_to_circuit<EOL>pass_ = Decompose()<EOL>decomposed_dag = pass_.run(circuit_to_dag(self))<EOL>return dag_to_circuit(decomposed_dag)<EOL>

Call a decomposition pass on this circuit,
        to decompose one level (shallow decompose).

        Returns:
            QuantumCircuit: a circuit one level decomposed


list1 = self.qregs + self.cregs<EOL>list2 = rhs.qregs + rhs.cregs<EOL>for element1 in list1:<EOL><INDENT>for element2 in list2:<EOL><INDENT>if element2.name == element1.name:<EOL><INDENT>if element1 != element2:<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT><DEDENT>

Raise exception if the circuits are defined on incompatible registers


string_temp = self.header + "<STR_LIT:\n>"<EOL>string_temp += self.extension_lib + "<STR_LIT:\n>"<EOL>for register in self.qregs:<EOL><INDENT>string_temp += register.qasm() + "<STR_LIT:\n>"<EOL><DEDENT>for register in self.cregs:<EOL><INDENT>string_temp += register.qasm() + "<STR_LIT:\n>"<EOL><DEDENT>for instruction, qargs, cargs in self.data:<EOL><INDENT>if instruction.name == '<STR_LIT>':<EOL><INDENT>qubit = qargs[<NUM_LIT:0>]<EOL>clbit = cargs[<NUM_LIT:0>]<EOL>string_temp += "<STR_LIT>" % (instruction.qasm(),<EOL>qubit[<NUM_LIT:0>].name, qubit[<NUM_LIT:1>],<EOL>clbit[<NUM_LIT:0>].name, clbit[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>string_temp += "<STR_LIT>" % (instruction.qasm(),<EOL>"<STR_LIT:U+002C>".join(["<STR_LIT>" % (j[<NUM_LIT:0>].name, j[<NUM_LIT:1>])<EOL>for j in qargs + cargs]))<EOL><DEDENT><DEDENT>return string_temp<EOL>


def draw(self, scale=<NUM_LIT>, filename=None, style=None, output='<STR_LIT:text>',<EOL>interactive=False, line_length=None, plot_barriers=True,<EOL>reverse_bits=False, justify=None):

from qiskit.tools import visualization<EOL>return visualization.circuit_drawer(self, scale=scale,<EOL>filename=filename, style=style,<EOL>output=output,<EOL>interactive=interactive,<EOL>line_length=line_length,<EOL>plot_barriers=plot_barriers,<EOL>reverse_bits=reverse_bits,<EOL>justify=justify)<EOL>

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


gate_ops = <NUM_LIT:0><EOL>for instr, _, _ in self.data:<EOL><INDENT>if instr.name not in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>gate_ops += <NUM_LIT:1><EOL><DEDENT><DEDENT>return gate_ops<EOL>

Returns total number of gate operations in circuit.

        Returns:
            int: Total number of gate operations.


<EOL>reg_offset = <NUM_LIT:0><EOL>reg_map = {}<EOL>for reg in self.qregs+self.cregs:<EOL><INDENT>reg_map[reg.name] = reg_offset<EOL>reg_offset += reg.size<EOL><DEDENT>op_stack = [<NUM_LIT:0>]*reg_offset<EOL>for instr, qargs, cargs in self.data:<EOL><INDENT>if instr.name not in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>levels = []<EOL>reg_ints = []<EOL>for ind, reg in enumerate(qargs+cargs):<EOL><INDENT>reg_ints.append(reg_map[reg[<NUM_LIT:0>].name]+reg[<NUM_LIT:1>])<EOL>levels.append(op_stack[reg_ints[ind]] + <NUM_LIT:1>)<EOL><DEDENT>if instr.control:<EOL><INDENT>cint = reg_map[instr.control[<NUM_LIT:0>].name]<EOL>for off in range(instr.control[<NUM_LIT:0>].size):<EOL><INDENT>if cint+off not in reg_ints:<EOL><INDENT>reg_ints.append(cint+off)<EOL>levels.append(op_stack[cint+off]+<NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>max_level = max(levels)<EOL>for ind in reg_ints:<EOL><INDENT>op_stack[ind] = max_level<EOL><DEDENT><DEDENT><DEDENT>return max(op_stack)<EOL>

Return circuit depth (i.e. length of critical path).
        This does not include compiler or simulator directives
        such as 'barrier' or 'snapshot'.

        Returns:
            int: Depth of circuit.

        Notes:
            The circuit depth and the DAG depth need not bt the
            same.


return sum(reg.size for reg in self.qregs+self.cregs)<EOL>

Return number of qubits plus clbits in circuit.

        Returns:
            int: Width of circuit.


count_ops = {}<EOL>for instr, _, _ in self.data:<EOL><INDENT>if instr.name in count_ops.keys():<EOL><INDENT>count_ops[instr.name] += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>count_ops[instr.name] = <NUM_LIT:1><EOL><DEDENT><DEDENT>return count_ops<EOL>

Count each operation kind in the circuit.

        Returns:
            dict: a breakdown of how many operations of each kind.


<EOL>reg_offset = <NUM_LIT:0><EOL>reg_map = {}<EOL>if unitary_only:<EOL><INDENT>regs = self.qregs<EOL><DEDENT>else:<EOL><INDENT>regs = self.qregs+self.cregs<EOL><DEDENT>for reg in regs:<EOL><INDENT>reg_map[reg.name] = reg_offset<EOL>reg_offset += reg.size<EOL><DEDENT>sub_graphs = [[bit] for bit in range(reg_offset)]<EOL>num_sub_graphs = len(sub_graphs)<EOL>for instr, qargs, cargs in self.data:<EOL><INDENT>if unitary_only:<EOL><INDENT>args = qargs<EOL>num_qargs = len(args)<EOL><DEDENT>else:<EOL><INDENT>args = qargs+cargs<EOL>num_qargs = len(args) + (<NUM_LIT:1> if instr.control else <NUM_LIT:0>)<EOL><DEDENT>if num_qargs >= <NUM_LIT:2> and instr.name not in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>graphs_touched = []<EOL>num_touched = <NUM_LIT:0><EOL>if instr.control and not unitary_only:<EOL><INDENT>creg = instr.control[<NUM_LIT:0>]<EOL>creg_int = reg_map[creg.name]<EOL>for coff in range(creg.size):<EOL><INDENT>temp_int = creg_int+coff<EOL>for k in range(num_sub_graphs):<EOL><INDENT>if temp_int in sub_graphs[k]:<EOL><INDENT>graphs_touched.append(k)<EOL>num_touched += <NUM_LIT:1><EOL>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT>for item in args:<EOL><INDENT>reg_int = reg_map[item[<NUM_LIT:0>].name]+item[<NUM_LIT:1>]<EOL>for k in range(num_sub_graphs):<EOL><INDENT>if reg_int in sub_graphs[k]:<EOL><INDENT>if k not in graphs_touched:<EOL><INDENT>graphs_touched.append(k)<EOL>num_touched += <NUM_LIT:1><EOL>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if num_touched > <NUM_LIT:1>:<EOL><INDENT>connections = []<EOL>for idx in graphs_touched:<EOL><INDENT>connections.extend(sub_graphs[idx])<EOL><DEDENT>_sub_graphs = []<EOL>for idx in range(num_sub_graphs):<EOL><INDENT>if idx not in graphs_touched:<EOL><INDENT>_sub_graphs.append(sub_graphs[idx])<EOL><DEDENT><DEDENT>_sub_graphs.append(connections)<EOL>sub_graphs = _sub_graphs<EOL>num_sub_graphs -= (num_touched-<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if num_sub_graphs == <NUM_LIT:1>:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return num_sub_graphs<EOL>

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.


return self.num_connected_components(unitary_only=True)<EOL>

Computes the number of tensor factors in the unitary
        (quantum) part of the circuit only.


return self.num_unitary_factors()<EOL>

Computes the number of tensor factors in the unitary
        (quantum) part of the circuit only.

        Notes:
            This is here for backwards compatibility, and will be
            removed in a future release of qiskit. You should call
            `num_unitary_factors` instead.


cpy = deepcopy(self)<EOL>if name:<EOL><INDENT>cpy.name = name<EOL><DEDENT>return cpy<EOL>

Args:
  name (str): name to be given to the copied circuit, if None then the name stays the same
Returns:
  QuantumCircuit: a deepcopy of the current circuit, with the name updated if
                  it was provided


qasm = Qasm(filename=path)<EOL>return _circuit_from_qasm(qasm)<EOL>

Take in a QASM file and generate a QuantumCircuit object.

        Args:
          path (str): Path to the file for a QASM program
        Return:
          QuantumCircuit: The QuantumCircuit object for the input QASM


qasm = Qasm(data=qasm_str)<EOL>return _circuit_from_qasm(qasm)<EOL>

Take in a QASM string and generate a QuantumCircuit object.

        Args:
          qasm_str (str): A QASM program string
        Return:
          QuantumCircuit: The QuantumCircuit object for the input QASM


return set(self._parameter_table.keys())<EOL>

convenience function to get the parameters defined in the parameter table


new_circuit = self.copy()<EOL>if value_dict.keys() > self.parameters:<EOL><INDENT>raise QiskitError('<STR_LIT>'.format(<EOL>[str(p) for p in value_dict.keys() - self.parameters]))<EOL><DEDENT>for parameter, value in value_dict.items():<EOL><INDENT>new_circuit._bind_parameter(parameter, value)<EOL><DEDENT>for parameter in value_dict:<EOL><INDENT>del new_circuit._parameter_table[parameter]<EOL><DEDENT>return new_circuit<EOL>

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.


def _bind_parameter(self, parameter, value):

for (instr, param_index) in self._parameter_table[parameter]:<EOL><INDENT>instr.params[param_index] = value<EOL><DEDENT>

Assigns a parameter value to matching instructions in-place.


def __init__(self, name, params, inverse_name=None):

warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>', DeprecationWarning)<EOL>super().__init__(name, params)<EOL>self.data = []  <EOL>self.inverse_flag = False<EOL>self.inverse_name = inverse_name or (name + '<STR_LIT>')<EOL>

Create a new composite gate.

        name = instruction name string
        params = list of real parameters


instruction_list = []<EOL>for instruction in self.data:<EOL><INDENT>if isinstance(instruction, CompositeGate):<EOL><INDENT>instruction_list.extend(instruction.instruction_list())<EOL><DEDENT>else:<EOL><INDENT>instruction_list.append(instruction)<EOL><DEDENT><DEDENT>return instruction_list<EOL>

Return a list of instructions for this CompositeGate.

        If the CompositeGate itself contains composites, call
        this method recursively.


self.data.append(gate)<EOL>return gate<EOL>


self.append(gate)<EOL>


squbits = set(qubits)<EOL>if len(squbits) != len(qubits):<EOL><INDENT>raise QiskitError("<STR_LIT>")<EOL><DEDENT>

Raise exception.

        if list of qubits contains duplicates.


return "<STR_LIT:\n>".join([g.qasm() for g in self.data])<EOL>


self.data = [gate.inverse() for gate in reversed(self.data)]<EOL>self.inverse_flag = not self.inverse_flag<EOL>return self<EOL>


self.data = [gate.q_if(qregs) for gate in self.data]<EOL>return self<EOL>


self.data = [gate.c_if(classical, val) for gate in self.data]<EOL>return self<EOL>


def __init__(self,<EOL>qubits: List[Qubit],<EOL>registers: List[RegisterSlot],<EOL>mem_slots: List[MemorySlot]):

self._qubits = qubits<EOL>self._reg_slots = registers<EOL>self._mem_slots = mem_slots<EOL>

Create device specification with specified `qubits`.
Args:
    qubits:


backend_config = backend.configuration()<EOL>try:<EOL><INDENT>backend_default = backend.defaults()<EOL><DEDENT>except ModelValidationError:<EOL><INDENT>from collections import namedtuple<EOL>BackendDefault = namedtuple('<STR_LIT>', ('<STR_LIT>', '<STR_LIT>'))<EOL>backend_default = BackendDefault(<EOL>qubit_freq_est=backend_config.defaults['<STR_LIT>'],<EOL>meas_freq_est=backend_config.defaults['<STR_LIT>']<EOL>)<EOL><DEDENT>n_qubits = backend_config.n_qubits<EOL>n_registers = backend_config.n_registers<EOL>n_uchannels = backend_config.n_uchannels<EOL>if n_uchannels > <NUM_LIT:0> and n_uchannels != n_qubits:<EOL><INDENT>raise PulseError("<STR_LIT>")<EOL><DEDENT>qubit_lo_freqs = backend_default.qubit_freq_est<EOL>qubit_lo_ranges = backend_config.qubit_lo_range<EOL>meas_lo_freqs = backend_default.meas_freq_est<EOL>meas_lo_ranges = backend_config.meas_lo_range<EOL>drives = [<EOL>DriveChannel(i, qubit_lo_freqs[i], tuple(qubit_lo_ranges[i]))<EOL>for i in range(n_qubits)<EOL>]<EOL>measures = [<EOL>MeasureChannel(i, meas_lo_freqs[i], tuple(meas_lo_ranges[i]))<EOL>for i in range(n_qubits)<EOL>]<EOL>acquires = [AcquireChannel(i) for i in range(n_qubits)]<EOL>controls = [ControlChannel(i) for i in range(n_uchannels)]<EOL>qubits = []<EOL>for i in range(n_qubits):<EOL><INDENT>qubit = Qubit(i,<EOL>drive_channels=[drives[i]],<EOL>control_channels=None if n_uchannels == <NUM_LIT:0> else controls[i],<EOL>measure_channels=[measures[i]],<EOL>acquire_channels=[acquires[i]])<EOL>qubits.append(qubit)<EOL><DEDENT>registers = [RegisterSlot(i) for i in range(n_registers)]<EOL>mem_slots = [MemorySlot(i) for i in range(len(qubits))]<EOL>return DeviceSpecification(qubits, registers, mem_slots)<EOL>

Create device specification with values in backend configuration.
Args:
    backend(Backend): backend configuration
Returns:
    DeviceSpecification: created device specification
Raises:
    PulseError: when an invalid backend is specified


if type(self) is type(other) andself._qubits == other._qubits:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Two device specs are the same if they have the same qubits.

        Args:
            other (DeviceSpecification): other DeviceSpecification

        Returns:
            bool: are self and other equal.


@property<EOL><INDENT>def q(self) -> List[Qubit]:<DEDENT>

return self._qubits<EOL>


@property<EOL><INDENT>def c(self) -> List[RegisterSlot]:<DEDENT>

return self._reg_slots<EOL>


@property<EOL><INDENT>def mem(self) -> List[MemorySlot]:<DEDENT>

return self._mem_slots<EOL>


def includes(self, lo_freq: float) -> bool:

if self._lb <= lo_freq <= self._ub:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Whether `lo_freq` is within the `LoRange`.

        Args:
            lo_freq: LO frequency to be checked

        Returns:
            bool: True if lo_freq is included in this range, otherwise False


@property<EOL><INDENT>def lower_bound(self) -> float:<DEDENT>

return self._lb<EOL>


@property<EOL><INDENT>def upper_bound(self) -> float:<DEDENT>

return self._ub<EOL>


if (type(self) is type(other) and<EOL>self._ub == other._ub and<EOL>self._lb == other._lb):<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Two LO ranges are the same if they are of the same type, and
        have the same frequency range

        Args:
            other (LoRange): other LoRange

        Returns:
            bool: are self and other equal.


@property<EOL><INDENT>def lo_freq(self) -> float:<DEDENT>

return self._lo_freq<EOL>


@property<EOL><INDENT>def lo_freq_range(self) -> LoRange:<DEDENT>

return self._lo_freq_range<EOL>


def __init__(self, index: int,<EOL>lo_freq: float = None,<EOL>lo_freq_range: Tuple[float, float] = (<NUM_LIT:0>, float("<STR_LIT>"))):

super().__init__(index, lo_freq, lo_freq_range)<EOL>

Create new drive (d) channel.

        Args:
            index (int): index of the channel
            lo_freq (float): default frequency of LO (local oscillator)
            lo_freq_range (tuple): feasible range of LO frequency


Create new control (u) channel.

        Args:
            index (int): index of the channel
            lo_freq (float): default frequency of LO (local oscillator)
            lo_freq_range (tuple): feasible range of LO frequency


Create new measurement (m) channel.

        Args:
            index (int): index of the channel
            lo_freq (float): default frequency of LO (local oscillator)
            lo_freq_range (tuple): feasible range of LO frequency


@property<EOL><INDENT>def index(self) -> int:<DEDENT>

return self._index<EOL>


@property<EOL><INDENT>def name(self) -> str:<DEDENT>

return '<STR_LIT>' % (self.__class__.prefix, self._index)<EOL>


if type(self) is type(other) andself._index == other._index:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Two channels are the same if they are of the same type, and have the same index.

        Args:
            other (Channel): other Channel

        Returns:
            bool: are self and other equal.


Create new acquire channel.

        Args:
            index (int): Index of the channel.


Create new memory slot.

        Args:
            index (int): Index of the channel.


Create new register slot.

        Args:
            index (int): Index of the channel.


<EOL>if (type(self) is type(other) and<EOL>self._index == other._index and<EOL>self._drives == other._drives and<EOL>self._controls == other._controls and<EOL>self._measures == other._measures and<EOL>self._acquires == other._acquires):<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Two physical qubits are the same if they have the same index and channels.

        Args:
            other (Qubit): other Qubit

        Returns:
            bool: are self and other equal.


return self._index<EOL>


@property<EOL><INDENT>def drive(self) -> DriveChannel:<DEDENT>

if self._drives:<EOL><INDENT>return self._drives[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>raise PulseError("<STR_LIT>" % self._index)<EOL><DEDENT>

Return the primary drive channel of this qubit.


@property<EOL><INDENT>def control(self) -> ControlChannel:<DEDENT>

if self._controls:<EOL><INDENT>return self._controls[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>raise PulseError("<STR_LIT>" % self._index)<EOL><DEDENT>

Return the primary control channel of this qubit.


@property<EOL><INDENT>def measure(self) -> MeasureChannel:<DEDENT>

if self._measures:<EOL><INDENT>return self._measures[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>raise PulseError("<STR_LIT>" % self._index)<EOL><DEDENT>

Return the primary measure channel of this qubit.


@property<EOL><INDENT>def acquire(self) -> AcquireChannel:<DEDENT>

if self._acquires:<EOL><INDENT>return self._acquires[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>raise PulseError("<STR_LIT>" % self._index)<EOL><DEDENT>

Return the primary acquire channel of this qubit.


def union(*schedules: List[Union[ScheduleComponent, Tuple[int, ScheduleComponent]]],<EOL>name: str = None) -> Schedule:

if name is None and schedules:<EOL><INDENT>sched = schedules[<NUM_LIT:0>]<EOL>if isinstance(sched, (list, tuple)):<EOL><INDENT>name = sched[<NUM_LIT:1>].name<EOL><DEDENT>else:<EOL><INDENT>name = sched.name<EOL><DEDENT><DEDENT>return Schedule(*schedules, name=name)<EOL>

Create a union (and also shift if desired) of all input `Schedule`s.

    Args:
        *schedules: Schedules to take the union of
        name: Name of the new schedule. Defaults to first element of `schedules`


def flatten(schedule: ScheduleComponent, name: str = None) -> Schedule:

if name is None:<EOL><INDENT>name = schedule.name<EOL><DEDENT>return Schedule(*schedule.instructions, name=name)<EOL>

Create a flattened schedule.

    Args:
        schedule: Schedules to flatten
        name: Name of the new schedule. Defaults to first element of `schedules`


def shift(schedule: ScheduleComponent, time: int, name: str = None) -> Schedule:

if name is None:<EOL><INDENT>name = schedule.name<EOL><DEDENT>return union((time, schedule), name=name)<EOL>

Return schedule shifted by `time`.

    Args:
        schedule: The schedule to shift
        time: The time to shift by
        name: Name of shifted schedule. Defaults to name of `schedule`


def insert(parent: ScheduleComponent, time: int, child: ScheduleComponent,<EOL>name: str = None) -> Schedule:

return union(parent, (time, child), name=name)<EOL>

Return a new schedule with the `child` schedule inserted into the `parent` at `start_time`.

    Args:
        parent: Schedule to be inserted into
        time: Time to be inserted defined with respect to `parent`
        child: Schedule to insert
        name: Name of the new schedule. Defaults to name of parent


def append(parent: ScheduleComponent, child: ScheduleComponent,<EOL>name: str = None) -> Schedule:

common_channels = set(parent.channels) & set(child.channels)<EOL>insertion_time = parent.ch_stop_time(*common_channels)<EOL>return insert(parent, insertion_time, child, name=name)<EOL>

r"""Return a new schedule with by appending `child` to `parent` at
       the last time of the `parent` schedule's channels
       over the intersection of the parent and child schedule's channels.

       $t = \textrm{max}({x.stop\_time |x \in parent.channels \cap child.channels})$

    Args:
        parent: The schedule to be inserted into
        child: The schedule to insert
        name: Name of the new schedule. Defaults to name of parent


def left_sample(continuous_pulse: Callable, duration: int, *args, **kwargs) -> np.ndarray:

times = np.arange(duration)<EOL>return continuous_pulse(times, *args, **kwargs)<EOL>

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 right_sample(continuous_pulse: Callable, duration: int, *args, **kwargs) -> np.ndarray:

times = np.arange(<NUM_LIT:1>, duration+<NUM_LIT:1>)<EOL>return continuous_pulse(times, *args, **kwargs)<EOL>

Sampling strategy for decorator.
    Args:
        continuous_pulse: Continuous pulse function to sample.
        duration: Duration to sample for.
        *args: Continuous pulse function args.
        **kwargs: Continuous pulse function kwargs.


def midpoint_sample(continuous_pulse: Callable, duration: int, *args, **kwargs) -> np.ndarray:

times = np.arange(<NUM_LIT:1>/<NUM_LIT:2>, duration + <NUM_LIT:1>/<NUM_LIT:2>)<EOL>return continuous_pulse(times, *args, **kwargs)<EOL>


def _update_annotations(discretized_pulse: Callable) -> Callable:

undecorated_annotations = list(discretized_pulse.__annotations__.items())<EOL>decorated_annotations = undecorated_annotations[<NUM_LIT:1>:]<EOL>decorated_annotations.insert(<NUM_LIT:0>, ('<STR_LIT>', int))<EOL>discretized_pulse.__annotations__ = dict(decorated_annotations)<EOL>return discretized_pulse<EOL>

Update annotations of discretized continuous pulse function with duration.

    Args:
        discretized_pulse: Discretized decorated continuous pulse.


def _update_docstring(discretized_pulse: Callable, sampler_inst: Callable) -> Callable:

wrapped_docstring = pydoc.render_doc(discretized_pulse, '<STR_LIT:%s>')<EOL>header, body = wrapped_docstring.split('<STR_LIT:\n>', <NUM_LIT:1>)<EOL>body = textwrap.indent(body, '<STR_LIT:U+0020>')<EOL>wrapped_docstring = header+body<EOL>updated_ds = """<STR_LIT>""".format(continuous_name=discretized_pulse.__name__,<EOL>sampler_name=sampler_inst.__name__,<EOL>continuous_doc=wrapped_docstring)<EOL>discretized_pulse.__doc__ = updated_ds<EOL>return discretized_pulse<EOL>

Update annotations of discretized continuous pulse function.

    Args:
        discretized_pulse: Discretized decorated continuous pulse.
        sampler_inst: Applied sampler.


def sampler(sample_function: Callable) -> Callable:

def generate_sampler(continuous_pulse: Callable) -> Callable:<EOL><INDENT>"""<STR_LIT>"""<EOL>@functools.wraps(continuous_pulse)<EOL>def call_sampler(duration: int, *args, **kwargs) -> commands.SamplePulse:<EOL><INDENT>"""<STR_LIT>"""<EOL>sampled_pulse = sample_function(continuous_pulse, duration, *args, **kwargs)<EOL>return np.asarray(sampled_pulse, dtype=np.complex_)<EOL><DEDENT>call_sampler = _update_annotations(call_sampler)<EOL>call_sampler = _update_docstring(call_sampler, sample_function)<EOL>call_sampler.__dict__.pop('<STR_LIT>')<EOL>return commands.functional_pulse(call_sampler)<EOL><DEDENT>return generate_sampler<EOL>

Sampler decorator base method.

    Samplers are used for converting an continuous function to a discretized pulse.

    They operate on a function with the signature:
        `def f(times: np.ndarray, *args, **kwargs) -> np.ndarray`
    Where `times` is a numpy array of floats with length n_times and the output array
    is a complex numpy array with length n_times. The output of the decorator is an
    instance of `FunctionalPulse` with signature:
        `def g(duration: int, *args, **kwargs) -> SamplePulse`

    Note if your continuous pulse function outputs a `complex` scalar rather than a
    `np.ndarray`, you should first vectorize it before applying a sampler.

    This class implements the sampler boilerplate for the sampler.

    Args:
        sample_function: A sampler function to be decorated.


def left(continuous_pulse: Callable) -> Callable:

return sampler(strategies.left_sample)(continuous_pulse)<EOL>

r"""Left sampling strategy decorator.

    See `pulse.samplers.sampler` for more information.

    For `duration`, return:
        $$\{f(t) \in \mathbb{C} | t \in \mathbb{Z} \wedge  0<=t<\texttt{duration}\}$$

    Args:
        continuous_pulse: To sample.


def right(continuous_pulse: Callable) -> Callable:

return sampler(strategies.right_sample)(continuous_pulse)<EOL>

r"""Right sampling strategy decorator.

    See `pulse.samplers.sampler` for more information.

    For `duration`, return:
        $$\{f(t) \in \mathbb{C} | t \in \mathbb{Z} \wedge  0<t<=\texttt{duration}\}$$

    Args:
        continuous_pulse: To sample.


def midpoint(continuous_pulse: Callable) -> Callable:

return sampler(strategies.midpoint_sample)(continuous_pulse)<EOL>

r"""Midpoint sampling strategy decorator.

    See `pulse.samplers.sampler` for more information.

    For `duration`, return:
        $$\{f(t+0.5) \in \mathbb{C} | t \in \mathbb{Z} \wedge  0<=t<\texttt{duration}\}$$

    Args:
        continuous_pulse: To sample.


def constant(times: np.ndarray, amp: complex) -> np.ndarray:

return np.full(len(times), amp, dtype=np.complex_)<EOL>

Continuous constant pulse.

    Args:
        times: Times to output pulse for.
        amp: Complex pulse amplitude.


def zero(times: np.ndarray) -> np.ndarray:

return constant(times, <NUM_LIT:0>)<EOL>

Continuous zero pulse.

    Args:
        times: Times to output pulse for.


def square(times: np.ndarray, amp: complex, period: float, phase: float = <NUM_LIT:0>) -> np.ndarray:

x = times/period+phase/np.pi<EOL>return amp*(<NUM_LIT:2>*(<NUM_LIT:2>*np.floor(x) - np.floor(<NUM_LIT:2>*x)) + <NUM_LIT:1>).astype(np.complex_)<EOL>

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.


def sawtooth(times: np.ndarray, amp: complex, period: float, phase: float = <NUM_LIT:0>) -> np.ndarray:

x = times/period+phase/np.pi<EOL>return amp*<NUM_LIT:2>*(x-np.floor(<NUM_LIT:1>/<NUM_LIT:2>+x)).astype(np.complex_)<EOL>

Continuous sawtooth 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.


def triangle(times: np.ndarray, amp: complex, period: float, phase: float = <NUM_LIT:0>) -> np.ndarray:

return amp*(-<NUM_LIT:2>*np.abs(sawtooth(times, <NUM_LIT:1>, period, (phase-np.pi/<NUM_LIT:2>)/<NUM_LIT:2>)) + <NUM_LIT:1>).astype(np.complex_)<EOL>

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.


def cos(times: np.ndarray, amp: complex, freq: float, phase: float = <NUM_LIT:0>) -> np.ndarray:

return amp*np.cos(<NUM_LIT:2>*np.pi*freq*times+phase).astype(np.complex_)<EOL>

Continuous cosine wave.

    Args:
        times: Times to output wave for.
        amp: Pulse amplitude.
        freq: Pulse frequency, units of 1/dt.
        phase: Pulse phase.


def sin(times: np.ndarray, amp: complex, freq: float, phase: float = <NUM_LIT:0>) -> np.ndarray:

return amp*np.sin(<NUM_LIT:2>*np.pi*freq*times+phase).astype(np.complex_)<EOL>


def _fix_gaussian_width(gaussian_samples, amp: float, center: float, sigma: float,<EOL>zeroed_width: Union[None, float] = None, rescale_amp: bool = False,<EOL>ret_scale_factor: bool = False) -> np.ndarray:

if zeroed_width is None:<EOL><INDENT>zeroed_width = <NUM_LIT:2>*(center+<NUM_LIT:1>)<EOL><DEDENT>zero_offset = gaussian(np.array([-zeroed_width/<NUM_LIT:2>]), amp, center, sigma)<EOL>gaussian_samples -= zero_offset<EOL>amp_scale_factor = <NUM_LIT:1.><EOL>if rescale_amp:<EOL><INDENT>amp_scale_factor = amp/(amp-zero_offset)<EOL>gaussian_samples *= amp_scale_factor<EOL><DEDENT>if ret_scale_factor:<EOL><INDENT>return gaussian_samples, amp_scale_factor<EOL><DEDENT>return gaussian_samples<EOL>

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.


def gaussian(times: np.ndarray, amp: complex, center: float, sigma: float,<EOL>zeroed_width: Union[None, float] = None, rescale_amp: bool = False,<EOL>ret_x: bool = False) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]:

times = np.asarray(times, dtype=np.complex_)<EOL>x = (times-center)/sigma<EOL>gauss = amp*np.exp(-x**<NUM_LIT:2>/<NUM_LIT:2>).astype(np.complex_)<EOL>if zeroed_width is not None:<EOL><INDENT>gauss = _fix_gaussian_width(gauss, amp=amp, center=center, sigma=sigma,<EOL>zeroed_width=zeroed_width, rescale_amp=rescale_amp)<EOL><DEDENT>if ret_x:<EOL><INDENT>return gauss, x<EOL><DEDENT>return gauss<EOL>

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.


def gaussian_deriv(times: np.ndarray, amp: complex, center: float, sigma: float,<EOL>ret_gaussian: bool = False) -> np.ndarray:

gauss, x = gaussian(times, amp=amp, center=center, sigma=sigma, ret_x=True)<EOL>gauss_deriv = -x/sigma*gauss<EOL>if ret_gaussian:<EOL><INDENT>return gauss_deriv, gauss<EOL><DEDENT>return gauss_deriv<EOL>

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.


def gaussian_square(times: np.ndarray, amp: complex, center: float, width: float,<EOL>sigma: float, zeroed_width: Union[None, float] = None) -> np.ndarray:

square_start = center-width/<NUM_LIT:2><EOL>square_stop = center+width/<NUM_LIT:2><EOL>if zeroed_width:<EOL><INDENT>zeroed_width = min(width, zeroed_width)<EOL>gauss_zeroed_width = zeroed_width-width<EOL><DEDENT>else:<EOL><INDENT>gauss_zeroed_width = None<EOL><DEDENT>funclist = [functools.partial(gaussian, amp=amp, center=square_start, sigma=sigma,<EOL>zeroed_width=gauss_zeroed_width, rescale_amp=True),<EOL>functools.partial(gaussian, amp=amp, center=square_stop, sigma=sigma,<EOL>zeroed_width=gauss_zeroed_width, rescale_amp=True),<EOL>functools.partial(constant, amp=amp)]<EOL>condlist = [times <= square_start, times >= square_stop]<EOL>return np.piecewise(times.astype(np.complex_), condlist, funclist)<EOL>

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$.


def drag(times: np.ndarray, amp: complex, center: float, sigma: float, beta: float,<EOL>zeroed_width: Union[None, float] = None, rescale_amp: bool = False) -> np.ndarray:

gauss_deriv, gauss = gaussian_deriv(times, amp=amp, center=center, sigma=sigma,<EOL>ret_gaussian=True)<EOL>if zeroed_width is not None:<EOL><INDENT>gauss, scale_factor = _fix_gaussian_width(gauss, amp=amp, center=center, sigma=sigma,<EOL>zeroed_width=zeroed_width,<EOL>rescale_amp=rescale_amp,<EOL>ret_scale_factor=True)<EOL>gauss_deriv *= scale_factor<EOL><DEDENT>return gauss + <NUM_LIT>*beta*gauss_deriv<EOL>

r"""Continuous Y-only correction DRAG pulse for standard nonlinear oscillator (SNO) [1].

    [1] Gambetta, J. M., Motzoi, F., Merkel, S. T. & Wilhelm, F. K.
        Analytic control methods for high-fidelity unitary operations
        in a weakly nonlinear oscillator. Phys. Rev. A 83, 012308 (2011).

    Args:
        times: Times to output pulse for.
        amp: Pulse amplitude at `center`.
        center: Center (mean) of pulse.
        sigma: Width (standard deviation) of pulse.
        beta: Y correction amplitude. For the SNO this is $\beta=-\frac{\lambda_1^2}{4\Delta_2}$.
            Where $\lambds_1$ is the relative coupling strength between the first excited and second
            excited states and $\Delta_2$ is the detuning between the resepective excited states.
        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$.


def constant(duration: int, amp: complex, name: str = None) -> SamplePulse:

return _sampled_constant_pulse(duration, amp, name=name)<EOL>

Generates constant-sampled `SamplePulse`.

    Applies `left` sampling strategy to generate discrete pulse from continuous function.

    Args:
        duration: Duration of pulse. Must be greater than zero.
        amp: Complex pulse amplitude.
        name: Name of pulse.


def zero(duration: int, name: str = None) -> SamplePulse:

return _sampled_zero_pulse(duration, name=name)<EOL>

Generates zero-sampled `SamplePulse`.

    Args:
        duration: Duration of pulse. Must be greater than zero.
        name: Name of pulse.


def square(duration: int, amp: complex, period: float = None,<EOL>phase: float = <NUM_LIT:0>, name: str = None) -> SamplePulse:

if period is None:<EOL><INDENT>period = duration<EOL><DEDENT>return _sampled_square_pulse(duration, amp, period, phase=phase, name=name)<EOL>

Generates square wave `SamplePulse`.

    Applies `left` sampling strategy to generate discrete pulse from continuous function.

    Args:
        duration: Duration of pulse. Must be greater than zero.
        amp: Pulse amplitude. Wave range is [-amp, amp].
        period: Pulse period, units of dt. If `None` defaults to single cycle.
        phase: Pulse phase.
        name: Name of pulse.


def sawtooth(duration: int, amp: complex, period: float = None,<EOL>phase: float = <NUM_LIT:0>, name: str = None) -> SamplePulse:

if period is None:<EOL><INDENT>period = duration<EOL><DEDENT>return _sampled_sawtooth_pulse(duration, amp, period, phase=phase, name=name)<EOL>

Generates sawtooth wave `SamplePulse`.

    Args:
        duration: Duration of pulse. Must be greater than zero.
        amp: Pulse amplitude. Wave range is [-amp, amp].
        period: Pulse period, units of dt. If `None` defaults to single cycle.
        phase: Pulse phase.
        name: Name of pulse.


def triangle(duration: int, amp: complex, period: float = None,<EOL>phase: float = <NUM_LIT:0>, name: str = None) -> SamplePulse:

if period is None:<EOL><INDENT>period = duration<EOL><DEDENT>return _sampled_triangle_pulse(duration, amp, period, phase=phase, name=name)<EOL>

Generates triangle wave `SamplePulse`.

    Applies `left` sampling strategy to generate discrete pulse from continuous function.

    Args:
        duration: Duration of pulse. Must be greater than zero.
        amp: Pulse amplitude. Wave range is [-amp, amp].
        period: Pulse period, units of dt. If `None` defaults to single cycle.
        phase: Pulse phase.
        name: Name of pulse.


def cos(duration: int, amp: complex, freq: float = None,<EOL>phase: float = <NUM_LIT:0>, name: str = None) -> SamplePulse:

if freq is None:<EOL><INDENT>freq = <NUM_LIT:1>/duration<EOL><DEDENT>return _sampled_cos_pulse(duration, amp, freq, phase=phase, name=name)<EOL>

Generates cosine wave `SamplePulse`.

    Applies `left` sampling strategy to generate discrete pulse from continuous function.

    Args:
        duration: Duration of pulse. Must be greater than zero.
        amp: Pulse amplitude.
        freq: Pulse frequency, units of 1/dt. If `None` defaults to single cycle.
        phase: Pulse phase.
        name: Name of pulse.


def sin(duration: int, amp: complex, freq: float = None,<EOL>phase: float = <NUM_LIT:0>, name: str = None) -> SamplePulse:

if freq is None:<EOL><INDENT>freq = <NUM_LIT:1>/duration<EOL><DEDENT>return _sampled_sin_pulse(duration, amp, freq, phase=phase, name=name)<EOL>

Generates sine wave `SamplePulse`.

    Args:
        duration: Duration of pulse. Must be greater than zero.
        amp: Pulse amplitude.
        freq: Pulse frequency, units of 1/dt. If `None` defaults to single cycle.
        phase: Pulse phase.
        name: Name of pulse.


def gaussian(duration: int, amp: complex, sigma: float, name: str = None) -> SamplePulse:

center = duration/<NUM_LIT:2><EOL>zeroed_width = duration + <NUM_LIT:2><EOL>return _sampled_gaussian_pulse(duration, amp, center, sigma,<EOL>zeroed_width=zeroed_width, rescale_amp=True, name=name)<EOL>

r"""Generates unnormalized gaussian `SamplePulse`.

    Centered at `duration/2` and zeroed at `t=-1` to prevent large initial discontinuity.

    Applies `left` sampling strategy to generate discrete pulse from continuous function.

    Integrated area under curve is $\Omega_g(amp, sigma) = amp \times np.sqrt(2\pi \sigma^2)$

    Args:
        duration: Duration of pulse. Must be greater than zero.
        amp: Pulse amplitude at `duration/2`.
        sigma: Width (standard deviation) of pulse.
        name: Name of pulse.


def gaussian_deriv(duration: int, amp: complex, sigma: float, name: str = None) -> SamplePulse:

center = duration/<NUM_LIT:2><EOL>return _sampled_gaussian_deriv_pulse(duration, amp, center, sigma, name=name)<EOL>

r"""Generates unnormalized gaussian derivative `SamplePulse`.

    Applies `left` sampling strategy to generate discrete pulse from continuous function.

    Args:
        duration: Duration of pulse. Must be greater than zero.
        amp: Pulse amplitude at `center`.
        sigma: Width (standard deviation) of pulse.
        name: Name of pulse.


def gaussian_square(duration: int, amp: complex, sigma: float,<EOL>risefall: int, name: str = None) -> SamplePulse:

center = duration/<NUM_LIT:2><EOL>width = duration-<NUM_LIT:2>*risefall<EOL>zeroed_width = duration + <NUM_LIT:2><EOL>return _sampled_gaussian_square_pulse(duration, amp, center, width, sigma,<EOL>zeroed_width=zeroed_width, name=name)<EOL>

Generates gaussian square `SamplePulse`.

    Centered at `duration/2` and zeroed at `t=-1` and `t=duration+1` to prevent
    large initial/final discontinuities.

    Applies `left` sampling strategy to generate discrete pulse from continuous function.

    Args:
        duration: Duration of pulse. Must be greater than zero.
        amp: Pulse amplitude.
        sigma: Width (standard deviation) of gaussian rise/fall portion of the pulse.
        risefall: Number of samples over which pulse rise and fall happen. Width of
            square portion of pulse will be `duration-2*risefall`.
        name: Name of pulse.


def drag(duration: int, amp: complex, sigma: float, beta: float, name: str = None) -> SamplePulse:

center = duration/<NUM_LIT:2><EOL>zeroed_width = duration + <NUM_LIT:2><EOL>return _sampled_drag_pulse(duration, amp, center, sigma, beta,<EOL>zeroed_width=zeroed_width, rescale_amp=True, name=name)<EOL>

r"""Generates Y-only correction DRAG `SamplePulse` for standard nonlinear oscillator (SNO) [1].

    Centered at `duration/2` and zeroed at `t=-1` to prevent large initial discontinuity.

    Applies `left` sampling strategy to generate discrete pulse from continuous function.

    [1] Gambetta, J. M., Motzoi, F., Merkel, S. T. & Wilhelm, F. K.
        Analytic control methods for high-fidelity unitary operations
        in a weakly nonlinear oscillator. Phys. Rev. A 83, 012308 (2011).

    Args:
        duration: Duration of pulse. Must be greater than zero.
        amp: Pulse amplitude at `center`.
        sigma: Width (standard deviation) of pulse.
        beta: Y correction amplitude. For the SNO this is $\beta=-\frac{\lambda_1^2}{4\Delta_2}$.
            Where $\lambds_1$ is the relative coupling strength between the first excited and second
            excited states and $\Delta_2$ is the detuning between the resepective excited states.
        name: Name of pulse.


@property<EOL><INDENT>@abstractmethod<EOL>def name(self) -> str:<DEDENT>

pass<EOL>


@property<EOL><INDENT>@abstractmethod<EOL>def channels(self) -> List[Channel]:<DEDENT>

pass<EOL>


@property<EOL><INDENT>@abstractmethod<EOL>def duration(self) -> int:<DEDENT>

pass<EOL>


@property<EOL><INDENT>@abstractmethod<EOL>def start_time(self) -> int:<DEDENT>

pass<EOL>

Starting time of this schedule component.


@property<EOL><INDENT>@abstractmethod<EOL>def stop_time(self) -> int:<DEDENT>

pass<EOL>

Stopping time of this schedule component.


@abstractmethod<EOL><INDENT>def ch_duration(self, *channels: List[Channel]) -> int:<DEDENT>

pass<EOL>

Duration of the `channels` in schedule component.


@abstractmethod<EOL><INDENT>def ch_start_time(self, *channels: List[Channel]) -> int:<DEDENT>

pass<EOL>

Starting time of the `channels` in schedule component.


@abstractmethod<EOL><INDENT>def ch_stop_time(self, *channels: List[Channel]) -> int:<DEDENT>

pass<EOL>

Stopping of the `channels` in schedule component.


@property<EOL><INDENT>@abstractmethod<EOL>def timeslots(self) -> TimeslotCollection:<DEDENT>

pass<EOL>

Occupied time slots by this schedule component.


@property<EOL><INDENT>@abstractmethod<EOL>def children(self) -> Tuple[Union[int, '<STR_LIT>']]:<DEDENT>

pass<EOL>


@property<EOL><INDENT>@abstractmethod<EOL>def instructions(self) -> Tuple[Tuple[int, '<STR_LIT>']]:<DEDENT>

pass<EOL>

Return iterable for all `Instruction`s in `Schedule` tree.


@abstractmethod<EOL><INDENT>def flatten(self) -> '<STR_LIT>':<DEDENT>

pass<EOL>

Return a new schedule which is the flattened schedule contained all `instructions`.


@abstractmethod<EOL><INDENT>def union(self, *schedules: List['<STR_LIT>']) -> '<STR_LIT>':<DEDENT>

pass<EOL>

Return a new schedule which is the union of the parent `Schedule` and `schedule`.
        Args:
            schedules: Schedules to be take the union with the parent `Schedule`.


@abstractmethod<EOL><INDENT>def shift(self: '<STR_LIT>', time: int) -> '<STR_LIT>':<DEDENT>

pass<EOL>

Return a new schedule shifted forward by `time`.
        Args:
            time: Time to shift by


@abstractmethod<EOL><INDENT>def insert(self, start_time: int, schedule: '<STR_LIT>') -> '<STR_LIT>':<DEDENT>

pass<EOL>

Return a new schedule with `schedule` inserted at `start_time` of `self`.
        Args:
            start_time: time to be inserted
            schedule: schedule to be inserted


@abstractmethod<EOL><INDENT>def append(self, schedule: '<STR_LIT>') -> '<STR_LIT>':<DEDENT>

pass<EOL>

Return a new schedule with `schedule` inserted at the maximum time over
        all channels shared between `self` and `schedule`.
        Args:
            schedule: schedule to be appended


@abstractmethod<EOL><INDENT>def __add__(self, schedule: '<STR_LIT>') -> '<STR_LIT>':<DEDENT>

pass<EOL>

Return a new schedule with `schedule` inserted within `self` at `start_time`.


@abstractmethod<EOL><INDENT>def __or__(self, schedule: '<STR_LIT>') -> '<STR_LIT>':<DEDENT>

pass<EOL>

Return a new schedule which is the union of `self` and `schedule`.


@abstractmethod<EOL><INDENT>def __lshift__(self, time: int) -> '<STR_LIT>':<DEDENT>

pass<EOL>

Return a new schedule which is shifted forward by `time`.


def __init__(self, name: str, snap_type: str):

self._type = snap_type<EOL>self._channel = SnapshotChannel()<EOL>Command.__init__(self, duration=<NUM_LIT:0>, name=name)<EOL>Instruction.__init__(self, self, self._channel, name=name)<EOL>

Create new snapshot command.

        Args:
            name (str): Snapshot name which is used to identify the snapshot in the output.
            snap_type (str): Type of snapshot, e.g., “state” (take a snapshot of the quantum state).
                The types of snapshots offered are defined in a separate specification
                document for simulators.


@property<EOL><INDENT>def type(self) -> str:<DEDENT>

return self._type<EOL>


if (type(self) is type(other) and<EOL>self.name == other.name and<EOL>self.type == other.type):<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Two Snapshots are the same if they are of the same type
        and have the same name and type.

        Args:
            other (Snapshot): other Snapshot,

        Returns:
            bool: are self and other equal.


def __init__(self, name=None, **params):

self._name = name<EOL>self._params = params<EOL>

Create new measurement options.

        Parameters:
            name (str): Name of measurement option to be used.


return self._name<EOL>


return self._params<EOL>


if type(self) is type(other) andself._name == other._name andself._params == other._params:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Two measurement options are the same if they are of the same type
        and have the same name and params.

        Args:
            other (MeasOpts): Other Discriminator/Kernel.

        Returns:
            bool: are self and other equal.


super().__init__(name, **params)<EOL>

Create new discriminator.

        Parameters:
            name (str): Name of discriminator to be used.


super().__init__(name, **params)<EOL>

Create new kernel.

        Parameters:
            name (str): Name of kernel to be used.


super().__init__(duration=<NUM_LIT:0>)<EOL>self._phase = phase<EOL>

Create new frame change pulse.

        Args:
            phase (float): Frame change phase in radians.
                The allowable precision is device specific.


return self._phase<EOL>


if type(self) is type(other) andself.phase == other.phase:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Two FrameChanges are the same if they are of the same type
        and have the same phase.

        Args:
            other (FrameChange): other FrameChange

        Returns:
            bool: are self and other equal.


def __init__(self, command, *channels: List[Channel],<EOL>timeslots: TimeslotCollection = None, name=None):

self._command = command<EOL>self._name = name if name else self._command.name<EOL>if timeslots and channels:<EOL><INDENT>raise PulseError('<STR_LIT>')<EOL><DEDENT>if not timeslots:<EOL><INDENT>duration = command.duration<EOL>self._timeslots = TimeslotCollection(*(Timeslot(Interval(<NUM_LIT:0>, duration), channel)<EOL>for channel in channels))<EOL><DEDENT>else:<EOL><INDENT>self._timeslots = timeslots<EOL><DEDENT>

command (Command): Pulse command to schedule
*channels: List of pulse channels to schedule with command
timeslots: Optional list of timeslots. If channels are supplied timeslots
    cannot also be given
name: Name of Instruction


@property<EOL><INDENT>def name(self) -> str:<DEDENT>

return self._name<EOL>


return self._command<EOL>

Acquire command.

        Returns: Command


@property<EOL><INDENT>def channels(self) -> Tuple[Channel]:<DEDENT>

return self.timeslots.channels<EOL>

Returns channels that this schedule uses.


@property<EOL><INDENT>def timeslots(self) -> TimeslotCollection:<DEDENT>

return self._timeslots<EOL>

Occupied time slots by this instruction.


@property<EOL><INDENT>def start_time(self) -> int:<DEDENT>

return self.timeslots.start_time<EOL>

Relative begin time of this instruction.


@property<EOL><INDENT>def stop_time(self) -> int:<DEDENT>

return self.timeslots.stop_time<EOL>


@property<EOL><INDENT>def duration(self) -> int:<DEDENT>

return self.timeslots.duration<EOL>


@property<EOL><INDENT>def children(self) -> Tuple[ScheduleComponent]:<DEDENT>

return ()<EOL>


@property<EOL><INDENT>def instructions(self) -> Tuple[Tuple[int, '<STR_LIT>']]:<DEDENT>

return tuple(self._instructions())<EOL>

Iterable for getting instructions from Schedule tree.


def ch_duration(self, *channels: List[Channel]) -> int:

return self.timeslots.ch_duration(*channels)<EOL>

Return duration of the supplied channels in this Instruction.

        Args:
            *channels: Supplied channels


def ch_start_time(self, *channels: List[Channel]) -> int:

return self.timeslots.ch_start_time(*channels)<EOL>

Return minimum start time for supplied channels.

        Args:
            *channels: Supplied channels


def ch_stop_time(self, *channels: List[Channel]) -> int:

return self.timeslots.ch_stop_time(*channels)<EOL>

Return maximum start time for supplied channels.

        Args:
            *channels: Supplied channels


def _instructions(self, time: int = <NUM_LIT:0>) -> Iterable[Tuple[int, '<STR_LIT>']]:

yield (time, self)<EOL>

Iterable for flattening Schedule tree.

        Args:
            time: Shifted time of this node due to parent

        Yields:
            Tuple[int, ScheduleComponent]: Tuple containing time `ScheduleComponent` starts
                at and the flattened `ScheduleComponent`.


return self<EOL>

Return itself as already single instruction.


def union(self, *schedules: List[ScheduleComponent]) -> '<STR_LIT>':

return ops.union(self, *schedules)<EOL>

Return a new schedule which is the union of `self` and `schedule`.

        Args:
            *schedules: Schedules to be take the union with the parent `Schedule`.


def shift(self: ScheduleComponent, time: int) -> '<STR_LIT>':

return ops.shift(self, time)<EOL>

Return a new schedule shifted forward by `time`.

        Args:
            time: Time to shift by


def insert(self, start_time: int, schedule: ScheduleComponent) -> '<STR_LIT>':

return ops.insert(self, start_time, schedule)<EOL>

Return a new schedule with `schedule` inserted within `self` at `start_time`.

        Args:
            start_time: time to be inserted
            schedule: schedule to be inserted


def append(self, schedule: ScheduleComponent) -> '<STR_LIT>':

return ops.append(self, schedule)<EOL>

Return a new schedule with `schedule` inserted at the maximum time over
        all channels shared between `self` and `schedule`.

        Args:
            schedule: schedule to be appended


def __add__(self, schedule: ScheduleComponent) -> '<STR_LIT>':

return self.append(schedule)<EOL>

Return a new schedule with `schedule` inserted within `self` at `start_time`.


def __or__(self, schedule: ScheduleComponent) -> '<STR_LIT>':

return self.union(schedule)<EOL>

Return a new schedule which is the union of `self` and `schedule`.


def __lshift__(self, time: int) -> '<STR_LIT>':

return self.shift(time)<EOL>

Return a new schedule which is shifted forward by `time`.