def simplify_U(theta, phi, lam):
    """Return the gate u1, u2, or u3 implementing U with the fewest pulses.

    The returned gate implements U exactly, not up to a global phase.

    Args:
        theta, phi, lam: input Euler rotation angles for a general U gate

    Returns:
        Gate: one of IdGate, U1Gate, U2Gate, U3Gate.
    """
    gate = U3Gate(theta, phi, lam)
    # Y rotation is 0 mod 2*pi, so the gate is a u1
    if abs(gate.params[0] % (2.0 * math.pi)) < _CUTOFF_PRECISION:
        gate = U1Gate(gate.params[0] + gate.params[1] + gate.params[2])
    # Y rotation is pi/2 or -pi/2 mod 2*pi, so the gate is a u2
    if isinstance(gate, U3Gate):
        # theta = pi/2 + 2*k*pi
        if abs((gate.params[0] - math.pi / 2) % (2.0 * math.pi)) < _CUTOFF_PRECISION:
            gate = U2Gate(gate.params[1],
                          gate.params[2] + (gate.params[0] - math.pi / 2))
        # theta = -pi/2 + 2*k*pi
        if abs((gate.params[0] + math.pi / 2) % (2.0 * math.pi)) < _CUTOFF_PRECISION:
            gate = U2Gate(gate.params[1] + math.pi,
                          gate.params[2] - math.pi + (gate.params[0] + math.pi / 2))
    # u1 and lambda is 0 mod 4*pi so gate is nop
    if isinstance(gate, U1Gate) and abs(gate.params[0] % (4.0 * math.pi)) < _CUTOFF_PRECISION:
        gate = IdGate()
    return gate

def simplify_U ( theta , phi , lam ) : gate = U3Gate ( theta , phi , lam ) if abs ( gate . params [ 0 ] % ( 2.0 * math . pi ) ) < _CUTOFF_PRECISION : gate = U1Gate ( gate . params [ 0 ] + gate . params [ 1 ] + gate . params [ 2 ] ) if isinstance ( gate , U3Gate ) : if abs ( ( gate . params [ 0 ] - math . pi / 2 ) % ( 2.0 * math . pi ) ) < _CUTOFF_PRECISION : gate = U2Gate ( gate . params [ 1 ] , gate . params [ 2 ] + ( gate . params [ 0 ] - math . pi / 2 ) ) if abs ( ( gate . params [ 0 ] + math . pi / 2 ) % ( 2.0 * math . pi ) ) < _CUTOFF_PRECISION : gate = U2Gate ( gate . params [ 1 ] + math . pi , gate . params [ 2 ] - math . pi + ( gate . params [ 0 ] + math . pi / 2 ) ) if isinstance ( gate , U1Gate ) and abs ( gate . params [ 0 ] % ( 4.0 * math . pi ) ) < _CUTOFF_PRECISION : gate = IdGate ( ) return gate

Return the gate u1 u2 or u3 implementing U with the fewest pulses .


def run(self, dag):
        """
        Extends dag with virtual qubits that are in layout but not in the circuit yet.

        Args:
            dag (DAGCircuit): DAG to extend.

        Returns:
            DAGCircuit: An extended DAG.

        Raises:
            TranspilerError: If there is not layout in the property set or not set at init time.
        """
        self.layout = self.layout or self.property_set['layout']

        if self.layout is None:
            raise TranspilerError("EnlargeWithAncilla requires property_set[\"layout\"] or"
                                  " \"layout\" parameter to run")

        layout_virtual_qubits = self.layout.get_virtual_bits().keys()
        new_qregs = set(virtual_qubit[0] for virtual_qubit in layout_virtual_qubits
                        if virtual_qubit not in dag.wires)

        for qreg in new_qregs:
            dag.add_qreg(qreg)

        return dag

Extends dag with virtual qubits that are in layout but not in the circuit yet .


def qubits_tab(backend):
    """The qubits properties widget

    Args:
        backend (IBMQbackend): The backend.

    Returns:
        VBox: A VBox widget.
    """
    props = backend.properties().to_dict()

    header_html = "
{key}: {value}
"
    header_html = header_html.format(key='last_update_date',
                                     value=props['last_update_date'])
    update_date_widget = widgets.HTML(value=header_html)

    qubit_html = "
"
    qubit_html += """"""

    qubit_html += "
	Frequency	T1	T2	"
    qubit_html += "U1 gate error	U2 gate error	U3 gate error	"
    qubit_html += "Readout error
"
    qubit_footer = "
"

    for qub in range(len(props['qubits'])):
        name = 'Q%s' % qub
        qubit_data = props['qubits'][qub]
        gate_data = props['gates'][3*qub:3*qub+3]
        t1_info = qubit_data[0]
        t2_info = qubit_data[1]
        freq_info = qubit_data[2]
        readout_info = qubit_data[3]

        freq = str(round(freq_info['value'], 5))+' '+freq_info['unit']
        T1 = str(round(t1_info['value'],  # pylint: disable=invalid-name
                       5))+' ' + t1_info['unit']
        T2 = str(round(t2_info['value'],  # pylint: disable=invalid-name
                       5))+' ' + t2_info['unit']
        # pylint: disable=invalid-name
        U1 = str(round(gate_data[0]['parameters'][0]['value'], 5))
        # pylint: disable=invalid-name
        U2 = str(round(gate_data[1]['parameters'][0]['value'], 5))
        # pylint: disable=invalid-name
        U3 = str(round(gate_data[2]['parameters'][0]['value'], 5))

        readout_error = round(readout_info['value'], 5)
        qubit_html += "
%s	%s	"
        qubit_html += "%s	%s	%s	%s	%s	%s
"
        qubit_html = qubit_html % (name, freq, T1, T2, U1, U2, U3, readout_error)
    qubit_html += qubit_footer

    qubit_widget = widgets.HTML(value=qubit_html)

    out = widgets.VBox([update_date_widget,
                        qubit_widget])

    return out


def job_history(backend):
    """Widget for displaying job history

    Args:
     backend (IBMQbackend): The backend.

    Returns:
        Tab: A tab widget for history images.
    """
    year = widgets.Output(layout=widgets.Layout(display='flex-inline',
                                                align_items='center',
                                                min_height='400px'))

    month = widgets.Output(layout=widgets.Layout(display='flex-inline',
                                                 align_items='center',
                                                 min_height='400px'))

    week = widgets.Output(layout=widgets.Layout(display='flex-inline',
                                                align_items='center',
                                                min_height='400px'))

    tabs = widgets.Tab(layout=widgets.Layout(max_height='620px'))
    tabs.children = [year, month, week]
    tabs.set_title(0, 'Year')
    tabs.set_title(1, 'Month')
    tabs.set_title(2, 'Week')
    tabs.selected_index = 1

    _build_job_history(tabs, backend)
    return tabs

def job_history ( backend ) : year = widgets . Output ( layout = widgets . Layout ( display = 'flex-inline' , align_items = 'center' , min_height = '400px' ) ) month = widgets . Output ( layout = widgets . Layout ( display = 'flex-inline' , align_items = 'center' , min_height = '400px' ) ) week = widgets . Output ( layout = widgets . Layout ( display = 'flex-inline' , align_items = 'center' , min_height = '400px' ) ) tabs = widgets . Tab ( layout = widgets . Layout ( max_height = '620px' ) ) tabs . children = [ year , month , week ] tabs . set_title ( 0 , 'Year' ) tabs . set_title ( 1 , 'Month' ) tabs . set_title ( 2 , 'Week' ) tabs . selected_index = 1 _build_job_history ( tabs , backend ) return tabs


def plot_job_history(jobs, interval='year'):
    """Plots the job history of the user from the given list of jobs.

    Args:
        jobs (list): A list of jobs with type IBMQjob.
        interval (str): Interval over which to examine.

    Returns:
        fig: A Matplotlib figure instance.
    """
    def get_date(job):
        """Returns a datetime object from a IBMQJob instance.

        Args:
            job (IBMQJob): A job.

        Returns:
            dt: A datetime object.
        """
        return datetime.datetime.strptime(job.creation_date(),
                                          '%Y-%m-%dT%H:%M:%S.%fZ')

    current_time = datetime.datetime.now()

    if interval == 'year':
        bins = [(current_time - datetime.timedelta(days=k*365/12))
                for k in range(12)]
    elif interval == 'month':
        bins = [(current_time - datetime.timedelta(days=k)) for k in range(30)]
    elif interval == 'week':
        bins = [(current_time - datetime.timedelta(days=k)) for k in range(7)]

    binned_jobs = [0]*len(bins)

    if interval == 'year':
        for job in jobs:
            for ind, dat in enumerate(bins):
                date = get_date(job)
                if date.month == dat.month:
                    binned_jobs[ind] += 1
                    break
            else:
                continue
    else:
        for job in jobs:
            for ind, dat in enumerate(bins):
                date = get_date(job)
                if date.day == dat.day and date.month == dat.month:
                    binned_jobs[ind] += 1
                    break
            else:
                continue

    nz_bins = []
    nz_idx = []
    for ind, val in enumerate(binned_jobs):
        if val != 0:
            nz_idx.append(ind)
            nz_bins.append(val)

    total_jobs = sum(binned_jobs)

    colors = ['#003f5c', '#ffa600', '#374c80', '#ff764a',
              '#7a5195', '#ef5675', '#bc5090']

    if interval == 'year':
        labels = ['{}-{}'.format(str(bins[b].year)[2:], bins[b].month) for b in nz_idx]
    else:
        labels = ['{}-{}'.format(bins[b].month, bins[b].day) for b in nz_idx]
    fig, ax = plt.subplots(1, 1, figsize=(5, 5))  # pylint: disable=invalid-name
    ax.pie(nz_bins[::-1], labels=labels, colors=colors, textprops={'fontsize': 14},
           rotatelabels=True, counterclock=False)
    ax.add_artist(Circle((0, 0), 0.7, color='white', zorder=1))
    ax.text(0, 0, total_jobs, horizontalalignment='center',
            verticalalignment='center', fontsize=26)
    fig.tight_layout()
    return fig

def plot_job_history ( jobs , interval = 'year' ) : def get_date ( job ) : return datetime . datetime . strptime ( job . creation_date ( ) , '%Y-%m-%dT%H:%M:%S.%fZ' ) current_time = datetime . datetime . now ( ) if interval == 'year' : bins = [ ( current_time - datetime . timedelta ( days = k * 365 / 12 ) ) for k in range ( 12 ) ] elif interval == 'month' : bins = [ ( current_time - datetime . timedelta ( days = k ) ) for k in range ( 30 ) ] elif interval == 'week' : bins = [ ( current_time - datetime . timedelta ( days = k ) ) for k in range ( 7 ) ] binned_jobs = [ 0 ] * len ( bins ) if interval == 'year' : for job in jobs : for ind , dat in enumerate ( bins ) : date = get_date ( job ) if date . month == dat . month : binned_jobs [ ind ] += 1 break else : continue else : for job in jobs : for ind , dat in enumerate ( bins ) : date = get_date ( job ) if date . day == dat . day and date . month == dat . month : binned_jobs [ ind ] += 1 break else : continue nz_bins = [ ] nz_idx = [ ] for ind , val in enumerate ( binned_jobs ) : if val != 0 : nz_idx . append ( ind ) nz_bins . append ( val ) total_jobs = sum ( binned_jobs ) colors = [ '#003f5c' , '#ffa600' , '#374c80' , '#ff764a' , '#7a5195' , '#ef5675' , '#bc5090' ] if interval == 'year' : labels = [ '{}-{}' . format ( str ( bins [ b ] . year ) [ 2 : ] , bins [ b ] . month ) for b in nz_idx ] else : labels = [ '{}-{}' . format ( bins [ b ] . month , bins [ b ] . day ) for b in nz_idx ] fig , ax = plt . subplots ( 1 , 1 , figsize = ( 5 , 5 ) ) ax . pie ( nz_bins [ : : - 1 ] , labels = labels , colors = colors , textprops = { 'fontsize' : 14 } , rotatelabels = True , counterclock = False ) ax . add_artist ( Circle ( ( 0 , 0 ) , 0.7 , color = 'white' , zorder = 1 ) ) ax . text ( 0 , 0 , total_jobs , horizontalalignment = 'center' , verticalalignment = 'center' , fontsize = 26 ) fig . tight_layout ( ) return fig

Plots the job history of the user from the given list of jobs .


def draw(self, **kwargs):
        """Plot the interpolated envelope of pulse.

        Keyword Args:
            dt (float): Time interval of samples.
            interp_method (str): Method of interpolation
                (set `None` for turn off the interpolation).
            filename (str): Name required to save pulse image.
            interactive (bool): When set true show the circuit in a new window
                (this depends on the matplotlib backend being used supporting this).
            dpi (int): Resolution of saved image.
            nop (int): Data points for interpolation.
            size (tuple): Size of figure.
        """
        from qiskit.tools.visualization import pulse_drawer

        return pulse_drawer(self._samples, self.duration, **kwargs)

def draw ( self , ** kwargs ) : from qiskit . tools . visualization import pulse_drawer return pulse_drawer ( self . _samples , self . duration , ** kwargs )

Plot the interpolated envelope of pulse .


def cu3(self, theta, phi, lam, ctl, tgt):
    """Apply cu3 from ctl to tgt with angle theta, phi, lam."""
    return self.append(Cu3Gate(theta, phi, lam), [ctl, tgt], [])

def cu3 ( self , theta , phi , lam , ctl , tgt ) : return self . append ( Cu3Gate ( theta , phi , lam ) , [ ctl , tgt ] , [ ] )

Apply cu3 from ctl to tgt with angle theta phi lam .


def build_bell_circuit():
    """Returns a circuit putting 2 qubits in the Bell state."""
    q = QuantumRegister(2)
    c = ClassicalRegister(2)
    qc = QuantumCircuit(q, c)
    qc.h(q[0])
    qc.cx(q[0], q[1])
    qc.measure(q, c)
    return qc

def build_bell_circuit ( ) : q = QuantumRegister ( 2 ) c = ClassicalRegister ( 2 ) qc = QuantumCircuit ( q , c ) qc . h ( q [ 0 ] ) qc . cx ( q [ 0 ] , q [ 1 ] ) qc . measure ( q , c ) return qc

Returns a circuit putting 2 qubits in the Bell state .


def transpile(circuits,
              backend=None,
              basis_gates=None, coupling_map=None, backend_properties=None,
              initial_layout=None, seed_transpiler=None,
              optimization_level=None,
              pass_manager=None,
              seed_mapper=None):  # deprecated
    """transpile one or more circuits, according to some desired
    transpilation targets.

    All arguments may be given as either singleton or list. In case of list,
    the length must be equal to the number of circuits being transpiled.

    Transpilation is done in parallel using multiprocessing.

    Args:
        circuits (QuantumCircuit or list[QuantumCircuit]):
            Circuit(s) to transpile

        backend (BaseBackend):
            If set, transpiler options are automatically grabbed from
            backend.configuration() and backend.properties().
            If any other option is explicitly set (e.g. coupling_map), it
            will override the backend's.
            Note: the backend arg is purely for convenience. The resulting
                circuit may be run on any backend as long as it is compatible.

        basis_gates (list[str]):
            List of basis gate names to unroll to.
            e.g:
                ['u1', 'u2', 'u3', 'cx']
            If None, do not unroll.

        coupling_map (CouplingMap or list):
            Coupling map (perhaps custom) to target in mapping.
            Multiple formats are supported:
            a. CouplingMap instance

            b. list
                Must be given as an adjacency matrix, where each entry
                specifies all two-qubit interactions supported by backend
                e.g:
                    [[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]

        backend_properties (BackendProperties):
            properties returned by a backend, including information on gate
            errors, readout errors, qubit coherence times, etc. For a backend
            that provides this information, it can be obtained with:
            ``backend.properties()``

        initial_layout (Layout or dict or list):
            Initial position of virtual qubits on physical qubits.
            If this layout makes the circuit compatible with the coupling_map
            constraints, it will be used.
            The final layout is not guaranteed to be the same, as the transpiler
            may permute qubits through swaps or other means.

            Multiple formats are supported:
            a. Layout instance

            b. dict
                virtual to physical:
                    {qr[0]: 0,
                     qr[1]: 3,
                     qr[2]: 5}

                physical to virtual:
                    {0: qr[0],
                     3: qr[1],
                     5: qr[2]}

            c. list
                virtual to physical:
                    [0, 3, 5]  # virtual qubits are ordered (in addition to named)

                physical to virtual:
                    [qr[0], None, None, qr[1], None, qr[2]]

        seed_transpiler (int):
            sets random seed for the stochastic parts of the transpiler

        optimization_level (int):
            How much optimization to perform on the circuits.
            Higher levels generate more optimized circuits,
            at the expense of longer transpilation time.
                0: no optimization
                1: light optimization
                2: heavy optimization

        pass_manager (PassManager):
            The pass manager to use for a custom pipeline of transpiler passes.
            If this arg is present, all other args will be ignored and the
            pass manager will be used directly (Qiskit will not attempt to
            auto-select a pass manager based on transpile options).

        seed_mapper (int):
            DEPRECATED in 0.8: use ``seed_transpiler`` kwarg instead

    Returns:
        QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s).

    Raises:
        TranspilerError: in case of bad inputs to transpiler or errors in passes
    """
    # Deprecation matter
    if seed_mapper:
        warnings.warn("seed_mapper has been deprecated and will be removed in the "
                      "0.9 release. Instead use seed_transpiler to set the seed "
                      "for all stochastic parts of the.", DeprecationWarning)
        seed_transpiler = seed_mapper

    # transpiling schedules is not supported yet.
    if isinstance(circuits, Schedule) or \
       (isinstance(circuits, list) and all(isinstance(c, Schedule) for c in circuits)):
        return circuits

    # Get TranspileConfig(s) to configure the circuit transpilation job(s)
    circuits = circuits if isinstance(circuits, list) else [circuits]
    transpile_configs = _parse_transpile_args(circuits, backend, basis_gates, coupling_map,
                                              backend_properties, initial_layout,
                                              seed_transpiler, optimization_level,
                                              pass_manager)

    # Transpile circuits in parallel
    circuits = parallel_map(_transpile_circuit, list(zip(circuits, transpile_configs)))

    if len(circuits) == 1:
        return circuits[0]
    return circuits

transpile one or more circuits according to some desired transpilation targets .


def _transpile_circuit(circuit_config_tuple):
    """Select a PassManager and run a single circuit through it.

    Args:
        circuit_config_tuple (tuple):
            circuit (QuantumCircuit): circuit to transpile
            transpile_config (TranspileConfig): configuration dictating how to transpile

    Returns:
        QuantumCircuit: transpiled circuit
    """
    circuit, transpile_config = circuit_config_tuple

    # if the pass manager is not already selected, choose an appropriate one.
    if transpile_config.pass_manager:
        pass_manager = transpile_config.pass_manager

    elif transpile_config.coupling_map:
        pass_manager = default_pass_manager(transpile_config.basis_gates,
                                            transpile_config.coupling_map,
                                            transpile_config.initial_layout,
                                            transpile_config.seed_transpiler)
    else:
        pass_manager = default_pass_manager_simulator(transpile_config.basis_gates)

    return pass_manager.run(circuit)

Select a PassManager and run a single circuit through it .


def execute(experiments, backend,
            basis_gates=None, coupling_map=None,  # circuit transpile options
            backend_properties=None, initial_layout=None,
            seed_transpiler=None, optimization_level=None, pass_manager=None,
            qobj_id=None, qobj_header=None, shots=1024,  # common run options
            memory=False, max_credits=10, seed_simulator=None,
            default_qubit_los=None, default_meas_los=None,  # schedule run options
            schedule_los=None, meas_level=2, meas_return='avg',
            memory_slots=None, memory_slot_size=100, rep_time=None, parameter_binds=None,
            seed=None, seed_mapper=None,  # deprecated
            config=None, circuits=None,
            **run_config):
    """Execute a list of circuits or pulse schedules on a backend.

    The execution is asynchronous, and a handle to a job instance is returned.

    Args:
        experiments (QuantumCircuit or list[QuantumCircuit] or Schedule or list[Schedule]):
            Circuit(s) or pulse schedule(s) to execute

        backend (BaseBackend):
            Backend to execute circuits on.
            Transpiler options are automatically grabbed from
            backend.configuration() and backend.properties().
            If any other option is explicitly set (e.g. coupling_map), it
            will override the backend's.

        basis_gates (list[str]):
            List of basis gate names to unroll to.
            e.g:
                ['u1', 'u2', 'u3', 'cx']
            If None, do not unroll.

        coupling_map (CouplingMap or list):
            Coupling map (perhaps custom) to target in mapping.
            Multiple formats are supported:
            a. CouplingMap instance

            b. list
                Must be given as an adjacency matrix, where each entry
                specifies all two-qubit interactions supported by backend
                e.g:
                    [[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]

        backend_properties (BackendProperties):
            Properties returned by a backend, including information on gate
            errors, readout errors, qubit coherence times, etc. For a backend
            that provides this information, it can be obtained with:
            ``backend.properties()``

        initial_layout (Layout or dict or list):
            Initial position of virtual qubits on physical qubits.
            If this layout makes the circuit compatible with the coupling_map
            constraints, it will be used.
            The final layout is not guaranteed to be the same, as the transpiler
            may permute qubits through swaps or other means.

            Multiple formats are supported:
            a. Layout instance

            b. dict
                virtual to physical:
                    {qr[0]: 0,
                     qr[1]: 3,
                     qr[2]: 5}

                physical to virtual:
                    {0: qr[0],
                     3: qr[1],
                     5: qr[2]}

            c. list
                virtual to physical:
                    [0, 3, 5]  # virtual qubits are ordered (in addition to named)

                physical to virtual:
                    [qr[0], None, None, qr[1], None, qr[2]]

        seed_transpiler (int):
            Sets random seed for the stochastic parts of the transpiler

        optimization_level (int):
            How much optimization to perform on the circuits.
            Higher levels generate more optimized circuits,
            at the expense of longer transpilation time.
                0: no optimization
                1: light optimization
                2: heavy optimization

        pass_manager (PassManager):
            The pass manager to use during transpilation. If this arg is present,
            auto-selection of pass manager based on the transpile options will be
            turned off and this pass manager will be used directly.

        qobj_id (str):
            String identifier to annotate the Qobj

        qobj_header (QobjHeader or dict):
            User input that will be inserted in Qobj header, and will also be
            copied to the corresponding Result header. Headers do not affect the run.

        shots (int):
            Number of repetitions of each circuit, for sampling. Default: 2014

        memory (bool):
            If True, per-shot measurement bitstrings are returned as well
            (provided the backend supports it). For OpenPulse jobs, only
            measurement level 2 supports this option. Default: False

        max_credits (int):
            Maximum credits to spend on job. Default: 10

        seed_simulator (int):
            Random seed to control sampling, for when backend is a simulator

        default_qubit_los (list):
            List of default qubit lo frequencies

        default_meas_los (list):
            List of default meas lo frequencies

        schedule_los (None or list[Union[Dict[PulseChannel, float], LoConfig]] or
                      Union[Dict[PulseChannel, float], LoConfig]):
            Experiment LO configurations

        meas_level (int):
            Set the appropriate level of the measurement output for pulse experiments.

        meas_return (str):
            Level of measurement data for the backend to return
            For `meas_level` 0 and 1:
                "single" returns information from every shot.
                "avg" returns average measurement output (averaged over number of shots).

        memory_slots (int):
            Number of classical memory slots used in this job.

        memory_slot_size (int):
            Size of each memory slot if the output is Level 0.

        rep_time (int): repetition time of the experiment in μs.
            The delay between experiments will be rep_time.
            Must be from the list provided by the device.

        parameter_binds (list[dict{Parameter: Value}]):
            List of Parameter bindings over which the set of experiments will be
            executed. Each list element (bind) should be of the form
            {Parameter1: value1, Parameter2: value2, ...}. All binds will be
            executed across all experiments, e.g. if parameter_binds is a
            length-n list, and there are m experiments, a total of m x n
            experiments will be run (one for each experiment/bind pair).

        seed (int):
            DEPRECATED in 0.8: use ``seed_simulator`` kwarg instead

        seed_mapper (int):
            DEPRECATED in 0.8: use ``seed_transpiler`` kwarg instead

        config (dict):
            DEPRECATED in 0.8: use run_config instead

        circuits (QuantumCircuit or list[QuantumCircuit]):
            DEPRECATED in 0.8: use ``experiments`` kwarg instead.

        run_config (dict):
            Extra arguments used to configure the run (e.g. for Aer configurable backends)
            Refer to the backend documentation for details on these arguments
            Note: for now, these keyword arguments will both be copied to the
            Qobj config, and passed to backend.run()

    Returns:
        BaseJob: returns job instance derived from BaseJob

    Raises:
        QiskitError: if the execution cannot be interpreted as either circuits or schedules
    """
    if circuits is not None:
        experiments = circuits
        warnings.warn("the `circuits` arg in `execute()` has been deprecated. "
                      "please use `experiments`, which can handle both circuit "
                      "and pulse Schedules", DeprecationWarning)

    # transpiling the circuits using given transpile options
    experiments = transpile(experiments,
                            basis_gates=basis_gates,
                            coupling_map=coupling_map,
                            backend_properties=backend_properties,
                            initial_layout=initial_layout,
                            seed_transpiler=seed_transpiler,
                            optimization_level=optimization_level,
                            backend=backend,
                            pass_manager=pass_manager,
                            seed_mapper=seed_mapper,  # deprecated
                            )

    # assembling the circuits into a qobj to be run on the backend
    qobj = assemble(experiments,
                    qobj_id=qobj_id,
                    qobj_header=qobj_header,
                    shots=shots,
                    memory=memory,
                    max_credits=max_credits,
                    seed_simulator=seed_simulator,
                    default_qubit_los=default_qubit_los,
                    default_meas_los=default_meas_los,
                    schedule_los=schedule_los,
                    meas_level=meas_level,
                    meas_return=meas_return,
                    memory_slots=memory_slots,
                    memory_slot_size=memory_slot_size,
                    rep_time=rep_time,
                    parameter_binds=parameter_binds,
                    backend=backend,
                    config=config,  # deprecated
                    seed=seed,  # deprecated
                    run_config=run_config
                    )

    # executing the circuits on the backend and returning the job
    return backend.run(qobj, **run_config)

Execute a list of circuits or pulse schedules on a backend .


def drive(self) -> DriveChannel:
        """Return the primary drive channel of this qubit."""
        if self._drives:
            return self._drives[0]
        else:
            raise PulseError("No drive channels in q[%d]" % self._index)

def
drive
(
self
)
->
DriveChannel
:
if
self
.
_drives
:
return
self
.
_drives
[
0
]
else
:
raise
PulseError
(
"No drive channels in q[%d]"
%
self
.
_index
)

Return the primary drive channel of this qubit .


def control(self) -> ControlChannel:
        """Return the primary control channel of this qubit."""
        if self._controls:
            return self._controls[0]
        else:
            raise PulseError("No control channels in q[%d]" % self._index)

def
control
(
self
)
->
ControlChannel
:
if
self
.
_controls
:
return
self
.
_controls
[
0
]
else
:
raise
PulseError
(
"No control channels in q[%d]"
%
self
.
_index
)

Return the primary control channel of this qubit .


def measure(self) -> MeasureChannel:
        """Return the primary measure channel of this qubit."""
        if self._measures:
            return self._measures[0]
        else:
            raise PulseError("No measurement channels in q[%d]" % self._index)

def
measure
(
self
)
->
MeasureChannel
:
if
self
.
_measures
:
return
self
.
_measures
[
0
]
else
:
raise
PulseError
(
"No measurement channels in q[%d]"
%
self
.
_index
)

Return the primary measure channel of this qubit .


def acquire(self) -> AcquireChannel:
        """Return the primary acquire channel of this qubit."""
        if self._acquires:
            return self._acquires[0]
        else:
            raise PulseError("No acquire channels in q[%d]" % self._index)

def
acquire
(
self
)
->
AcquireChannel
:
if
self
.
_acquires
:
return
self
.
_acquires
[
0
]
else
:
raise
PulseError
(
"No acquire channels in q[%d]"
%
self
.
_index
)

Return the primary acquire channel of this qubit .


def input_state(circ, q, n):
    """n-qubit input state for QFT that produces output 1."""
    for j in range(n):
        circ.h(q[j])
        circ.u1(math.pi/float(2**(j)), q[j]).inverse()

def input_state ( circ , q , n ) : for j in range ( n ) : circ . h ( q [ j ] ) circ . u1 ( math . pi / float ( 2 ** ( j ) ) , q [ j ] ) . inverse ( )

n - qubit input state for QFT that produces output 1 .


def assemble(experiments,
             backend=None,
             qobj_id=None, qobj_header=None,  # common run options
             shots=1024, memory=False, max_credits=None, seed_simulator=None,
             default_qubit_los=None, default_meas_los=None,  # schedule run options
             schedule_los=None, meas_level=2, meas_return='avg',
             memory_slots=None, memory_slot_size=100, rep_time=None, parameter_binds=None,
             config=None, seed=None,  # deprecated
             **run_config):
    """Assemble a list of circuits or pulse schedules into a Qobj.

    This function serializes the payloads, which could be either circuits or schedules,
    to create Qobj "experiments". It further annotates the experiment payload with
    header and configurations.

    Args:
        experiments (QuantumCircuit or list[QuantumCircuit] or Schedule or list[Schedule]):
            Circuit(s) or pulse schedule(s) to execute

        backend (BaseBackend):
            If set, some runtime options are automatically grabbed from
            backend.configuration() and backend.defaults().
            If any other option is explicitly set (e.g. rep_rate), it
            will override the backend's.
            If any other options is set in the run_config, it will
            also override the backend's.

        qobj_id (str):
            String identifier to annotate the Qobj

        qobj_header (QobjHeader or dict):
            User input that will be inserted in Qobj header, and will also be
            copied to the corresponding Result header. Headers do not affect the run.

        shots (int):
            Number of repetitions of each circuit, for sampling. Default: 2014

        memory (bool):
            If True, per-shot measurement bitstrings are returned as well
            (provided the backend supports it). For OpenPulse jobs, only
            measurement level 2 supports this option. Default: False

        max_credits (int):
            Maximum credits to spend on job. Default: 10

        seed_simulator (int):
            Random seed to control sampling, for when backend is a simulator

        default_qubit_los (list):
            List of default qubit lo frequencies

        default_meas_los (list):
            List of default meas lo frequencies

        schedule_los (None or list[Union[Dict[PulseChannel, float], LoConfig]] or
                      Union[Dict[PulseChannel, float], LoConfig]):
            Experiment LO configurations

        meas_level (int):
            Set the appropriate level of the measurement output for pulse experiments.

        meas_return (str):
            Level of measurement data for the backend to return
            For `meas_level` 0 and 1:
                "single" returns information from every shot.
                "avg" returns average measurement output (averaged over number of shots).

        memory_slots (int):
            Number of classical memory slots used in this job.

        memory_slot_size (int):
            Size of each memory slot if the output is Level 0.

        rep_time (int): repetition time of the experiment in μs.
            The delay between experiments will be rep_time.
            Must be from the list provided by the device.

        parameter_binds (list[dict{Parameter: Value}]):
            List of Parameter bindings over which the set of experiments will be
            executed. Each list element (bind) should be of the form
            {Parameter1: value1, Parameter2: value2, ...}. All binds will be
            executed across all experiments, e.g. if parameter_binds is a
            length-n list, and there are m experiments, a total of m x n
            experiments will be run (one for each experiment/bind pair).

        seed (int):
            DEPRECATED in 0.8: use ``seed_simulator`` kwarg instead

        config (dict):
            DEPRECATED in 0.8: use run_config instead

        run_config (dict):
            extra arguments used to configure the run (e.g. for Aer configurable backends)
            Refer to the backend documentation for details on these arguments

    Returns:
        Qobj: a qobj which can be run on a backend. Depending on the type of input,
            this will be either a QasmQobj or a PulseQobj.

    Raises:
        QiskitError: if the input cannot be interpreted as either circuits or schedules
    """
    # deprecation matter
    if config:
        warnings.warn('config is not used anymore. Set all configs in '
                      'run_config.', DeprecationWarning)
        run_config = run_config or config
    if seed:
        warnings.warn('seed is deprecated in favor of seed_simulator.', DeprecationWarning)
        seed_simulator = seed_simulator or seed

    # Get RunConfig(s) that will be inserted in Qobj to configure the run
    experiments = experiments if isinstance(experiments, list) else [experiments]
    qobj_id, qobj_header, run_config = _parse_run_args(backend, qobj_id, qobj_header,
                                                       shots, memory, max_credits, seed_simulator,
                                                       default_qubit_los, default_meas_los,
                                                       schedule_los, meas_level, meas_return,
                                                       memory_slots, memory_slot_size, rep_time,
                                                       parameter_binds, **run_config)

    # assemble either circuits or schedules
    if all(isinstance(exp, QuantumCircuit) for exp in experiments):
        # If circuits are parameterized, bind parameters and remove from run_config
        bound_experiments, run_config = _expand_parameters(circuits=experiments,
                                                           run_config=run_config)
        return assemble_circuits(circuits=bound_experiments, qobj_id=qobj_id,
                                 qobj_header=qobj_header, run_config=run_config)

    elif all(isinstance(exp, Schedule) for exp in experiments):
        return assemble_schedules(schedules=experiments, qobj_id=qobj_id,
                                  qobj_header=qobj_header, run_config=run_config)

    else:
        raise QiskitError("bad input to assemble() function; "
                          "must be either circuits or schedules")

Assemble a list of circuits or pulse schedules into a Qobj .


def unset_qiskit_logger():
    """Remove the handlers for the 'qiskit' logger."""
    qiskit_logger = logging.getLogger('qiskit')
    for handler in qiskit_logger.handlers:
        qiskit_logger.removeHandler(handler)

def unset_qiskit_logger ( ) : qiskit_logger = logging . getLogger ( 'qiskit' ) for handler in qiskit_logger . handlers : qiskit_logger . removeHandler ( handler )

Remove the handlers for the qiskit logger .


def iplot_state_hinton(rho, figsize=None):
    """ Create a hinton representation.

        Graphical representation of the input array using a 2D city style
        graph (hinton).

        Args:
            rho (array): Density matrix
            figsize (tuple): Figure size in pixels.
    """

    # HTML
    html_template = Template("""

    """)

    # JavaScript
    javascript_template = Template("""

    """)
    rho = _validate_input_state(rho)
    if figsize is None:
        options = {}
    else:
        options = {'width': figsize[0], 'height': figsize[1]}

    # Process data and execute
    div_number = str(time.time())
    div_number = re.sub('[.]', '', div_number)

    # Process data and execute
    real = []
    imag = []
    for xvalue in rho:
        row_real = []
        col_imag = []

        for value_real in xvalue.real:
            row_real.append(float(value_real))
        real.append(row_real)

        for value_imag in xvalue.imag:
            col_imag.append(float(value_imag))
        imag.append(col_imag)

    html = html_template.substitute({
        'divNumber': div_number
    })

    javascript = javascript_template.substitute({
        'divNumber': div_number,
        'executions': [{'data': real}, {'data': imag}],
        'options': options
    })

    display(HTML(html + javascript))

def iplot_state_hinton ( rho , figsize = None ) : html_template = Template ( ) javascript_template = Template ( ) rho = _validate_input_state ( rho ) if figsize is None : options = { } else : options = { 'width' : figsize [ 0 ] , 'height' : figsize [ 1 ] } div_number = str ( time . time ( ) ) div_number = re . sub ( '[.]' , '' , div_number ) real = [ ] imag = [ ] for xvalue in rho : row_real = [ ] col_imag = [ ] for value_real in xvalue . real : row_real . append ( float ( value_real ) ) real . append ( row_real ) for value_imag in xvalue . imag : col_imag . append ( float ( value_imag ) ) imag . append ( col_imag ) html = html_template . substitute ( { 'divNumber' : div_number } ) javascript = javascript_template . substitute ( { 'divNumber' : div_number , 'executions' : [ { 'data' : real } , { 'data' : imag } ] , 'options' : options } ) display ( HTML ( html + javascript ) )


def process_fidelity(channel1, channel2, require_cptp=True):
    """Return the process fidelity between two quantum channels.

    This is given by

        F_p(E1, E2) = Tr[S2^dagger.S1])/dim^2

    where S1 and S2 are the SuperOp matrices for channels E1 and E2,
    and dim is the dimension of the input output statespace.

    Args:
        channel1 (QuantumChannel or matrix): a quantum channel or unitary matrix.
        channel2 (QuantumChannel or matrix): a quantum channel or unitary matrix.
        require_cptp (bool): require input channels to be CPTP [Default: True].

    Returns:
        array_like: The state fidelity F(state1, state2).

    Raises:
        QiskitError: if inputs channels do not have the same dimensions,
        have different input and output dimensions, or are not CPTP with
        `require_cptp=True`.
    """
    # First we must determine if input is to be interpreted as a unitary matrix
    # or as a channel.
    # If input is a raw numpy array we will interpret it as a unitary matrix.
    is_cptp1 = None
    is_cptp2 = None
    if isinstance(channel1, (list, np.ndarray)):
        channel1 = Operator(channel1)
        if require_cptp:
            is_cptp1 = channel1.is_unitary()
    if isinstance(channel2, (list, np.ndarray)):
        channel2 = Operator(channel2)
        if require_cptp:
            is_cptp2 = channel2.is_unitary()

    # Next we convert inputs SuperOp objects
    # This works for objects that also have a `to_operator` or `to_channel` method
    s1 = SuperOp(channel1)
    s2 = SuperOp(channel2)

    # Check inputs are CPTP
    if require_cptp:
        # Only check SuperOp if we didn't already check unitary inputs
        if is_cptp1 is None:
            is_cptp1 = s1.is_cptp()
        if not is_cptp1:
            raise QiskitError('channel1 is not CPTP')
        if is_cptp2 is None:
            is_cptp2 = s2.is_cptp()
        if not is_cptp2:
            raise QiskitError('channel2 is not CPTP')

    # Check dimensions match
    input_dim1, output_dim1 = s1.dim
    input_dim2, output_dim2 = s2.dim
    if input_dim1 != output_dim1 or input_dim2 != output_dim2:
        raise QiskitError('Input channels must have same size input and output dimensions.')
    if input_dim1 != input_dim2:
        raise QiskitError('Input channels have different dimensions.')

    # Compute process fidelity
    fidelity = np.trace(s1.compose(s2.adjoint()).data) / (input_dim1 ** 2)
    return fidelity

Return the process fidelity between two quantum channels .


def input(self, data):
        """Set the input text data."""
        self.data = data
        self.lexer.input(data)

def input ( self , data ) : self . data = data self . lexer . input ( data )


def pop(self):
        """Pop a PLY lexer off the stack."""
        self.lexer = self.stack.pop()
        self.filename = self.lexer.qasm_file
        self.lineno = self.lexer.qasm_line

def pop ( self ) : self . lexer = self . stack . pop ( ) self . filename = self . lexer . qasm_file self . lineno = self . lexer . qasm_line


def push(self, filename):
        """Push a PLY lexer on the stack to parse filename."""
        self.lexer.qasm_file = self.filename
        self.lexer.qasm_line = self.lineno
        self.stack.append(self.lexer)
        self.__mklexer__(filename)

def push ( self , filename ) : self . lexer . qasm_file = self . filename self . lexer . qasm_line = self . lineno self . stack . append ( self . lexer ) self . __mklexer__ ( filename )

Push a PLY lexer on the stack to parse filename .


def run(self, dag):
        """iterate over each block and replace it with an equivalent Unitary
        on the same wires.
        """
        new_dag = DAGCircuit()
        for qreg in dag.qregs.values():
            new_dag.add_qreg(qreg)
        for creg in dag.cregs.values():
            new_dag.add_creg(creg)

        # compute ordered indices for the global circuit wires
        global_index_map = {}
        for wire in dag.wires:
            if not isinstance(wire[0], QuantumRegister):
                continue
            global_qregs = list(dag.qregs.values())
            global_index_map[wire] = global_qregs.index(wire[0]) + wire[1]

        blocks = self.property_set['block_list']
        nodes_seen = set()

        for node in dag.topological_op_nodes():
            # skip already-visited nodes or input/output nodes
            if node in nodes_seen or node.type == 'in' or node.type == 'out':
                continue
            # check if the node belongs to the next block
            if blocks and node in blocks[0]:
                block = blocks[0]
                # find the qubits involved in this block
                block_qargs = set()
                for nd in block:
                    block_qargs |= set(nd.qargs)
                # convert block to a sub-circuit, then simulate unitary and add
                block_width = len(block_qargs)
                q = QuantumRegister(block_width)
                subcirc = QuantumCircuit(q)
                block_index_map = self._block_qargs_to_indices(block_qargs,
                                                               global_index_map)
                for nd in block:
                    nodes_seen.add(nd)
                    subcirc.append(nd.op, [q[block_index_map[i]] for i in nd.qargs])
                unitary = UnitaryGate(Operator(subcirc))  # simulates the circuit
                new_dag.apply_operation_back(
                    unitary, sorted(block_qargs, key=lambda x: block_index_map[x]))
                del blocks[0]
            else:
                # the node could belong to some future block, but in that case
                # we simply skip it. It is guaranteed that we will revisit that
                # future block, via its other nodes
                for block in blocks[1:]:
                    if node in block:
                        break
                # freestanding nodes can just be added
                else:
                    nodes_seen.add(node)
                    new_dag.apply_operation_back(node.op, node.qargs, node.cargs)

        return new_dag

def run ( self , dag ) : new_dag = DAGCircuit ( ) for qreg in dag . qregs . values ( ) : new_dag . add_qreg ( qreg ) for creg in dag . cregs . values ( ) : new_dag . add_creg ( creg ) global_index_map = { } for wire in dag . wires : if not isinstance ( wire [ 0 ] , QuantumRegister ) : continue global_qregs = list ( dag . qregs . values ( ) ) global_index_map [ wire ] = global_qregs . index ( wire [ 0 ] ) + wire [ 1 ] blocks = self . property_set [ 'block_list' ] nodes_seen = set ( ) for node in dag . topological_op_nodes ( ) : if node in nodes_seen or node . type == 'in' or node . type == 'out' : continue if blocks and node in blocks [ 0 ] : block = blocks [ 0 ] block_qargs = set ( ) for nd in block : block_qargs |= set ( nd . qargs ) block_width = len ( block_qargs ) q = QuantumRegister ( block_width ) subcirc = QuantumCircuit ( q ) block_index_map = self . _block_qargs_to_indices ( block_qargs , global_index_map ) for nd in block : nodes_seen . add ( nd ) subcirc . append ( nd . op , [ q [ block_index_map [ i ] ] for i in nd . qargs ] ) unitary = UnitaryGate ( Operator ( subcirc ) ) new_dag . apply_operation_back ( unitary , sorted ( block_qargs , key = lambda x : block_index_map [ x ] ) ) del blocks [ 0 ] else : for block in blocks [ 1 : ] : if node in block : break else : nodes_seen . add ( node ) new_dag . apply_operation_back ( node . op , node . qargs , node . cargs ) return new_dag

iterate over each block and replace it with an equivalent Unitary on the same wires .


def get_bound_method(self, instruction):
        """Get conversion method for instruction."""
        try:
            return self._bound_instructions[type(instruction)]
        except KeyError:
            raise PulseError('Qobj conversion method for %s is not found.' % instruction)


def convert_acquire(self, shift, instruction):
        """Return converted `AcquireInstruction`.

        Args:
            shift(int): Offset time.
            instruction (AcquireInstruction): acquire instruction.
        Returns:
            dict: Dictionary of required parameters.
        """
        meas_level = self._run_config.get('meas_level', 2)

        command_dict = {
            'name': 'acquire',
            't0': shift+instruction.start_time,
            'duration': instruction.duration,
            'qubits': [q.index for q in instruction.acquires],
            'memory_slot': [m.index for m in instruction.mem_slots]
        }
        if meas_level == 2:
            # setup discriminators
            if instruction.command.discriminator:
                command_dict.update({
                    'discriminators': [
                        QobjMeasurementOption(
                            name=instruction.command.discriminator.name,
                            params=instruction.command.discriminator.params)
                    ]
                })
            # setup register_slots
            command_dict.update({
                'register_slot': [regs.index for regs in instruction.reg_slots]
            })
        if meas_level >= 1:
            # setup kernels
            if instruction.command.kernel:
                command_dict.update({
                    'kernels': [
                        QobjMeasurementOption(
                            name=instruction.command.kernel.name,
                            params=instruction.command.kernel.params)
                    ]
                })
        return self._qobj_model(**command_dict)

def convert_acquire ( self , shift , instruction ) : meas_level = self . _run_config . get ( 'meas_level' , 2 ) command_dict = { 'name' : 'acquire' , 't0' : shift + instruction . start_time , 'duration' : instruction . duration , 'qubits' : [ q . index for q in instruction . acquires ] , 'memory_slot' : [ m . index for m in instruction . mem_slots ] } if meas_level == 2 : if instruction . command . discriminator : command_dict . update ( { 'discriminators' : [ QobjMeasurementOption ( name = instruction . command . discriminator . name , params = instruction . command . discriminator . params ) ] } ) command_dict . update ( { 'register_slot' : [ regs . index for regs in instruction . reg_slots ] } ) if meas_level >= 1 : if instruction . command . kernel : command_dict . update ( { 'kernels' : [ QobjMeasurementOption ( name = instruction . command . kernel . name , params = instruction . command . kernel . params ) ] } ) return self . _qobj_model ( ** command_dict )


def convert_frame_change(self, shift, instruction):
        """Return converted `FrameChangeInstruction`.

        Args:
            shift(int): Offset time.
            instruction (FrameChangeInstruction): frame change instruction.
        Returns:
            dict: Dictionary of required parameters.
        """
        command_dict = {
            'name': 'fc',
            't0': shift+instruction.start_time,
            'ch': instruction.channels[0].name,
            'phase': instruction.command.phase
        }
        return self._qobj_model(**command_dict)

def convert_frame_change ( self , shift , instruction ) : command_dict = { 'name' : 'fc' , 't0' : shift + instruction . start_time , 'ch' : instruction . channels [ 0 ] . name , 'phase' : instruction . command . phase } return self . _qobj_model ( ** command_dict )

Return converted FrameChangeInstruction .


def convert_persistent_value(self, shift, instruction):
        """Return converted `PersistentValueInstruction`.

        Args:
            shift(int): Offset time.
            instruction (PersistentValueInstruction): persistent value instruction.
        Returns:
            dict: Dictionary of required parameters.
        """
        command_dict = {
            'name': 'pv',
            't0': shift+instruction.start_time,
            'ch': instruction.channels[0].name,
            'val': instruction.command.value
        }
        return self._qobj_model(**command_dict)

def convert_persistent_value ( self , shift , instruction ) : command_dict = { 'name' : 'pv' , 't0' : shift + instruction . start_time , 'ch' : instruction . channels [ 0 ] . name , 'val' : instruction . command . value } return self . _qobj_model ( ** command_dict )

Return converted PersistentValueInstruction .


def convert_drive(self, shift, instruction):
        """Return converted `PulseInstruction`.

        Args:
            shift(int): Offset time.
            instruction (PulseInstruction): drive instruction.
        Returns:
            dict: Dictionary of required parameters.
        """
        command_dict = {
            'name': instruction.command.name,
            't0': shift+instruction.start_time,
            'ch': instruction.channels[0].name
        }
        return self._qobj_model(**command_dict)

def convert_drive ( self , shift , instruction ) : command_dict = { 'name' : instruction . command . name , 't0' : shift + instruction . start_time , 'ch' : instruction . channels [ 0 ] . name } return self . _qobj_model ( ** command_dict )


def convert_snapshot(self, shift, instruction):
        """Return converted `Snapshot`.

        Args:
            shift(int): Offset time.
            instruction (Snapshot): snapshot instruction.
        Returns:
            dict: Dictionary of required parameters.
        """
        command_dict = {
            'name': 'snapshot',
            't0': shift+instruction.start_time,
            'label': instruction.name,
            'type': instruction.type
        }
        return self._qobj_model(**command_dict)

def convert_snapshot ( self , shift , instruction ) : command_dict = { 'name' : 'snapshot' , 't0' : shift + instruction . start_time , 'label' : instruction . name , 'type' : instruction . type } return self . _qobj_model ( ** command_dict )


def _update_annotations(discretized_pulse: Callable) -> Callable:
    """Update annotations of discretized continuous pulse function with duration.

    Args:
        discretized_pulse: Discretized decorated continuous pulse.
    """
    undecorated_annotations = list(discretized_pulse.__annotations__.items())
    decorated_annotations = undecorated_annotations[1:]
    decorated_annotations.insert(0, ('duration', int))
    discretized_pulse.__annotations__ = dict(decorated_annotations)
    return discretized_pulse

def _update_annotations ( discretized_pulse : Callable ) -> Callable : undecorated_annotations = list ( discretized_pulse . __annotations__ . items ( ) ) decorated_annotations = undecorated_annotations [ 1 : ] decorated_annotations . insert ( 0 , ( 'duration' , int ) ) discretized_pulse . __annotations__ = dict ( decorated_annotations ) return discretized_pulse

Update annotations of discretized continuous pulse function with duration .


def sampler(sample_function: Callable) -> Callable:
    """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 generate_sampler(continuous_pulse: Callable) -> Callable:
        """Return a decorated sampler function."""

        @functools.wraps(continuous_pulse)
        def call_sampler(duration: int, *args, **kwargs) -> commands.SamplePulse:
            """Replace the call to the continuous function with a call to the sampler applied
            to the anlytic pulse function."""
            sampled_pulse = sample_function(continuous_pulse, duration, *args, **kwargs)
            return np.asarray(sampled_pulse, dtype=np.complex_)

        # Update type annotations for wrapped continuous function to be discrete
        call_sampler = _update_annotations(call_sampler)
        # Update docstring with that of the sampler and include sampled function documentation.
        call_sampler = _update_docstring(call_sampler, sample_function)
        # Unset wrapped to return base sampler signature
        # but still get rest of benefits of wraps
        # such as __name__, __qualname__
        call_sampler.__dict__.pop('__wrapped__')
        # wrap with functional pulse
        return commands.functional_pulse(call_sampler)

    return generate_sampler

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


def filter_backends(backends, filters=None, **kwargs):
    """Return the backends matching the specified filtering.

    Filter the `backends` list by their `configuration` or `status`
    attributes, or from a boolean callable. The criteria for filtering can
    be specified via `**kwargs` or as a callable via `filters`, and the
    backends must fulfill all specified conditions.

    Args:
        backends (list[BaseBackend]): list of backends.
        filters (callable): filtering conditions as a callable.
        **kwargs (dict): dict of criteria.

    Returns:
        list[BaseBackend]: a list of backend instances matching the
            conditions.
    """
    def _match_all(obj, criteria):
        """Return True if all items in criteria matches items in obj."""
        return all(getattr(obj, key_, None) == value_ for
                   key_, value_ in criteria.items())

    # Inspect the backends to decide which filters belong to
    # backend.configuration and which ones to backend.status, as it does
    # not involve querying the API.
    configuration_filters = {}
    status_filters = {}
    for key, value in kwargs.items():
        if all(key in backend.configuration() for backend in backends):
            configuration_filters[key] = value
        else:
            status_filters[key] = value

    # 1. Apply backend.configuration filtering.
    if configuration_filters:
        backends = [b for b in backends if
                    _match_all(b.configuration(), configuration_filters)]

    # 2. Apply backend.status filtering (it involves one API call for
    # each backend).
    if status_filters:
        backends = [b for b in backends if
                    _match_all(b.status(), status_filters)]

    # 3. Apply acceptor filter.
    backends = list(filter(filters, backends))

    return backends

def filter_backends ( backends , filters = None , ** kwargs ) : def _match_all ( obj , criteria ) : return all ( getattr ( obj , key_ , None ) == value_ for key_ , value_ in criteria . items ( ) ) configuration_filters = { } status_filters = { } for key , value in kwargs . items ( ) : if all ( key in backend . configuration ( ) for backend in backends ) : configuration_filters [ key ] = value else : status_filters [ key ] = value if configuration_filters : backends = [ b for b in backends if _match_all ( b . configuration ( ) , configuration_filters ) ] if status_filters : backends = [ b for b in backends if _match_all ( b . status ( ) , status_filters ) ] backends = list ( filter ( filters , backends ) ) return backends

Return the backends matching the specified filtering .


def resolve_backend_name(name, backends, deprecated, aliased):
    """Resolve backend name from a deprecated name or an alias.

    A group will be resolved in order of member priorities, depending on
    availability.

    Args:
        name (str): name of backend to resolve
        backends (list[BaseBackend]): list of available backends.
        deprecated (dict[str: str]): dict of deprecated names.
        aliased (dict[str: list[str]]): dict of aliased names.

    Returns:
        str: resolved name (name of an available backend)

    Raises:
        LookupError: if name cannot be resolved through regular available
            names, nor deprecated, nor alias names.
    """
    available = [backend.name() for backend in backends]

    resolved_name = deprecated.get(name, aliased.get(name, name))
    if isinstance(resolved_name, list):
        resolved_name = next((b for b in resolved_name if b in available), "")

    if resolved_name not in available:
        raise LookupError("backend '{}' not found.".format(name))

    if name in deprecated:
        logger.warning("WARNING: '%s' is deprecated. Use '%s'.", name, resolved_name)

    return resolved_name

Resolve backend name from a deprecated name or an alias .


def dag_to_circuit(dag):
    """Build a ``QuantumCircuit`` object from a ``DAGCircuit``.

    Args:
        dag (DAGCircuit): the input dag.

    Return:
        QuantumCircuit: the circuit representing the input dag.
    """
    qregs = collections.OrderedDict()
    for qreg in dag.qregs.values():
        qreg_tmp = QuantumRegister(qreg.size, name=qreg.name)
        qregs[qreg.name] = qreg_tmp
    cregs = collections.OrderedDict()
    for creg in dag.cregs.values():
        creg_tmp = ClassicalRegister(creg.size, name=creg.name)
        cregs[creg.name] = creg_tmp

    name = dag.name or None
    circuit = QuantumCircuit(*qregs.values(), *cregs.values(), name=name)

    for node in dag.topological_op_nodes():
        qubits = []
        for qubit in node.qargs:
            qubits.append(qregs[qubit[0].name][qubit[1]])

        clbits = []
        for clbit in node.cargs:
            clbits.append(cregs[clbit[0].name][clbit[1]])

        # Get arguments for classical control (if any)
        if node.condition is None:
            control = None
        else:
            control = (node.condition[0], node.condition[1])

        inst = node.op.copy()
        inst.control = control
        circuit.append(inst, qubits, clbits)
    return circuit

def dag_to_circuit ( dag ) : qregs = collections . OrderedDict ( ) for qreg in dag . qregs . values ( ) : qreg_tmp = QuantumRegister ( qreg . size , name = qreg . name ) qregs [ qreg . name ] = qreg_tmp cregs = collections . OrderedDict ( ) for creg in dag . cregs . values ( ) : creg_tmp = ClassicalRegister ( creg . size , name = creg . name ) cregs [ creg . name ] = creg_tmp name = dag . name or None circuit = QuantumCircuit ( * qregs . values ( ) , * cregs . values ( ) , name = name ) for node in dag . topological_op_nodes ( ) : qubits = [ ] for qubit in node . qargs : qubits . append ( qregs [ qubit [ 0 ] . name ] [ qubit [ 1 ] ] ) clbits = [ ] for clbit in node . cargs : clbits . append ( cregs [ clbit [ 0 ] . name ] [ clbit [ 1 ] ] ) if node . condition is None : control = None else : control = ( node . condition [ 0 ] , node . condition [ 1 ] ) inst = node . op . copy ( ) inst . control = control circuit . append ( inst , qubits , clbits ) return circuit

Build a QuantumCircuit object from a DAGCircuit .


def make_dict_observable(matrix_observable):
    """Convert an observable in matrix form to dictionary form.

    Takes in a diagonal observable as a matrix and converts it to a dictionary
    form. Can also handle a list sorted of the diagonal elements.

    Args:
        matrix_observable (list): The observable to be converted to dictionary
        form. Can be a matrix or just an ordered list of observed values

    Returns:
        Dict: A dictionary with all observable states as keys, and corresponding
        values being the observed value for that state
    """
    dict_observable = {}
    observable = np.array(matrix_observable)
    observable_size = len(observable)
    observable_bits = int(np.ceil(np.log2(observable_size)))
    binary_formater = '0{}b'.format(observable_bits)
    if observable.ndim == 2:
        observable = observable.diagonal()
    for state_no in range(observable_size):
        state_str = format(state_no, binary_formater)
        dict_observable[state_str] = observable[state_no]
    return dict_observable

def make_dict_observable ( matrix_observable ) : dict_observable = { } observable = np . array ( matrix_observable ) observable_size = len ( observable ) observable_bits = int ( np . ceil ( np . log2 ( observable_size ) ) ) binary_formater = '0{}b' . format ( observable_bits ) if observable . ndim == 2 : observable = observable . diagonal ( ) for state_no in range ( observable_size ) : state_str = format ( state_no , binary_formater ) dict_observable [ state_str ] = observable [ state_no ] return dict_observable

Convert an observable in matrix form to dictionary form .


def update_symtab(self, obj):
        """Update a node in the symbol table.

        Everything in the symtab must be a node with these attributes:
        name - the string name of the object
        type - the string type of the object
        line - the source line where the type was first found
        file - the source file where the type was first found
        """
        if obj.name in self.current_symtab:
            prev = self.current_symtab[obj.name]
            raise QasmError("Duplicate declaration for", obj.type + " '"
                            + obj.name + "' at line", str(obj.line)
                            + ', file', obj.file
                            + '.\nPrevious occurrence at line',
                            str(prev.line) + ', file', prev.file)
        self.current_symtab[obj.name] = obj

def
update_symtab
(
self
,
obj
)
:
if
obj
.
name
in
self
.
current_symtab
:
prev
=
self
.
current_symtab
[
obj
.
name
]
raise
QasmError
(
"Duplicate declaration for"
,
obj
.
type
+
" '"
+
obj
.
name
+
"' at line"
,
str
(
obj
.
line
)
+
', file'
,
obj
.
file
+
'.\nPrevious occurrence at line'
,
str
(
prev
.
line
)
+
', file'
,
prev
.
file
)
self
.
current_symtab
[
obj
.
name
]
=
obj


def verify_declared_bit(self, obj):
        """Verify a qubit id against the gate prototype."""
        # We are verifying gate args against the formal parameters of a
        # gate prototype.
        if obj.name not in self.current_symtab:
            raise QasmError("Cannot find symbol '" + obj.name
                            + "' in argument list for gate, line",
                            str(obj.line), 'file', obj.file)

        # This insures the thing is from the bitlist and not from the
        # argument list.
        sym = self.current_symtab[obj.name]
        if not (sym.type == 'id' and sym.is_bit):
            raise QasmError("Bit", obj.name,
                            'is not declared as a bit in the gate.')

def
verify_declared_bit
(
self
,
obj
)
:
if
obj
.
name
not
in
self
.
current_symtab
:
raise
QasmError
(
"Cannot find symbol '"
+
obj
.
name
+
"' in argument list for gate, line"
,
str
(
obj
.
line
)
,
'file'
,
obj
.
file
)
sym
=
self
.
current_symtab
[
obj
.
name
]
if
not
(
sym
.
type
==
'id'
and
sym
.
is_bit
)
:
raise
QasmError
(
"Bit"
,
obj
.
name
,
'is not declared as a bit in the gate.'
)

Verify a qubit id against the gate prototype .


def verify_exp_list(self, obj):
        """Verify each expression in a list."""
        # A tad harder.  This is a list of expressions each of which could be
        # the head of a tree. We need to recursively walk each of these and
        # ensure that any Id elements resolve to the current stack.
        #
        # I believe we only have to look at the current symtab.
        if obj.children is not None:
            for children in obj.children:
                if isinstance(children, node.Id):
                    if children.name in self.external_functions:
                        continue

                    if children.name not in self.current_symtab:
                        raise QasmError("Argument '" + children.name
                                        + "' in expression cannot be "
                                        + "found, line", str(children.line),
                                        "file", children.file)
                else:
                    if hasattr(children, "children"):
                        self.verify_exp_list(children)

def
verify_exp_list
(
self
,
obj
)
:
if
obj
.
children
is
not
:
for
children
in
obj
.
children
:
if
isinstance
(
children
,
node
.
Id
)
:
if
children
.
name
in
self
.
external_functions
:
continue
if
children
.
name
not
in
self
.
current_symtab
:
raise
QasmError
(
"Argument '"
+
children
.
name
+
"' in expression cannot be "
+
"found, line"
,
str
(
children
.
line
)
,
"file"
,
children
.
file
)
else
:
if
hasattr
(
children
,
"children"
)
:
self
.
verify_exp_list
(
children
)


def verify_as_gate(self, obj, bitlist, arglist=None):
        """Verify a user defined gate call."""
        if obj.name not in self.global_symtab:
            raise QasmError("Cannot find gate definition for '" + obj.name
                            + "', line", str(obj.line), 'file', obj.file)
        g_sym = self.global_symtab[obj.name]
        if not (g_sym.type == 'gate' or g_sym.type == 'opaque'):
            raise QasmError("'" + obj.name + "' is used as a gate "
                            + "or opaque call but the symbol is neither;"
                            + " it is a '" + g_sym.type + "' line",
                            str(obj.line), 'file', obj.file)

        if g_sym.n_bits() != bitlist.size():
            raise QasmError("Gate or opaque call to '" + obj.name
                            + "' uses", str(bitlist.size()),
                            "qubits but is declared for",
                            str(g_sym.n_bits()), "qubits", "line",
                            str(obj.line), 'file', obj.file)

        if arglist:
            if g_sym.n_args() != arglist.size():
                raise QasmError("Gate or opaque call to '" + obj.name
                                + "' uses", str(arglist.size()),
                                "qubits but is declared for",
                                str(g_sym.n_args()), "qubits", "line",
                                str(obj.line), 'file', obj.file)
        else:
            if g_sym.n_args() > 0:
                raise QasmError("Gate or opaque call to '" + obj.name
                                + "' has no arguments but is declared for",
                                str(g_sym.n_args()), "qubits", "line",
                                str(obj.line), 'file', obj.file)


def verify_reg(self, obj, object_type):
        """Verify a register."""
        # How to verify:
        #    types must match
        #    indexes must be checked
        if obj.name not in self.global_symtab:
            raise QasmError('Cannot find definition for', object_type, "'"
                            + obj.name + "'", 'at line', str(obj.line),
                            'file', obj.file)

        g_sym = self.global_symtab[obj.name]

        if g_sym.type != object_type:
            raise QasmError("Type for '" + g_sym.name + "' should be '"
                            + object_type + "' but was found to be '"
                            + g_sym.type + "'", "line", str(obj.line),
                            "file", obj.file)

        if obj.type == 'indexed_id':
            bound = g_sym.index
            ndx = obj.index
            if ndx < 0 or ndx >= bound:
                raise QasmError("Register index for '" + g_sym.name
                                + "' out of bounds. Index is", str(ndx),
                                "bound is 0 <= index <", str(bound),
                                "at line", str(obj.line), "file", obj.file)

def
verify_reg
(
self
,
obj
,
object_type
)
:
if
obj
.
name
not
in
self
.
global_symtab
:
raise
QasmError
(
'Cannot find definition for'
,
object_type
,
"'"
+
obj
.
name
+
"'"
,
'at line'
,
str
(
obj
.
line
)
,
'file'
,
obj
.
file
)
g_sym
=
self
.
global_symtab
[
obj
.
name
]
if
g_sym
.
type
!=
object_type
:
raise
QasmError
(
"Type for '"
+
g_sym
.
name
+
"' should be '"
+
object_type
+
"' but was found to be '"
+
g_sym
.
type
+
"'"
,
"line"
,
str
(
obj
.
line
)
,
"file"
,
obj
.
file
)
if
obj
.
type
==
'indexed_id'
:
bound
=
g_sym
.
index
ndx
=
obj
.
index
if
ndx
<
0
or
ndx
>=
bound
:
raise
QasmError
(
"Register index for '"
+
g_sym
.
name
+
"' out of bounds. Index is"
,
str
(
ndx
)
,
"bound is 0 <= index <"
,
str
(
bound
)
,
"at line"
,
str
(
obj
.
line
)
,
"file"
,
obj
.
file
)


def verify_reg_list(self, obj, object_type):
        """Verify a list of registers."""
        # We expect the object to be a bitlist or an idlist, we don't care.
        # We will iterate it and ensure everything in it is declared as a bit,
        # and throw if not.
        for children in obj.children:
            self.verify_reg(children, object_type)

def verify_reg_list ( self , obj , object_type ) : for children in obj . children : self . verify_reg ( children , object_type )


def find_column(self, input_, token):
        """Compute the column.

        Input is the input text string.
        token is a token instance.
        """
        if token is None:
            return 0
        last_cr = input_.rfind('\n', 0, token.lexpos)
        if last_cr < 0:
            last_cr = 0
        column = (token.lexpos - last_cr) + 1
        return column

def find_column ( self , input_ , token ) : if token is None : return 0 last_cr = input_ . rfind ( '\n' , 0 , token . lexpos ) if last_cr < 0 : last_cr = 0 column = ( token . lexpos - last_cr ) + 1 return column


def parse_debug(self, val):
        """Set the parse_deb field."""
        if val is True:
            self.parse_deb = True
        elif val is False:
            self.parse_deb = False
        else:
            raise QasmError("Illegal debug value '" + str(val)
                            + "' must be True or False.")

def
parse_debug
(
self
,
val
)
:
if
val
is
True
:
self
.
parse_deb
=
True
elif
val
is
False
:
self
.
parse_deb
=
False
else
:
raise
QasmError
(
"Illegal debug value '"
+
str
(
val
)
+
"' must be True or False."
)


def parse(self, data):
        """Parse some data."""
        self.parser.parse(data, lexer=self.lexer, debug=self.parse_deb)
        if self.qasm is None:
            raise QasmError("Uncaught exception in parser; "
                            + "see previous messages for details.")
        return self.qasm

def
parse
(
self
,
data
)
:
self
.
parser
.
parse
(
data
,
lexer
=
self
.
lexer
,
debug
=
self
.
parse_deb
)
if
self
.
qasm
is
:
raise
QasmError
(
"Uncaught exception in parser; "
+
"see previous messages for details."
)
return
self
.
qasm


def run(self, data):
        """Parser runner.

        To use this module stand-alone.
        """
        ast = self.parser.parse(data, debug=True)
        self.parser.parse(data, debug=True)
        ast.to_string(0)

def run ( self , data ) : ast = self . parser . parse ( data , debug = True ) self . parser . parse ( data , debug = True ) ast . to_string ( 0 )


def parse(self):
        """Parse the data."""
        if self._filename:
            with open(self._filename) as ifile:
                self._data = ifile.read()

        with QasmParser(self._filename) as qasm_p:
            qasm_p.parse_debug(False)
            return qasm_p.parse(self._data)

def parse ( self ) : if self . _filename : with open ( self . _filename ) as ifile : self . _data = ifile . read ( ) with QasmParser ( self . _filename ) as qasm_p : qasm_p . parse_debug ( False ) return qasm_p . parse ( self . _data )


def crz(self, theta, ctl, tgt):
    """Apply crz from ctl to tgt with angle theta."""
    return self.append(CrzGate(theta), [ctl, tgt], [])

def crz ( self , theta , ctl , tgt ) : return self . append ( CrzGate ( theta ) , [ ctl , tgt ] , [ ] )

Apply crz from ctl to tgt with angle theta .


def basis_state(str_state, num):
    """
    Return a basis state ndarray.

    Args:
        str_state (string): a string representing the state.
        num (int): the number of qubits
    Returns:
        ndarray:  state(2**num) a quantum state with basis basis state.
     Raises:
        QiskitError: if the dimensions is wrong
    """
    n = int(str_state, 2)
    if num >= len(str_state):
        state = np.zeros(1 << num, dtype=complex)
        state[n] = 1
        return state
    else:
        raise QiskitError('size of bitstring is greater than num.')


def projector(state, flatten=False):
    """
    maps a pure state to a state matrix

    Args:
        state (ndarray): the number of qubits
        flatten (bool): determine if state matrix of column work
    Returns:
        ndarray:  state_mat(2**num, 2**num) if flatten is false
        ndarray:  state_mat(4**num) if flatten is true stacked on by the column
    """
    density_matrix = np.outer(state.conjugate(), state)
    if flatten:
        return density_matrix.flatten(order='F')
    return density_matrix

def projector ( state , flatten = False ) : density_matrix = np . outer ( state . conjugate ( ) , state ) if flatten : return density_matrix . flatten ( order = 'F' ) return density_matrix


def purity(state):
    """Calculate the purity of a quantum state.

    Args:
        state (ndarray): a quantum state
    Returns:
        float: purity.
    """
    rho = np.array(state)
    if rho.ndim == 1:
        return 1.0
    return np.real(np.trace(rho.dot(rho)))

def purity ( state ) : rho = np . array ( state ) if rho . ndim == 1 : return 1.0 return np . real ( np . trace ( rho . dot ( rho ) ) )

Calculate the purity of a quantum state .


def run(self, dag):
        """
        Run the pass on the DAG, and write the discovered commutation relations
        into the property_set.
        """
        # Initiate the commutation set
        self.property_set['commutation_set'] = defaultdict(list)

        # Build a dictionary to keep track of the gates on each qubit
        for wire in dag.wires:
            wire_name = "{0}[{1}]".format(str(wire[0].name), str(wire[1]))
            self.property_set['commutation_set'][wire_name] = []

        # Add edges to the dictionary for each qubit
        for node in dag.topological_op_nodes():
            for (_, _, edge_data) in dag.edges(node):

                edge_name = edge_data['name']
                self.property_set['commutation_set'][(node, edge_name)] = -1

        for wire in dag.wires:
            wire_name = "{0}[{1}]".format(str(wire[0].name), str(wire[1]))

            for current_gate in dag.nodes_on_wire(wire):

                current_comm_set = self.property_set['commutation_set'][wire_name]
                if not current_comm_set:
                    current_comm_set.append([current_gate])

                if current_gate not in current_comm_set[-1]:
                    prev_gate = current_comm_set[-1][-1]
                    if _commute(current_gate, prev_gate):
                        current_comm_set[-1].append(current_gate)

                    else:
                        current_comm_set.append([current_gate])

                temp_len = len(current_comm_set)
                self.property_set['commutation_set'][(current_gate, wire_name)] = temp_len - 1

def run ( self , dag ) : self . property_set [ 'commutation_set' ] = defaultdict ( list ) for wire in dag . wires : wire_name = "{0}[{1}]" . format ( str ( wire [ 0 ] . name ) , str ( wire [ 1 ] ) ) self . property_set [ 'commutation_set' ] [ wire_name ] = [ ] for node in dag . topological_op_nodes ( ) : for ( _ , _ , edge_data ) in dag . edges ( node ) : edge_name = edge_data [ 'name' ] self . property_set [ 'commutation_set' ] [ ( node , edge_name ) ] = - 1 for wire in dag . wires : wire_name = "{0}[{1}]" . format ( str ( wire [ 0 ] . name ) , str ( wire [ 1 ] ) ) for current_gate in dag . nodes_on_wire ( wire ) : current_comm_set = self . property_set [ 'commutation_set' ] [ wire_name ] if not current_comm_set : current_comm_set . append ( [ current_gate ] ) if current_gate not in current_comm_set [ - 1 ] : prev_gate = current_comm_set [ - 1 ] [ - 1 ] if _commute ( current_gate , prev_gate ) : current_comm_set [ - 1 ] . append ( current_gate ) else : current_comm_set . append ( [ current_gate ] ) temp_len = len ( current_comm_set ) self . property_set [ 'commutation_set' ] [ ( current_gate , wire_name ) ] = temp_len - 1

Run the pass on the DAG and write the discovered commutation relations into the property_set .


def backend_widget(backend):
    """Creates a backend widget.
    """
    config = backend.configuration().to_dict()
    props = backend.properties().to_dict()

    name = widgets.HTML(value="
{name}
".format(name=backend.name()),
                        layout=widgets.Layout())

    n_qubits = config['n_qubits']

    qubit_count = widgets.HTML(value="
{qubits}
".format(qubits=n_qubits),
                               layout=widgets.Layout(justify_content='center'))

    cmap = widgets.Output(layout=widgets.Layout(min_width='250px', max_width='250px',
                                                max_height='250px',
                                                min_height='250px',
                                                justify_content='center',
                                                align_items='center',
                                                margin='0px 0px 0px 0px'))

    with cmap:
        _cmap_fig = plot_gate_map(backend,
                                  plot_directed=False,
                                  label_qubits=False)
        if _cmap_fig is not None:
            display(_cmap_fig)
            # Prevents plot from showing up twice.
            plt.close(_cmap_fig)

    pending = generate_jobs_pending_widget()

    is_oper = widgets.HTML(value="

",
                           layout=widgets.Layout(justify_content='center'))

    least_busy = widgets.HTML(value="

",
                              layout=widgets.Layout(justify_content='center'))

    t1_units = props['qubits'][0][0]['unit']
    avg_t1 = round(sum([q[0]['value'] for q in props['qubits']])/n_qubits, 1)
    t1_widget = widgets.HTML(value="
{t1} {units}
".format(t1=avg_t1, units=t1_units),
                             layout=widgets.Layout())

    t2_units = props['qubits'][0][1]['unit']
    avg_t2 = round(sum([q[1]['value'] for q in props['qubits']])/n_qubits, 1)
    t2_widget = widgets.HTML(value="
{t2} {units}
".format(t2=avg_t2, units=t2_units),
                             layout=widgets.Layout())

    out = widgets.VBox([name, cmap, qubit_count, pending,
                        least_busy, is_oper, t1_widget, t2_widget],
                       layout=widgets.Layout(display='inline-flex',
                                             flex_flow='column',
                                             align_items='center'))

    out._is_alive = True
    return out

def
backend_widget
(
backend
)
:
config
=
backend
.
configuration
(
)
.
to_dict
(
)
props
=
backend
.
properties
(
)
.
to_dict
(
)
name
=
widgets
.
HTML
(
value
=
"
{name}
"
.
format
(
name
=
backend
.
name
(
)
)
,
layout
=
widgets
.
Layout
(
)
)
n_qubits
=
config
[
'n_qubits'
]
qubit_count
=
widgets
.
HTML
(
value
=
"
{qubits}
"
.
format
(
qubits
=
n_qubits
)
,
layout
=
widgets
.
Layout
(
justify_content
=
'center'
)
)
cmap
=
widgets
.
Output
(
layout
=
widgets
.
Layout
(
min_width
=
'250px'
,
max_width
=
'250px'
,
max_height
=
'250px'
,
min_height
=
'250px'
,
justify_content
=
'center'
,
align_items
=
'center'
,
margin
=
'0px 0px 0px 0px'
)
)
with
cmap
:
_cmap_fig
=
plot_gate_map
(
backend
,
plot_directed
=
False
,
label_qubits
=
False
)
if
_cmap_fig
is
not
:
display
(
_cmap_fig
)
plt
.
close
(
_cmap_fig
)
pending
=
generate_jobs_pending_widget
(
)
is_oper
=
widgets
.
HTML
(
value
=
"

"
,
layout
=
widgets
.
Layout
(
justify_content
=
'center'
)
)
least_busy
=
widgets
.
HTML
(
value
=
"

"
,
layout
=
widgets
.
Layout
(
justify_content
=
'center'
)
)
t1_units
=
props
[
'qubits'
]
[
0
]
[
0
]
[
'unit'
]
avg_t1
=
round
(
sum
(
[
q
[
0
]
[
'value'
]
for
q
in
props
[
'qubits'
]
]
)
/
n_qubits
,
1
)
t1_widget
=
widgets
.
HTML
(
value
=
"
{t1} {units}
"
.
format
(
t1
=
avg_t1
,
units
=
t1_units
)
,
layout
=
widgets
.
Layout
(
)
)
t2_units
=
props
[
'qubits'
]
[
0
]
[
1
]
[
'unit'
]
avg_t2
=
round
(
sum
(
[
q
[
1
]
[
'value'
]
for
q
in
props
[
'qubits'
]
]
)
/
n_qubits
,
1
)
t2_widget
=
widgets
.
HTML
(
value
=
"
{t2} {units}
"
.
format
(
t2
=
avg_t2
,
units
=
t2_units
)
,
layout
=
widgets
.
Layout
(
)
)
out
=
widgets
.
VBox
(
[
name
,
cmap
,
qubit_count
,
pending
,
least_busy
,
is_oper
,
t1_widget
,
t2_widget
]
,
layout
=
widgets
.
Layout
(
display
=
'inline-flex'
,
flex_flow
=
'column'
,
align_items
=
'center'
)
)
out
.
_is_alive
=
True
return
out


def update_backend_info(self, interval=60):
    """Updates the monitor info
    Called from another thread.
    """
    my_thread = threading.currentThread()
    current_interval = 0
    started = False
    all_dead = False
    stati = [None]*len(self._backends)
    while getattr(my_thread, "do_run", True) and not all_dead:
        if current_interval == interval or started is False:
            for ind, back in enumerate(self._backends):
                _value = self.children[ind].children[2].value
                _head = _value.split('')[0]
                try:
                    _status = back.status()
                    stati[ind] = _status
                except Exception:  # pylint: disable=W0703
                    self.children[ind].children[2].value = _value.replace(
                        _head, "
")
                    self.children[ind]._is_alive = False
                else:
                    self.children[ind]._is_alive = True
                    self.children[ind].children[2].value = _value.replace(
                        _head, "
")

            idx = list(range(len(self._backends)))
            pending = [s.pending_jobs for s in stati]
            _, least_idx = zip(*sorted(zip(pending, idx)))

            # Make sure least pending is operational
            for ind in least_idx:
                if stati[ind].operational:
                    least_pending_idx = ind
                    break

            for var in idx:
                if var == least_pending_idx:
                    self.children[var].children[4].value = "
True
"
                else:
                    self.children[var].children[4].value = "
False
"

                self.children[var].children[3].children[1].value = pending[var]
                self.children[var].children[3].children[1].max = max(
                    self.children[var].children[3].children[1].max, pending[var]+10)
                if stati[var].operational:
                    self.children[var].children[5].value = "
True
"
                else:
                    self.children[var].children[5].value = "
False
"

            started = True
            current_interval = 0
        time.sleep(1)
        all_dead = not any([wid._is_alive for wid in self.children])
        current_interval += 1

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

Updates the monitor info Called from another thread .


def generate_jobs_pending_widget():
    """Generates a jobs_pending progress bar widget.
    """
    pbar = widgets.IntProgress(
        value=0,
        min=0,
        max=50,
        description='',
        orientation='horizontal', layout=widgets.Layout(max_width='180px'))
    pbar.style.bar_color = '#71cddd'

    pbar_current = widgets.Label(
        value=str(pbar.value), layout=widgets.Layout(min_width='auto'))
    pbar_max = widgets.Label(
        value=str(pbar.max), layout=widgets.Layout(min_width='auto'))

    def _on_max_change(change):
        pbar_max.value = str(change['new'])

    def _on_val_change(change):
        pbar_current.value = str(change['new'])

    pbar.observe(_on_max_change, names='max')
    pbar.observe(_on_val_change, names='value')

    jobs_widget = widgets.HBox([pbar_current, pbar, pbar_max],
                               layout=widgets.Layout(max_width='250px',
                                                     min_width='250px',
                                                     justify_content='center'))

    return jobs_widget

def generate_jobs_pending_widget ( ) : pbar = widgets . IntProgress ( value = 0 , min = 0 , max = 50 , description = '' , orientation = 'horizontal' , layout = widgets . Layout ( max_width = '180px' ) ) pbar . style . bar_color = '#71cddd' pbar_current = widgets . Label ( value = str ( pbar . value ) , layout = widgets . Layout ( min_width = 'auto' ) ) pbar_max = widgets . Label ( value = str ( pbar . max ) , layout = widgets . Layout ( min_width = 'auto' ) ) def _on_max_change ( change ) : pbar_max . value = str ( change [ 'new' ] ) def _on_val_change ( change ) : pbar_current . value = str ( change [ 'new' ] ) pbar . observe ( _on_max_change , names = 'max' ) pbar . observe ( _on_val_change , names = 'value' ) jobs_widget = widgets . HBox ( [ pbar_current , pbar , pbar_max ] , layout = widgets . Layout ( max_width = '250px' , min_width = '250px' , justify_content = 'center' ) ) return jobs_widget

Generates a jobs_pending progress bar widget .


def run(self, dag):
        """
        Run one pass of cx cancellation on the circuit

        Args:
            dag (DAGCircuit): the directed acyclic graph to run on.
        Returns:
            DAGCircuit: Transformed DAG.
        """
        cx_runs = dag.collect_runs(["cx"])
        for cx_run in cx_runs:
            # Partition the cx_run into chunks with equal gate arguments
            partition = []
            chunk = []
            for i in range(len(cx_run) - 1):
                chunk.append(cx_run[i])

                qargs0 = cx_run[i].qargs
                qargs1 = cx_run[i + 1].qargs

                if qargs0 != qargs1:
                    partition.append(chunk)
                    chunk = []
            chunk.append(cx_run[-1])
            partition.append(chunk)
            # Simplify each chunk in the partition
            for chunk in partition:
                if len(chunk) % 2 == 0:
                    for n in chunk:
                        dag.remove_op_node(n)
                else:
                    for n in chunk[1:]:
                        dag.remove_op_node(n)
        return dag

def run ( self , dag ) : cx_runs = dag . collect_runs ( [ "cx" ] ) for cx_run in cx_runs : partition = [ ] chunk = [ ] for i in range ( len ( cx_run ) - 1 ) : chunk . append ( cx_run [ i ] ) qargs0 = cx_run [ i ] . qargs qargs1 = cx_run [ i + 1 ] . qargs if qargs0 != qargs1 : partition . append ( chunk ) chunk = [ ] chunk . append ( cx_run [ - 1 ] ) partition . append ( chunk ) for chunk in partition : if len ( chunk ) % 2 == 0 : for n in chunk : dag . remove_op_node ( n ) else : for n in chunk [ 1 : ] : dag . remove_op_node ( n ) return dag


def get_backend(self, name=None, **kwargs):
        """Return a single backend matching the specified filtering.

        Args:
            name (str): name of the backend.
            **kwargs (dict): dict used for filtering.

        Returns:
            BaseBackend: a backend matching the filtering.

        Raises:
            QiskitBackendNotFoundError: if no backend could be found or
                more than one backend matches.
        """
        backends = self.backends(name, **kwargs)
        if len(backends) > 1:
            raise QiskitBackendNotFoundError('More than one backend matches the criteria')
        elif not backends:
            raise QiskitBackendNotFoundError('No backend matches the criteria')

        return backends[0]

Return a single backend matching the specified filtering .


def _bipartite_shape(self):
        """Return the shape for bipartite matrix"""
        return (self._input_dim, self._output_dim, self._input_dim,
                self._output_dim)

def _bipartite_shape ( self ) : return ( self . _input_dim , self . _output_dim , self . _input_dim , self . _output_dim )


def _get_register_specs(bit_labels):
    """Get the number and size of unique registers from bit_labels list.

    Args:
        bit_labels (list): this list is of the form::

            [['reg1', 0], ['reg1', 1], ['reg2', 0]]

            which indicates a register named "reg1" of size 2
            and a register named "reg2" of size 1. This is the
            format of classic and quantum bit labels in qobj
            header.

    Yields:
        tuple: iterator of register_name:size pairs.
    """
    it = itertools.groupby(bit_labels, operator.itemgetter(0))
    for register_name, sub_it in it:
        yield register_name, max(ind[1] for ind in sub_it) + 1

def _get_register_specs ( bit_labels ) : it = itertools . groupby ( bit_labels , operator . itemgetter ( 0 ) ) for register_name , sub_it in it : yield register_name , max ( ind [ 1 ] for ind in sub_it ) + 1

Get the number and size of unique registers from bit_labels list .


def _truncate_float(matchobj, format_str='0.2g'):
    """Truncate long floats

    Args:
        matchobj (re.Match): contains original float
        format_str (str): format specifier
    Returns:
       str: returns truncated float
    """
    if matchobj.group(0):
        return format(float(matchobj.group(0)), format_str)
    return ''

def _truncate_float ( matchobj , format_str = '0.2g' ) : if matchobj . group ( 0 ) : return format ( float ( matchobj . group ( 0 ) ) , format_str ) return ''


def latex(self, aliases=None):
        """Return LaTeX string representation of circuit.

        This method uses the LaTeX Qconfig package to create a graphical
        representation of the circuit.

        Returns:
            string: for writing to a LaTeX file.
        """
        self._initialize_latex_array(aliases)
        self._build_latex_array(aliases)
        header_1 = r"""% \documentclass[preview]{standalone}
% If the image is too large to fit on this documentclass use
\documentclass[draft]{beamer}
"""
        beamer_line = "\\usepackage[size=custom,height=%d,width=%d,scale=%.1f]{beamerposter}\n"
        header_2 = r"""% instead and customize the height and width (in cm) to fit.
% Large images may run out of memory quickly.
% To fix this use the LuaLaTeX compiler, which dynamically
% allocates memory.
\usepackage[braket, qm]{qcircuit}
\usepackage{amsmath}
\pdfmapfile{+sansmathaccent.map}
% \usepackage[landscape]{geometry}
% Comment out the above line if using the beamer documentclass.
\begin{document}
\begin{equation*}"""
        qcircuit_line = r"""
    \Qcircuit @C=%.1fem @R=%.1fem @!R {
"""
        output = io.StringIO()
        output.write(header_1)
        output.write('%% img_width = %d, img_depth = %d\n' % (self.img_width, self.img_depth))
        output.write(beamer_line % self._get_beamer_page())
        output.write(header_2)
        output.write(qcircuit_line %
                     (self.column_separation, self.row_separation))
        for i in range(self.img_width):
            output.write("\t \t")
            for j in range(self.img_depth + 1):
                cell_str = self._latex[i][j]
                # Don't truncate offset float if drawing a barrier
                if 'barrier' in cell_str:
                    output.write(cell_str)
                else:
                    # floats can cause "Dimension too large" latex error in
                    # xymatrix this truncates floats to avoid issue.
                    cell_str = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
                                      _truncate_float,
                                      cell_str)
                    output.write(cell_str)
                if j != self.img_depth:
                    output.write(" & ")
                else:
                    output.write(r'\\' + '\n')
        output.write('\t }\n')
        output.write('\\end{equation*}\n\n')
        output.write('\\end{document}')
        contents = output.getvalue()
        output.close()
        return contents

Return LaTeX string representation of circuit .